import * as plugins from './plugins.js'; import { promptTooLong } from './errors.js'; import type { IAnthropicMessagesControls, IAnthropicMessagesFailure, IAnthropicMessagesModel } from './interfaces.js'; export interface IOpenAiResponsesMessagesDialectOptions { /** * Whether the model reasons. A reasoning model is asked for its encrypted reasoning, which a thinking * signature carries back to it, so a conversation keeps its reasoning across turns and tool calls. */ reasoning: boolean; } const isRecord = (valueArg: unknown): valueArg is Record => typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg); /** The OpenAI error of a failure: an HTTP error body, a failed response, or an error frame of a stream. */ const readOpenAiError = (valueArg: unknown): { code?: unknown; message?: unknown } | undefined => { if (!isRecord(valueArg)) return undefined; if (isRecord(valueArg.error)) return valueArg.error; if (isRecord(valueArg.response) && isRecord(valueArg.response.error)) return valueArg.response.error; if ('code' in valueArg) return valueArg; return undefined; }; /** * Reads the OpenAI Responses failures the generic rules cannot: an input beyond the model's context window * answers with the wording an Anthropic client compacts its conversation on. */ export const classifyOpenAiResponsesMessagesFailure = (errorArg: unknown): IAnthropicMessagesFailure | undefined => { const error = plugins.APICallError.isInstance(errorArg) ? readOpenAiError(errorArg.data) : readOpenAiError(errorArg); if (error?.code !== 'context_length_exceeded') return undefined; return promptTooLong(typeof error.message === 'string' ? error.message : 'the input exceeds the model\'s context window.'); }; /** * The OpenAI Responses dialect of a served model: nothing is stored at the provider, reasoning returns * encrypted so a thinking signature can carry it, reasoning summaries are requested only when the client * asked for thinking, and the client's session id keys the provider's prompt cache. */ export const createOpenAiResponsesMessagesDialect = ( optionsArg: IOpenAiResponsesMessagesDialectOptions, ): Pick => ({ providerOptions: (controlsArg: IAnthropicMessagesControls) => ({ openai: { store: false, ...(optionsArg.reasoning ? { forceReasoning: true, reasoningSummary: controlsArg.thinking ? 'auto' : null, ...(controlsArg.reasoningEffort === undefined ? {} : { reasoningEffort: controlsArg.reasoningEffort }), } : {}), ...(controlsArg.parallelToolCalls ? {} : { parallelToolCalls: false }), ...(controlsArg.sessionId === undefined ? {} : { promptCacheKey: controlsArg.sessionId }), }, }), classifyFailure: classifyOpenAiResponsesMessagesFailure, });