@openai/agents-openai
Version:
The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows.
611 lines • 28.5 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpenAIChatCompletionsModel = exports.FAKE_ID = void 0;
const openaiEndpoint_1 = require("./utils/openaiEndpoint.js");
const agents_core_1 = require("@openai/agents-core");
const logger_1 = __importDefault(require("./logger.js"));
const defaults_1 = require("./defaults.js");
const openaiChatCompletionsStreaming_1 = require("./openaiChatCompletionsStreaming.js");
const openaiChatCompletionsConverter_1 = require("./openaiChatCompletionsConverter.js");
const retryAdvice_1 = require("./retryAdvice.js");
const modelSettings_1 = require("./utils/modelSettings.js");
const openaiChatCompletionsContentFilter_1 = require("./openaiChatCompletionsContentFilter.js");
const internal_1 = require("@openai/agents-core/utils/internal");
const openaiItemIds_1 = require("./openaiItemIds.js");
Object.defineProperty(exports, "FAKE_ID", { enumerable: true, get: function () { return openaiItemIds_1.FAKE_ID; } });
const openaiChatCompletionsTruncation_1 = require("./openaiChatCompletionsTruncation.js");
function getModelTracingParent(request) {
return request._internal?.tracingParent;
}
const GPT_56_MODEL_PATTERN = /^gpt-5\.6(?:-(?:sol|terra|luna)(?:-\d{4}-\d{2}-\d{2})?)?$/;
function normalizeRequestId(requestId) {
return typeof requestId === 'string' && requestId.length > 0
? requestId
: undefined;
}
function hasReasoningContent(message) {
return ('reasoning' in message &&
typeof message.reasoning === 'string' &&
message.reasoning !== '');
}
class OpenAIChatCompletionsModel {
#client;
#model;
#strictFeatureValidation;
#hasWarnedUnsupportedPrompt = false;
#hasWarnedUnsupportedConversationState = false;
#hasWarnedUnsupportedReasoningSettings = false;
constructor(client, model, options = {}) {
this.#client = client;
this.#model = model;
this.#strictFeatureValidation = options.strictFeatureValidation ?? false;
}
getRetryAdvice(args) {
return (0, retryAdvice_1.getOpenAIRetryAdvice)(args);
}
async getResponse(request) {
this.#handleUnsupportedServerManagedConversationState(request);
this.#handleUnsupportedPrompt(request);
this.#handleUnsupportedReasoningSettings(request);
const { response, rawResponse, rawUsage, preservedUsage } = await (0, agents_core_1.withGenerationSpan)(async (span) => {
span.spanData.model = this.#model;
span.spanData.model_config = request.modelSettings
? {
temperature: request.modelSettings.temperature,
top_p: request.modelSettings.topP,
frequency_penalty: request.modelSettings.frequencyPenalty,
presence_penalty: request.modelSettings.presencePenalty,
reasoning_effort: request.modelSettings.reasoning?.effort,
verbosity: request.modelSettings.text?.verbosity,
}
: { base_url: this.#client.baseURL };
const rawResponse = await this.#fetchResponse(request, span, false).catch((error) => {
if (request.tracing !== true) {
// Provider and conversion errors may echo the submitted schemas.
span.setError({ message: 'Error requesting response' });
}
throw error;
});
const rawUsage = request.modelSettings.preserveRawUsage === true
? (0, internal_1.snapshotRawUsage)(rawResponse.usage)
: undefined;
const preservedUsage = rawUsage !== undefined
? new agents_core_1.Usage(toResponseUsage(rawUsage))
: undefined;
let response = rawResponse;
const firstChoice = rawResponse.choices?.[0];
const message = firstChoice?.message;
// Some providers signal a filtered completion only through the finish reason.
// Normalize that terminal signal before tracing and protocol conversion.
if (firstChoice &&
message &&
(0, openaiChatCompletionsContentFilter_1.shouldSynthesizeContentFilterRefusal)({
finishReason: firstChoice.finish_reason,
hasOutput: Boolean(message.content ||
message.refusal ||
message.tool_calls?.length ||
message.audio),
})) {
response = {
...rawResponse,
choices: [
{
...firstChoice,
message: {
...message,
content: null,
refusal: openaiChatCompletionsContentFilter_1.CONTENT_FILTER_REFUSAL_MESSAGE,
},
},
...rawResponse.choices.slice(1),
],
};
}
if (span && request.tracing === true) {
span.spanData.output = [response];
}
const normalizedMessage = response.choices?.[0]?.message;
const hasStrictCustomToolCall = Boolean(this.#strictFeatureValidation &&
normalizedMessage?.tool_calls?.some((toolCall) => toolCall.type === 'custom'));
if (normalizedMessage &&
!hasStrictCustomToolCall &&
(0, openaiChatCompletionsTruncation_1.isTruncatedEmptyChatCompletion)({
finishReason: response.choices[0]?.finish_reason,
hasText: typeof normalizedMessage.content === 'string' &&
normalizedMessage.content.length > 0,
hasRefusal: typeof normalizedMessage.refusal === 'string' &&
normalizedMessage.refusal.length > 0,
hasAudio: normalizedMessage.audio != null,
hasReasoning: hasReasoningContent(normalizedMessage),
hasFunctionCall: Boolean(normalizedMessage.tool_calls?.some((toolCall) => toolCall.type === 'function')),
})) {
const error = (0, openaiChatCompletionsTruncation_1.createChatCompletionTruncationError)();
const failureUsage = toResponseUsage(response.usage ?? {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0,
});
if (span) {
span.spanData.usage = failureUsage;
}
(0, internal_1.reportModelFailureUsage)(request, error, new agents_core_1.Usage(failureUsage));
throw error;
}
return { response, rawResponse, rawUsage, preservedUsage };
}, undefined, getModelTracingParent(request));
const output = [];
if (response.choices && response.choices[0]) {
const message = response.choices[0].message;
if (hasReasoningContent(message)) {
output.push({
type: 'reasoning',
content: [],
rawContent: [
{
type: 'reasoning_text',
text: message.reasoning,
},
],
});
}
const hasContent = message.content !== undefined &&
message.content !== null &&
// Azure OpenAI returns empty string instead of null for tool calls, causing parser rejection
!(message.tool_calls && message.content === '');
if (hasContent) {
const { content, ...rest } = message;
output.push({
id: response.id,
type: 'message',
role: 'assistant',
content: [
{
type: 'output_text',
text: content || '',
providerData: rest,
},
],
status: 'completed',
});
}
else if (message.refusal) {
const { refusal, ...rest } = message;
output.push({
id: response.id,
type: 'message',
role: 'assistant',
content: [
{
type: 'refusal',
refusal: refusal || '',
providerData: rest,
},
],
status: 'completed',
});
}
else if (message.audio) {
const { data, ...remainingAudioData } = message.audio;
output.push({
id: response.id,
type: 'message',
role: 'assistant',
content: [
{
type: 'audio',
audio: data,
providerData: remainingAudioData,
},
],
status: 'completed',
});
}
if (message.tool_calls) {
for (const tool_call of message.tool_calls) {
if (tool_call.type === 'function') {
// Note: custom tools are not supported for now
const { id: callId, ...remainingToolCallData } = tool_call;
const { arguments: args, name, ...remainingFunctionData } = tool_call.function;
output.push({
id: response.id,
type: 'function_call',
arguments: args,
name: name,
callId: callId,
status: 'completed',
providerData: {
...remainingToolCallData,
...remainingFunctionData,
},
});
}
else if (tool_call.type === 'custom') {
if (this.#strictFeatureValidation) {
throw new agents_core_1.UserError('Custom tool calls are not supported by the Chat Completions converter.');
}
}
}
}
}
const modelResponse = {
usage: preservedUsage ??
(response.usage
? new agents_core_1.Usage(toResponseUsage(response.usage))
: new agents_core_1.Usage({ requests: 1 })),
output,
responseId: response.id,
requestId: normalizeRequestId(rawResponse._request_id),
providerData: rawResponse,
...(rawUsage !== undefined ? { rawUsage } : {}),
};
return modelResponse;
}
async *getStreamedResponse(request) {
this.#handleUnsupportedServerManagedConversationState(request);
this.#handleUnsupportedPrompt(request);
this.#handleUnsupportedReasoningSettings(request);
const span = request.tracing
? (0, agents_core_1.createGenerationSpan)(undefined, getModelTracingParent(request))
: undefined;
let response;
try {
if (span) {
span.spanData.model = this.#model;
span.spanData.model_config = request.modelSettings
? {
temperature: request.modelSettings.temperature,
top_p: request.modelSettings.topP,
frequency_penalty: request.modelSettings.frequencyPenalty,
presence_penalty: request.modelSettings.presencePenalty,
reasoning_effort: request.modelSettings.reasoning?.effort,
verbosity: request.modelSettings.text?.verbosity,
}
: { base_url: this.#client.baseURL };
span.start();
(0, agents_core_1.setCurrentSpan)(span);
}
const { stream, requestId } = await this.#fetchResponse(request, span, true);
response = {
id: openaiItemIds_1.FAKE_ID,
created: Math.floor(Date.now() / 1000),
model: this.#model,
object: 'chat.completion',
choices: [],
usage: {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0,
},
};
for await (const event of (0, openaiChatCompletionsStreaming_1.convertChatCompletionsStreamToResponses)(response, stream, {
requireFinishReason: (0, openaiEndpoint_1.isOfficialOpenAIEndpoint)(this.#client.baseURL, 'http'),
signal: request.signal,
strictFeatureValidation: this.#strictFeatureValidation,
...(request.modelSettings.preserveRawUsage === true
? { preserveRawUsage: true }
: {}),
})) {
if (event.type === 'response_done' &&
response.usage?.total_tokens === 0) {
response.usage = {
prompt_tokens: event.response.usage.inputTokens,
completion_tokens: event.response.usage.outputTokens,
total_tokens: event.response.usage.totalTokens,
prompt_tokens_details: Array.isArray(event.response.usage.inputTokensDetails)
? event.response.usage.inputTokensDetails[0]
: event.response.usage.inputTokensDetails,
completion_tokens_details: Array.isArray(event.response.usage.outputTokensDetails)
? event.response.usage.outputTokensDetails[0]
: event.response.usage.outputTokensDetails,
};
}
if (event.type === 'response_done' && requestId) {
event.response.requestId = requestId;
}
yield event;
}
if (span && response && request.tracing === true) {
span.spanData.output = [response];
}
}
catch (error) {
const truncatedResponse = response !== undefined && (0, openaiChatCompletionsTruncation_1.isChatCompletionTruncationError)(error)
? response
: undefined;
if (truncatedResponse) {
(0, internal_1.reportModelFailureUsage)(request, error, new agents_core_1.Usage(toResponseUsage(truncatedResponse.usage ?? {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0,
})));
}
if (span) {
if (truncatedResponse) {
if (request.tracing === true) {
span.spanData.output = [truncatedResponse];
}
span.spanData.usage = toResponseUsage(truncatedResponse.usage ?? {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0,
});
}
span.setError({
message: 'Error streaming response',
data: {
error: request.tracing === true
? String(error)
: error instanceof Error
? error.name
: undefined,
},
});
}
throw error;
}
finally {
if (span) {
span.end();
(0, agents_core_1.resetCurrentSpan)();
}
}
}
#handleUnsupportedServerManagedConversationState(request) {
const unsupported = [];
if (request.previousResponseId) {
unsupported.push('previousResponseId');
}
if (request.conversationId) {
unsupported.push('conversationId');
}
if (unsupported.length === 0) {
return;
}
const message = 'OpenAIChatCompletionsModel does not support server-managed conversation state ' +
`(${unsupported.join(', ')}). Chat Completions requires callers to pass the full ` +
'conversation history; use a Responses API model for previousResponseId or a ' +
'conversation-capable model for conversationId.';
if (this.#strictFeatureValidation) {
throw new agents_core_1.UserError(message);
}
if (!this.#hasWarnedUnsupportedConversationState) {
logger_1.default.warn(`${message} Ignoring unsupported server-managed conversation state; ` +
'enable strict feature validation to raise an error instead.');
this.#hasWarnedUnsupportedConversationState = true;
}
}
#handleUnsupportedPrompt(request) {
if (!request.prompt) {
return;
}
const message = 'Reusable prompts are only supported by the Responses API. ' +
'OpenAIChatCompletionsModel does not support prompt; use a Responses model instead.';
if (this.#strictFeatureValidation) {
throw new agents_core_1.UserError(message);
}
if (!this.#hasWarnedUnsupportedPrompt) {
logger_1.default.warn(`${message} Ignoring prompt; enable strict feature validation to raise an error instead.`);
this.#hasWarnedUnsupportedPrompt = true;
}
}
#handleUnsupportedReasoningSettings(request) {
const reasoning = request.modelSettings.reasoning;
if (!reasoning) {
return;
}
const unsupported = ['mode', 'context'].filter((name) => reasoning[name] !== undefined && reasoning[name] !== null);
if (unsupported.length === 0) {
return;
}
const unsupportedParams = unsupported
.map((name) => `reasoning.${name}`)
.join(', ');
const message = `OpenAIChatCompletionsModel does not support ${unsupportedParams}. ` +
'These reasoning settings require the Responses API; Chat Completions only uses reasoning.effort.';
if (this.#strictFeatureValidation) {
throw new agents_core_1.UserError(message);
}
if (!this.#hasWarnedUnsupportedReasoningSettings) {
logger_1.default.warn(`${message} Ignoring unsupported reasoning settings; ` +
'enable strict feature validation to raise an error instead.');
this.#hasWarnedUnsupportedReasoningSettings = true;
}
}
async #fetchResponse(request, span, stream) {
const tools = [];
if (request.tools) {
for (const tool of request.tools) {
if ((tool.type === 'function' ||
tool.type === 'shell' ||
tool.type === 'apply_patch') &&
tool.allowedCallers?.some((caller) => caller === 'programmatic')) {
throw new agents_core_1.UserError('Tools callable from Programmatic Tool Calling are only supported with the Responses API.');
}
if (tool.type === 'function' && tool.outputSchema) {
throw new agents_core_1.UserError('Function tool outputSchema is only supported with the Responses API.');
}
if (tool.type === 'hosted_tool' &&
(tool.providerData?.type === 'programmatic_tool_calling' ||
(Array.isArray(tool.providerData?.allowed_callers) &&
tool.providerData.allowed_callers.includes('programmatic')))) {
throw new agents_core_1.UserError('Programmatic Tool Calling is only supported with the Responses API.');
}
if (tool.type === 'function') {
if (typeof tool.namespace === 'string' &&
tool.namespace.trim().length > 0) {
throw new agents_core_1.UserError('Namespaced function tools created with toolNamespace() are only supported with the Responses API.');
}
if (tool.deferLoading === true) {
throw new agents_core_1.UserError('Function tools with deferLoading: true are only supported with the Responses API.');
}
}
tools.push((0, openaiChatCompletionsConverter_1.toolToOpenAI)(tool));
}
}
if (request.handoffs) {
for (const handoff of request.handoffs) {
tools.push((0, openaiChatCompletionsConverter_1.convertHandoffTool)(handoff));
}
}
const responseFormat = getResponseFormat(request.outputType);
const parallelToolCalls = request.modelSettings.parallelToolCalls;
const messages = (0, openaiChatCompletionsConverter_1.itemsToMessages)(request.input, {
strictFeatureValidation: this.#strictFeatureValidation,
});
if (request.systemInstructions) {
messages.unshift({
content: request.systemInstructions,
role: 'system',
});
}
if (span && request.tracing === true) {
span.spanData.input = messages;
}
const providerData = { ...(request.modelSettings.providerData ?? {}) };
const requestInternal = request._internal;
const omitImplicitReasoningEffort = requestInternal?.reasoningEffortImplicit === true &&
(providerData.reasoning_effort !== undefined ||
(tools.length > 0 && GPT_56_MODEL_PATTERN.test(this.#model)));
if (request.modelSettings.reasoning &&
request.modelSettings.reasoning.effort &&
!omitImplicitReasoningEffort) {
// merge the top-level reasoning.effort into provider data
providerData.reasoning_effort = request.modelSettings.reasoning.effort;
}
if (request.modelSettings.text && request.modelSettings.text.verbosity) {
// merge the top-level text.verbosity into provider data
providerData.verbosity = request.modelSettings.text.verbosity;
}
const requestData = {
model: this.#model,
messages,
tools: tools.length ? tools : undefined,
temperature: request.modelSettings.temperature,
top_p: request.modelSettings.topP,
frequency_penalty: request.modelSettings.frequencyPenalty,
presence_penalty: request.modelSettings.presencePenalty,
max_tokens: request.modelSettings.maxTokens,
tool_choice: (0, openaiChatCompletionsConverter_1.getCompatibleToolChoice)(request.modelSettings.toolChoice, tools),
...(tools.length > 0 && typeof parallelToolCalls === 'boolean'
? { parallel_tool_calls: parallelToolCalls }
: {}),
stream: stream ? true : false,
stream_options: stream ? { include_usage: true } : undefined,
store: request.modelSettings.store,
prompt_cache_retention: (0, modelSettings_1.normalizePromptCacheRetention)(request.modelSettings.promptCacheRetention),
prompt_cache_options: request.modelSettings.promptCacheOptions,
...providerData,
};
// These Chat Completions models require non-reasoning mode for function tools.
if ((requestData.model === 'gpt-6-sol' ||
requestData.model === 'gpt-6-luna') &&
requestData.tools === tools &&
(requestInternal?.reasoningEffortImplicit ??
request.modelSettings.reasoning?.effort === undefined) &&
request.modelSettings.providerData?.reasoning_effort === undefined &&
(0, openaiEndpoint_1.isOfficialOpenAIEndpoint)(this.#client.baseURL, 'http')) {
requestData.reasoning_effort = 'none';
}
if (!requestData.tools?.length) {
delete requestData.parallel_tool_calls;
}
if (responseFormat) {
requestData.response_format = responseFormat;
}
if (logger_1.default.dontLogModelData) {
logger_1.default.debug('Calling LLM');
}
else {
logger_1.default.debug(`Calling LLM. Request data: ${JSON.stringify(requestData, null, 2)}`);
}
const requestOptions = {
headers: defaults_1.HEADERS,
signal: request.signal,
};
if (request._internal?.runnerManagedRetry === true) {
requestOptions.maxRetries = 0;
}
if (request.tracing === true &&
span &&
!(span instanceof agents_core_1.NoopSpan) &&
Array.isArray(requestData.tools) &&
requestData.tools.length > 0) {
try {
// A compatible client may rewrite nested request schemas during dispatch.
span.spanData.tools = structuredClone(requestData.tools);
}
catch {
// A provider-specific value that cannot be copied must not prevent dispatch.
}
}
const completionPromise = this.#client.chat.completions.create(requestData, requestOptions);
let completion;
let requestId;
if (stream) {
const withResponse = completionPromise.withResponse;
if (typeof withResponse === 'function') {
const streamedResponse = await withResponse.call(completionPromise);
completion = streamedResponse.data;
requestId = normalizeRequestId(streamedResponse.request_id);
}
else {
completion =
(await completionPromise);
}
}
else {
completion =
(await completionPromise);
}
if (logger_1.default.dontLogModelData) {
logger_1.default.debug('Response received');
}
else {
logger_1.default.debug(`Response received: ${JSON.stringify(completion, null, 2)}`);
}
return stream
? {
stream: completion,
...(requestId ? { requestId } : {}),
}
: completion;
}
}
exports.OpenAIChatCompletionsModel = OpenAIChatCompletionsModel;
function getResponseFormat(outputType) {
if (outputType === 'text') {
// Avoid sending response_format for plain text responses because some Chat Completions
// compatible providers (e.g., Claude) reject non-json_schema values here. OpenAI's API
// already treats text as the default when the field is omitted.
return undefined;
}
if (outputType.type === 'json_schema') {
return {
type: 'json_schema',
json_schema: {
name: outputType.name,
strict: outputType.strict,
schema: outputType.schema,
},
};
}
return { type: 'json_object' };
}
function toResponseUsage(usage) {
return {
requests: 1,
input_tokens: usage.prompt_tokens,
output_tokens: usage.completion_tokens,
total_tokens: usage.total_tokens,
input_tokens_details: {
cached_tokens: usage.prompt_tokens_details?.cached_tokens || 0,
},
output_tokens_details: {
reasoning_tokens: usage.completion_tokens_details?.reasoning_tokens || 0,
},
};
}
//# sourceMappingURL=openaiChatCompletionsModel.js.map