@openai/agents-openai
Version:
The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows.
557 lines • 25.1 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertToolChoice = convertToolChoice;
exports.getCompatibleToolChoice = getCompatibleToolChoice;
exports.extractAllAssistantContent = extractAllAssistantContent;
exports.extractAllUserContent = extractAllUserContent;
exports.itemsToMessages = itemsToMessages;
exports.toolToOpenAI = toolToOpenAI;
exports.convertHandoffTool = convertHandoffTool;
const agents_core_1 = require("@openai/agents-core");
const providerData_1 = require("./utils/providerData.js");
const logger_1 = __importDefault(require("./logger.js"));
const CHAT_COMPLETIONS_FUNCTION_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
const OMITTED_TOOL_OUTPUT_PLACEHOLDER = '[tool output omitted]';
function convertToolChoice(toolChoice) {
if (toolChoice == undefined || toolChoice == null)
return undefined;
if (toolChoice === 'auto')
return 'auto';
if (toolChoice === 'required')
return 'required';
if (toolChoice === 'none')
return 'none';
return {
type: 'function',
function: { name: toolChoice },
};
}
function getCompatibleToolChoice(toolChoice, tools) {
const converted = convertToolChoice(toolChoice);
if (converted == undefined || converted === 'auto' || converted === 'none') {
return converted;
}
if (converted === 'required') {
if (tools.length === 0) {
throw new agents_core_1.UserError('modelSettings.toolChoice="required" requires at least one available tool in Chat Completions mode.');
}
return converted;
}
if (typeof converted !== 'object' || !('function' in converted)) {
return converted;
}
const availableToolNames = new Set(tools
.map((tool) => tool.type === 'function' && 'function' in tool
? tool.function.name
: undefined)
.filter((name) => typeof name === 'string'));
if (!availableToolNames.has(converted.function.name)) {
throw new agents_core_1.UserError(`modelSettings.toolChoice="${converted.function.name}" does not match any available tool or handoff in Chat Completions mode.`);
}
return converted;
}
function extractAllAssistantContent(content) {
if (typeof content === 'string') {
return content;
}
const out = [];
for (const c of content) {
if (c.type === 'output_text') {
out.push({
type: 'text',
text: c.text,
...(0, providerData_1.getProviderDataWithoutReservedKeys)(c.providerData, ['type', 'text']),
});
}
else if (c.type === 'refusal') {
out.push({
type: 'refusal',
refusal: c.refusal,
...(0, providerData_1.getProviderDataWithoutReservedKeys)(c.providerData, [
'type',
'refusal',
]),
});
}
else if (c.type === 'audio' || c.type === 'image') {
// ignoring audio as it is handled on the assistant message level
continue;
}
else {
const exhaustive = c; // ensures that the type is exhaustive
throw new Error(`Unknown content: ${JSON.stringify(exhaustive)}`);
}
}
return out;
}
function extractAllUserContent(content) {
if (typeof content === 'string') {
return content;
}
const out = [];
for (const c of content) {
if (c.type === 'input_text') {
out.push({
type: 'text',
text: c.text,
...(c.promptCacheBreakpoint
? { prompt_cache_breakpoint: c.promptCacheBreakpoint }
: {}),
...(0, providerData_1.getProviderDataWithoutReservedKeys)(c.providerData, ['type', 'text']),
});
}
else if (c.type === 'input_image') {
// The Chat Completions API only accepts image URLs. If we see a file reference we reject it
// early so callers get an actionable error instead of a cryptic API response.
const imageSource = typeof c.image === 'string'
? c.image
: typeof c.imageUrl === 'string'
? c.imageUrl
: undefined;
if (!imageSource) {
throw new Error(`Only image URLs are supported for input_image: ${JSON.stringify(c)}`);
}
const rest = (0, providerData_1.getProviderDataWithoutReservedKeys)(c.providerData, [
'type',
'image_url',
]);
const imageUrl = (0, providerData_1.getProviderDataWithoutReservedKeys)(c.providerData?.image_url, ['url']);
out.push({
type: 'image_url',
image_url: {
url: imageSource,
// Honor the top-level `detail` field, matching the Responses path
// (openaiResponsesModel) and the Python SDK. `providerData.image_url.detail`
// still takes precedence (spread last) to preserve existing behavior.
...(c.detail !== undefined
? { detail: c.detail }
: {}),
...imageUrl,
},
...(c.promptCacheBreakpoint
? { prompt_cache_breakpoint: c.promptCacheBreakpoint }
: {}),
...rest,
});
}
else if (c.type === 'input_file') {
// Chat Completions API supports file inputs via the "file" content part type.
// See: https://platform.openai.com/docs/guides/pdf-files?api-mode=chat
const file = {};
if (typeof c.file === 'string') {
const value = c.file.trim();
if (value.startsWith('data:')) {
file.file_data = value;
}
else {
throw new agents_core_1.UserError(`Chat Completions only supports data URLs for file input. If you're trying to pass an uploaded file's ID, use an object with the id property instead: ${JSON.stringify(c)}`);
}
}
else if (c.file && typeof c.file === 'object' && 'id' in c.file) {
file.file_id = c.file.id;
}
else {
throw new agents_core_1.UserError(`File input requires a data URL or file ID: ${JSON.stringify(c)}`);
}
// Handle filename from the content item or providerData
if (c.filename) {
file.filename = c.filename;
}
else if (c.providerData?.filename) {
file.filename = c.providerData.filename;
}
const rest = (0, providerData_1.getProviderDataWithoutReservedKeys)(c.providerData, [
'type',
'file',
'filename',
]);
out.push({
type: 'file',
file,
...(c.promptCacheBreakpoint
? { prompt_cache_breakpoint: c.promptCacheBreakpoint }
: {}),
...rest,
});
}
else if (c.type === 'audio') {
if (typeof c.audio !== 'string') {
throw new agents_core_1.UserError(`Chat Completions only supports inline audio data for input_audio: ${JSON.stringify(c)}`);
}
const inputAudioFormat = c.format === 'wav' || c.format === 'mp3'
? c.format
: c.providerData?.input_audio?.format === 'wav' ||
c.providerData?.input_audio?.format === 'mp3'
? c.providerData.input_audio.format
: undefined;
if (!inputAudioFormat) {
throw new agents_core_1.UserError(`Chat Completions input_audio requires format "wav" or "mp3": ${JSON.stringify(c)}`);
}
const rest = (0, providerData_1.getProviderDataWithoutReservedKeys)(c.providerData, [
'type',
'input_audio',
]);
const inputAudio = (0, providerData_1.getProviderDataWithoutReservedKeys)(c.providerData?.input_audio, ['data', 'format']);
out.push({
type: 'input_audio',
input_audio: {
data: c.audio,
format: inputAudioFormat,
...inputAudio,
},
...(c.promptCacheBreakpoint
? { prompt_cache_breakpoint: c.promptCacheBreakpoint }
: {}),
...rest,
});
}
else {
const exhaustive = c; // ensures that the type is exhaustive
throw new Error(`Unknown content: ${JSON.stringify(exhaustive)}`);
}
}
return out;
}
function isMessageItem(item) {
if (item.type === 'message') {
return true;
}
if (typeof item.type === 'undefined' && typeof item.role === 'string') {
return true;
}
return false;
}
function itemsToMessages(items, options = {}) {
if (typeof items === 'string') {
return [{ role: 'user', content: items }];
}
const result = [];
let currentAssistantMsg = null;
let pendingAssistantFunctionCallProviderData = {};
const flushAssistantMessage = () => {
if (currentAssistantMsg) {
if (!currentAssistantMsg.tool_calls ||
currentAssistantMsg.tool_calls.length === 0) {
delete currentAssistantMsg.tool_calls;
}
result.push(currentAssistantMsg);
currentAssistantMsg = null;
}
pendingAssistantFunctionCallProviderData = {};
};
const ensureAssistantMessage = () => {
if (!currentAssistantMsg) {
currentAssistantMsg = {
role: 'assistant',
content: null,
tool_calls: [],
};
}
return currentAssistantMsg;
};
// A reasoning item is emitted right before the assistant message it belongs
// to, so hand its reasoning back to that message instead of flushing an
// assistant turn that carries no content and no tool calls.
const takeReasoningOnlyAssistantMessage = () => {
const pending = currentAssistantMsg;
if (!pending ||
pending.content !== null ||
(pending.tool_calls && pending.tool_calls.length > 0) ||
!('reasoning' in pending)) {
return undefined;
}
currentAssistantMsg = null;
return pending;
};
for (const item of items) {
if (isMessageItem(item)) {
const { content, role, providerData } = item;
const pendingAssistantToolCallMessage = role === 'assistant' &&
currentAssistantMsg?.content === null &&
currentAssistantMsg.tool_calls &&
currentAssistantMsg.tool_calls.length > 0
? currentAssistantMsg
: undefined;
const pendingReasoningMsg = role === 'assistant' && !pendingAssistantToolCallMessage
? takeReasoningOnlyAssistantMessage()
: undefined;
if (!pendingAssistantToolCallMessage) {
flushAssistantMessage();
}
if (role === 'assistant') {
const phase = item.phase ?? providerData?.phase;
if (typeof phase !== 'undefined' && phase !== null) {
if (phase !== 'commentary' && phase !== 'final_answer') {
throw new agents_core_1.UserError(`Invalid assistant message phase: ${JSON.stringify(phase)}. Expected "commentary" or "final_answer".`);
}
const message = 'Assistant message phase is not supported by the Chat Completions API. Use the Responses API to preserve assistant message phases.';
if (options.strictFeatureValidation) {
throw new agents_core_1.UserError(message);
}
logger_1.default.warn(`${message} The phase will be dropped.`);
}
const assistant = {
role: 'assistant',
content: extractAllAssistantContent(content),
...(typeof (pendingReasoningMsg?.reasoning ??
pendingAssistantToolCallMessage?.reasoning) === 'string'
? {
reasoning: pendingReasoningMsg?.reasoning ??
pendingAssistantToolCallMessage?.reasoning,
}
: {}),
...(0, providerData_1.getProviderDataWithoutReservedKeys)(providerData, [
'role',
'content',
'tool_calls',
'audio',
'phase',
]),
};
if (Array.isArray(content)) {
const audio = content.find((c) => c.type === 'audio');
if (audio) {
assistant.audio = {
id: '', // setting this to empty ID and expecting that the user sets providerData.id
...audio.providerData,
};
}
}
if (pendingAssistantToolCallMessage) {
// A streamed turn may place its function calls before its assistant
// message. Keep the pending tool calls on the same Chat Completions
// assistant message instead of emitting two consecutive assistants.
// Reapply function-call provider data last so streamed and
// non-streamed orderings preserve the released message-first
// precedence for overlapping provider extension fields.
Object.assign(pendingAssistantToolCallMessage, assistant, pendingAssistantFunctionCallProviderData);
}
else {
// Keep the assistant message pending so following tool calls from the
// same turn can attach before the next turn boundary flushes it.
currentAssistantMsg = assistant;
}
}
else if (role === 'user') {
result.push({
role,
content: extractAllUserContent(content),
...(0, providerData_1.getProviderDataWithoutReservedKeys)(providerData, [
'role',
'content',
'phase',
]),
});
}
else if (role === 'system') {
result.push({
role: 'system',
content: content,
...(0, providerData_1.getProviderDataWithoutReservedKeys)(providerData, [
'role',
'content',
'phase',
]),
});
}
}
else if (item.type === 'reasoning') {
if (currentAssistantMsg?.content !== null) {
// A reasoning item starts the next assistant turn. Do not let a
// completed content-bearing assistant message absorb its reasoning or
// following tool calls while waiting for a later flush boundary.
flushAssistantMessage();
}
const asst = ensureAssistantMessage();
// Some third-party providers support reasoning on assistant messages even
// though it is not part of the official Chat Completions API type.
asst.reasoning = item.rawContent?.[0]?.text;
continue;
}
else if (item.type === 'hosted_tool_call') {
if (item.name === 'file_search_call') {
const asst = ensureAssistantMessage();
const toolCalls = asst.tool_calls ?? [];
const fileSearch = item;
const { function: functionData, ...rest } = fileSearch.providerData ?? {};
const { arguments: argumentData, ...remainingFunctionData } = functionData ?? {};
toolCalls.push({
id: fileSearch.id || '',
type: 'function',
function: {
name: 'file_search_call',
arguments: JSON.stringify({
queries: fileSearch.providerData?.queries ?? [],
status: fileSearch.status,
...(0, providerData_1.getProviderDataWithoutReservedKeys)(argumentData, [
'queries',
'status',
]),
}),
...(0, providerData_1.getProviderDataWithoutReservedKeys)(remainingFunctionData, [
'name',
'arguments',
]),
},
...(0, providerData_1.getProviderDataWithoutReservedKeys)(rest, [
'id',
'type',
'function',
]),
});
asst.tool_calls = toolCalls;
continue;
}
else {
throw new agents_core_1.UserError('Hosted tool calls are not supported for chat completions. Got item: ' +
JSON.stringify(item));
}
}
else if (item.type === 'computer_call' ||
item.type === 'computer_call_result' ||
item.type === 'shell_call' ||
item.type === 'shell_call_output' ||
item.type === 'apply_patch_call' ||
item.type === 'apply_patch_call_output') {
throw new agents_core_1.UserError('Computer use calls are not supported for chat completions. Got item: ' +
JSON.stringify(item));
}
else if (item.type === 'tool_search_call' ||
item.type === 'tool_search_output') {
throw new agents_core_1.UserError('Tool search items are not supported for chat completions. Please use the Responses API when replaying tool search history.');
}
else if (item.type === 'function_call') {
if (item.caller?.type === 'program') {
throw new agents_core_1.UserError('Programmatic Tool Calling history is not supported for chat completions. Please use the Responses API.');
}
const hasQualifiedOrInvalidName = typeof item.name === 'string' &&
!CHAT_COMPLETIONS_FUNCTION_NAME_PATTERN.test(item.name);
if (hasQualifiedOrInvalidName ||
(typeof item.namespace === 'string' && item.namespace.trim().length > 0)) {
throw new agents_core_1.UserError('Namespaced function call history is not supported for chat completions. Please use the Responses API when replaying namespaced tool calls.');
}
const asst = ensureAssistantMessage();
const toolCalls = asst.tool_calls ?? [];
const funcCall = item;
const toolCallProviderData = (0, providerData_1.getProviderDataWithoutReservedKeys)(funcCall.providerData, ['id', 'type', 'function', 'role', 'content', 'tool_calls', 'audio']);
const functionProviderData = (0, providerData_1.getProviderDataWithoutReservedKeys)(funcCall.providerData?.function, ['name', 'arguments']);
const assistantProviderData = (0, providerData_1.getProviderDataWithoutReservedKeys)(funcCall.providerData, ['role', 'content', 'tool_calls', 'audio', 'id', 'type', 'function']);
toolCalls.push({
id: funcCall.callId,
type: 'function',
function: {
name: funcCall.name,
arguments: funcCall.arguments ?? '{}',
...functionProviderData,
},
...toolCallProviderData,
});
asst.tool_calls = toolCalls;
Object.assign(pendingAssistantFunctionCallProviderData, assistantProviderData);
Object.assign(asst, assistantProviderData);
}
else if (item.type === 'function_call_result') {
if (item.caller?.type === 'program') {
throw new agents_core_1.UserError('Programmatic Tool Calling history is not supported for chat completions. Please use the Responses API.');
}
flushAssistantMessage();
const funcOutput = item;
const toolContent = normalizeFunctionCallOutputForChat(funcOutput.output, options);
result.push({
role: 'tool',
tool_call_id: funcOutput.callId,
content: toolContent,
...(0, providerData_1.getProviderDataWithoutReservedKeys)(funcOutput.providerData, [
'role',
'tool_call_id',
'content',
]),
});
}
else if (item.type === 'unknown') {
// An unknown provider item ends the current assistant turn. Flushing here
// keeps it in history order and stops reasoning from carrying across it
// to an assistant message it does not belong to.
flushAssistantMessage();
result.push({
...item.providerData,
});
}
else if (item.type === 'compaction') {
throw new agents_core_1.UserError('Compaction items are not supported for chat completions. Please use the Responses API when working with compaction.');
}
else if (item.type === 'program' || item.type === 'program_output') {
throw new agents_core_1.UserError('Programmatic Tool Calling history is not supported for chat completions. Please use the Responses API.');
}
else {
const exhaustive = item; // ensures that the type is exhaustive
throw new Error(`Unknown item type: ${JSON.stringify(exhaustive)}`);
}
}
flushAssistantMessage();
return result;
}
function normalizeFunctionCallOutputForChat(output, options) {
if (typeof output === 'string') {
return output;
}
if (Array.isArray(output)) {
const textItems = output.filter((item) => item.type === 'input_text');
if (textItems.length === 0) {
return handleEmptyOrNonTextToolOutput(options);
}
if (options.strictFeatureValidation && textItems.length !== output.length) {
throw new agents_core_1.UserError('Only text tool outputs are supported for chat completions.');
}
return textItems.map((item) => item.text).join('');
}
if (isRecord(output) &&
output.type === 'text' &&
typeof output.text === 'string') {
return output.text;
}
if (isRecord(output) && (output.type === 'image' || output.type === 'file')) {
return handleEmptyOrNonTextToolOutput(options);
}
throw new agents_core_1.UserError('Only text tool outputs are supported for chat completions. Got item: ' +
JSON.stringify(output));
}
function handleEmptyOrNonTextToolOutput(options) {
const message = 'Chat Completions tool outputs cannot be empty or contain only non-text content.';
if (options.strictFeatureValidation) {
throw new agents_core_1.UserError(message);
}
logger_1.default.warn(`${message} Replacing the tool output with a placeholder; enable strict feature validation to raise an error instead.`);
return OMITTED_TOOL_OUTPUT_PLACEHOLDER;
}
function isRecord(value) {
return typeof value === 'object' && value !== null;
}
function toolToOpenAI(tool) {
if (tool.type === 'function') {
return {
type: 'function',
function: {
name: tool.name,
description: tool.description || '',
parameters: tool.parameters,
strict: tool.strict,
},
};
}
throw new Error(`Hosted tools are not supported with the ChatCompletions API. Got tool type: ${tool.type}, tool: ${JSON.stringify(tool)}`);
}
function convertHandoffTool(handoff) {
return {
type: 'function',
function: {
name: handoff.toolName,
description: handoff.toolDescription || '',
parameters: handoff.inputJsonSchema,
},
};
}
//# sourceMappingURL=openaiChatCompletionsConverter.js.map