@warlock.js/ai-openai 5.29.0 → 5.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -1
- package/README.md +3 -3
- package/cjs/index.cjs +437 -69
- package/cjs/index.cjs.map +1 -1
- package/esm/config.type.d.mts +6 -4
- package/esm/config.type.d.mts.map +1 -1
- package/esm/embedder.d.mts +1 -1
- package/esm/embedder.d.mts.map +1 -1
- package/esm/embedder.mjs +1 -1
- package/esm/embedder.mjs.map +1 -1
- package/esm/image.d.mts +1 -1
- package/esm/image.d.mts.map +1 -1
- package/esm/image.mjs +1 -1
- package/esm/image.mjs.map +1 -1
- package/esm/index.d.mts +3 -1
- package/esm/index.mjs +2 -1
- package/esm/known-pricing.d.mts +35 -0
- package/esm/known-pricing.d.mts.map +1 -0
- package/esm/known-pricing.mjs +117 -0
- package/esm/known-pricing.mjs.map +1 -0
- package/esm/known-reasoning-models.mjs +1 -1
- package/esm/known-reasoning-models.mjs.map +1 -1
- package/esm/known-vision-models.mjs +1 -1
- package/esm/known-vision-models.mjs.map +1 -1
- package/esm/model.mjs +76 -24
- package/esm/model.mjs.map +1 -1
- package/esm/provider-options.d.mts +8 -0
- package/esm/provider-options.d.mts.map +1 -0
- package/esm/provider-options.mjs +49 -0
- package/esm/provider-options.mjs.map +1 -0
- package/esm/responses-model.mjs +117 -18
- package/esm/responses-model.mjs.map +1 -1
- package/esm/sdk.d.mts +4 -3
- package/esm/sdk.d.mts.map +1 -1
- package/esm/sdk.mjs +6 -4
- package/esm/sdk.mjs.map +1 -1
- package/esm/speech.d.mts +1 -1
- package/esm/speech.d.mts.map +1 -1
- package/esm/speech.mjs +1 -1
- package/esm/speech.mjs.map +1 -1
- package/esm/transcription.d.mts +1 -1
- package/esm/transcription.d.mts.map +1 -1
- package/esm/transcription.mjs +1 -1
- package/esm/transcription.mjs.map +1 -1
- package/esm/utils/build-usage.mjs +15 -3
- package/esm/utils/build-usage.mjs.map +1 -1
- package/esm/utils/index.mjs +1 -1
- package/esm/utils/map-finish-reason.mjs +1 -1
- package/esm/utils/map-finish-reason.mjs.map +1 -1
- package/esm/utils/map-responses-status.mjs +1 -1
- package/esm/utils/map-responses-status.mjs.map +1 -1
- package/esm/utils/prompt-cache-params.mjs +26 -7
- package/esm/utils/prompt-cache-params.mjs.map +1 -1
- package/esm/utils/reasoning-effort.mjs +1 -1
- package/esm/utils/reasoning-effort.mjs.map +1 -1
- package/esm/utils/reasoning-replay.mjs +24 -2
- package/esm/utils/reasoning-replay.mjs.map +1 -1
- package/esm/utils/structured-output.mjs +1 -1
- package/esm/utils/structured-output.mjs.map +1 -1
- package/esm/utils/to-openai-messages.mjs +1 -1
- package/esm/utils/to-openai-messages.mjs.map +1 -1
- package/esm/utils/to-openai-tools.mjs +1 -1
- package/esm/utils/to-openai-tools.mjs.map +1 -1
- package/esm/utils/to-responses-input.mjs +1 -1
- package/esm/utils/to-responses-input.mjs.map +1 -1
- package/esm/utils/to-responses-tools.mjs +1 -1
- package/esm/utils/to-responses-tools.mjs.map +1 -1
- package/esm/utils/wrap-openai-error.mjs +7 -2
- package/esm/utils/wrap-openai-error.mjs.map +1 -1
- package/llms-full.txt +128 -37
- package/llms.txt +1 -1
- package/package.json +5 -4
- package/skills/setup-openai/SKILL.md +128 -37
package/esm/model.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.mjs","names":[],"sources":["../../../../../../ai-openai/src/model.ts"],"sourcesContent":["import {\n InvalidRequestError,\n ProviderError,\n safeJsonParse,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type OpenAI from \"openai\";\nimport type { OpenAIModelConfig } from \"./config.type\";\nimport { inferReasoningCapability } from \"./known-reasoning-models\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n buildPromptCacheParams,\n buildUsage,\n inferStructuredOutput,\n mapFinishReason,\n planStructuredOutput,\n toOpenAIMessages,\n toOpenAIReasoningEffort,\n toOpenAITools,\n wrapOpenAIError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\n/**\n * OpenAI-backed implementation of `ModelContract`.\n *\n * **Role.** The provider-facing bridge between the vendor-neutral\n * `@warlock.js/ai` agent runtime and the official `openai` SDK. Agents,\n * workflows, and supervisors never talk to OpenAI directly — they hold a\n * `ModelContract`, and this class is what makes that contract concrete for\n * any OpenAI-compatible endpoint (OpenAI, Azure OpenAI, OpenRouter, local\n * gateways that speak the Chat Completions protocol).\n *\n * **Responsibility.**\n * - Owns: a long-lived `OpenAI` client + frozen `ModelConfig` (name,\n * temperature, maxTokens) used as defaults for every call.\n * - Owns: translating vendor-neutral `Message[]` and\n * `ToolContract[]` into OpenAI wire shapes on the way out, and\n * translating OpenAI's response (content, finish reason, tool calls,\n * usage) back into the neutral shapes on the way in.\n * - Does NOT own: dispatching tools, deciding whether to loop, tracking\n * conversation history, or retrying on failure — those are agent\n * concerns. The model is a stateless (per-call) protocol adapter.\n *\n * Because it holds a live client and shared defaults, it is modeled as a\n * class (see §4.2 of code-style.md — \"long-lived state across calls\").\n *\n * @example\n * import OpenAI from \"openai\";\n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * const model = new OpenAIModel(client, { name: \"gpt-4o\", temperature: 0.3 });\n *\n * const myAgent = agent({\n * model,\n * systemPrompt: \"You are a helpful assistant.\",\n * tools: [searchTool],\n * });\n *\n * const result = await myAgent.execute(\"Summarize today's news.\");\n */\nexport class OpenAIModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly client: OpenAI;\n private readonly config: OpenAIModelConfig;\n private readonly logger: Logger = log;\n\n public constructor(client: OpenAI, config: OpenAIModelConfig, provider: string = \"openai\") {\n // `api: \"responses\"` belongs to `OpenAIResponsesModel`, which only the\n // `OpenAISDK.model()` factory constructs. This class speaks Chat\n // Completions only; accepting the flag here would silently ignore it.\n if (config.api === \"responses\") {\n throw new InvalidRequestError(\n 'OpenAIModel speaks Chat Completions only and cannot serve api: \"responses\". Use OpenAISDK.model({ api: \"responses\" }) on the direct OpenAI provider.',\n { context: { provider, model: config.name, api: config.api } },\n );\n }\n\n this.client = client;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? inferStructuredOutput(config.responseFormat),\n vision: config.vision ?? inferVisionCapability(config.name),\n // o-series + gpt-5 / gpt-6 models surface a reasoning channel and accept\n // the `reasoning_effort` param. Explicit config wins over the\n // name-prefix inference.\n reasoning: config.reasoning ?? inferReasoningCapability(config.name),\n // Direct OpenAI requests support automatic cache hits and explicit\n // content-part breakpoints. Wrapper endpoints have distinct provider\n // labels and may reject these OpenAI-only request fields.\n promptCaching: this.provider === \"openai\",\n // PDF + audio INPUT are off by default — OpenAI accepts `file`\n // (PDF) and `input_audio` parts only on specific models, so the\n // flags are conservative/honest and opt-in via config rather than\n // name-inferred. When set, the agent admits the attachments and\n // `toOpenAIMessages` maps them to the real wire parts.\n pdf: config.pdf ?? false,\n audio: config.audio ?? false,\n };\n }\n\n /**\n * Single-shot completion. Sends the full message list to the Chat\n * Completions endpoint, waits for the terminal response, and reshapes it\n * into a vendor-neutral `ModelResponse`. Per-call `options` override the\n * instance's `ModelConfig` defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n // Per-call request/response logs are hot-path in production agents\n // — keep them at `debug` so `info` stays reserved for lifecycle\n // events (agent starting/completed, etc.). Operators who need to\n // audit every LLM call can raise log-level at runtime.\n this.logger.debug(LOG_MODULE, \"request\", \"Starting call to chat.completions\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let response: OpenAI.Chat.Completions.ChatCompletion;\n\n try {\n response = await this.client.chat.completions.create(\n {\n model: this.name,\n messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),\n ...this.buildSamplingParams(options),\n ...buildPromptCacheParams(this.provider, this.config),\n tools: toOpenAITools(options?.tools),\n ...this.buildResponseFormat(options?.responseSchema),\n ...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length)),\n },\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n const wrapped = wrapOpenAIError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n throw wrapped;\n }\n\n const [choice] = response.choices;\n\n if (choice === undefined) {\n // A 200 carrying an empty `choices` array. Every line below reads off\n // `choice`, so without this the caller got a bare `TypeError: Cannot\n // read properties of undefined` — no provider, no model, no hint that\n // the response itself was the problem rather than our handling of it.\n //\n // `ProviderError` because that is what this is: the provider answered\n // successfully and returned nothing usable. Callers already branch on\n // `instanceof ProviderError` for any provider-side failure.\n throw new ProviderError(\"OpenAI returned a response with no choices.\", {\n context: { provider: \"openai\", model: this.name, choices: response.choices.length },\n });\n }\n\n const finishReason = mapFinishReason(choice.finish_reason);\n const usage = this.extractUsage(response.usage);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to chat.completions succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n content: choice.message.content ?? \"\",\n finishReason,\n usage,\n toolCalls: this.extractToolCalls(choice.message.tool_calls),\n };\n }\n\n /**\n * Incremental streaming completion. Yields neutral `ModelStreamChunk`s —\n * `delta` for text tokens, `tool-call` when the model requests a tool,\n * and a terminal `done` carrying the final finish reason + usage totals.\n * Callers consume it with `for await`.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting streaming call to chat.completions\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let stream: Awaited<ReturnType<typeof this.client.chat.completions.create>>;\n\n try {\n stream = await this.client.chat.completions.create(\n {\n model: this.name,\n messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),\n ...this.buildSamplingParams(options),\n ...buildPromptCacheParams(this.provider, this.config),\n tools: toOpenAITools(options?.tools),\n stream: true,\n stream_options: { include_usage: true },\n ...this.buildResponseFormat(options?.responseSchema),\n ...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length)),\n },\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n const wrapped = wrapOpenAIError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n throw wrapped;\n }\n\n let rawFinishReason: string = \"stop\";\n const usage: Usage = { input: 0, output: 0, total: 0 };\n const toolCallAccum = new Map<number, { id: string; name: string; arguments: string }>();\n\n try {\n for await (const chunk of stream as AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>) {\n const delta = chunk.choices[0]?.delta;\n const finish = chunk.choices[0]?.finish_reason;\n\n if (delta?.content) {\n yield { type: \"delta\", content: delta.content };\n }\n\n if (delta?.tool_calls) {\n for (const toolCall of delta.tool_calls) {\n const idx = toolCall.index ?? 0;\n if (!toolCallAccum.has(idx)) {\n toolCallAccum.set(idx, { id: \"\", name: \"\", arguments: \"\" });\n }\n const acc = toolCallAccum.get(idx)!;\n if (toolCall.id) acc.id = toolCall.id;\n if (toolCall.function?.name) acc.name = toolCall.function.name;\n if (toolCall.function?.arguments) acc.arguments += toolCall.function.arguments;\n }\n }\n\n if (finish) {\n rawFinishReason = finish;\n }\n\n if (chunk.usage) {\n usage.input = chunk.usage.prompt_tokens ?? 0;\n usage.output = chunk.usage.completion_tokens ?? 0;\n usage.total = chunk.usage.total_tokens ?? 0;\n const cached = chunk.usage.prompt_tokens_details?.cached_tokens;\n if (cached !== undefined && cached > 0) {\n usage.cachedTokens = cached;\n }\n const reasoning = chunk.usage.completion_tokens_details?.reasoning_tokens;\n if (reasoning !== undefined && reasoning > 0) {\n usage.reasoningTokens = reasoning;\n }\n }\n }\n\n for (const acc of toolCallAccum.values()) {\n // Skip accumulators that never received a function name — those\n // are partial fragments the model started but never identified\n // (e.g. arguments-only deltas with no originating `id`/`name`).\n // Yielding them produces nameless tool-calls the agent runtime\n // can't dispatch and would mis-attribute as a registered tool.\n if (!acc.name) continue;\n\n yield {\n type: \"tool-call\",\n id: acc.id,\n name: acc.name,\n input: safeJsonParse<Record<string, unknown>>(acc.arguments, {}),\n };\n }\n } catch (thrown) {\n const wrapped = wrapOpenAIError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n throw wrapped;\n }\n\n const finishReason = mapFinishReason(rawFinishReason);\n\n this.logger.debug(LOG_MODULE, \"response\", \"Streaming call to chat.completions succeeded\", {\n finishReason,\n usage,\n });\n\n yield { type: \"done\", finishReason, usage };\n }\n\n /** Map the neutral cache hint only for the direct OpenAI provider. */\n private promptCacheBreakpoints(options: ModelCallOptions | undefined): number {\n return this.provider === \"openai\" ? (options?.cacheControl?.breakpoints ?? 0) : 0;\n }\n\n /**\n * Translate the neutral `responseSchema` option into OpenAI's\n * `response_format` parameter. The mode decision (override handling,\n * strict-compatibility downgrade to `json_object`) lives in\n * `planStructuredOutput`, shared with the Responses adapter.\n *\n * Returns an empty spread when no schema was supplied, so the caller\n * can unconditionally `...buildResponseFormat(...)` into the request.\n */\n private buildResponseFormat(responseSchema: Record<string, unknown> | undefined): {\n response_format?: OpenAI.Chat.Completions.ChatCompletionCreateParams[\"response_format\"];\n } {\n const plan = planStructuredOutput(responseSchema, this.config.responseFormat);\n\n if (plan.mode === \"json_schema\") {\n return {\n response_format: {\n type: \"json_schema\",\n json_schema: { name: \"response\", schema: plan.schema, strict: true },\n },\n };\n }\n\n if (plan.mode === \"json_object\") {\n return { response_format: { type: \"json_object\" } };\n }\n\n return {};\n }\n\n /**\n * Normalize OpenAI's `usage` block (which may be absent on some responses\n * or partials) into the neutral `Usage` shape. Missing usage collapses to\n * zeros rather than propagating `undefined`, so downstream aggregation\n * math stays safe.\n *\n * `cachedTokens` mirrors `prompt_tokens_details.cached_tokens` (the\n * subset of the prompt served from OpenAI's automatic prompt cache);\n * `reasoningTokens` mirrors `completion_tokens_details.reasoning_tokens`\n * (the hidden reasoning channel on o-series / gpt-5 models, already\n * counted within `output`). Both are emitted only when the provider\n * reports a positive value, so non-reasoning / uncached calls keep the\n * lean `{ input, output, total }` shape.\n */\n private extractUsage(raw: OpenAI.Completions.CompletionUsage | undefined): Usage {\n if (!raw) {\n return { input: 0, output: 0, total: 0 };\n }\n\n return buildUsage({\n input: raw.prompt_tokens,\n output: raw.completion_tokens,\n total: raw.total_tokens,\n cachedTokens: raw.prompt_tokens_details?.cached_tokens,\n reasoningTokens: raw.completion_tokens_details?.reasoning_tokens,\n });\n }\n\n /**\n * Translate the neutral `ModelCallOptions.reasoning` hint into OpenAI's\n * `reasoning_effort` request param. Only `effort` maps — OpenAI's Chat\n * Completions API exposes a discrete effort knob, not a token budget,\n * so `reasoning.maxTokens` (the Anthropic extended-thinking cap) has no\n * wire equivalent here and is silently ignored.\n *\n * The neutral `ReasoningEffort` (`\"low\" | \"medium\" | \"high\" | \"none\"`)\n * is a subset of OpenAI's accepted values, so it forwards verbatim —\n * `\"none\"` included. `\"none\"` is load-bearing: gpt-5 / o-series models\n * **reject function tools** on Chat Completions while reasoning is\n * active, and the endpoint accepts tools only when `reasoning_effort`\n * is `\"none\"` (the alternative is the Responses API). This is why the\n * param is EMITTED for `\"none\"` rather than omitted — omitting it\n * leaves the model reasoning server-side by default, so tools would\n * still be rejected.\n *\n * No-ops when the model is not reasoning-capable\n * (`capabilities.reasoning` is false — e.g. `gpt-4o`, which 400s on any\n * `reasoning_effort`).\n *\n * When the caller gave no explicit `effort`: defaults to `\"none\"` IF\n * `hasTools` is true, else omits the param (provider default — the\n * pre-existing behavior for a tool-less call). The default exists\n * because, on a reasoning-capable model, there is no working alternative\n * to `\"none\"` when tools are attached — omitting `reasoning_effort`\n * leaves reasoning on server-side, which Chat Completions rejects tools\n * for (empty replies on some model generations, a hard 400 — \"Function\n * tools with reasoning_effort are not supported ... in\n * /v1/chat/completions\" — on newer ones). An explicit `effort` from the\n * caller always wins over this default, in either direction.\n *\n * Returns an empty spread when nothing applies, so the caller can\n * unconditionally `...buildReasoningParams(...)` into the request.\n */\n /**\n * Output-length and sampling params, in current Chat Completions shapes only.\n *\n * - `max_completion_tokens`, never the legacy `max_tokens`: current\n * models (the gpt-5 family and later) answer `400 unsupported_parameter`\n * to `max_tokens`, and `max_completion_tokens` is accepted everywhere.\n * - No `temperature` for a reasoning-capable model: those accept only the\n * default value and reject any other with a 400.\n */\n private buildSamplingParams(options: ModelCallOptions | undefined): {\n max_completion_tokens?: number;\n temperature?: number;\n } {\n const maxTokens = options?.maxTokens ?? this.config.maxTokens;\n const temperature = options?.temperature ?? this.config.temperature;\n\n return {\n max_completion_tokens: maxTokens,\n ...(!this.capabilities.reasoning && { temperature }),\n };\n }\n\n private buildReasoningParams(\n reasoning: ModelCallOptions[\"reasoning\"],\n hasTools: boolean,\n ): {\n reasoning_effort?: OpenAI.Chat.Completions.ChatCompletionCreateParams[\"reasoning_effort\"];\n } {\n if (!this.capabilities.reasoning) {\n return {};\n }\n\n if (!reasoning?.effort) {\n return hasTools ? { reasoning_effort: \"none\" } : {};\n }\n\n return { reasoning_effort: toOpenAIReasoningEffort(reasoning.effort) };\n }\n\n /**\n * Reshape OpenAI's `tool_calls` array into the neutral\n * `ModelToolCallRequest[]`. The raw `arguments` field is a JSON string\n * per OpenAI's protocol — we parse it defensively via `safeJsonParse` so\n * malformed or empty arguments yield an empty object instead of crashing\n * the trip. Returns `undefined` when no tools were requested so callers\n * can branch on presence.\n */\n private extractToolCalls(\n rawToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] | undefined,\n ): ModelToolCallRequest[] | undefined {\n if (!rawToolCalls || rawToolCalls.length === 0) {\n return undefined;\n }\n\n return rawToolCalls.map((toolCall) => ({\n id: toolCall.id,\n name: (toolCall as any).function.name,\n input: safeJsonParse<Record<string, unknown>>((toolCall as any).function.arguments, {}),\n }));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA+BA,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCnB,IAAa,cAAb,MAAkD;CAUhD,AAAO,YAAY,QAAgB,QAA2B,WAAmB,UAAU;gBAFzD;EAMhC,IAAI,OAAO,QAAQ,aACjB,MAAM,IAAI,oBACR,4JACA,EAAE,SAAS;GAAE;GAAU,OAAO,OAAO;GAAM,KAAK,OAAO;EAAI,EAAE,CAC/D;EAGF,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;EACtB,KAAK,eAAe;GAClB,kBAAkB,OAAO,oBAAoB,sBAAsB,OAAO,cAAc;GACxF,QAAQ,OAAO,UAAU,sBAAsB,OAAO,IAAI;GAI1D,WAAW,OAAO,aAAa,yBAAyB,OAAO,IAAI;GAInE,eAAe,KAAK,aAAa;GAMjC,KAAK,OAAO,OAAO;GACnB,OAAO,OAAO,SAAS;EACzB;CACF;;;;;;;CAQA,MAAa,SAAS,UAAqB,SAAoD;EAK7F,KAAK,OAAO,MAAM,YAAY,WAAW,qCAAqC;GAC5E,OAAO,KAAK;GACZ,cAAc,SAAS;GACvB,WAAW;GACX,WAAW,SAAS,OAAO,UAAU;EACvC,CAAC;EAED,IAAI;EAEJ,IAAI;GACF,WAAW,MAAM,KAAK,OAAO,KAAK,YAAY,OAC5C;IACE,OAAO,KAAK;IACZ,UAAU,iBAAiB,UAAU,KAAK,uBAAuB,OAAO,CAAC;IACzE,GAAG,KAAK,oBAAoB,OAAO;IACnC,GAAG,uBAAuB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,OAAO;EAAE;EAGzC,OAAO,WAAW;GAChB,OAAO,IAAI;GACX,QAAQ,IAAI;GACZ,OAAO,IAAI;GACX,cAAc,IAAI,uBAAuB;GACzC,iBAAiB,IAAI,2BAA2B;EAClD,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CA,AAAQ,oBAAoB,SAG1B;EACA,MAAM,YAAY,SAAS,aAAa,KAAK,OAAO;EACpD,MAAM,cAAc,SAAS,eAAe,KAAK,OAAO;EAExD,OAAO;GACL,uBAAuB;GACvB,GAAI,CAAC,KAAK,aAAa,aAAa,EAAE,YAAY;EACpD;CACF;CAEA,AAAQ,qBACN,WACA,UAGA;EACA,IAAI,CAAC,KAAK,aAAa,WACrB,OAAO,CAAC;EAGV,IAAI,CAAC,WAAW,QACd,OAAO,WAAW,EAAE,kBAAkB,OAAO,IAAI,CAAC;EAGpD,OAAO,EAAE,kBAAkB,wBAAwB,UAAU,MAAM,EAAE;CACvE;;;;;;;;;CAUA,AAAQ,iBACN,cACoC;EACpC,IAAI,CAAC,gBAAgB,aAAa,WAAW,GAC3C;EAGF,OAAO,aAAa,KAAK,cAAc;GACrC,IAAI,SAAS;GACb,MAAO,SAAiB,SAAS;GACjC,OAAO,cAAwC,SAAiB,SAAS,WAAW,CAAC,CAAC;EACxF,EAAE;CACJ;AACF"}
|
|
1
|
+
{"version":3,"file":"model.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/model.ts"],"sourcesContent":["import {\n InvalidRequestError,\n ProviderError,\n resolveStreamChunks,\n safeJsonParse,\n selectProviderTools,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type OpenAI from \"openai\";\nimport { mergeProviderBody } from \"./provider-options\";\nimport type { OpenAIModelConfig } from \"./config.type\";\nimport { inferReasoningCapability } from \"./known-reasoning-models\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n buildPromptCacheParams,\n buildUsage,\n inferStructuredOutput,\n mapFinishReason,\n planStructuredOutput,\n toOpenAIMessages,\n toOpenAIReasoningEffort,\n toOpenAITools,\n wrapOpenAIError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\n/**\n * OpenAI-backed implementation of `ModelContract`.\n *\n * **Role.** The provider-facing bridge between the vendor-neutral\n * `@warlock.js/ai` agent runtime and the official `openai` SDK. Agents,\n * workflows, and supervisors never talk to OpenAI directly — they hold a\n * `ModelContract`, and this class is what makes that contract concrete for\n * any OpenAI-compatible endpoint (OpenAI, Azure OpenAI, OpenRouter, local\n * gateways that speak the Chat Completions protocol).\n *\n * **Responsibility.**\n * - Owns: a long-lived `OpenAI` client + frozen `ModelConfig` (name,\n * temperature, maxTokens) used as defaults for every call.\n * - Owns: translating vendor-neutral `Message[]` and\n * `ToolContract[]` into OpenAI wire shapes on the way out, and\n * translating OpenAI's response (content, finish reason, tool calls,\n * usage) back into the neutral shapes on the way in.\n * - Does NOT own: dispatching tools, deciding whether to loop, tracking\n * conversation history, or retrying on failure — those are agent\n * concerns. The model is a stateless (per-call) protocol adapter.\n *\n * Because it holds a live client and shared defaults, it is modeled as a\n * class (see §4.2 of code-style.md — \"long-lived state across calls\").\n *\n * @example\n * import OpenAI from \"openai\";\n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * const model = new OpenAIModel(client, { name: \"gpt-4o\", temperature: 0.3 });\n *\n * const myAgent = agent({\n * model,\n * systemPrompt: \"You are a helpful assistant.\",\n * tools: [searchTool],\n * });\n *\n * const result = await myAgent.execute(\"Summarize today's news.\");\n */\nexport class OpenAIModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly client: OpenAI;\n private readonly config: OpenAIModelConfig;\n private readonly logger: Logger = log;\n\n public constructor(client: OpenAI, config: OpenAIModelConfig, provider: string = \"openai\") {\n // `api: \"responses\"` belongs to `OpenAIResponsesModel`, which only the\n // `OpenAISDK.model()` factory constructs. This class speaks Chat\n // Completions only; accepting the flag here would silently ignore it.\n if (config.api === \"responses\") {\n throw new InvalidRequestError(\n 'OpenAIModel speaks Chat Completions only and cannot serve api: \"responses\". Use OpenAISDK.model({ api: \"responses\" }) on the direct OpenAI provider.',\n { context: { provider, model: config.name, api: config.api } },\n );\n }\n\n this.client = client;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? inferStructuredOutput(config.responseFormat),\n vision: config.vision ?? inferVisionCapability(config.name),\n // o-series + gpt-5 / gpt-6 models surface a reasoning channel and accept\n // the `reasoning_effort` param. Explicit config wins over the\n // name-prefix inference.\n reasoning: config.reasoning ?? inferReasoningCapability(config.name),\n // Direct OpenAI requests support automatic cache hits and explicit\n // content-part breakpoints. Wrapper endpoints have distinct provider\n // labels and may reject these OpenAI-only request fields.\n promptCaching: this.provider === \"openai\",\n // PDF + audio INPUT are off by default — OpenAI accepts `file`\n // (PDF) and `input_audio` parts only on specific models, so the\n // flags are conservative/honest and opt-in via config rather than\n // name-inferred. When set, the agent admits the attachments and\n // `toOpenAIMessages` maps them to the real wire parts.\n pdf: config.pdf ?? false,\n audio: config.audio ?? false,\n };\n }\n\n /**\n * Single-shot completion. Sends the full message list to the Chat\n * Completions endpoint, waits for the terminal response, and reshapes it\n * into a vendor-neutral `ModelResponse`. Per-call `options` override the\n * instance's `ModelConfig` defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n // Per-call request/response logs are hot-path in production agents\n // — keep them at `debug` so `info` stays reserved for lifecycle\n // events (agent starting/completed, etc.). Operators who need to\n // audit every LLM call can raise log-level at runtime.\n this.logger.debug(LOG_MODULE, \"request\", \"Starting call to chat.completions\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let response: OpenAI.Chat.Completions.ChatCompletion;\n\n try {\n response = await this.client.chat.completions.create(\n mergeProviderBody<OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming>(\n {\n model: this.name,\n messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),\n ...this.buildSamplingParams(options),\n ...buildPromptCacheParams(this.provider, this.config),\n ...this.buildTools(options),\n ...this.buildResponseFormat(options?.responseSchema),\n ...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length)),\n },\n options,\n ),\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n const wrapped = wrapOpenAIError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n throw wrapped;\n }\n\n const [choice] = response.choices;\n\n if (choice === undefined) {\n // A 200 carrying an empty `choices` array. Every line below reads off\n // `choice`, so without this the caller got a bare `TypeError: Cannot\n // read properties of undefined` — no provider, no model, no hint that\n // the response itself was the problem rather than our handling of it.\n //\n // `ProviderError` because that is what this is: the provider answered\n // successfully and returned nothing usable. Callers already branch on\n // `instanceof ProviderError` for any provider-side failure.\n throw new ProviderError(\"OpenAI returned a response with no choices.\", {\n context: { provider: \"openai\", model: this.name, choices: response.choices.length },\n });\n }\n\n const finishReason = mapFinishReason(choice.finish_reason);\n const usage = this.extractUsage(response.usage);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to chat.completions succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n content: choice.message.content ?? \"\",\n finishReason,\n usage,\n toolCalls: this.extractToolCalls(choice.message.tool_calls),\n };\n }\n\n /**\n * Incremental streaming completion. Yields neutral `ModelStreamChunk`s —\n * `delta` for text tokens, `tool-call` when the model requests a tool,\n * and a terminal `done` carrying the final finish reason + usage totals.\n * Callers consume it with `for await`.\n *\n * With `options.streamChunks` it also yields `tool-args` for each\n * `tool_calls[].function.arguments` fragment and `reasoning` for a\n * vendor's `reasoning_content` / `reasoning` delta field. Usage arrives\n * only on the final chunk here, so no `usage` chunk is emitted.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting streaming call to chat.completions\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let stream: Awaited<ReturnType<typeof this.client.chat.completions.create>>;\n\n try {\n stream = await this.client.chat.completions.create(\n mergeProviderBody<OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming>(\n {\n model: this.name,\n messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),\n ...this.buildSamplingParams(options),\n ...buildPromptCacheParams(this.provider, this.config),\n ...this.buildTools(options),\n stream: true,\n stream_options: { include_usage: true },\n ...this.buildResponseFormat(options?.responseSchema),\n ...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length)),\n },\n options,\n ),\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n const wrapped = wrapOpenAIError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n throw wrapped;\n }\n\n let rawFinishReason: string = \"stop\";\n let usage: Usage = { input: 0, output: 0, total: 0 };\n const want = resolveStreamChunks(options);\n const toolCallAccum = new Map<\n number,\n { id: string; name: string; arguments: string; streamed: number }\n >();\n\n try {\n for await (const chunk of stream as AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>) {\n const delta = chunk.choices[0]?.delta;\n const finish = chunk.choices[0]?.finish_reason;\n\n if (want.reasoning && delta) {\n const reasoning = readReasoningDelta(delta);\n\n if (reasoning) {\n yield { type: \"reasoning\", delta: reasoning };\n }\n }\n\n if (delta?.content) {\n yield { type: \"delta\", content: delta.content };\n }\n\n if (delta?.tool_calls) {\n for (const toolCall of delta.tool_calls) {\n const idx = toolCall.index ?? 0;\n if (!toolCallAccum.has(idx)) {\n toolCallAccum.set(idx, { id: \"\", name: \"\", arguments: \"\", streamed: 0 });\n }\n const acc = toolCallAccum.get(idx)!;\n if (toolCall.id) acc.id = toolCall.id;\n if (toolCall.function?.name) acc.name = toolCall.function.name;\n if (toolCall.function?.arguments) acc.arguments += toolCall.function.arguments;\n\n // The first fragment of a call carries its id and name; later\n // ones only `index` + argument text. Anything that arrived\n // before the name is flushed once the call is identified.\n if (want.toolArgs && acc.name && acc.arguments.length > acc.streamed) {\n yield {\n type: \"tool-args\",\n callId: acc.id,\n name: acc.name,\n delta: acc.arguments.slice(acc.streamed),\n };\n acc.streamed = acc.arguments.length;\n }\n }\n }\n\n if (finish) {\n rawFinishReason = finish;\n }\n\n if (chunk.usage) {\n usage = this.extractUsage(chunk.usage);\n }\n }\n\n for (const acc of toolCallAccum.values()) {\n // Skip accumulators that never received a function name — those\n // are partial fragments the model started but never identified\n // (e.g. arguments-only deltas with no originating `id`/`name`).\n // Yielding them produces nameless tool-calls the agent runtime\n // can't dispatch and would mis-attribute as a registered tool.\n if (!acc.name) continue;\n\n yield {\n type: \"tool-call\",\n id: acc.id,\n name: acc.name,\n input: safeJsonParse<Record<string, unknown>>(acc.arguments, {}),\n };\n }\n } catch (thrown) {\n const wrapped = wrapOpenAIError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n throw wrapped;\n }\n\n const finishReason = mapFinishReason(rawFinishReason);\n\n this.logger.debug(LOG_MODULE, \"response\", \"Streaming call to chat.completions succeeded\", {\n finishReason,\n usage,\n });\n\n yield { type: \"done\", finishReason, usage };\n }\n\n /**\n * Spread-friendly `tools` fragment: the function tools, then the\n * provider-defined entries whose `provider` equals this model's\n * provider label (`\"openai\"`, or the vendor label an OpenAI-compatible\n * wrapper sets, e.g. `\"groq\"`), sent verbatim. Chat Completions only\n * accepts `function` and `custom` tool types from OpenAI itself; its\n * hosted tools (`web_search`, `file_search`, …) need `api: \"responses\"`\n * and OpenAI rejects them here with a 400.\n */\n private buildTools(options: ModelCallOptions | undefined): {\n tools?: OpenAI.Chat.Completions.ChatCompletionTool[];\n } {\n const { tools, definitions } = selectProviderTools(options, {\n accepts: [this.provider],\n module: LOG_MODULE,\n model: this.name,\n logger: this.logger,\n });\n const mapped = [\n ...(toOpenAITools(tools) ?? []),\n ...(definitions as unknown as OpenAI.Chat.Completions.ChatCompletionTool[]),\n ];\n\n return mapped.length > 0 ? { tools: mapped } : {};\n }\n\n /** Map the neutral cache hint only for the direct OpenAI provider. */\n private promptCacheBreakpoints(options: ModelCallOptions | undefined): number {\n return this.provider === \"openai\" ? (options?.cacheControl?.breakpoints ?? 0) : 0;\n }\n\n /**\n * Translate the neutral `responseSchema` option into OpenAI's\n * `response_format` parameter. The mode decision (override handling,\n * strict-compatibility downgrade to `json_object`) lives in\n * `planStructuredOutput`, shared with the Responses adapter.\n *\n * Returns an empty spread when no schema was supplied, so the caller\n * can unconditionally `...buildResponseFormat(...)` into the request.\n */\n private buildResponseFormat(responseSchema: Record<string, unknown> | undefined): {\n response_format?: OpenAI.Chat.Completions.ChatCompletionCreateParams[\"response_format\"];\n } {\n const plan = planStructuredOutput(responseSchema, this.config.responseFormat);\n\n if (plan.mode === \"json_schema\") {\n return {\n response_format: {\n type: \"json_schema\",\n json_schema: { name: \"response\", schema: plan.schema, strict: true },\n },\n };\n }\n\n if (plan.mode === \"json_object\") {\n return { response_format: { type: \"json_object\" } };\n }\n\n return {};\n }\n\n /**\n * Normalize OpenAI's `usage` block (which may be absent on some responses\n * or partials) into the neutral `Usage` shape. Missing usage collapses to\n * zeros rather than propagating `undefined`, so downstream aggregation\n * math stays safe.\n *\n * `cachedTokens` mirrors `prompt_tokens_details.cached_tokens` (the\n * subset of the prompt served from OpenAI's automatic prompt cache);\n * `reasoningTokens` mirrors `completion_tokens_details.reasoning_tokens`\n * (the hidden reasoning channel on o-series / gpt-5 models, already\n * counted within `output`). Both are emitted only when the provider\n * reports a positive value, so non-reasoning / uncached calls keep the\n * lean `{ input, output, total }` shape. `cacheWriteTokens` mirrors\n * `prompt_tokens_details.cache_write_tokens` (billed writes on the\n * models that charge for them). `cost` is attached when priced.\n */\n private extractUsage(raw: OpenAI.Completions.CompletionUsage | undefined): Usage {\n if (!raw) {\n return { input: 0, output: 0, total: 0 };\n }\n\n return buildUsage(\n {\n input: raw.prompt_tokens ?? 0,\n output: raw.completion_tokens ?? 0,\n total: raw.total_tokens ?? 0,\n cachedTokens: raw.prompt_tokens_details?.cached_tokens,\n cacheWriteTokens: raw.prompt_tokens_details?.cache_write_tokens,\n reasoningTokens: raw.completion_tokens_details?.reasoning_tokens,\n },\n this.pricing,\n );\n }\n\n /**\n * Translate the neutral `ModelCallOptions.reasoning` hint into OpenAI's\n * `reasoning_effort` request param. Only `effort` maps — OpenAI's Chat\n * Completions API exposes a discrete effort knob, not a token budget,\n * so `reasoning.maxTokens` (the Anthropic extended-thinking cap) has no\n * wire equivalent here and is silently ignored.\n *\n * The neutral `ReasoningEffort` (`\"low\" | \"medium\" | \"high\" | \"none\"`)\n * is a subset of OpenAI's accepted values, so it forwards verbatim —\n * `\"none\"` included. `\"none\"` is load-bearing: gpt-5 / o-series models\n * **reject function tools** on Chat Completions while reasoning is\n * active, and the endpoint accepts tools only when `reasoning_effort`\n * is `\"none\"` (the alternative is the Responses API). This is why the\n * param is EMITTED for `\"none\"` rather than omitted — omitting it\n * leaves the model reasoning server-side by default, so tools would\n * still be rejected.\n *\n * No-ops when the model is not reasoning-capable\n * (`capabilities.reasoning` is false — e.g. `gpt-4o`, which 400s on any\n * `reasoning_effort`).\n *\n * When the caller gave no explicit `effort`: defaults to `\"none\"` IF\n * `hasTools` is true, else omits the param (provider default — the\n * pre-existing behavior for a tool-less call). The default exists\n * because, on a reasoning-capable model, there is no working alternative\n * to `\"none\"` when tools are attached — omitting `reasoning_effort`\n * leaves reasoning on server-side, which Chat Completions rejects tools\n * for (empty replies on some model generations, a hard 400 — \"Function\n * tools with reasoning_effort are not supported ... in\n * /v1/chat/completions\" — on newer ones). An explicit `effort` from the\n * caller always wins over this default, in either direction.\n *\n * Returns an empty spread when nothing applies, so the caller can\n * unconditionally `...buildReasoningParams(...)` into the request.\n */\n /**\n * Output-length and sampling params, in current Chat Completions shapes only.\n *\n * - `max_completion_tokens`, never the legacy `max_tokens`: current\n * models (the gpt-5 family and later) answer `400 unsupported_parameter`\n * to `max_tokens`, and `max_completion_tokens` is accepted everywhere.\n * - No `temperature` for a reasoning-capable model: those accept only the\n * default value and reject any other with a 400.\n */\n private buildSamplingParams(options: ModelCallOptions | undefined): {\n max_completion_tokens?: number;\n temperature?: number;\n } {\n const maxTokens = options?.maxTokens ?? this.config.maxTokens;\n const temperature = options?.temperature ?? this.config.temperature;\n\n return {\n max_completion_tokens: maxTokens,\n ...(!this.capabilities.reasoning && { temperature }),\n };\n }\n\n private buildReasoningParams(\n reasoning: ModelCallOptions[\"reasoning\"],\n hasTools: boolean,\n ): {\n reasoning_effort?: OpenAI.Chat.Completions.ChatCompletionCreateParams[\"reasoning_effort\"];\n } {\n if (!this.capabilities.reasoning) {\n return {};\n }\n\n if (!reasoning?.effort) {\n return hasTools ? { reasoning_effort: \"none\" } : {};\n }\n\n return { reasoning_effort: toOpenAIReasoningEffort(reasoning.effort) };\n }\n\n /**\n * Reshape OpenAI's `tool_calls` array into the neutral\n * `ModelToolCallRequest[]`. The raw `arguments` field is a JSON string\n * per OpenAI's protocol — we parse it defensively via `safeJsonParse` so\n * malformed or empty arguments yield an empty object instead of crashing\n * the trip. Returns `undefined` when no tools were requested so callers\n * can branch on presence.\n */\n private extractToolCalls(\n rawToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] | undefined,\n ): ModelToolCallRequest[] | undefined {\n if (!rawToolCalls || rawToolCalls.length === 0) {\n return undefined;\n }\n\n return rawToolCalls.map((toolCall) => ({\n id: toolCall.id,\n name: (toolCall as any).function.name,\n input: safeJsonParse<Record<string, unknown>>((toolCall as any).function.arguments, {}),\n }));\n }\n}\n\n/**\n * Reasoning text an OpenAI-compatible vendor puts on a Chat Completions\n * stream delta. OpenAI itself streams none on this API. DeepSeek documents\n * `delta.reasoning_content` (API reference, chat completion chunk); Groq\n * documents the parsed reasoning under a `reasoning` field. Neither is in\n * the OpenAI SDK's delta type, so the delta is read as a plain record.\n */\nfunction readReasoningDelta(delta: object): string | undefined {\n const record = delta as Record<string, unknown>;\n\n for (const key of [\"reasoning_content\", \"reasoning\"]) {\n const value = record[key];\n\n if (typeof value === \"string\" && value !== \"\") {\n return value;\n }\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCnB,IAAa,cAAb,MAAkD;CAUhD,AAAO,YAAY,QAAgB,QAA2B,WAAmB,UAAU;gBAFzD;EAMhC,IAAI,OAAO,QAAQ,aACjB,MAAM,IAAI,oBACR,4JACA,EAAE,SAAS;GAAE;GAAU,OAAO,OAAO;GAAM,KAAK,OAAO;EAAI,EAAE,CAC/D;EAGF,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;EACtB,KAAK,eAAe;GAClB,kBAAkB,OAAO,oBAAoB,sBAAsB,OAAO,cAAc;GACxF,QAAQ,OAAO,UAAU,sBAAsB,OAAO,IAAI;GAI1D,WAAW,OAAO,aAAa,yBAAyB,OAAO,IAAI;GAInE,eAAe,KAAK,aAAa;GAMjC,KAAK,OAAO,OAAO;GACnB,OAAO,OAAO,SAAS;EACzB;CACF;;;;;;;CAQA,MAAa,SAAS,UAAqB,SAAoD;EAK7F,KAAK,OAAO,MAAM,YAAY,WAAW,qCAAqC;GAC5E,OAAO,KAAK;GACZ,cAAc,SAAS;GACvB,WAAW;GACX,WAAW,SAAS,OAAO,UAAU;EACvC,CAAC;EAED,I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OAAO,WAAW,EAAE,kBAAkB,OAAO,IAAI,CAAC;EAGpD,OAAO,EAAE,kBAAkB,wBAAwB,UAAU,MAAM,EAAE;CACvE;;;;;;;;;CAUA,AAAQ,iBACN,cACoC;EACpC,IAAI,CAAC,gBAAgB,aAAa,WAAW,GAC3C;EAGF,OAAO,aAAa,KAAK,cAAc;GACrC,IAAI,SAAS;GACb,MAAO,SAAiB,SAAS;GACjC,OAAO,cAAwC,SAAiB,SAAS,WAAW,CAAC,CAAC;EACxF,EAAE;CACJ;AACF;;;;;;;;AASA,SAAS,mBAAmB,OAAmC;CAC7D,MAAM,SAAS;CAEf,KAAK,MAAM,OAAO,CAAC,qBAAqB,WAAW,GAAG;EACpD,MAAM,QAAQ,OAAO;EAErB,IAAI,OAAO,UAAU,YAAY,UAAU,IACzC,OAAO;CAEX;AAGF"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
//#region ../../packages/ai-openai/src/provider-options.d.ts
|
|
2
|
+
/** Adapter-only fields merged after the neutral request parameters. */
|
|
3
|
+
type OpenAICallOptions = {
|
|
4
|
+
body?: Record<string, unknown>;
|
|
5
|
+
};
|
|
6
|
+
//#endregion
|
|
7
|
+
export { OpenAICallOptions };
|
|
8
|
+
//# sourceMappingURL=provider-options.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider-options.d.mts","names":[],"sources":["../../../../../../../packages/ai-openai/src/provider-options.ts"],"mappings":";;KAGY,iBAAA;EAAsB,IAAA,GAAO,MAAM;AAAA"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { InvalidRequestError } from "@warlock.js/ai";
|
|
2
|
+
|
|
3
|
+
//#region ../../packages/ai-openai/src/provider-options.ts
|
|
4
|
+
const RESERVED_FIELDS = new Set([
|
|
5
|
+
"model",
|
|
6
|
+
"messages",
|
|
7
|
+
"input",
|
|
8
|
+
"instructions",
|
|
9
|
+
"tools",
|
|
10
|
+
"stream",
|
|
11
|
+
"stream_options",
|
|
12
|
+
"previous_response_id",
|
|
13
|
+
"conversation",
|
|
14
|
+
"store",
|
|
15
|
+
"include",
|
|
16
|
+
"functions",
|
|
17
|
+
"function_call",
|
|
18
|
+
"prompt",
|
|
19
|
+
"background"
|
|
20
|
+
]);
|
|
21
|
+
function mergeProviderBody(built, options) {
|
|
22
|
+
const body = (options?.providerOptions?.openai)?.body ?? {};
|
|
23
|
+
const reserved = Object.keys(body).filter((key) => RESERVED_FIELDS.has(key));
|
|
24
|
+
if (reserved.length > 0) throw new InvalidRequestError(`providerOptions.openai.body cannot set ${reserved.join(", ")}: use the call's messages, tools and model options.`, { context: { fields: reserved } });
|
|
25
|
+
const defaults = built;
|
|
26
|
+
const overrides = Object.fromEntries(Object.entries(body).map(([key, value]) => {
|
|
27
|
+
const previous = defaults[key];
|
|
28
|
+
if (!isPlainObject(previous) || !isPlainObject(value)) return [key, value];
|
|
29
|
+
if (typeof previous.type === "string" && typeof value.type === "string" && previous.type !== value.type) return [key, value];
|
|
30
|
+
return [key, {
|
|
31
|
+
...previous,
|
|
32
|
+
...value
|
|
33
|
+
}];
|
|
34
|
+
}));
|
|
35
|
+
return {
|
|
36
|
+
...built,
|
|
37
|
+
...overrides
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** Merge only plain objects; arrays, null and provider scalar values replace the field. */
|
|
41
|
+
function isPlainObject(value) {
|
|
42
|
+
if (value === null || typeof value !== "object") return false;
|
|
43
|
+
const prototype = Object.getPrototypeOf(value);
|
|
44
|
+
return prototype === Object.prototype || prototype === null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
//#endregion
|
|
48
|
+
export { mergeProviderBody };
|
|
49
|
+
//# sourceMappingURL=provider-options.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider-options.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/provider-options.ts"],"sourcesContent":["import { InvalidRequestError, type ModelCallOptions } from \"@warlock.js/ai\";\n\n/** Adapter-only fields merged after the neutral request parameters. */\nexport type OpenAICallOptions = { body?: Record<string, unknown> };\n\nconst RESERVED_FIELDS = new Set([\n \"model\",\n \"messages\",\n \"input\",\n \"instructions\",\n \"tools\",\n \"stream\",\n \"stream_options\",\n \"previous_response_id\",\n \"conversation\",\n \"store\",\n \"include\",\n \"functions\",\n \"function_call\",\n \"prompt\",\n \"background\",\n]);\n\nexport function mergeProviderBody<T extends object>(\n built: T,\n options: ModelCallOptions | undefined,\n): T {\n const provider = options?.providerOptions?.openai as OpenAICallOptions | undefined;\n const body = provider?.body ?? {};\n const reserved = Object.keys(body).filter((key) => RESERVED_FIELDS.has(key));\n if (reserved.length > 0) {\n throw new InvalidRequestError(\n `providerOptions.openai.body cannot set ${reserved.join(\", \")}: use the call's messages, tools and model options.`,\n { context: { fields: reserved } },\n );\n }\n const defaults = built as Record<string, unknown>;\n const overrides = Object.fromEntries(\n Object.entries(body).map(([key, value]) => {\n const previous = defaults[key];\n if (!isPlainObject(previous) || !isPlainObject(value)) return [key, value];\n // A different discriminator selects a whole SDK variant. Keeping fields\n // from the previous variant can make an otherwise valid override invalid.\n if (\n typeof previous.type === \"string\" &&\n typeof value.type === \"string\" &&\n previous.type !== value.type\n )\n return [key, value];\n return [key, { ...previous, ...value }];\n }),\n );\n return { ...built, ...overrides };\n}\n\n/** Merge only plain objects; arrays, null and provider scalar values replace the field. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"],"mappings":";;;AAKA,MAAM,kBAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,kBACd,OACA,SACG;CAEH,MAAM,QADW,SAAS,iBAAiB,OACtB,EAAE,QAAQ,CAAC;CAChC,MAAM,WAAW,OAAO,KAAK,IAAI,CAAC,CAAC,QAAQ,QAAQ,gBAAgB,IAAI,GAAG,CAAC;CAC3E,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,oBACR,0CAA0C,SAAS,KAAK,IAAI,EAAE,sDAC9D,EAAE,SAAS,EAAE,QAAQ,SAAS,EAAE,CAClC;CAEF,MAAM,WAAW;CACjB,MAAM,YAAY,OAAO,YACvB,OAAO,QAAQ,IAAI,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW;EACzC,MAAM,WAAW,SAAS;EAC1B,IAAI,CAAC,cAAc,QAAQ,KAAK,CAAC,cAAc,KAAK,GAAG,OAAO,CAAC,KAAK,KAAK;EAGzE,IACE,OAAO,SAAS,SAAS,YACzB,OAAO,MAAM,SAAS,YACtB,SAAS,SAAS,MAAM,MAExB,OAAO,CAAC,KAAK,KAAK;EACpB,OAAO,CAAC,KAAK;GAAE,GAAG;GAAU,GAAG;EAAM,CAAC;CACxC,CAAC,CACH;CACA,OAAO;EAAE,GAAG;EAAO,GAAG;CAAU;AAClC;;AAGA,SAAS,cAAc,OAAkD;CACvE,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD"}
|
package/esm/responses-model.mjs
CHANGED
|
@@ -4,18 +4,32 @@ import { mapResponsesFinishReason, toResponseFailure } from "./utils/map-respons
|
|
|
4
4
|
import { buildPromptCacheParams } from "./utils/prompt-cache-params.mjs";
|
|
5
5
|
import { toOpenAIReasoningEffort } from "./utils/reasoning-effort.mjs";
|
|
6
6
|
import { inferStructuredOutput, planStructuredOutput } from "./utils/structured-output.mjs";
|
|
7
|
-
import { attachReasoningReplay } from "./utils/reasoning-replay.mjs";
|
|
7
|
+
import { attachReasoningReplay, pickTurnReasoning } from "./utils/reasoning-replay.mjs";
|
|
8
8
|
import { toResponsesInput } from "./utils/to-responses-input.mjs";
|
|
9
9
|
import { toResponsesToolChoice, toResponsesTools } from "./utils/to-responses-tools.mjs";
|
|
10
10
|
import "./utils/index.mjs";
|
|
11
|
+
import { mergeProviderBody } from "./provider-options.mjs";
|
|
11
12
|
import { inferReasoningCapability } from "./known-reasoning-models.mjs";
|
|
12
13
|
import { inferVisionCapability } from "./known-vision-models.mjs";
|
|
13
|
-
import { InvalidRequestError, ProviderError, safeJsonParse } from "@warlock.js/ai";
|
|
14
|
+
import { InvalidRequestError, ProviderError, resolveStreamChunks, safeJsonParse, selectProviderTools } from "@warlock.js/ai";
|
|
14
15
|
import { log } from "@warlock.js/logger";
|
|
15
16
|
|
|
16
|
-
//#region
|
|
17
|
+
//#region ../../packages/ai-openai/src/responses-model.ts
|
|
17
18
|
const LOG_MODULE = "ai.openai";
|
|
18
19
|
/**
|
|
20
|
+
* Responses output item types of built-in tools the CALLER must execute
|
|
21
|
+
* (installed SDK `ResponseOutputItem` union). The adapter maps only
|
|
22
|
+
* `function_call` to a neutral tool call, so these fail closed.
|
|
23
|
+
*/
|
|
24
|
+
const CLIENT_RUN_ITEM_TYPES = new Set([
|
|
25
|
+
"computer_call",
|
|
26
|
+
"custom_tool_call",
|
|
27
|
+
"local_shell_call",
|
|
28
|
+
"shell_call",
|
|
29
|
+
"apply_patch_call",
|
|
30
|
+
"mcp_approval_request"
|
|
31
|
+
]);
|
|
32
|
+
/**
|
|
19
33
|
* OpenAI Responses API implementation of `ModelContract` (`api: "responses"`).
|
|
20
34
|
*
|
|
21
35
|
* **Role.** A sibling of `OpenAIModel` that speaks `POST /v1/responses`
|
|
@@ -42,7 +56,16 @@ const LOG_MODULE = "ai.openai";
|
|
|
42
56
|
*
|
|
43
57
|
* **Streaming.** `stream()` uses `responses.create({ stream: true })` and yields
|
|
44
58
|
* the same chunk sequence as the Chat path: text `delta`s, then the
|
|
45
|
-
* `tool-call`s, then one `done`.
|
|
59
|
+
* `tool-call`s, then one `done`. With `streamChunks` it also yields
|
|
60
|
+
* `reasoning` (reasoning summary / reasoning text deltas) and `tool-args`
|
|
61
|
+
* (`response.function_call_arguments.delta`).
|
|
62
|
+
*
|
|
63
|
+
* **Provider-defined tools.** `ai.providerTool({ provider: "openai" })`
|
|
64
|
+
* definitions are appended to `tools` verbatim. Hosted tools run inside the
|
|
65
|
+
* response; their output items (`web_search_call`, …) are not replayed
|
|
66
|
+
* (with `store: false` the next turn only needs the answer text), and a
|
|
67
|
+
* reasoning item that led into one is not replayed either (see
|
|
68
|
+
* `pickTurnReasoning`).
|
|
46
69
|
*/
|
|
47
70
|
var OpenAIResponsesModel = class {
|
|
48
71
|
constructor(client, config, provider = "openai") {
|
|
@@ -105,6 +128,26 @@ var OpenAIResponsesModel = class {
|
|
|
105
128
|
...toolCalls ? { toolCalls } : {}
|
|
106
129
|
};
|
|
107
130
|
}
|
|
131
|
+
/** Count native Responses input tokens using the same converted input and tools. */
|
|
132
|
+
async countTokens(messages, options) {
|
|
133
|
+
const request = this.buildRequest(messages, options);
|
|
134
|
+
const body = {
|
|
135
|
+
model: request.model,
|
|
136
|
+
input: request.input,
|
|
137
|
+
instructions: request.instructions,
|
|
138
|
+
tools: request.tools,
|
|
139
|
+
tool_choice: request.tool_choice,
|
|
140
|
+
reasoning: request.reasoning,
|
|
141
|
+
text: request.text,
|
|
142
|
+
parallel_tool_calls: request.parallel_tool_calls,
|
|
143
|
+
truncation: request.truncation ?? void 0
|
|
144
|
+
};
|
|
145
|
+
try {
|
|
146
|
+
return (await this.client.responses.inputTokens.count(body, options?.signal ? { signal: options.signal } : void 0)).input_tokens;
|
|
147
|
+
} catch (thrown) {
|
|
148
|
+
throw this.logAndWrap(thrown);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
108
151
|
/**
|
|
109
152
|
* Incremental streaming completion via `responses.create({ stream: true })`
|
|
110
153
|
* (the SDK's `Stream<ResponseStreamEvent>`, `responses.d.ts:55`). Yields the
|
|
@@ -139,7 +182,9 @@ var OpenAIResponsesModel = class {
|
|
|
139
182
|
throw this.logAndWrap(thrown);
|
|
140
183
|
}
|
|
141
184
|
const toolCalls = [];
|
|
142
|
-
const
|
|
185
|
+
const outputItems = [];
|
|
186
|
+
const want = resolveStreamChunks(options);
|
|
187
|
+
const streamingCalls = /* @__PURE__ */ new Map();
|
|
143
188
|
let terminal;
|
|
144
189
|
try {
|
|
145
190
|
for await (const event of events) {
|
|
@@ -150,10 +195,36 @@ var OpenAIResponsesModel = class {
|
|
|
150
195
|
};
|
|
151
196
|
continue;
|
|
152
197
|
}
|
|
198
|
+
if (event.type === "response.reasoning_summary_text.delta" || event.type === "response.reasoning_text.delta") {
|
|
199
|
+
if (want.reasoning && event.delta) yield {
|
|
200
|
+
type: "reasoning",
|
|
201
|
+
delta: event.delta
|
|
202
|
+
};
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (event.type === "response.output_item.added") {
|
|
206
|
+
const { item } = event;
|
|
207
|
+
if (item.type === "function_call" && item.id) streamingCalls.set(item.id, {
|
|
208
|
+
callId: item.call_id,
|
|
209
|
+
name: item.name
|
|
210
|
+
});
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
if (event.type === "response.function_call_arguments.delta") {
|
|
214
|
+
const call = streamingCalls.get(event.item_id);
|
|
215
|
+
if (want.toolArgs && call && event.delta) yield {
|
|
216
|
+
type: "tool-args",
|
|
217
|
+
callId: call.callId,
|
|
218
|
+
name: call.name,
|
|
219
|
+
delta: event.delta
|
|
220
|
+
};
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
153
223
|
if (event.type === "response.output_item.done") {
|
|
154
224
|
const { item } = event;
|
|
155
|
-
|
|
156
|
-
|
|
225
|
+
this.assertServerRunItem(item);
|
|
226
|
+
outputItems.push(item);
|
|
227
|
+
if (item.type === "function_call" && item.status !== "incomplete") toolCalls.push(this.toToolCall(item));
|
|
157
228
|
continue;
|
|
158
229
|
}
|
|
159
230
|
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
@@ -174,7 +245,7 @@ var OpenAIResponsesModel = class {
|
|
|
174
245
|
} catch (thrown) {
|
|
175
246
|
throw this.logAndWrap(thrown);
|
|
176
247
|
}
|
|
177
|
-
for (const call of attachReasoningReplay(toolCalls, this.name,
|
|
248
|
+
for (const call of attachReasoningReplay(toolCalls, this.name, pickTurnReasoning(outputItems))) yield {
|
|
178
249
|
type: "tool-call",
|
|
179
250
|
id: call.id,
|
|
180
251
|
name: call.name,
|
|
@@ -212,11 +283,11 @@ var OpenAIResponsesModel = class {
|
|
|
212
283
|
*/
|
|
213
284
|
buildRequest(messages, options) {
|
|
214
285
|
const { instructions, input } = toResponsesInput(messages, this.name);
|
|
215
|
-
const tools =
|
|
286
|
+
const tools = this.buildTools(options);
|
|
216
287
|
const toolChoice = tools ? toResponsesToolChoice(options?.toolChoice) : void 0;
|
|
217
288
|
const maxTokens = options?.maxTokens ?? this.config.maxTokens;
|
|
218
289
|
const temperature = options?.temperature ?? this.config.temperature;
|
|
219
|
-
return {
|
|
290
|
+
return mergeProviderBody({
|
|
220
291
|
model: this.name,
|
|
221
292
|
...instructions !== void 0 ? { instructions } : {},
|
|
222
293
|
input,
|
|
@@ -229,7 +300,24 @@ var OpenAIResponsesModel = class {
|
|
|
229
300
|
...this.buildTextFormat(options?.responseSchema),
|
|
230
301
|
...this.buildReasoningParams(options?.reasoning),
|
|
231
302
|
...buildPromptCacheParams(this.provider, this.config)
|
|
232
|
-
};
|
|
303
|
+
}, options);
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* The request `tools`: function tools (flat, `strict: false`), then the
|
|
307
|
+
* `ai.providerTool({ provider: "openai" })` definitions verbatim — the
|
|
308
|
+
* Responses built-in tools (`web_search`, `file_search`,
|
|
309
|
+
* `code_interpreter`, `image_generation`, `mcp`, …). Other providers'
|
|
310
|
+
* definitions are skipped with a warning. `undefined` when there are none.
|
|
311
|
+
*/
|
|
312
|
+
buildTools(options) {
|
|
313
|
+
const { tools, definitions } = selectProviderTools(options, {
|
|
314
|
+
accepts: [this.provider],
|
|
315
|
+
module: LOG_MODULE,
|
|
316
|
+
model: this.name,
|
|
317
|
+
logger: this.logger
|
|
318
|
+
});
|
|
319
|
+
const mapped = [...toResponsesTools(tools) ?? [], ...definitions];
|
|
320
|
+
return mapped.length > 0 ? mapped : void 0;
|
|
233
321
|
}
|
|
234
322
|
/**
|
|
235
323
|
* Structured output on Responses lives in `text.format`, and `name` /
|
|
@@ -266,12 +354,8 @@ var OpenAIResponsesModel = class {
|
|
|
266
354
|
readOutput(output) {
|
|
267
355
|
let content = "";
|
|
268
356
|
const toolCalls = [];
|
|
269
|
-
const reasoningItems = [];
|
|
270
357
|
for (const item of output) {
|
|
271
|
-
|
|
272
|
-
reasoningItems.push(item);
|
|
273
|
-
continue;
|
|
274
|
-
}
|
|
358
|
+
this.assertServerRunItem(item);
|
|
275
359
|
if (item.type === "message") {
|
|
276
360
|
for (const part of item.content) content += part.type === "refusal" ? part.refusal : part.text;
|
|
277
361
|
continue;
|
|
@@ -280,9 +364,24 @@ var OpenAIResponsesModel = class {
|
|
|
280
364
|
}
|
|
281
365
|
return {
|
|
282
366
|
content,
|
|
283
|
-
toolCalls: toolCalls.length > 0 ? attachReasoningReplay(toolCalls, this.name,
|
|
367
|
+
toolCalls: toolCalls.length > 0 ? attachReasoningReplay(toolCalls, this.name, pickTurnReasoning(output)) : void 0
|
|
284
368
|
};
|
|
285
369
|
}
|
|
370
|
+
/**
|
|
371
|
+
* Fail closed on a built-in tool call that YOUR code would have to run
|
|
372
|
+
* (`shell_call`, `apply_patch_call`, `computer_call`, …, from a
|
|
373
|
+
* provider-defined client tool). These items have their own output item
|
|
374
|
+
* types that this adapter does not map, so the turn would otherwise end
|
|
375
|
+
* silently with the call dropped. Hosted (server-run) tool items pass.
|
|
376
|
+
*/
|
|
377
|
+
assertServerRunItem(item) {
|
|
378
|
+
if (!CLIENT_RUN_ITEM_TYPES.has(item.type)) return;
|
|
379
|
+
throw new InvalidRequestError(`OpenAI returned a "${item.type}" item: that built-in tool is executed by the caller, which the Responses adapter does not support. Use OpenAI's server-run built-in tools (web_search, file_search, code_interpreter, image_generation, mcp without approval) with ai.providerTool(), or a function tool from ai.tool().`, { context: {
|
|
380
|
+
provider: this.provider,
|
|
381
|
+
model: this.name,
|
|
382
|
+
itemType: item.type
|
|
383
|
+
} });
|
|
384
|
+
}
|
|
286
385
|
/** One completed `function_call` item as a neutral tool call (`call_id` -> `id`). */
|
|
287
386
|
toToolCall(item) {
|
|
288
387
|
return {
|
|
@@ -311,7 +410,7 @@ var OpenAIResponsesModel = class {
|
|
|
311
410
|
cachedTokens: raw.input_tokens_details?.cached_tokens,
|
|
312
411
|
cacheWriteTokens: raw.input_tokens_details?.cache_write_tokens,
|
|
313
412
|
reasoningTokens: raw.output_tokens_details?.reasoning_tokens
|
|
314
|
-
});
|
|
413
|
+
}, this.pricing);
|
|
315
414
|
}
|
|
316
415
|
/** Wrap (idempotently), log and return a failure for the caller to throw. */
|
|
317
416
|
logAndWrap(thrown) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responses-model.mjs","names":[],"sources":["../../../../../../ai-openai/src/responses-model.ts"],"sourcesContent":["import {\n InvalidRequestError,\n ProviderError,\n safeJsonParse,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type OpenAI from \"openai\";\nimport type { OpenAIModelConfig } from \"./config.type\";\nimport { inferReasoningCapability } from \"./known-reasoning-models\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n attachReasoningReplay,\n buildPromptCacheParams,\n buildUsage,\n inferStructuredOutput,\n mapResponsesFinishReason,\n planStructuredOutput,\n toOpenAIReasoningEffort,\n toResponseFailure,\n toResponsesInput,\n toResponsesToolChoice,\n toResponsesTools,\n wrapOpenAIError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\n/**\n * OpenAI Responses API implementation of `ModelContract` (`api: \"responses\"`).\n *\n * **Role.** A sibling of `OpenAIModel` that speaks `POST /v1/responses`\n * instead of Chat Completions. Its point is letting a tool-using agent run a\n * reasoning model with reasoning ON: the Chat path has to force\n * `reasoning_effort: \"none\"` whenever tools are attached, Responses does not.\n *\n * **Why a separate class.** Only `OpenAISDK.model()` constructs it, and only\n * for the direct `\"openai\"` provider. The wrapper packages (deepseek, groq,\n * xai, mistral) build `OpenAIModel` and cannot reach this class, so an\n * endpoint that does not implement `/v1/responses` is never sent there. The\n * constructor re-checks the provider label as a second lock.\n *\n * **Stateless.** Every request sends `store: false`; nothing is kept on the\n * server and no `previous_response_id` is used. Full history is re-sent each\n * call, exactly like the Chat path.\n *\n * **Reasoning replay.** Every request asks for\n * `include: [\"reasoning.encrypted_content\"]`. The `reasoning` items of a\n * tool-calling turn are stored on the FIRST tool call as\n * `providerMetadata.openaiResponses = { model, reasoningItems }` and sent back\n * before that turn's `function_call` items on the next request (only when the\n * stored model equals the current one). Text-only turns are not replayed.\n *\n * **Streaming.** `stream()` uses `responses.create({ stream: true })` and yields\n * the same chunk sequence as the Chat path: text `delta`s, then the\n * `tool-call`s, then one `done`.\n */\nexport class OpenAIResponsesModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly client: OpenAI;\n private readonly config: OpenAIModelConfig;\n private readonly logger: Logger = log;\n\n public constructor(client: OpenAI, config: OpenAIModelConfig, provider: string = \"openai\") {\n if (provider !== \"openai\") {\n throw new InvalidRequestError(\n `api: \"responses\" is supported only on the direct \"openai\" provider; got provider \"${provider}\".`,\n { context: { provider, model: config.name, api: \"responses\" } },\n );\n }\n\n this.client = client;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? inferStructuredOutput(config.responseFormat),\n vision: config.vision ?? inferVisionCapability(config.name),\n reasoning: config.reasoning ?? inferReasoningCapability(config.name),\n // Read-side cache accounting (`cachedTokens`, `cacheWriteTokens`) works\n // and `prompt_cache_key` is forwarded. Explicit write breakpoints are not\n // mapped onto Responses yet, so a `cacheControl.breakpoints` hint is\n // ignored rather than rejected.\n promptCaching: true,\n // PDF and audio input are off under Responses in this adapter: the\n // `input_file` / `input_audio` field-level mapping is unverified. The\n // `pdf` / `audio` config flags are deliberately NOT honoured here.\n pdf: false,\n audio: false,\n };\n }\n\n /**\n * Single-shot completion against `client.responses.create`. Sends the full\n * history as Responses `input` items, walks `response.output`, and reshapes\n * it into a vendor-neutral `ModelResponse`. Per-call `options` override the\n * instance defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting call to responses.create\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let response: OpenAI.Responses.Response;\n\n try {\n response = await this.client.responses.create(\n this.buildRequest(messages, options),\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n if (response.status === \"failed\") {\n throw this.logAndWrap(toResponseFailure(response, this.name));\n }\n\n const output = Array.isArray(response.output) ? response.output : [];\n const { content, toolCalls } = this.readOutput(output);\n const finishReason = mapResponsesFinishReason({\n status: response.status,\n incomplete_details: response.incomplete_details,\n hasToolCalls: toolCalls !== undefined,\n });\n const usage = this.extractUsage(response.usage);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to responses.create succeeded\", {\n finishReason,\n usage,\n });\n\n return { content, finishReason, usage, ...(toolCalls ? { toolCalls } : {}) };\n }\n\n /**\n * Incremental streaming completion via `responses.create({ stream: true })`\n * (the SDK's `Stream<ResponseStreamEvent>`, `responses.d.ts:55`). Yields the\n * same neutral `ModelStreamChunk` sequence as the Chat path:\n *\n * - `response.output_text.delta` / `response.refusal.delta` -> `delta`.\n * - `response.output_item.done` with a completed `function_call` item ->\n * buffered; `reasoning` items are captured for replay. The `done` copy is\n * used because the `added` copy may be incomplete (`responses.d.ts:5711`).\n * - After the loop: the buffered `tool-call`s (the first carries the\n * replay metadata), then a single `done` with the finish reason and usage\n * from `response.completed` / `response.incomplete`.\n * - `response.failed` and `error` events throw a typed `AIError`; a stream\n * that ends with no terminal event throws `ProviderError`.\n * - Abort goes through the request `signal`; the SDK rejects the read and\n * the error is wrapped like any other.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting streaming call to responses.create\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let events: AsyncIterable<OpenAI.Responses.ResponseStreamEvent>;\n\n try {\n events = await this.client.responses.create(\n { ...this.buildRequest(messages, options), stream: true },\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const toolCalls: ModelToolCallRequest[] = [];\n const reasoningItems: OpenAI.Responses.ResponseReasoningItem[] = [];\n let terminal: OpenAI.Responses.Response | undefined;\n\n try {\n for await (const event of events) {\n if (event.type === \"response.output_text.delta\" || event.type === \"response.refusal.delta\") {\n if (event.delta) {\n yield { type: \"delta\", content: event.delta };\n }\n\n continue;\n }\n\n if (event.type === \"response.output_item.done\") {\n const { item } = event;\n\n if (item.type === \"reasoning\") {\n reasoningItems.push(item);\n } else if (item.type === \"function_call\" && item.status !== \"incomplete\") {\n toolCalls.push(this.toToolCall(item));\n }\n\n continue;\n }\n\n if (event.type === \"response.completed\" || event.type === \"response.incomplete\") {\n terminal = event.response;\n continue;\n }\n\n if (event.type === \"response.failed\") {\n throw toResponseFailure(event.response, this.name);\n }\n\n if (event.type === \"error\") {\n throw wrapOpenAIError({ code: event.code, message: event.message, param: event.param });\n }\n }\n\n if (terminal === undefined) {\n throw new ProviderError(\"OpenAI Responses stream ended before response.completed.\", {\n context: { provider: this.provider, model: this.name },\n });\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n for (const call of attachReasoningReplay(toolCalls, this.name, reasoningItems)) {\n yield {\n type: \"tool-call\",\n id: call.id,\n name: call.name,\n input: call.input,\n ...(call.providerMetadata ? { providerMetadata: call.providerMetadata } : {}),\n };\n }\n\n const finishReason = mapResponsesFinishReason({\n status: terminal.status,\n incomplete_details: terminal.incomplete_details,\n hasToolCalls: toolCalls.length > 0,\n });\n const usage = this.extractUsage(terminal.usage);\n\n this.logger.debug(LOG_MODULE, \"response\", \"Streaming call to responses.create succeeded\", {\n finishReason,\n usage,\n });\n\n yield { type: \"done\", finishReason, usage };\n }\n\n /**\n * Assemble the `responses.create` body.\n *\n * - System prompt -> `instructions`; history -> `input` items.\n * - `store: false` always (the API default is `true` when omitted), plus\n * `include: [\"reasoning.encrypted_content\"]` for stateless reasoning replay.\n * - `max_output_tokens` caps reasoning and visible output together.\n * - `temperature` only for non-reasoning models (same rule as Chat).\n * - `tools` flat with `strict: false`; `tool_choice` only with tools.\n * - `reasoning.effort` only when the caller gave one, through the same\n * clamp table as Chat. With no explicit effort the provider default\n * applies EVEN with tools attached - that is the point of this API.\n */\n private buildRequest(\n messages: Message[],\n options: ModelCallOptions | undefined,\n ): OpenAI.Responses.ResponseCreateParamsNonStreaming {\n const { instructions, input } = toResponsesInput(messages, this.name);\n const tools = toResponsesTools(options?.tools);\n const toolChoice = tools ? toResponsesToolChoice(options?.toolChoice) : undefined;\n const maxTokens = options?.maxTokens ?? this.config.maxTokens;\n const temperature = options?.temperature ?? this.config.temperature;\n\n return {\n model: this.name,\n ...(instructions !== undefined ? { instructions } : {}),\n input,\n store: false,\n // Stateless replay: ask for the encrypted reasoning blobs so they can be\n // sent back on the next tool turn (decision 3).\n include: [\"reasoning.encrypted_content\"],\n ...(maxTokens !== undefined ? { max_output_tokens: maxTokens } : {}),\n ...(!this.capabilities.reasoning && temperature !== undefined ? { temperature } : {}),\n ...(tools ? { tools } : {}),\n ...(toolChoice !== undefined ? { tool_choice: toolChoice } : {}),\n ...this.buildTextFormat(options?.responseSchema),\n ...this.buildReasoningParams(options?.reasoning),\n ...buildPromptCacheParams(this.provider, this.config),\n };\n }\n\n /**\n * Structured output on Responses lives in `text.format`, and `name` /\n * `schema` / `strict` sit directly on the format object (Chat nests them\n * under `json_schema`). The strict-or-downgrade decision is the shared\n * `planStructuredOutput`.\n */\n private buildTextFormat(responseSchema: Record<string, unknown> | undefined): {\n text?: OpenAI.Responses.ResponseTextConfig;\n } {\n const plan = planStructuredOutput(responseSchema, this.config.responseFormat);\n\n if (plan.mode === \"json_schema\") {\n return {\n text: { format: { type: \"json_schema\", name: \"response\", schema: plan.schema, strict: true } },\n };\n }\n\n if (plan.mode === \"json_object\") {\n return { text: { format: { type: \"json_object\" } } };\n }\n\n return {};\n }\n\n /** `reasoning.effort` for reasoning-capable models, only when the caller set one. */\n private buildReasoningParams(reasoning: ModelCallOptions[\"reasoning\"]): {\n reasoning?: { effort: ReturnType<typeof toOpenAIReasoningEffort> };\n } {\n if (!this.capabilities.reasoning || !reasoning?.effort) {\n return {};\n }\n\n return { reasoning: { effort: toOpenAIReasoningEffort(reasoning.effort) } };\n }\n\n /**\n * Walk `response.output`: `message` items contribute their `output_text`\n * text and any `refusal` text (surfaced as ordinary content, decision 5);\n * each completed `function_call` item becomes one tool call with\n * `id = call_id`. `reasoning` items carry no visible content and are\n * not content. A `function_call` the API marked `incomplete` (truncated\n * arguments) is skipped rather than dispatched with empty input.\n * `reasoning` items are captured and attached to the first tool call for\n * replay (see `attachReasoningReplay`).\n */\n private readOutput(output: OpenAI.Responses.ResponseOutputItem[]): {\n content: string;\n toolCalls: ModelToolCallRequest[] | undefined;\n } {\n let content = \"\";\n const toolCalls: ModelToolCallRequest[] = [];\n const reasoningItems: OpenAI.Responses.ResponseReasoningItem[] = [];\n\n for (const item of output) {\n if (item.type === \"reasoning\") {\n reasoningItems.push(item);\n continue;\n }\n\n if (item.type === \"message\") {\n for (const part of item.content) {\n content += part.type === \"refusal\" ? part.refusal : part.text;\n }\n\n continue;\n }\n\n if (item.type === \"function_call\" && item.status !== \"incomplete\") {\n toolCalls.push(this.toToolCall(item));\n }\n }\n\n return {\n content,\n toolCalls:\n toolCalls.length > 0\n ? attachReasoningReplay(toolCalls, this.name, reasoningItems)\n : undefined,\n };\n }\n\n /** One completed `function_call` item as a neutral tool call (`call_id` -> `id`). */\n private toToolCall(item: OpenAI.Responses.ResponseFunctionToolCall): ModelToolCallRequest {\n return {\n id: item.call_id,\n name: item.name,\n input: safeJsonParse<Record<string, unknown>>(item.arguments, {}),\n };\n }\n\n /**\n * Normalize `usage` (absent on some partials) into the neutral `Usage`.\n * `input_tokens_details.cached_tokens` -> `cachedTokens`,\n * `cache_write_tokens` -> `cacheWriteTokens`,\n * `output_tokens_details.reasoning_tokens` -> `reasoningTokens`. The\n * detail blocks are typed non-optional but read defensively.\n */\n private extractUsage(raw: OpenAI.Responses.ResponseUsage | undefined): Usage {\n if (!raw) {\n return { input: 0, output: 0, total: 0 };\n }\n\n return buildUsage({\n input: raw.input_tokens,\n output: raw.output_tokens,\n total: raw.total_tokens,\n cachedTokens: raw.input_tokens_details?.cached_tokens,\n cacheWriteTokens: raw.input_tokens_details?.cache_write_tokens,\n reasoningTokens: raw.output_tokens_details?.reasoning_tokens,\n });\n }\n\n /** Wrap (idempotently), log and return a failure for the caller to throw. */\n private logAndWrap(thrown: unknown): ReturnType<typeof wrapOpenAIError> {\n const wrapped = wrapOpenAIError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n return wrapped;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BnB,IAAa,uBAAb,MAA2D;CAUzD,AAAO,YAAY,QAAgB,QAA2B,WAAmB,UAAU;gBAFzD;EAGhC,IAAI,aA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K;GACX,OAAO,cAAuC,KAAK,WAAW,CAAC,CAAC;EAClE;CACF;;;;;;;;CASA,AAAQ,aAAa,KAAwD;EAC3E,IAAI,CAAC,KACH,OAAO;GAAE,OAAO;GAAG,QAAQ;GAAG,OAAO;EAAE;EAGzC,OAAO,WAAW;GAChB,OAAO,IAAI;GACX,QAAQ,IAAI;GACZ,OAAO,IAAI;GACX,cAAc,IAAI,sBAAsB;GACxC,kBAAkB,IAAI,sBAAsB;GAC5C,iBAAiB,IAAI,uBAAuB;EAC9C,CAAC;CACH;;CAGA,AAAQ,WAAW,QAAqD;EACtE,MAAM,UAAU,gBAAgB,MAAM;EAEtC,KAAK,OAAO,MAAM,YAAY,SAAS,QAAQ,SAAS;GACtD,MAAM,QAAQ;GACd,SAAS,QAAQ;EACnB,CAAC;EAED,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"responses-model.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/responses-model.ts"],"sourcesContent":["import {\n InvalidRequestError,\n ProviderError,\n resolveStreamChunks,\n safeJsonParse,\n selectProviderTools,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type OpenAI from \"openai\";\nimport { mergeProviderBody } from \"./provider-options\";\nimport type { OpenAIModelConfig } from \"./config.type\";\nimport { inferReasoningCapability } from \"./known-reasoning-models\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n attachReasoningReplay,\n buildPromptCacheParams,\n buildUsage,\n inferStructuredOutput,\n mapResponsesFinishReason,\n pickTurnReasoning,\n planStructuredOutput,\n toOpenAIReasoningEffort,\n toResponseFailure,\n toResponsesInput,\n toResponsesToolChoice,\n toResponsesTools,\n wrapOpenAIError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\n/**\n * Responses output item types of built-in tools the CALLER must execute\n * (installed SDK `ResponseOutputItem` union). The adapter maps only\n * `function_call` to a neutral tool call, so these fail closed.\n */\nconst CLIENT_RUN_ITEM_TYPES: ReadonlySet<string> = new Set([\n \"computer_call\",\n \"custom_tool_call\",\n \"local_shell_call\",\n \"shell_call\",\n \"apply_patch_call\",\n \"mcp_approval_request\",\n]);\n\n/**\n * OpenAI Responses API implementation of `ModelContract` (`api: \"responses\"`).\n *\n * **Role.** A sibling of `OpenAIModel` that speaks `POST /v1/responses`\n * instead of Chat Completions. Its point is letting a tool-using agent run a\n * reasoning model with reasoning ON: the Chat path has to force\n * `reasoning_effort: \"none\"` whenever tools are attached, Responses does not.\n *\n * **Why a separate class.** Only `OpenAISDK.model()` constructs it, and only\n * for the direct `\"openai\"` provider. The wrapper packages (deepseek, groq,\n * xai, mistral) build `OpenAIModel` and cannot reach this class, so an\n * endpoint that does not implement `/v1/responses` is never sent there. The\n * constructor re-checks the provider label as a second lock.\n *\n * **Stateless.** Every request sends `store: false`; nothing is kept on the\n * server and no `previous_response_id` is used. Full history is re-sent each\n * call, exactly like the Chat path.\n *\n * **Reasoning replay.** Every request asks for\n * `include: [\"reasoning.encrypted_content\"]`. The `reasoning` items of a\n * tool-calling turn are stored on the FIRST tool call as\n * `providerMetadata.openaiResponses = { model, reasoningItems }` and sent back\n * before that turn's `function_call` items on the next request (only when the\n * stored model equals the current one). Text-only turns are not replayed.\n *\n * **Streaming.** `stream()` uses `responses.create({ stream: true })` and yields\n * the same chunk sequence as the Chat path: text `delta`s, then the\n * `tool-call`s, then one `done`. With `streamChunks` it also yields\n * `reasoning` (reasoning summary / reasoning text deltas) and `tool-args`\n * (`response.function_call_arguments.delta`).\n *\n * **Provider-defined tools.** `ai.providerTool({ provider: \"openai\" })`\n * definitions are appended to `tools` verbatim. Hosted tools run inside the\n * response; their output items (`web_search_call`, …) are not replayed\n * (with `store: false` the next turn only needs the answer text), and a\n * reasoning item that led into one is not replayed either (see\n * `pickTurnReasoning`).\n */\nexport class OpenAIResponsesModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly client: OpenAI;\n private readonly config: OpenAIModelConfig;\n private readonly logger: Logger = log;\n\n public constructor(client: OpenAI, config: OpenAIModelConfig, provider: string = \"openai\") {\n if (provider !== \"openai\") {\n throw new InvalidRequestError(\n `api: \"responses\" is supported only on the direct \"openai\" provider; got provider \"${provider}\".`,\n { context: { provider, model: config.name, api: \"responses\" } },\n );\n }\n\n this.client = client;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? inferStructuredOutput(config.responseFormat),\n vision: config.vision ?? inferVisionCapability(config.name),\n reasoning: config.reasoning ?? inferReasoningCapability(config.name),\n // Read-side cache accounting (`cachedTokens`, `cacheWriteTokens`) works\n // and `prompt_cache_key` is forwarded. Explicit write breakpoints are not\n // mapped onto Responses yet, so a `cacheControl.breakpoints` hint is\n // ignored rather than rejected.\n promptCaching: true,\n // PDF and audio input are off under Responses in this adapter: the\n // `input_file` / `input_audio` field-level mapping is unverified. The\n // `pdf` / `audio` config flags are deliberately NOT honoured here.\n pdf: false,\n audio: false,\n };\n }\n\n /**\n * Single-shot completion against `client.responses.create`. Sends the full\n * history as Responses `input` items, walks `response.output`, and reshapes\n * it into a vendor-neutral `ModelResponse`. Per-call `options` override the\n * instance defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting call to responses.create\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let response: OpenAI.Responses.Response;\n\n try {\n response = await this.client.responses.create(\n this.buildRequest(messages, options),\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n if (response.status === \"failed\") {\n throw this.logAndWrap(toResponseFailure(response, this.name));\n }\n\n const output = Array.isArray(response.output) ? response.output : [];\n const { content, toolCalls } = this.readOutput(output);\n const finishReason = mapResponsesFinishReason({\n status: response.status,\n incomplete_details: response.incomplete_details,\n hasToolCalls: toolCalls !== undefined,\n });\n const usage = this.extractUsage(response.usage);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to responses.create succeeded\", {\n finishReason,\n usage,\n });\n\n return { content, finishReason, usage, ...(toolCalls ? { toolCalls } : {}) };\n }\n\n /** Count native Responses input tokens using the same converted input and tools. */\n public async countTokens(messages: Message[], options?: ModelCallOptions): Promise<number> {\n const request = this.buildRequest(messages, options);\n const body: OpenAI.Responses.InputTokenCountParams = {\n model: request.model,\n input: request.input,\n instructions: request.instructions,\n tools: request.tools,\n tool_choice: request.tool_choice,\n reasoning: request.reasoning,\n text: request.text,\n parallel_tool_calls: request.parallel_tool_calls,\n truncation: request.truncation ?? undefined,\n };\n try {\n const response = await this.client.responses.inputTokens.count(\n body,\n options?.signal ? { signal: options.signal } : undefined,\n );\n return response.input_tokens;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n }\n\n /**\n * Incremental streaming completion via `responses.create({ stream: true })`\n * (the SDK's `Stream<ResponseStreamEvent>`, `responses.d.ts:55`). Yields the\n * same neutral `ModelStreamChunk` sequence as the Chat path:\n *\n * - `response.output_text.delta` / `response.refusal.delta` -> `delta`.\n * - `response.output_item.done` with a completed `function_call` item ->\n * buffered; `reasoning` items are captured for replay. The `done` copy is\n * used because the `added` copy may be incomplete (`responses.d.ts:5711`).\n * - After the loop: the buffered `tool-call`s (the first carries the\n * replay metadata), then a single `done` with the finish reason and usage\n * from `response.completed` / `response.incomplete`.\n * - `response.failed` and `error` events throw a typed `AIError`; a stream\n * that ends with no terminal event throws `ProviderError`.\n * - Abort goes through the request `signal`; the SDK rejects the read and\n * the error is wrapped like any other.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting streaming call to responses.create\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let events: AsyncIterable<OpenAI.Responses.ResponseStreamEvent>;\n\n try {\n events = await this.client.responses.create(\n { ...this.buildRequest(messages, options), stream: true },\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const toolCalls: ModelToolCallRequest[] = [];\n const outputItems: OpenAI.Responses.ResponseOutputItem[] = [];\n const want = resolveStreamChunks(options);\n // `function_call_arguments.delta` names its item by `item_id` only; the\n // `call_id` and `name` come from that item's `output_item.added`.\n const streamingCalls = new Map<string, { callId: string; name: string }>();\n let terminal: OpenAI.Responses.Response | undefined;\n\n try {\n for await (const event of events) {\n if (\n event.type === \"response.output_text.delta\" ||\n event.type === \"response.refusal.delta\"\n ) {\n if (event.delta) {\n yield { type: \"delta\", content: event.delta };\n }\n\n continue;\n }\n\n if (\n event.type === \"response.reasoning_summary_text.delta\" ||\n event.type === \"response.reasoning_text.delta\"\n ) {\n if (want.reasoning && event.delta) {\n yield { type: \"reasoning\", delta: event.delta };\n }\n\n continue;\n }\n\n if (event.type === \"response.output_item.added\") {\n const { item } = event;\n\n if (item.type === \"function_call\" && item.id) {\n streamingCalls.set(item.id, { callId: item.call_id, name: item.name });\n }\n\n continue;\n }\n\n if (event.type === \"response.function_call_arguments.delta\") {\n const call = streamingCalls.get(event.item_id);\n\n if (want.toolArgs && call && event.delta) {\n yield { type: \"tool-args\", callId: call.callId, name: call.name, delta: event.delta };\n }\n\n continue;\n }\n\n if (event.type === \"response.output_item.done\") {\n const { item } = event;\n\n this.assertServerRunItem(item);\n outputItems.push(item);\n\n if (item.type === \"function_call\" && item.status !== \"incomplete\") {\n toolCalls.push(this.toToolCall(item));\n }\n\n continue;\n }\n\n if (event.type === \"response.completed\" || event.type === \"response.incomplete\") {\n terminal = event.response;\n continue;\n }\n\n if (event.type === \"response.failed\") {\n throw toResponseFailure(event.response, this.name);\n }\n\n if (event.type === \"error\") {\n throw wrapOpenAIError({ code: event.code, message: event.message, param: event.param });\n }\n }\n\n if (terminal === undefined) {\n throw new ProviderError(\"OpenAI Responses stream ended before response.completed.\", {\n context: { provider: this.provider, model: this.name },\n });\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n for (const call of attachReasoningReplay(\n toolCalls,\n this.name,\n pickTurnReasoning(outputItems),\n )) {\n yield {\n type: \"tool-call\",\n id: call.id,\n name: call.name,\n input: call.input,\n ...(call.providerMetadata ? { providerMetadata: call.providerMetadata } : {}),\n };\n }\n\n const finishReason = mapResponsesFinishReason({\n status: terminal.status,\n incomplete_details: terminal.incomplete_details,\n hasToolCalls: toolCalls.length > 0,\n });\n const usage = this.extractUsage(terminal.usage);\n\n this.logger.debug(LOG_MODULE, \"response\", \"Streaming call to responses.create succeeded\", {\n finishReason,\n usage,\n });\n\n yield { type: \"done\", finishReason, usage };\n }\n\n /**\n * Assemble the `responses.create` body.\n *\n * - System prompt -> `instructions`; history -> `input` items.\n * - `store: false` always (the API default is `true` when omitted), plus\n * `include: [\"reasoning.encrypted_content\"]` for stateless reasoning replay.\n * - `max_output_tokens` caps reasoning and visible output together.\n * - `temperature` only for non-reasoning models (same rule as Chat).\n * - `tools` flat with `strict: false`; `tool_choice` only with tools.\n * - `reasoning.effort` only when the caller gave one, through the same\n * clamp table as Chat. With no explicit effort the provider default\n * applies EVEN with tools attached - that is the point of this API.\n */\n private buildRequest(\n messages: Message[],\n options: ModelCallOptions | undefined,\n ): OpenAI.Responses.ResponseCreateParamsNonStreaming {\n const { instructions, input } = toResponsesInput(messages, this.name);\n const tools = this.buildTools(options);\n const toolChoice = tools ? toResponsesToolChoice(options?.toolChoice) : undefined;\n const maxTokens = options?.maxTokens ?? this.config.maxTokens;\n const temperature = options?.temperature ?? this.config.temperature;\n\n return mergeProviderBody<OpenAI.Responses.ResponseCreateParamsNonStreaming>(\n {\n model: this.name,\n ...(instructions !== undefined ? { instructions } : {}),\n input,\n store: false,\n // Stateless replay: ask for the encrypted reasoning blobs so they can be\n // sent back on the next tool turn (decision 3).\n include: [\"reasoning.encrypted_content\"],\n ...(maxTokens !== undefined ? { max_output_tokens: maxTokens } : {}),\n ...(!this.capabilities.reasoning && temperature !== undefined ? { temperature } : {}),\n ...(tools ? { tools } : {}),\n ...(toolChoice !== undefined ? { tool_choice: toolChoice } : {}),\n ...this.buildTextFormat(options?.responseSchema),\n ...this.buildReasoningParams(options?.reasoning),\n ...buildPromptCacheParams(this.provider, this.config),\n },\n options,\n );\n }\n\n /**\n * The request `tools`: function tools (flat, `strict: false`), then the\n * `ai.providerTool({ provider: \"openai\" })` definitions verbatim — the\n * Responses built-in tools (`web_search`, `file_search`,\n * `code_interpreter`, `image_generation`, `mcp`, …). Other providers'\n * definitions are skipped with a warning. `undefined` when there are none.\n */\n private buildTools(options: ModelCallOptions | undefined): OpenAI.Responses.Tool[] | undefined {\n const { tools, definitions } = selectProviderTools(options, {\n accepts: [this.provider],\n module: LOG_MODULE,\n model: this.name,\n logger: this.logger,\n });\n const mapped: OpenAI.Responses.Tool[] = [\n ...(toResponsesTools(tools) ?? []),\n ...(definitions as unknown as OpenAI.Responses.Tool[]),\n ];\n\n return mapped.length > 0 ? mapped : undefined;\n }\n\n /**\n * Structured output on Responses lives in `text.format`, and `name` /\n * `schema` / `strict` sit directly on the format object (Chat nests them\n * under `json_schema`). The strict-or-downgrade decision is the shared\n * `planStructuredOutput`.\n */\n private buildTextFormat(responseSchema: Record<string, unknown> | undefined): {\n text?: OpenAI.Responses.ResponseTextConfig;\n } {\n const plan = planStructuredOutput(responseSchema, this.config.responseFormat);\n\n if (plan.mode === \"json_schema\") {\n return {\n text: {\n format: { type: \"json_schema\", name: \"response\", schema: plan.schema, strict: true },\n },\n };\n }\n\n if (plan.mode === \"json_object\") {\n return { text: { format: { type: \"json_object\" } } };\n }\n\n return {};\n }\n\n /** `reasoning.effort` for reasoning-capable models, only when the caller set one. */\n private buildReasoningParams(reasoning: ModelCallOptions[\"reasoning\"]): {\n reasoning?: { effort: ReturnType<typeof toOpenAIReasoningEffort> };\n } {\n if (!this.capabilities.reasoning || !reasoning?.effort) {\n return {};\n }\n\n return { reasoning: { effort: toOpenAIReasoningEffort(reasoning.effort) } };\n }\n\n /**\n * Walk `response.output`: `message` items contribute their `output_text`\n * text and any `refusal` text (surfaced as ordinary content, decision 5);\n * each completed `function_call` item becomes one tool call with\n * `id = call_id`. `reasoning` items carry no visible content and are\n * not content. A `function_call` the API marked `incomplete` (truncated\n * arguments) is skipped rather than dispatched with empty input.\n * `reasoning` items are captured and attached to the first tool call for\n * replay (see `attachReasoningReplay`).\n */\n private readOutput(output: OpenAI.Responses.ResponseOutputItem[]): {\n content: string;\n toolCalls: ModelToolCallRequest[] | undefined;\n } {\n let content = \"\";\n const toolCalls: ModelToolCallRequest[] = [];\n\n for (const item of output) {\n this.assertServerRunItem(item);\n\n if (item.type === \"message\") {\n for (const part of item.content) {\n content += part.type === \"refusal\" ? part.refusal : part.text;\n }\n\n continue;\n }\n\n if (item.type === \"function_call\" && item.status !== \"incomplete\") {\n toolCalls.push(this.toToolCall(item));\n }\n }\n\n return {\n content,\n toolCalls:\n toolCalls.length > 0\n ? attachReasoningReplay(toolCalls, this.name, pickTurnReasoning(output))\n : undefined,\n };\n }\n\n /**\n * Fail closed on a built-in tool call that YOUR code would have to run\n * (`shell_call`, `apply_patch_call`, `computer_call`, …, from a\n * provider-defined client tool). These items have their own output item\n * types that this adapter does not map, so the turn would otherwise end\n * silently with the call dropped. Hosted (server-run) tool items pass.\n */\n private assertServerRunItem(item: { type: string }): void {\n if (!CLIENT_RUN_ITEM_TYPES.has(item.type)) {\n return;\n }\n\n throw new InvalidRequestError(\n `OpenAI returned a \"${item.type}\" item: that built-in tool is executed by the caller, ` +\n \"which the Responses adapter does not support. Use OpenAI's server-run built-in tools \" +\n \"(web_search, file_search, code_interpreter, image_generation, mcp without approval) \" +\n \"with ai.providerTool(), or a function tool from ai.tool().\",\n { context: { provider: this.provider, model: this.name, itemType: item.type } },\n );\n }\n\n /** One completed `function_call` item as a neutral tool call (`call_id` -> `id`). */\n private toToolCall(item: OpenAI.Responses.ResponseFunctionToolCall): ModelToolCallRequest {\n return {\n id: item.call_id,\n name: item.name,\n input: safeJsonParse<Record<string, unknown>>(item.arguments, {}),\n };\n }\n\n /**\n * Normalize `usage` (absent on some partials) into the neutral `Usage`.\n * `input_tokens_details.cached_tokens` -> `cachedTokens`,\n * `cache_write_tokens` -> `cacheWriteTokens`,\n * `output_tokens_details.reasoning_tokens` -> `reasoningTokens`. The\n * detail blocks are typed non-optional but read defensively.\n */\n private extractUsage(raw: OpenAI.Responses.ResponseUsage | undefined): Usage {\n if (!raw) {\n return { input: 0, output: 0, total: 0 };\n }\n\n return buildUsage(\n {\n input: raw.input_tokens,\n output: raw.output_tokens,\n total: raw.total_tokens,\n cachedTokens: raw.input_tokens_details?.cached_tokens,\n cacheWriteTokens: raw.input_tokens_details?.cache_write_tokens,\n reasoningTokens: raw.output_tokens_details?.reasoning_tokens,\n },\n this.pricing,\n );\n }\n\n /** Wrap (idempotently), log and return a failure for the caller to throw. */\n private logAndWrap(thrown: unknown): ReturnType<typeof wrapOpenAIError> {\n const wrapped = wrapOpenAIError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n return wrapped;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsCA,MAAM,aAAa;;;;;;AAOnB,MAAM,wBAA6C,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCD,IAAa,uBAAb,MAA2D;CAUzD,AAAO,YAAY,QAAgB,QAA2B,WAAmB,UAAU;gBAFzD;EAGhC,IAAI,aAAa,UACf,MAAM,IAAI,oBACR,qFAAqF,SAA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,oBAAoB,MAA8B;EACxD,IAAI,CAAC,sBAAsB,IAAI,KAAK,IAAI,GACtC;EAGF,MAAM,IAAI,oBACR,sBAAsB,KAAK,KAAK,4RAIhC,EAAE,SAAS;GAAE,UAAU,KAAK;GAAU,OAAO,KAAK;GAAM,UAAU,KAAK;EAAK,EAAE,CAChF;CACF;;CAGA,AAAQ,WAAW,MAAuE;EACxF,OAAO;GACL,IAAI,KAAK;GACT,MAAM,KAAK;GACX,OAAO,cAAuC,KAAK,WAAW,CAAC,CAAC;EAClE;CACF;;;;;;;;CASA,AAAQ,aAAa,KAAwD;EAC3E,IAAI,CAAC,KACH,OAAO;GAAE,OAAO;GAAG,QAAQ;GAAG,OAAO;EAAE;EAGzC,OAAO,WACL;GACE,OAAO,IAAI;GACX,QAAQ,IAAI;GACZ,OAAO,IAAI;GACX,cAAc,IAAI,sBAAsB;GACxC,kBAAkB,IAAI,sBAAsB;GAC5C,iBAAiB,IAAI,uBAAuB;EAC9C,GACA,KAAK,OACP;CACF;;CAGA,AAAQ,WAAW,QAAqD;EACtE,MAAM,UAAU,gBAAgB,MAAM;EAEtC,KAAK,OAAO,MAAM,YAAY,SAAS,QAAQ,SAAS;GACtD,MAAM,QAAQ;GACd,SAAS,QAAQ;EACnB,CAAC;EAED,OAAO;CACT;AACF"}
|
package/esm/sdk.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { OpenAIEmbedderConfig, OpenAIImageConfig, OpenAIModelConfig, OpenAISDKConfig, OpenAISpeechConfig, OpenAITranscriptionConfig } from "./config.type.mjs";
|
|
2
2
|
import { EmbedderContract, ImageModelContract, ModelContract, SDKAdapterContract, SpeechModelContract, TranscriptionModelContract } from "@warlock.js/ai";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../../packages/ai-openai/src/sdk.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* OpenAI-backed implementation of `SDKAdapterContract`.
|
|
7
7
|
*
|
|
@@ -50,8 +50,9 @@ declare class OpenAISDK implements SDKAdapterContract {
|
|
|
50
50
|
* coming from the same upstream.
|
|
51
51
|
*
|
|
52
52
|
* Pricing resolution: per-model `config.pricing` wins; otherwise the
|
|
53
|
-
* SDK-level registry entry keyed by `config.name`; otherwise
|
|
54
|
-
* `
|
|
53
|
+
* SDK-level registry entry keyed by `config.name`; otherwise, when the
|
|
54
|
+
* provider label is `"openai"`, the built-in list price
|
|
55
|
+
* (`OPENAI_MODEL_PRICING`); otherwise `undefined` (no cost computed).
|
|
55
56
|
*
|
|
56
57
|
* `config.api` selects the wire API. Omitted or `"chat"` builds the Chat
|
|
57
58
|
* Completions `OpenAIModel`. `"responses"` builds `OpenAIResponsesModel`
|
package/esm/sdk.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"sdk.d.mts","names":[],"sources":["../../../../../../../packages/ai-openai/src/sdk.ts"],"mappings":";;;;;;AA6DA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,SAAA,YAAqB,kBAAA;EAAA,iBACf,MAAA;EAAA,iBACA,QAAA;EAAA,iBACA,OAAA;cAEE,MAAA,EAAQ,eAAA;EAyGpB;;;;;;;;;;;;;AAkCyE;;;;;;;EA3GzE,KAAA,CAAM,MAAA,EAAQ,iBAAA,GAAoB,aAAA;;;;;;;;EAsC5B,KAAA,CAAM,IAAA,UAAc,MAAA,YAAkB,OAAA;;;;;;;;;;;EAc5C,QAAA,CAAS,MAAA,EAAQ,oBAAA,GAAuB,gBAAA;;;;;;;;;;;;;;;;;;EAqBxC,KAAA,CAAM,MAAA,EAAQ,iBAAA,GAAoB,kBAAA;;;;;;;;;;;;EAmBlC,MAAA,CAAO,MAAA,EAAQ,kBAAA,GAAqB,mBAAA;;;;;;;;;;;;EAepC,UAAA,CAAW,MAAA,EAAQ,yBAAA,GAA4B,0BAAA;AAAA"}
|
package/esm/sdk.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { openAIPricingFor } from "./known-pricing.mjs";
|
|
1
2
|
import { OpenAIEmbedder } from "./embedder.mjs";
|
|
2
3
|
import { OpenAIImageModel } from "./image.mjs";
|
|
3
4
|
import { OpenAIModel } from "./model.mjs";
|
|
@@ -7,7 +8,7 @@ import { OpenAITranscriptionModel } from "./transcription.mjs";
|
|
|
7
8
|
import OpenAI from "openai";
|
|
8
9
|
import { InvalidRequestError, approximateTokenCount } from "@warlock.js/ai";
|
|
9
10
|
|
|
10
|
-
//#region
|
|
11
|
+
//#region ../../packages/ai-openai/src/sdk.ts
|
|
11
12
|
/**
|
|
12
13
|
* OpenAI-backed implementation of `SDKAdapterContract`.
|
|
13
14
|
*
|
|
@@ -58,8 +59,9 @@ var OpenAISDK = class {
|
|
|
58
59
|
* coming from the same upstream.
|
|
59
60
|
*
|
|
60
61
|
* Pricing resolution: per-model `config.pricing` wins; otherwise the
|
|
61
|
-
* SDK-level registry entry keyed by `config.name`; otherwise
|
|
62
|
-
* `
|
|
62
|
+
* SDK-level registry entry keyed by `config.name`; otherwise, when the
|
|
63
|
+
* provider label is `"openai"`, the built-in list price
|
|
64
|
+
* (`OPENAI_MODEL_PRICING`); otherwise `undefined` (no cost computed).
|
|
63
65
|
*
|
|
64
66
|
* `config.api` selects the wire API. Omitted or `"chat"` builds the Chat
|
|
65
67
|
* Completions `OpenAIModel`. `"responses"` builds `OpenAIResponsesModel`
|
|
@@ -80,7 +82,7 @@ var OpenAISDK = class {
|
|
|
80
82
|
model: config.name,
|
|
81
83
|
api
|
|
82
84
|
} });
|
|
83
|
-
const resolvedPricing = config.pricing ?? this.pricing?.[config.name];
|
|
85
|
+
const resolvedPricing = config.pricing ?? this.pricing?.[config.name] ?? (this.provider === "openai" ? openAIPricingFor(config.name) : void 0);
|
|
84
86
|
const resolvedConfig = resolvedPricing === config.pricing ? config : {
|
|
85
87
|
...config,
|
|
86
88
|
pricing: resolvedPricing
|