@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/sdk.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.mjs","names":[],"sources":["../../../../../../ai-openai/src/sdk.ts"],"sourcesContent":["import OpenAI from \"openai\";\nimport type {\n EmbedderContract,\n ImageModelContract,\n ModelContract,\n ModelPricing,\n SDKAdapterContract,\n SpeechModelContract,\n TranscriptionModelContract,\n} from \"@warlock.js/ai\";\nimport { InvalidRequestError, approximateTokenCount } from \"@warlock.js/ai\";\nimport type {\n OpenAIEmbedderConfig,\n OpenAIImageConfig,\n OpenAIModelConfig,\n OpenAISDKConfig,\n OpenAISpeechConfig,\n OpenAITranscriptionConfig,\n} from \"./config.type\";\nimport { OpenAIEmbedder } from \"./embedder\";\nimport { OpenAIImageModel } from \"./image\";\nimport { OpenAIModel } from \"./model\";\nimport { OpenAIResponsesModel } from \"./responses-model\";\nimport { OpenAISpeechModel } from \"./speech\";\nimport { OpenAITranscriptionModel } from \"./transcription\";\n\n/**\n * OpenAI-backed implementation of `SDKAdapterContract`.\n *\n * **Role.** The package entry point for any OpenAI-compatible provider\n * (OpenAI, Azure OpenAI, OpenRouter, local gateways speaking the Chat\n * Completions protocol). A single `OpenAISDK` instance holds one live\n * `OpenAI` client, shared by every `ModelContract` it produces via\n * `model()`. Users construct one SDK per provider/account and reuse it\n * across all agents, workflows, and supervisors that target that\n * provider.\n *\n * **Responsibility.**\n * - Owns: a long-lived `OpenAI` client (authentication, base URL) and\n * its lifetime scope. Factory for `OpenAIModel` instances — each\n * model call gets a reference to the same client.\n * - Does NOT own: anything per-call (tool execution, message history,\n * streaming loop) — those live in `OpenAIModel` and the agent runtime.\n *\n * Modeled as a class (see §4.2 of code-style.md — \"long-lived state\n * across many calls\"): the `OpenAI` client is heavy to construct and\n * designed to be reused; keeping it on `this` makes that reuse\n * explicit and aligns with the PascalCase naming convention readers\n * expect from a constructor.\n *\n * @example\n * const openai = new OpenAISDK({ apiKey: process.env.OPENAI_API_KEY! });\n * const model = openai.model({ name: \"gpt-4o\", temperature: 0.7 });\n * const tokens = await openai.count(\"Hello world\");\n *\n * @example\n * // Compose into an `ai.openai` namespace for ergonomic agent wiring\n * const ai = { agent, tool, systemPrompt, persona, instruction, openai: new OpenAISDK({ apiKey }) };\n * const myAgent = ai.agent({ model: ai.openai.model({ name: \"gpt-4o-mini\" }) });\n */\nexport class OpenAISDK implements SDKAdapterContract {\n private readonly client: OpenAI;\n private readonly provider: string;\n private readonly pricing?: Record<string, ModelPricing>;\n\n public constructor(config: OpenAISDKConfig) {\n // Peel off the framework-only keys and forward every other upstream\n // `ClientOptions` (timeout, maxRetries, defaultHeaders, fetch,\n // organization, project, …) verbatim — they type-check, so dropping them\n // is a silent footgun. Mirrors the Bedrock/Google/Ollama adapters.\n const { provider, pricing, ...clientOptions } = config;\n\n this.client = new OpenAI(clientOptions);\n this.provider = provider ?? \"openai\";\n this.pricing = pricing;\n }\n\n /**\n * Build an `OpenAIModel` bound to this SDK's client. Each call returns\n * a fresh model instance, but all instances share the underlying\n * `OpenAI` client — connection pools, rate limits, and authentication\n * state stay unified across every model produced here. The SDK's\n * `provider` label is forwarded so every model self-identifies as\n * coming from the same upstream.\n *\n * Pricing resolution: per-model `config.pricing` wins; otherwise the\n * SDK-level registry entry keyed by `config.name`; otherwise\n * `undefined` (no cost computed).\n *\n * `config.api` selects the wire API. Omitted or `\"chat\"` builds the Chat\n * Completions `OpenAIModel`. `\"responses\"` builds `OpenAIResponsesModel`\n * and is accepted ONLY when this SDK's provider label is `\"openai\"`: any\n * other label (the wrapper packages deepseek / groq / xai / mistral, or a\n * custom gateway label) throws, so an endpoint not known to implement\n * `/v1/responses` is never sent there.\n */\n public model(config: OpenAIModelConfig): ModelContract {\n const api: unknown = config.api;\n\n if (api !== undefined && api !== \"chat\" && api !== \"responses\") {\n throw new InvalidRequestError(\n `Unknown OpenAI api \"${String(api)}\"; expected \"chat\" or \"responses\".`,\n { context: { provider: this.provider, model: config.name, api } },\n );\n }\n\n if (api === \"responses\" && this.provider !== \"openai\") {\n throw new InvalidRequestError(\n `api: \"responses\" is supported only on the direct \"openai\" provider; this SDK is labeled \"${this.provider}\". Use the default api: \"chat\".`,\n { context: { provider: this.provider, model: config.name, api } },\n );\n }\n\n const resolvedPricing = config.pricing ?? this.pricing?.[config.name];\n const resolvedConfig: OpenAIModelConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n if (api === \"responses\") {\n return new OpenAIResponsesModel(this.client, resolvedConfig, this.provider);\n }\n\n return new OpenAIModel(this.client, resolvedConfig, this.provider);\n }\n\n /**\n * Rough token-count estimate for a given text. Uses a\n * character-heuristic (`approximateTokenCount`) from the core package\n * — good enough for budgeting and quota guards, not for billing.\n * Accepts an optional model id for future per-model tokenizer\n * dispatch; currently ignored.\n */\n public async count(text: string, _model?: string): Promise<number> {\n return approximateTokenCount(text);\n }\n\n /**\n * Build an `OpenAIEmbedder` bound to this SDK's client. Each call\n * returns a fresh embedder instance sharing the same underlying\n * `OpenAI` client — connection pools and authentication stay unified\n * across every embedder produced here.\n *\n * @example\n * const embedder = openai.embedder({ name: \"text-embedding-3-small\" });\n * const { vector } = await embedder.embed(\"Hello world\");\n */\n public embedder(config: OpenAIEmbedderConfig): EmbedderContract {\n return new OpenAIEmbedder(this.client, config);\n }\n\n /**\n * Build an `OpenAIImageModel` bound to this SDK's client for use with\n * `ai.image({ model, prompt })`. `config.name` is passed through to\n * `client.images.generate` as given — no id is rejected locally, so\n * an unsupported model fails at OpenAI, not here. Metering follows\n * the family: `gpt-image-*` is token-metered, `dall-e-*` per-image.\n *\n * Pricing resolution mirrors `model()`: per-model `config.pricing`\n * wins, otherwise the SDK-level registry entry keyed by `config.name`,\n * otherwise `undefined` (no cost computed). A token-priced\n * `gpt-image-1` entry can live in the same SDK registry as the chat\n * models.\n *\n * @example\n * const model = openai.image({ name: \"gpt-image-1\" });\n * const { data } = await ai.image({ model, prompt: \"a red bicycle\" });\n */\n public image(config: OpenAIImageConfig): ImageModelContract {\n const resolvedPricing = config.pricing ?? this.pricing?.[config.name];\n const resolvedConfig: OpenAIImageConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n return new OpenAIImageModel(this.client, resolvedConfig, this.provider);\n }\n\n /**\n * Build an `OpenAISpeechModel` (text-to-speech) bound to this SDK's\n * client, for use with `ai.speech({ model, text })`. `config.name` is\n * passed through to `audio.speech.create` as given — no id is\n * rejected locally, so an unsupported model fails at OpenAI, not\n * here.\n *\n * @example\n * const tts = openai.speech({ name: \"tts-1\", voice: \"alloy\" });\n * const { data } = await ai.speech({ model: tts, text: \"Hello\" });\n */\n public speech(config: OpenAISpeechConfig): SpeechModelContract {\n return new OpenAISpeechModel(this.client, config, this.provider);\n }\n\n /**\n * Build an `OpenAITranscriptionModel` (speech-to-text) bound to this\n * SDK's client, for use with `ai.transcribe({ model, audio })`.\n * `config.name` is passed through to `audio.transcriptions.create`\n * as given — no id is rejected locally, so an unsupported model\n * fails at OpenAI, not here.\n *\n * @example\n * const stt = openai.transcribe({ name: \"whisper-1\" });\n * const { data } = await ai.transcribe({ model: stt, audio });\n */\n public transcribe(config: OpenAITranscriptionConfig): TranscriptionModelContract {\n return new OpenAITranscriptionModel(this.client, config, this.provider);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,IAAa,YAAb,MAAqD;CAKnD,AAAO,YAAY,QAAyB;EAK1C,MAAM,EAAE,UAAU,SAAS,GAAG,kBAAkB;EAEhD,KAAK,SAAS,IAAI,OAAO,aAAa;EACtC,KAAK,WAAW,YAAY;EAC5B,KAAK,UAAU;CACjB;;;;;;;;;;;;;;;;;;;;CAqBA,AAAO,MAAM,QAA0C;EACrD,MAAM,MAAe,OAAO;EAE5B,IAAI,QAAQ,UAAa,QAAQ,UAAU,QAAQ,aACjD,MAAM,IAAI,oBACR,uBAAuB,OAAO,GAAG,EAAE,qCACnC,EAAE,SAAS;GAAE,UAAU,KAAK;GAAU,OAAO,OAAO;GAAM;EAAI,EAAE,CAClE;EAGF,IAAI,QAAQ,eAAe,KAAK,aAAa,UAC3C,MAAM,IAAI,oBACR,4FAA4F,KAAK,SAAS,kCAC1G,EAAE,SAAS;GAAE,UAAU,KAAK;GAAU,OAAO,OAAO;GAAM;EAAI,EAAE,CAClE;EAGF,MAAM,kBAAkB,OAAO,WAAW,KAAK,UAAU,OAAO;EAChE,MAAM,iBACJ,oBAAoB,OAAO,UAAU,SAAS;GAAE,GAAG;GAAQ,SAAS;EAAgB;EAEtF,IAAI,QAAQ,aACV,OAAO,IAAI,qBAAqB,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;EAG5E,OAAO,IAAI,YAAY,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;CACnE;;;;;;;;CASA,MAAa,MAAM,MAAc,QAAkC;EACjE,OAAO,sBAAsB,IAAI;CACnC;;;;;;;;;;;CAYA,AAAO,SAAS,QAAgD;EAC9D,OAAO,IAAI,eAAe,KAAK,QAAQ,MAAM;CAC/C;;;;;;;;;;;;;;;;;;CAmBA,AAAO,MAAM,QAA+C;EAC1D,MAAM,kBAAkB,OAAO,WAAW,KAAK,UAAU,OAAO;EAChE,MAAM,iBACJ,oBAAoB,OAAO,UAAU,SAAS;GAAE,GAAG;GAAQ,SAAS;EAAgB;EAEtF,OAAO,IAAI,iBAAiB,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;CACxE;;;;;;;;;;;;CAaA,AAAO,OAAO,QAAiD;EAC7D,OAAO,IAAI,kBAAkB,KAAK,QAAQ,QAAQ,KAAK,QAAQ;CACjE;;;;;;;;;;;;CAaA,AAAO,WAAW,QAA+D;EAC/E,OAAO,IAAI,yBAAyB,KAAK,QAAQ,QAAQ,KAAK,QAAQ;CACxE;AACF"}
|
|
1
|
+
{"version":3,"file":"sdk.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/sdk.ts"],"sourcesContent":["import OpenAI from \"openai\";\nimport type {\n EmbedderContract,\n ImageModelContract,\n ModelContract,\n ModelPricing,\n SDKAdapterContract,\n SpeechModelContract,\n TranscriptionModelContract,\n} from \"@warlock.js/ai\";\nimport { InvalidRequestError, approximateTokenCount } from \"@warlock.js/ai\";\nimport { openAIPricingFor } from \"./known-pricing\";\nimport type {\n OpenAIEmbedderConfig,\n OpenAIImageConfig,\n OpenAIModelConfig,\n OpenAISDKConfig,\n OpenAISpeechConfig,\n OpenAITranscriptionConfig,\n} from \"./config.type\";\nimport { OpenAIEmbedder } from \"./embedder\";\nimport { OpenAIImageModel } from \"./image\";\nimport { OpenAIModel } from \"./model\";\nimport { OpenAIResponsesModel } from \"./responses-model\";\nimport { OpenAISpeechModel } from \"./speech\";\nimport { OpenAITranscriptionModel } from \"./transcription\";\n\n/**\n * OpenAI-backed implementation of `SDKAdapterContract`.\n *\n * **Role.** The package entry point for any OpenAI-compatible provider\n * (OpenAI, Azure OpenAI, OpenRouter, local gateways speaking the Chat\n * Completions protocol). A single `OpenAISDK` instance holds one live\n * `OpenAI` client, shared by every `ModelContract` it produces via\n * `model()`. Users construct one SDK per provider/account and reuse it\n * across all agents, workflows, and supervisors that target that\n * provider.\n *\n * **Responsibility.**\n * - Owns: a long-lived `OpenAI` client (authentication, base URL) and\n * its lifetime scope. Factory for `OpenAIModel` instances — each\n * model call gets a reference to the same client.\n * - Does NOT own: anything per-call (tool execution, message history,\n * streaming loop) — those live in `OpenAIModel` and the agent runtime.\n *\n * Modeled as a class (see §4.2 of code-style.md — \"long-lived state\n * across many calls\"): the `OpenAI` client is heavy to construct and\n * designed to be reused; keeping it on `this` makes that reuse\n * explicit and aligns with the PascalCase naming convention readers\n * expect from a constructor.\n *\n * @example\n * const openai = new OpenAISDK({ apiKey: process.env.OPENAI_API_KEY! });\n * const model = openai.model({ name: \"gpt-4o\", temperature: 0.7 });\n * const tokens = await openai.count(\"Hello world\");\n *\n * @example\n * // Compose into an `ai.openai` namespace for ergonomic agent wiring\n * const ai = { agent, tool, systemPrompt, persona, instruction, openai: new OpenAISDK({ apiKey }) };\n * const myAgent = ai.agent({ model: ai.openai.model({ name: \"gpt-4o-mini\" }) });\n */\nexport class OpenAISDK implements SDKAdapterContract {\n private readonly client: OpenAI;\n private readonly provider: string;\n private readonly pricing?: Record<string, ModelPricing>;\n\n public constructor(config: OpenAISDKConfig) {\n // Peel off the framework-only keys and forward every other upstream\n // `ClientOptions` (timeout, maxRetries, defaultHeaders, fetch,\n // organization, project, …) verbatim — they type-check, so dropping them\n // is a silent footgun. Mirrors the Bedrock/Google/Ollama adapters.\n const { provider, pricing, ...clientOptions } = config;\n\n this.client = new OpenAI(clientOptions);\n this.provider = provider ?? \"openai\";\n this.pricing = pricing;\n }\n\n /**\n * Build an `OpenAIModel` bound to this SDK's client. Each call returns\n * a fresh model instance, but all instances share the underlying\n * `OpenAI` client — connection pools, rate limits, and authentication\n * state stay unified across every model produced here. The SDK's\n * `provider` label is forwarded so every model self-identifies as\n * coming from the same upstream.\n *\n * Pricing resolution: per-model `config.pricing` wins; otherwise the\n * SDK-level registry entry keyed by `config.name`; otherwise, when the\n * provider label is `\"openai\"`, the built-in list price\n * (`OPENAI_MODEL_PRICING`); otherwise `undefined` (no cost computed).\n *\n * `config.api` selects the wire API. Omitted or `\"chat\"` builds the Chat\n * Completions `OpenAIModel`. `\"responses\"` builds `OpenAIResponsesModel`\n * and is accepted ONLY when this SDK's provider label is `\"openai\"`: any\n * other label (the wrapper packages deepseek / groq / xai / mistral, or a\n * custom gateway label) throws, so an endpoint not known to implement\n * `/v1/responses` is never sent there.\n */\n public model(config: OpenAIModelConfig): ModelContract {\n const api: unknown = config.api;\n\n if (api !== undefined && api !== \"chat\" && api !== \"responses\") {\n throw new InvalidRequestError(\n `Unknown OpenAI api \"${String(api)}\"; expected \"chat\" or \"responses\".`,\n { context: { provider: this.provider, model: config.name, api } },\n );\n }\n\n if (api === \"responses\" && this.provider !== \"openai\") {\n throw new InvalidRequestError(\n `api: \"responses\" is supported only on the direct \"openai\" provider; this SDK is labeled \"${this.provider}\". Use the default api: \"chat\".`,\n { context: { provider: this.provider, model: config.name, api } },\n );\n }\n\n const resolvedPricing =\n config.pricing ??\n this.pricing?.[config.name] ??\n (this.provider === \"openai\" ? openAIPricingFor(config.name) : undefined);\n const resolvedConfig: OpenAIModelConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n if (api === \"responses\") {\n return new OpenAIResponsesModel(this.client, resolvedConfig, this.provider);\n }\n\n return new OpenAIModel(this.client, resolvedConfig, this.provider);\n }\n\n /**\n * Rough token-count estimate for a given text. Uses a\n * character-heuristic (`approximateTokenCount`) from the core package\n * — good enough for budgeting and quota guards, not for billing.\n * Accepts an optional model id for future per-model tokenizer\n * dispatch; currently ignored.\n */\n public async count(text: string, _model?: string): Promise<number> {\n return approximateTokenCount(text);\n }\n\n /**\n * Build an `OpenAIEmbedder` bound to this SDK's client. Each call\n * returns a fresh embedder instance sharing the same underlying\n * `OpenAI` client — connection pools and authentication stay unified\n * across every embedder produced here.\n *\n * @example\n * const embedder = openai.embedder({ name: \"text-embedding-3-small\" });\n * const { vector } = await embedder.embed(\"Hello world\");\n */\n public embedder(config: OpenAIEmbedderConfig): EmbedderContract {\n return new OpenAIEmbedder(this.client, config);\n }\n\n /**\n * Build an `OpenAIImageModel` bound to this SDK's client for use with\n * `ai.image({ model, prompt })`. `config.name` is passed through to\n * `client.images.generate` as given — no id is rejected locally, so\n * an unsupported model fails at OpenAI, not here. Metering follows\n * the family: `gpt-image-*` is token-metered, `dall-e-*` per-image.\n *\n * Pricing resolution mirrors `model()`: per-model `config.pricing`\n * wins, otherwise the SDK-level registry entry keyed by `config.name`,\n * otherwise `undefined` (no cost computed). A token-priced\n * `gpt-image-1` entry can live in the same SDK registry as the chat\n * models.\n *\n * @example\n * const model = openai.image({ name: \"gpt-image-1\" });\n * const { data } = await ai.image({ model, prompt: \"a red bicycle\" });\n */\n public image(config: OpenAIImageConfig): ImageModelContract {\n const resolvedPricing = config.pricing ?? this.pricing?.[config.name];\n const resolvedConfig: OpenAIImageConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n return new OpenAIImageModel(this.client, resolvedConfig, this.provider);\n }\n\n /**\n * Build an `OpenAISpeechModel` (text-to-speech) bound to this SDK's\n * client, for use with `ai.speech({ model, text })`. `config.name` is\n * passed through to `audio.speech.create` as given — no id is\n * rejected locally, so an unsupported model fails at OpenAI, not\n * here.\n *\n * @example\n * const tts = openai.speech({ name: \"tts-1\", voice: \"alloy\" });\n * const { data } = await ai.speech({ model: tts, text: \"Hello\" });\n */\n public speech(config: OpenAISpeechConfig): SpeechModelContract {\n return new OpenAISpeechModel(this.client, config, this.provider);\n }\n\n /**\n * Build an `OpenAITranscriptionModel` (speech-to-text) bound to this\n * SDK's client, for use with `ai.transcribe({ model, audio })`.\n * `config.name` is passed through to `audio.transcriptions.create`\n * as given — no id is rejected locally, so an unsupported model\n * fails at OpenAI, not here.\n *\n * @example\n * const stt = openai.transcribe({ name: \"whisper-1\" });\n * const { data } = await ai.transcribe({ model: stt, audio });\n */\n public transcribe(config: OpenAITranscriptionConfig): TranscriptionModelContract {\n return new OpenAITranscriptionModel(this.client, config, this.provider);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,IAAa,YAAb,MAAqD;CAKnD,AAAO,YAAY,QAAyB;EAK1C,MAAM,EAAE,UAAU,SAAS,GAAG,kBAAkB;EAEhD,KAAK,SAAS,IAAI,OAAO,aAAa;EACtC,KAAK,WAAW,YAAY;EAC5B,KAAK,UAAU;CACjB;;;;;;;;;;;;;;;;;;;;;CAsBA,AAAO,MAAM,QAA0C;EACrD,MAAM,MAAe,OAAO;EAE5B,IAAI,QAAQ,UAAa,QAAQ,UAAU,QAAQ,aACjD,MAAM,IAAI,oBACR,uBAAuB,OAAO,GAAG,EAAE,qCACnC,EAAE,SAAS;GAAE,UAAU,KAAK;GAAU,OAAO,OAAO;GAAM;EAAI,EAAE,CAClE;EAGF,IAAI,QAAQ,eAAe,KAAK,aAAa,UAC3C,MAAM,IAAI,oBACR,4FAA4F,KAAK,SAAS,kCAC1G,EAAE,SAAS;GAAE,UAAU,KAAK;GAAU,OAAO,OAAO;GAAM;EAAI,EAAE,CAClE;EAGF,MAAM,kBACJ,OAAO,WACP,KAAK,UAAU,OAAO,UACrB,KAAK,aAAa,WAAW,iBAAiB,OAAO,IAAI,IAAI;EAChE,MAAM,iBACJ,oBAAoB,OAAO,UAAU,SAAS;GAAE,GAAG;GAAQ,SAAS;EAAgB;EAEtF,IAAI,QAAQ,aACV,OAAO,IAAI,qBAAqB,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;EAG5E,OAAO,IAAI,YAAY,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;CACnE;;;;;;;;CASA,MAAa,MAAM,MAAc,QAAkC;EACjE,OAAO,sBAAsB,IAAI;CACnC;;;;;;;;;;;CAYA,AAAO,SAAS,QAAgD;EAC9D,OAAO,IAAI,eAAe,KAAK,QAAQ,MAAM;CAC/C;;;;;;;;;;;;;;;;;;CAmBA,AAAO,MAAM,QAA+C;EAC1D,MAAM,kBAAkB,OAAO,WAAW,KAAK,UAAU,OAAO;EAChE,MAAM,iBACJ,oBAAoB,OAAO,UAAU,SAAS;GAAE,GAAG;GAAQ,SAAS;EAAgB;EAEtF,OAAO,IAAI,iBAAiB,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;CACxE;;;;;;;;;;;;CAaA,AAAO,OAAO,QAAiD;EAC7D,OAAO,IAAI,kBAAkB,KAAK,QAAQ,QAAQ,KAAK,QAAQ;CACjE;;;;;;;;;;;;CAaA,AAAO,WAAW,QAA+D;EAC/E,OAAO,IAAI,yBAAyB,KAAK,QAAQ,QAAQ,KAAK,QAAQ;CACxE;AACF"}
|
package/esm/speech.d.mts
CHANGED
|
@@ -2,7 +2,7 @@ import { OpenAISpeechConfig } from "./config.type.mjs";
|
|
|
2
2
|
import OpenAI from "openai";
|
|
3
3
|
import { SpeechGenerationResponse, SpeechModelContract, SpeechModelPricing, SpeechOptions } from "@warlock.js/ai";
|
|
4
4
|
|
|
5
|
-
//#region
|
|
5
|
+
//#region ../../packages/ai-openai/src/speech.d.ts
|
|
6
6
|
/**
|
|
7
7
|
* OpenAI-backed implementation of `SpeechModelContract` (text-to-speech)
|
|
8
8
|
* via `audio.speech.create`. Standalone primitive — no relation to chat
|
package/esm/speech.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"speech.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"speech.d.mts","names":[],"sources":["../../../../../../../packages/ai-openai/src/speech.ts"],"mappings":";;;;;;;AA8CA;;;;;;;;;;;;;cAAa,iBAAA,YAA6B,mBAAA;EAAA,SACxB,IAAA;EAAA,SACA,QAAA;EAAA,SACA,OAAA,GAAU,kBAAA;EAAA,iBAET,MAAA;EAAA,iBACA,YAAA;EAAA,iBACA,MAAA;cAEE,MAAA,EAAQ,MAAA,EAAQ,MAAA,EAAQ,kBAAA,EAAoB,QAAA;EAQlD,QAAA,CAAS,IAAA,UAAc,OAAA,GAAU,aAAA,GAAgB,OAAA,CAAQ,wBAAA;AAAA"}
|
package/esm/speech.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { wrapOpenAIError } from "./utils/wrap-openai-error.mjs";
|
|
|
2
2
|
import "./utils/index.mjs";
|
|
3
3
|
import { log } from "@warlock.js/logger";
|
|
4
4
|
|
|
5
|
-
//#region
|
|
5
|
+
//#region ../../packages/ai-openai/src/speech.ts
|
|
6
6
|
const LOG_MODULE = "ai.openai";
|
|
7
7
|
/** Map a neutral output container hint to its IANA audio media type. */
|
|
8
8
|
function audioMediaType(format) {
|
package/esm/speech.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"speech.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"speech.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/speech.ts"],"sourcesContent":["import {\n type SpeechGenerationResponse,\n type SpeechModelContract,\n type SpeechModelPricing,\n type SpeechOptions,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type OpenAI from \"openai\";\nimport type { OpenAISpeechConfig } from \"./config.type\";\nimport { wrapOpenAIError } from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\n/** Map a neutral output container hint to its IANA audio media type. */\nfunction audioMediaType(format: string | undefined): string {\n switch (format) {\n case \"opus\":\n return \"audio/opus\";\n case \"aac\":\n return \"audio/aac\";\n case \"flac\":\n return \"audio/flac\";\n case \"wav\":\n return \"audio/wav\";\n case \"pcm\":\n return \"audio/pcm\";\n default:\n return \"audio/mpeg\";\n }\n}\n\n/**\n * OpenAI-backed implementation of `SpeechModelContract` (text-to-speech)\n * via `audio.speech.create`. Standalone primitive — no relation to chat\n * completions or the agent loop. Consumed by the `ai.speech()` verb.\n *\n * **No model-id validation.** `config.name` is forwarded to\n * `audio.speech.create` exactly as given — the constructor never\n * inspects it. OpenAI ships and retires TTS model ids on its own\n * schedule, so an unrecognized id fails at OpenAI (wrapped into the\n * typed `AIError` hierarchy by `generate()`), not here.\n *\n * @example\n * const tts = new OpenAISpeechModel(client, { name: \"tts-1\", voice: \"alloy\" }, \"openai\");\n * const { audio } = await tts.generate(\"Welcome aboard.\");\n */\nexport class OpenAISpeechModel implements SpeechModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly pricing?: SpeechModelPricing;\n\n private readonly client: OpenAI;\n private readonly defaultVoice?: string;\n private readonly logger: Logger = log;\n\n public constructor(client: OpenAI, config: OpenAISpeechConfig, provider: string = \"openai\") {\n this.client = client;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n this.defaultVoice = config.voice;\n }\n\n public async generate(text: string, options?: SpeechOptions): Promise<SpeechGenerationResponse> {\n const format = options?.format ?? \"mp3\";\n\n this.logger.debug(LOG_MODULE, \"speech.request\", \"audio.speech.create\", {\n model: this.name,\n characters: text.length,\n });\n\n let response: Response;\n\n try {\n response = await this.client.audio.speech.create(\n {\n model: this.name,\n input: text,\n voice: options?.voice ?? this.defaultVoice ?? \"alloy\",\n response_format: format as OpenAI.Audio.SpeechCreateParams[\"response_format\"],\n ...(options?.speed !== undefined ? { speed: options.speed } : {}),\n ...(options?.instructions !== undefined ? { instructions: options.instructions } : {}),\n },\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n const wrapped = wrapOpenAIError(thrown);\n this.logger.error(LOG_MODULE, \"speech.error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n throw wrapped;\n }\n\n const base64 = Buffer.from(await response.arrayBuffer()).toString(\"base64\");\n\n return {\n audio: { type: \"base64\", base64, mediaType: audioMediaType(format) },\n // The Speech API reports no token usage; spend is priced per\n // character (or per token for gpt-4o-mini-tts) by `ai.speech()`.\n usage: { input: 0, output: 0, total: 0 },\n characters: text.length,\n };\n }\n}\n"],"mappings":";;;;;AAWA,MAAM,aAAa;;AAGnB,SAAS,eAAe,QAAoC;CAC1D,QAAQ,QAAR;EACE,KAAK,QACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;;;;;;;;;;;;;;;AAiBA,IAAa,oBAAb,MAA8D;CAS5D,AAAO,YAAY,QAAgB,QAA4B,WAAmB,UAAU;gBAF1D;EAGhC,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;EACtB,KAAK,eAAe,OAAO;CAC7B;CAEA,MAAa,SAAS,MAAc,SAA4D;EAC9F,MAAM,SAAS,SAAS,UAAU;EAElC,KAAK,OAAO,MAAM,YAAY,kBAAkB,uBAAuB;GACrE,OAAO,KAAK;GACZ,YAAY,KAAK;EACnB,CAAC;EAED,IAAI;EAEJ,IAAI;GACF,WAAW,MAAM,KAAK,OAAO,MAAM,OAAO,OACxC;IACE,OAAO,KAAK;IACZ,OAAO;IACP,OAAO,SAAS,SAAS,KAAK,gBAAgB;IAC9C,iBAAiB;IACjB,GAAI,SAAS,UAAU,SAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;IAC/D,GAAI,SAAS,iBAAiB,SAAY,EAAE,cAAc,QAAQ,aAAa,IAAI,CAAC;GACtF,GACA,SAAS,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,MACjD;EACF,SAAS,QAAQ;GACf,MAAM,UAAU,gBAAgB,MAAM;GACtC,KAAK,OAAO,MAAM,YAAY,gBAAgB,QAAQ,SAAS;IAC7D,MAAM,QAAQ;IACd,SAAS,QAAQ;GACnB,CAAC;GACD,MAAM;EACR;EAIA,OAAO;GACL,OAAO;IAAE,MAAM;IAAU,QAHZ,OAAO,KAAK,MAAM,SAAS,YAAY,CAAC,CAAC,CAAC,SAAS,QAGlC;IAAG,WAAW,eAAe,MAAM;GAAE;GAGnE,OAAO;IAAE,OAAO;IAAG,QAAQ;IAAG,OAAO;GAAE;GACvC,YAAY,KAAK;EACnB;CACF;AACF"}
|
package/esm/transcription.d.mts
CHANGED
|
@@ -2,7 +2,7 @@ import { OpenAITranscriptionConfig } from "./config.type.mjs";
|
|
|
2
2
|
import OpenAI from "openai";
|
|
3
3
|
import { AudioInput, TranscribeOptions, TranscriptionModelContract, TranscriptionModelPricing, TranscriptionResponse } from "@warlock.js/ai";
|
|
4
4
|
|
|
5
|
-
//#region
|
|
5
|
+
//#region ../../packages/ai-openai/src/transcription.d.ts
|
|
6
6
|
/**
|
|
7
7
|
* OpenAI-backed implementation of `TranscriptionModelContract`
|
|
8
8
|
* (speech-to-text) via `audio.transcriptions.create`. Consumed by the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcription.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"transcription.d.mts","names":[],"sources":["../../../../../../../packages/ai-openai/src/transcription.ts"],"mappings":";;;;;;;AAiDA;;;;;;;;;;;;;;;;;cAAa,wBAAA,YAAoC,0BAAA;EAAA,SAC/B,IAAA;EAAA,SACA,QAAA;EAAA,SACA,OAAA,GAAU,yBAAA;EAAA,iBAET,MAAA;EAAA,iBACA,MAAA;cAGf,MAAA,EAAQ,MAAA,EACR,MAAA,EAAQ,yBAAA,EACR,QAAA;EAQW,UAAA,CACX,KAAA,EAAO,UAAA,EACP,OAAA,GAAU,iBAAA,GACT,OAAA,CAAQ,qBAAA;AAAA"}
|
package/esm/transcription.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import "./utils/index.mjs";
|
|
|
3
3
|
import { toFile } from "openai";
|
|
4
4
|
import { log } from "@warlock.js/logger";
|
|
5
5
|
|
|
6
|
-
//#region
|
|
6
|
+
//#region ../../packages/ai-openai/src/transcription.ts
|
|
7
7
|
const LOG_MODULE = "ai.openai";
|
|
8
8
|
/**
|
|
9
9
|
* OpenAI-backed implementation of `TranscriptionModelContract`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcription.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"transcription.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/transcription.ts"],"sourcesContent":["import {\n type AudioInput,\n type TranscribeOptions,\n type TranscriptionModelContract,\n type TranscriptionModelPricing,\n type TranscriptionResponse,\n type TranscriptionSegment,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport OpenAI, { toFile } from \"openai\";\nimport type { OpenAITranscriptionConfig } from \"./config.type\";\nimport { wrapOpenAIError } from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\n/** Defensive view over the response, whose shape varies by `response_format`. */\ntype RawTranscription = {\n text: string;\n duration?: number;\n language?: string;\n segments?: Array<{ text: string; start?: number; end?: number }>;\n usage?: {\n type?: string;\n seconds?: number;\n input_tokens?: number;\n output_tokens?: number;\n total_tokens?: number;\n };\n};\n\n/**\n * OpenAI-backed implementation of `TranscriptionModelContract`\n * (speech-to-text) via `audio.transcriptions.create`. Consumed by the\n * `ai.transcribe()` verb.\n *\n * **No model-id validation.** `config.name` is forwarded to\n * `audio.transcriptions.create` exactly as given — the constructor\n * never inspects it. An unrecognized id fails at OpenAI (wrapped into\n * the typed `AIError` hierarchy by `transcribe()`), not here.\n *\n * **Response format.** Defaults to `verbose_json` for `whisper-1` (so\n * the run gets a `duration` + timestamped `segments`) and `json` for\n * the token-metered `gpt-4o-transcribe` family. Base64 audio is wrapped\n * in an uploadable via the SDK's `toFile`.\n *\n * @example\n * const stt = new OpenAITranscriptionModel(client, { name: \"whisper-1\" }, \"openai\");\n * const { text } = await stt.transcribe({ base64, mediaType: \"audio/mpeg\" });\n */\nexport class OpenAITranscriptionModel implements TranscriptionModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly pricing?: TranscriptionModelPricing;\n\n private readonly client: OpenAI;\n private readonly logger: Logger = log;\n\n public constructor(\n client: OpenAI,\n config: OpenAITranscriptionConfig,\n provider: string = \"openai\",\n ) {\n this.client = client;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n }\n\n public async transcribe(\n audio: AudioInput,\n options?: TranscribeOptions,\n ): Promise<TranscriptionResponse> {\n const isWhisper = this.name.startsWith(\"whisper\");\n const format = options?.format ?? (isWhisper ? \"verbose_json\" : \"json\");\n\n const file = await toFile(Buffer.from(audio.base64, \"base64\"), audio.filename ?? \"audio\", {\n type: audio.mediaType,\n });\n\n this.logger.debug(LOG_MODULE, \"transcription.request\", \"audio.transcriptions.create\", {\n model: this.name,\n format,\n });\n\n let raw: unknown;\n\n try {\n raw = await this.client.audio.transcriptions.create(\n {\n model: this.name,\n file,\n response_format: format as OpenAI.Audio.TranscriptionCreateParams[\"response_format\"],\n ...(options?.language ? { language: options.language } : {}),\n ...(options?.prompt ? { prompt: options.prompt } : {}),\n } as OpenAI.Audio.TranscriptionCreateParamsNonStreaming,\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n const wrapped = wrapOpenAIError(thrown);\n this.logger.error(LOG_MODULE, \"transcription.error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n throw wrapped;\n }\n\n const response = raw as RawTranscription;\n\n const segments: TranscriptionSegment[] | undefined = response.segments?.map((segment) => ({\n text: segment.text,\n ...(segment.start !== undefined ? { start: segment.start } : {}),\n ...(segment.end !== undefined ? { end: segment.end } : {}),\n }));\n\n const durationSeconds =\n response.duration ??\n (response.usage?.type === \"duration\" ? response.usage.seconds : undefined);\n\n const usage =\n response.usage?.type === \"tokens\"\n ? {\n input: response.usage.input_tokens ?? 0,\n output: response.usage.output_tokens ?? 0,\n total: response.usage.total_tokens ?? 0,\n }\n : { input: 0, output: 0, total: 0 };\n\n return {\n text: response.text,\n ...(segments && segments.length > 0 ? { segments } : {}),\n ...(durationSeconds !== undefined ? { durationSeconds } : {}),\n usage,\n };\n }\n}\n"],"mappings":";;;;;;AAaA,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;AAoCnB,IAAa,2BAAb,MAA4E;CAQ1E,AAAO,YACL,QACA,QACA,WAAmB,UACnB;gBANgC;EAOhC,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;CACxB;CAEA,MAAa,WACX,OACA,SACgC;EAChC,MAAM,YAAY,KAAK,KAAK,WAAW,SAAS;EAChD,MAAM,SAAS,SAAS,WAAW,YAAY,iBAAiB;EAEhE,MAAM,OAAO,MAAM,OAAO,OAAO,KAAK,MAAM,QAAQ,QAAQ,GAAG,MAAM,YAAY,SAAS,EACxF,MAAM,MAAM,UACd,CAAC;EAED,KAAK,OAAO,MAAM,YAAY,yBAAyB,+BAA+B;GACpF,OAAO,KAAK;GACZ;EACF,CAAC;EAED,IAAI;EAEJ,IAAI;GACF,MAAM,MAAM,KAAK,OAAO,MAAM,eAAe,OAC3C;IACE,OAAO,KAAK;IACZ;IACA,iBAAiB;IACjB,GAAI,SAAS,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;IAC1D,GAAI,SAAS,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;GACtD,GACA,SAAS,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,MACjD;EACF,SAAS,QAAQ;GACf,MAAM,UAAU,gBAAgB,MAAM;GACtC,KAAK,OAAO,MAAM,YAAY,uBAAuB,QAAQ,SAAS;IACpE,MAAM,QAAQ;IACd,SAAS,QAAQ;GACnB,CAAC;GACD,MAAM;EACR;EAEA,MAAM,WAAW;EAEjB,MAAM,WAA+C,SAAS,UAAU,KAAK,aAAa;GACxF,MAAM,QAAQ;GACd,GAAI,QAAQ,UAAU,SAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;GAC9D,GAAI,QAAQ,QAAQ,SAAY,EAAE,KAAK,QAAQ,IAAI,IAAI,CAAC;EAC1D,EAAE;EAEF,MAAM,kBACJ,SAAS,aACR,SAAS,OAAO,SAAS,aAAa,SAAS,MAAM,UAAU;EAElE,MAAM,QACJ,SAAS,OAAO,SAAS,WACrB;GACE,OAAO,SAAS,MAAM,gBAAgB;GACtC,QAAQ,SAAS,MAAM,iBAAiB;GACxC,OAAO,SAAS,MAAM,gBAAgB;EACxC,IACA;GAAE,OAAO;GAAG,QAAQ;GAAG,OAAO;EAAE;EAEtC,OAAO;GACL,MAAM,SAAS;GACf,GAAI,YAAY,SAAS,SAAS,IAAI,EAAE,SAAS,IAAI,CAAC;GACtD,GAAI,oBAAoB,SAAY,EAAE,gBAAgB,IAAI,CAAC;GAC3D;EACF;CACF;AACF"}
|
|
@@ -1,21 +1,33 @@
|
|
|
1
|
-
|
|
1
|
+
import { computeCost } from "@warlock.js/ai";
|
|
2
|
+
|
|
3
|
+
//#region ../../packages/ai-openai/src/utils/build-usage.ts
|
|
2
4
|
/**
|
|
3
5
|
* Build the neutral `Usage` from extracted counts. The optional detail
|
|
4
6
|
* counters are emitted only when the provider reports a positive value, so
|
|
5
7
|
* non-reasoning / uncached calls keep the lean `{ input, output, total }`
|
|
6
8
|
* shape. Shared by the Chat Completions and Responses adapters so both
|
|
7
9
|
* apply the same rule.
|
|
10
|
+
*
|
|
11
|
+
* OpenAI-style usage counts cache reads and writes inside the prompt
|
|
12
|
+
* total (`input_tokens` includes `cached_tokens` and `cache_write_tokens`,
|
|
13
|
+
* and the compatible vendors — DeepSeek, xAI, Groq, Mistral — document
|
|
14
|
+
* the same), so the result is marked `inputIncludesCache: true`. When the
|
|
15
|
+
* model is priced, `cost` is attached.
|
|
8
16
|
*/
|
|
9
|
-
function buildUsage(counts) {
|
|
17
|
+
function buildUsage(counts, pricing) {
|
|
10
18
|
const { input, output, total, cachedTokens, reasoningTokens, cacheWriteTokens } = counts;
|
|
11
|
-
|
|
19
|
+
const usage = {
|
|
12
20
|
input,
|
|
13
21
|
output,
|
|
14
22
|
total,
|
|
23
|
+
inputIncludesCache: true,
|
|
15
24
|
...cachedTokens !== void 0 && cachedTokens > 0 ? { cachedTokens } : {},
|
|
16
25
|
...reasoningTokens !== void 0 && reasoningTokens > 0 ? { reasoningTokens } : {},
|
|
17
26
|
...cacheWriteTokens !== void 0 && cacheWriteTokens > 0 ? { cacheWriteTokens } : {}
|
|
18
27
|
};
|
|
28
|
+
const cost = computeCost(usage, pricing);
|
|
29
|
+
if (cost) usage.cost = cost;
|
|
30
|
+
return usage;
|
|
19
31
|
}
|
|
20
32
|
|
|
21
33
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-usage.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"build-usage.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/build-usage.ts"],"sourcesContent":["import { computeCost, type ModelPricing, type Usage } from \"@warlock.js/ai\";\n\n/** The already-extracted token counts of one provider usage block. */\nexport type UsageCounts = {\n input: number;\n output: number;\n total: number;\n /** Subset of `input` served from the prompt cache. */\n cachedTokens?: number;\n /** Hidden reasoning channel, already counted within `output`. */\n reasoningTokens?: number;\n /** Subset of `input` written to the prompt cache. */\n cacheWriteTokens?: number;\n};\n\n/**\n * Build the neutral `Usage` from extracted counts. The optional detail\n * counters are emitted only when the provider reports a positive value, so\n * non-reasoning / uncached calls keep the lean `{ input, output, total }`\n * shape. Shared by the Chat Completions and Responses adapters so both\n * apply the same rule.\n *\n * OpenAI-style usage counts cache reads and writes inside the prompt\n * total (`input_tokens` includes `cached_tokens` and `cache_write_tokens`,\n * and the compatible vendors — DeepSeek, xAI, Groq, Mistral — document\n * the same), so the result is marked `inputIncludesCache: true`. When the\n * model is priced, `cost` is attached.\n */\nexport function buildUsage(counts: UsageCounts, pricing?: ModelPricing): Usage {\n const { input, output, total, cachedTokens, reasoningTokens, cacheWriteTokens } = counts;\n\n const usage: Usage = {\n input,\n output,\n total,\n inputIncludesCache: true,\n ...(cachedTokens !== undefined && cachedTokens > 0 ? { cachedTokens } : {}),\n ...(reasoningTokens !== undefined && reasoningTokens > 0 ? { reasoningTokens } : {}),\n ...(cacheWriteTokens !== undefined && cacheWriteTokens > 0 ? { cacheWriteTokens } : {}),\n };\n\n const cost = computeCost(usage, pricing);\n\n if (cost) {\n usage.cost = cost;\n }\n\n return usage;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,SAAgB,WAAW,QAAqB,SAA+B;CAC7E,MAAM,EAAE,OAAO,QAAQ,OAAO,cAAc,iBAAiB,qBAAqB;CAElF,MAAM,QAAe;EACnB;EACA;EACA;EACA,oBAAoB;EACpB,GAAI,iBAAiB,UAAa,eAAe,IAAI,EAAE,aAAa,IAAI,CAAC;EACzE,GAAI,oBAAoB,UAAa,kBAAkB,IAAI,EAAE,gBAAgB,IAAI,CAAC;EAClF,GAAI,qBAAqB,UAAa,mBAAmB,IAAI,EAAE,iBAAiB,IAAI,CAAC;CACvF;CAEA,MAAM,OAAO,YAAY,OAAO,OAAO;CAEvC,IAAI,MACF,MAAM,OAAO;CAGf,OAAO;AACT"}
|
package/esm/utils/index.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { mapFinishReason } from "./map-finish-reason.mjs";
|
|
|
5
5
|
import { buildPromptCacheParams } from "./prompt-cache-params.mjs";
|
|
6
6
|
import { toOpenAIReasoningEffort } from "./reasoning-effort.mjs";
|
|
7
7
|
import { inferStructuredOutput, planStructuredOutput } from "./structured-output.mjs";
|
|
8
|
-
import { RESPONSES_METADATA_KEY, attachReasoningReplay, pickReplayableReasoning, readReasoningReplay, toReplayReasoningItem } from "./reasoning-replay.mjs";
|
|
8
|
+
import { RESPONSES_METADATA_KEY, attachReasoningReplay, pickReplayableReasoning, pickTurnReasoning, readReasoningReplay, toReplayReasoningItem } from "./reasoning-replay.mjs";
|
|
9
9
|
import { toOpenAIMessages } from "./to-openai-messages.mjs";
|
|
10
10
|
import { toOpenAITools } from "./to-openai-tools.mjs";
|
|
11
11
|
import { toResponsesInput } from "./to-responses-input.mjs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"map-finish-reason.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"map-finish-reason.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/map-finish-reason.ts"],"sourcesContent":["import type { FinishReason } from \"@warlock.js/ai\";\n\nconst finishReasonMap: Record<string, FinishReason> = {\n stop: \"stop\",\n tool_calls: \"tool_calls\",\n length: \"length\",\n};\n\n/**\n * Map the raw OpenAI `finish_reason` string to the normalized FinishReason union.\n * Unknown/unexpected values fall through to \"error\".\n *\n * @example\n * mapFinishReason(\"stop\"); // \"stop\"\n * mapFinishReason(\"tool_calls\"); // \"tool_calls\"\n * mapFinishReason(null); // \"error\"\n */\nexport function mapFinishReason(raw: string | null | undefined): FinishReason {\n return finishReasonMap[raw ?? \"\"] ?? \"error\";\n}\n"],"mappings":";AAEA,MAAM,kBAAgD;CACpD,MAAM;CACN,YAAY;CACZ,QAAQ;AACV;;;;;;;;;;AAWA,SAAgB,gBAAgB,KAA8C;CAC5E,OAAO,gBAAgB,OAAO,OAAO;AACvC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { wrapOpenAIError } from "./wrap-openai-error.mjs";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region ../../packages/ai-openai/src/utils/map-responses-status.ts
|
|
4
4
|
/**
|
|
5
5
|
* Derive our `FinishReason` from a Responses terminal state. Responses has
|
|
6
6
|
* no `finish_reason`, so it comes from `status`, `incomplete_details` and the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"map-responses-status.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"map-responses-status.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/map-responses-status.ts"],"sourcesContent":["import type { AIError, FinishReason } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\nimport { wrapOpenAIError } from \"./wrap-openai-error\";\n\n/** The slice of a Responses `Response` the status mapper reads. */\nexport type ResponsesTerminalState = Pick<\n OpenAI.Responses.Response,\n \"status\" | \"incomplete_details\"\n> & {\n /** True when `output` holds at least one `function_call` item the model completed. */\n hasToolCalls: boolean;\n};\n\n/**\n * Derive our `FinishReason` from a Responses terminal state. Responses has\n * no `finish_reason`, so it comes from `status`, `incomplete_details` and the\n * output items (design section 2, decision 5):\n *\n * - `completed` with a function call -> `tool_calls`; without -> `stop`\n * (a refusal is ordinary text and also `stop`).\n * - `incomplete` / `max_output_tokens` and `max_messages` -> `length`.\n * - `incomplete` / `content_filter` and `steered` (or an unknown / missing\n * reason) -> `error`. There is no neutral `content_filter` value.\n * - `cancelled`, `queued`, `in_progress` at a terminal read -> `error`.\n * - `failed` is not mapped here: callers throw it via {@link toResponseFailure}.\n *\n * A missing `status` is treated as `completed` (the SDK types it optional).\n */\nexport function mapResponsesFinishReason(state: ResponsesTerminalState): FinishReason {\n const status = state.status ?? \"completed\";\n\n if (status === \"completed\") {\n return state.hasToolCalls ? \"tool_calls\" : \"stop\";\n }\n\n if (status === \"incomplete\") {\n const reason = state.incomplete_details?.reason;\n\n return reason === \"max_output_tokens\" || reason === \"max_messages\" ? \"length\" : \"error\";\n }\n\n return \"error\";\n}\n\n/**\n * Turn a `failed` Responses payload into the same typed `AIError` the Chat\n * path throws for a provider failure, by running it through\n * `wrapOpenAIError` (so `rate_limit_exceeded` becomes a\n * `ProviderRateLimitError`, everything else a `ProviderError`, with `code`\n * and request id kept on `context`). The response id and model are added so\n * the failure is traceable.\n */\nexport function toResponseFailure(response: OpenAI.Responses.Response, model: string): AIError {\n const error = response.error;\n const requestId = (response as { _request_id?: string | null })._request_id;\n\n const wrapped = wrapOpenAIError({\n code: error?.code,\n message: error?.message ?? \"OpenAI response failed without an error object.\",\n ...(requestId ? { request_id: requestId } : {}),\n });\n\n if (wrapped.context) {\n Object.assign(wrapped.context, { provider: \"openai\", model, responseId: response.id });\n }\n\n return wrapped;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,SAAgB,yBAAyB,OAA6C;CACpF,MAAM,SAAS,MAAM,UAAU;CAE/B,IAAI,WAAW,aACb,OAAO,MAAM,eAAe,eAAe;CAG7C,IAAI,WAAW,cAAc;EAC3B,MAAM,SAAS,MAAM,oBAAoB;EAEzC,OAAO,WAAW,uBAAuB,WAAW,iBAAiB,WAAW;CAClF;CAEA,OAAO;AACT;;;;;;;;;AAUA,SAAgB,kBAAkB,UAAqC,OAAwB;CAC7F,MAAM,QAAQ,SAAS;CACvB,MAAM,YAAa,SAA6C;CAEhE,MAAM,UAAU,gBAAgB;EAC9B,MAAM,OAAO;EACb,SAAS,OAAO,WAAW;EAC3B,GAAI,YAAY,EAAE,YAAY,UAAU,IAAI,CAAC;CAC/C,CAAC;CAED,IAAI,QAAQ,SACV,OAAO,OAAO,QAAQ,SAAS;EAAE,UAAU;EAAU;EAAO,YAAY,SAAS;CAAG,CAAC;CAGvF,OAAO;AACT"}
|
|
@@ -1,14 +1,33 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region ../../packages/ai-openai/src/utils/prompt-cache-params.ts
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* Provider labels whose OpenAI-compatible endpoint documents a
|
|
4
|
+
* `prompt_cache_key` request field:
|
|
5
|
+
*
|
|
6
|
+
* - `openai` — https://developers.openai.com/api/docs/guides/prompt-caching
|
|
7
|
+
* - `xai` — Chat Completions accepts `prompt_cache_key` ("plumbed to
|
|
8
|
+
* x-grok-conv-id"), https://docs.x.ai/openapi.json and
|
|
9
|
+
* https://docs.x.ai/developers/advanced-api-usage/prompt-caching/maximizing-cache-hits
|
|
10
|
+
* - `mistral` — https://docs.mistral.ai/studio/conversations/advanced/prompt-caching
|
|
11
|
+
*
|
|
12
|
+
* Groq and DeepSeek cache automatically and document no request hint, so
|
|
13
|
+
* they receive nothing (checked 2026-10-17).
|
|
14
|
+
*/
|
|
15
|
+
const PROMPT_CACHE_KEY_PROVIDERS = new Set([
|
|
16
|
+
"openai",
|
|
17
|
+
"xai",
|
|
18
|
+
"mistral"
|
|
19
|
+
]);
|
|
20
|
+
/**
|
|
21
|
+
* Build the prompt-cache request fields from the model config.
|
|
22
|
+
* `prompt_cache_key` is sent for the providers that document it
|
|
23
|
+
* ({@link PROMPT_CACHE_KEY_PROVIDERS}); `prompt_cache_retention` is
|
|
24
|
+
* OpenAI-only. Any other provider label — including a custom label on a
|
|
25
|
+
* wrapper SDK — gets neither, since an unknown endpoint may reject them.
|
|
6
26
|
*/
|
|
7
27
|
function buildPromptCacheParams(provider, config) {
|
|
8
|
-
if (provider !== "openai") return {};
|
|
9
28
|
return {
|
|
10
|
-
...config.promptCacheKey !== void 0 ? { prompt_cache_key: config.promptCacheKey } : {},
|
|
11
|
-
...config.promptCacheRetention !== void 0 ? { prompt_cache_retention: config.promptCacheRetention } : {}
|
|
29
|
+
...PROMPT_CACHE_KEY_PROVIDERS.has(provider) && config.promptCacheKey !== void 0 ? { prompt_cache_key: config.promptCacheKey } : {},
|
|
30
|
+
...provider === "openai" && config.promptCacheRetention !== void 0 ? { prompt_cache_retention: config.promptCacheRetention } : {}
|
|
12
31
|
};
|
|
13
32
|
}
|
|
14
33
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt-cache-params.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"prompt-cache-params.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/prompt-cache-params.ts"],"sourcesContent":["import type { OpenAIModelConfig } from \"../config.type\";\n\n/** The prompt-cache request fields common to Chat Completions and Responses. */\nexport type PromptCacheParams = {\n prompt_cache_key?: string;\n prompt_cache_retention?: NonNullable<OpenAIModelConfig[\"promptCacheRetention\"]>;\n};\n\n/**\n * Provider labels whose OpenAI-compatible endpoint documents a\n * `prompt_cache_key` request field:\n *\n * - `openai` — https://developers.openai.com/api/docs/guides/prompt-caching\n * - `xai` — Chat Completions accepts `prompt_cache_key` (\"plumbed to\n * x-grok-conv-id\"), https://docs.x.ai/openapi.json and\n * https://docs.x.ai/developers/advanced-api-usage/prompt-caching/maximizing-cache-hits\n * - `mistral` — https://docs.mistral.ai/studio/conversations/advanced/prompt-caching\n *\n * Groq and DeepSeek cache automatically and document no request hint, so\n * they receive nothing (checked 2026-10-17).\n */\nconst PROMPT_CACHE_KEY_PROVIDERS: ReadonlySet<string> = new Set([\"openai\", \"xai\", \"mistral\"]);\n\n/**\n * Build the prompt-cache request fields from the model config.\n * `prompt_cache_key` is sent for the providers that document it\n * ({@link PROMPT_CACHE_KEY_PROVIDERS}); `prompt_cache_retention` is\n * OpenAI-only. Any other provider label — including a custom label on a\n * wrapper SDK — gets neither, since an unknown endpoint may reject them.\n */\nexport function buildPromptCacheParams(\n provider: string,\n config: Pick<OpenAIModelConfig, \"promptCacheKey\" | \"promptCacheRetention\">,\n): PromptCacheParams {\n const sendsKey = PROMPT_CACHE_KEY_PROVIDERS.has(provider);\n\n return {\n ...(sendsKey && config.promptCacheKey !== undefined\n ? { prompt_cache_key: config.promptCacheKey }\n : {}),\n ...(provider === \"openai\" && config.promptCacheRetention !== undefined\n ? { prompt_cache_retention: config.promptCacheRetention }\n : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAqBA,MAAM,6BAAkD,IAAI,IAAI;CAAC;CAAU;CAAO;AAAS,CAAC;;;;;;;;AAS5F,SAAgB,uBACd,UACA,QACmB;CAGnB,OAAO;EACL,GAHe,2BAA2B,IAAI,QAGnC,KAAK,OAAO,mBAAmB,SACtC,EAAE,kBAAkB,OAAO,eAAe,IAC1C,CAAC;EACL,GAAI,aAAa,YAAY,OAAO,yBAAyB,SACzD,EAAE,wBAAwB,OAAO,qBAAqB,IACtD,CAAC;CACP;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reasoning-effort.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"reasoning-effort.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/reasoning-effort.ts"],"sourcesContent":["import type { ReasoningEffort } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\n\n/** The effort strings the OpenAI wire accepts (shared by Chat Completions and Responses). */\nexport type OpenAIReasoningEffort = NonNullable<\n OpenAI.Chat.Completions.ChatCompletionCreateParams[\"reasoning_effort\"]\n>;\n\n/**\n * The installed OpenAI SDK 7.23.0 declares `reasoning_effort` as\n * `none | minimal | low | medium | high | xhigh | max` in\n * `openai/src/resources/shared.ts:367`. Its type notes that model support\n * varies but does not provide a model-family-specific accepted set, so map by\n * that union alone. This exhaustive record makes a future core level a\n * typecheck failure until its OpenAI clamp is consciously selected.\n *\n * Both the Chat Completions adapter (`reasoning_effort`) and the Responses\n * adapter (`reasoning.effort`) read this one table, so the two can never\n * disagree on how a neutral level reaches the wire.\n */\nconst EFFORT_TO_OPENAI_EFFORT: Record<ReasoningEffort, OpenAIReasoningEffort> = {\n none: \"none\",\n minimal: \"minimal\",\n low: \"low\",\n medium: \"medium\",\n high: \"high\",\n xhigh: \"xhigh\",\n max: \"max\",\n};\n\n/**\n * Map a neutral `ReasoningEffort` to the value OpenAI accepts.\n *\n * @example\n * toOpenAIReasoningEffort(\"high\"); // \"high\"\n */\nexport function toOpenAIReasoningEffort(effort: ReasoningEffort): OpenAIReasoningEffort {\n return EFFORT_TO_OPENAI_EFFORT[effort];\n}\n"],"mappings":";;;;;;;;;;;;;AAoBA,MAAM,0BAA0E;CAC9E,MAAM;CACN,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MAAM;CACN,OAAO;CACP,KAAK;AACP;;;;;;;AAQA,SAAgB,wBAAwB,QAAgD;CACtF,OAAO,wBAAwB;AACjC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region ../../packages/ai-openai/src/utils/reasoning-replay.ts
|
|
2
2
|
/**
|
|
3
3
|
* Key under `ModelToolCallRequest.providerMetadata` owned by the Responses
|
|
4
4
|
* adapter. This name and the shape below are PERSISTED in users' conversation
|
|
@@ -14,6 +14,28 @@ const RESPONSES_METADATA_KEY = "openaiResponses";
|
|
|
14
14
|
function pickReplayableReasoning(items) {
|
|
15
15
|
return items.filter((item) => typeof item.encrypted_content === "string" && item.encrypted_content !== "");
|
|
16
16
|
}
|
|
17
|
+
/** Output item types that may follow a replayed reasoning item. */
|
|
18
|
+
const REPLAY_SAFE_FOLLOWERS = new Set(["function_call", "message"]);
|
|
19
|
+
/**
|
|
20
|
+
* The reasoning items of a turn that are safe to replay, in order.
|
|
21
|
+
*
|
|
22
|
+
* The API pairs a reasoning item with the output item that followed it and
|
|
23
|
+
* rejects a replayed reasoning item whose follower is missing. Only
|
|
24
|
+
* `function_call` items are replayed, so a reasoning item that led into a
|
|
25
|
+
* hosted (server-run) tool call — `web_search_call`, `file_search_call`,
|
|
26
|
+
* `code_interpreter_call`, … from a provider-defined tool — is dropped
|
|
27
|
+
* rather than sent without its follower. Encrypted reasoning only improves
|
|
28
|
+
* continuity; dropping it never breaks the request.
|
|
29
|
+
*/
|
|
30
|
+
function pickTurnReasoning(output) {
|
|
31
|
+
const picked = [];
|
|
32
|
+
output.forEach((item, index) => {
|
|
33
|
+
if (item.type !== "reasoning") return;
|
|
34
|
+
const follower = output.slice(index + 1).find((next) => next.type !== "reasoning");
|
|
35
|
+
if (follower === void 0 || REPLAY_SAFE_FOLLOWERS.has(follower.type)) picked.push(item);
|
|
36
|
+
});
|
|
37
|
+
return picked;
|
|
38
|
+
}
|
|
17
39
|
/**
|
|
18
40
|
* Attach the turn's reasoning items to the FIRST tool call only (parallel
|
|
19
41
|
* calls do not each repeat the blobs). Returns the calls unchanged when
|
|
@@ -81,5 +103,5 @@ function isReplayMetadata(value) {
|
|
|
81
103
|
}
|
|
82
104
|
|
|
83
105
|
//#endregion
|
|
84
|
-
export { RESPONSES_METADATA_KEY, attachReasoningReplay, pickReplayableReasoning, readReasoningReplay, toReplayReasoningItem };
|
|
106
|
+
export { RESPONSES_METADATA_KEY, attachReasoningReplay, pickReplayableReasoning, pickTurnReasoning, readReasoningReplay, toReplayReasoningItem };
|
|
85
107
|
//# sourceMappingURL=reasoning-replay.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reasoning-replay.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"reasoning-replay.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/reasoning-replay.ts"],"sourcesContent":["import type { ModelToolCallRequest } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\n\n/** A `reasoning` output item as the Responses API returns it. */\nexport type ResponsesReasoningItem = OpenAI.Responses.ResponseReasoningItem;\n\n/**\n * Key under `ModelToolCallRequest.providerMetadata` owned by the Responses\n * adapter. This name and the shape below are PERSISTED in users' conversation\n * memory, so they are part of the public contract: do not rename.\n */\nexport const RESPONSES_METADATA_KEY = \"openaiResponses\";\n\n/**\n * What the Responses adapter stores on the FIRST tool call of an assistant\n * turn so the next request can replay the model's reasoning (design\n * section 4, decisions 2 and 3).\n */\nexport type ResponsesReplayMetadata = {\n /** Model the items were produced by; replay is skipped when it differs. */\n model: string;\n /** Reasoning items of the turn, in the order the API emitted them. */\n reasoningItems: ResponsesReasoningItem[];\n};\n\n/**\n * Keep only the reasoning items that can actually be replayed. With\n * `store: false` the server keeps nothing, so an item without\n * `encrypted_content` has nothing to restore and replaying its bare `id`\n * would be rejected as an unknown item.\n */\nexport function pickReplayableReasoning(\n items: readonly ResponsesReasoningItem[],\n): ResponsesReasoningItem[] {\n return items.filter(\n (item) => typeof item.encrypted_content === \"string\" && item.encrypted_content !== \"\",\n );\n}\n\n/** Output item types that may follow a replayed reasoning item. */\nconst REPLAY_SAFE_FOLLOWERS: ReadonlySet<string> = new Set([\"function_call\", \"message\"]);\n\n/**\n * The reasoning items of a turn that are safe to replay, in order.\n *\n * The API pairs a reasoning item with the output item that followed it and\n * rejects a replayed reasoning item whose follower is missing. Only\n * `function_call` items are replayed, so a reasoning item that led into a\n * hosted (server-run) tool call — `web_search_call`, `file_search_call`,\n * `code_interpreter_call`, … from a provider-defined tool — is dropped\n * rather than sent without its follower. Encrypted reasoning only improves\n * continuity; dropping it never breaks the request.\n */\nexport function pickTurnReasoning(\n output: ReadonlyArray<{ type: string }>,\n): ResponsesReasoningItem[] {\n const picked: ResponsesReasoningItem[] = [];\n\n output.forEach((item, index) => {\n if (item.type !== \"reasoning\") {\n return;\n }\n\n const follower = output.slice(index + 1).find((next) => next.type !== \"reasoning\");\n\n if (follower === undefined || REPLAY_SAFE_FOLLOWERS.has(follower.type)) {\n picked.push(item as ResponsesReasoningItem);\n }\n });\n\n return picked;\n}\n\n/**\n * Attach the turn's reasoning items to the FIRST tool call only (parallel\n * calls do not each repeat the blobs). Returns the calls unchanged when\n * there is nothing to replay or no tool call to ride on (a text-only turn is\n * deliberately not replayed, decision 2). Does not mutate its input.\n */\nexport function attachReasoningReplay(\n toolCalls: readonly ModelToolCallRequest[],\n model: string,\n reasoningItems: readonly ResponsesReasoningItem[],\n): ModelToolCallRequest[] {\n const replayable = pickReplayableReasoning(reasoningItems);\n const [first, ...rest] = toolCalls;\n\n if (first === undefined || replayable.length === 0) {\n return [...toolCalls];\n }\n\n const metadata: ResponsesReplayMetadata = { model, reasoningItems: replayable };\n\n return [\n {\n ...first,\n providerMetadata: { ...first.providerMetadata, [RESPONSES_METADATA_KEY]: metadata },\n },\n ...rest,\n ];\n}\n\n/**\n * Read the stored reasoning items off an assistant turn's tool calls, for\n * replay on `model`. Returns `[]` when the key is absent or malformed, or\n * when the stored `model` differs from `model` (encrypted blobs are not\n * portable across models, design section 4). De-duplicates by item `id`.\n */\nexport function readReasoningReplay(\n toolCalls: readonly ModelToolCallRequest[],\n model: string,\n): ResponsesReasoningItem[] {\n const seen = new Set<string>();\n const items: ResponsesReasoningItem[] = [];\n\n for (const call of toolCalls) {\n const stored = call.providerMetadata?.[RESPONSES_METADATA_KEY];\n\n if (!isReplayMetadata(stored) || stored.model !== model) {\n continue;\n }\n\n for (const item of stored.reasoningItems) {\n if (item?.type !== \"reasoning\" || seen.has(item.id)) {\n continue;\n }\n\n seen.add(item.id);\n items.push(item);\n }\n }\n\n return items;\n}\n\n/**\n * Shape a stored reasoning item for the next request. Sends the four fields\n * a stateless replay needs (`type`, `id`, `summary`, `encrypted_content`) and\n * drops the response-only `status` and the optional raw `content`.\n *\n * UNVERIFIED: the SDK types accept the full item as input (`ResponseInputItem`\n * includes `ResponseReasoningItem`) and do not say which fields the API\n * refuses on replay with `store: false`. This is the conservative guess; a\n * live probe settles it.\n */\nexport function toReplayReasoningItem(item: ResponsesReasoningItem): ResponsesReasoningItem {\n return {\n type: \"reasoning\",\n id: item.id,\n summary: Array.isArray(item.summary) ? item.summary : [],\n encrypted_content: item.encrypted_content,\n };\n}\n\nfunction isReplayMetadata(value: unknown): value is ResponsesReplayMetadata {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const candidate = value as Partial<ResponsesReplayMetadata>;\n\n return typeof candidate.model === \"string\" && Array.isArray(candidate.reasoningItems);\n}\n"],"mappings":";;;;;;AAWA,MAAa,yBAAyB;;;;;;;AAoBtC,SAAgB,wBACd,OAC0B;CAC1B,OAAO,MAAM,QACV,SAAS,OAAO,KAAK,sBAAsB,YAAY,KAAK,sBAAsB,EACrF;AACF;;AAGA,MAAM,wBAA6C,IAAI,IAAI,CAAC,iBAAiB,SAAS,CAAC;;;;;;;;;;;;AAavF,SAAgB,kBACd,QAC0B;CAC1B,MAAM,SAAmC,CAAC;CAE1C,OAAO,SAAS,MAAM,UAAU;EAC9B,IAAI,KAAK,SAAS,aAChB;EAGF,MAAM,WAAW,OAAO,MAAM,QAAQ,CAAC,CAAC,CAAC,MAAM,SAAS,KAAK,SAAS,WAAW;EAEjF,IAAI,aAAa,UAAa,sBAAsB,IAAI,SAAS,IAAI,GACnE,OAAO,KAAK,IAA8B;CAE9C,CAAC;CAED,OAAO;AACT;;;;;;;AAQA,SAAgB,sBACd,WACA,OACA,gBACwB;CACxB,MAAM,aAAa,wBAAwB,cAAc;CACzD,MAAM,CAAC,OAAO,GAAG,QAAQ;CAEzB,IAAI,UAAU,UAAa,WAAW,WAAW,GAC/C,OAAO,CAAC,GAAG,SAAS;CAGtB,MAAM,WAAoC;EAAE;EAAO,gBAAgB;CAAW;CAE9E,OAAO,CACL;EACE,GAAG;EACH,kBAAkB;GAAE,GAAG,MAAM;IAAmB,yBAAyB;EAAS;CACpF,GACA,GAAG,IACL;AACF;;;;;;;AAQA,SAAgB,oBACd,WACA,OAC0B;CAC1B,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,QAAkC,CAAC;CAEzC,KAAK,MAAM,QAAQ,WAAW;EAC5B,MAAM,SAAS,KAAK,mBAAmB;EAEvC,IAAI,CAAC,iBAAiB,MAAM,KAAK,OAAO,UAAU,OAChD;EAGF,KAAK,MAAM,QAAQ,OAAO,gBAAgB;GACxC,IAAI,MAAM,SAAS,eAAe,KAAK,IAAI,KAAK,EAAE,GAChD;GAGF,KAAK,IAAI,KAAK,EAAE;GAChB,MAAM,KAAK,IAAI;EACjB;CACF;CAEA,OAAO;AACT;;;;;;;;;;;AAYA,SAAgB,sBAAsB,MAAsD;CAC1F,OAAO;EACL,MAAM;EACN,IAAI,KAAK;EACT,SAAS,MAAM,QAAQ,KAAK,OAAO,IAAI,KAAK,UAAU,CAAC;EACvD,mBAAmB,KAAK;CAC1B;AACF;AAEA,SAAS,iBAAiB,OAAkD;CAC1E,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAGT,MAAM,YAAY;CAElB,OAAO,OAAO,UAAU,UAAU,YAAY,MAAM,QAAQ,UAAU,cAAc;AACtF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"structured-output.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"structured-output.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/structured-output.ts"],"sourcesContent":["import type { OpenAIResponseFormat } from \"../config.type\";\n\n/**\n * How a `responseSchema` should reach the wire, decided once for both the\n * Chat Completions adapter (`response_format`) and the Responses adapter\n * (`text.format`). Only the wire location differs between the two.\n */\nexport type StructuredOutputPlan =\n | { mode: \"none\" }\n | { mode: \"json_object\" }\n | { mode: \"json_schema\"; schema: Record<string, unknown> };\n\n/**\n * Map an explicit `responseFormat` override to the default\n * `structuredOutput` capability. Loose wire modes (`\"json_object\"`,\n * `\"text\"`) don't enforce shape, so the agent needs to see the soft\n * schema hint in the system prompt — that only happens when the\n * capability is `false`. Default (no override) stays `true` to\n * preserve the prior assumption that OpenAI models support strict\n * structured output.\n */\nexport function inferStructuredOutput(responseFormat: OpenAIResponseFormat | undefined): boolean {\n if (responseFormat === \"json_object\" || responseFormat === \"text\") {\n return false;\n }\n\n return true;\n}\n\n/**\n * Decide the structured-output mode for a call.\n *\n * When `override` (the `responseFormat` config) is set, it wins: `\"text\"`\n * emits nothing, `\"json_object\"` always picks the loose mode, and\n * `\"json_schema\"` picks strict mode (with the same strict-compatibility\n * safety check - a malformed schema still degrades to `json_object` rather\n * than 400). The override exists because some targets (older OpenAI models,\n * OpenRouter routes, Ollama OpenAI-compat) reject strict `json_schema`\n * outright.\n *\n * When the override is omitted, strict `json_schema` mode (token-level\n * enforcement) is used only when the schema is a proper root-object JSON\n * Schema whose every object lists all of its properties in `required`. For\n * anything else it falls back to loose `json_object` mode. Client-side\n * Standard Schema `validate()` still enforces the full shape.\n */\nexport function planStructuredOutput(\n responseSchema: Record<string, unknown> | undefined,\n override: OpenAIResponseFormat | undefined,\n): StructuredOutputPlan {\n if (!responseSchema || override === \"text\") {\n return { mode: \"none\" };\n }\n\n if (override === \"json_object\") {\n return { mode: \"json_object\" };\n }\n\n // Either auto-select (no override) or explicit `\"json_schema\"`. The\n // strict-compat check still applies in the explicit case - a malformed or\n // non-object schema would 400 before sampling, so degrade to `json_object`.\n if (isStrictCompatible(responseSchema)) {\n return { mode: \"json_schema\", schema: responseSchema };\n }\n\n return { mode: \"json_object\" };\n}\n\n/**\n * OpenAI strict `json_schema` mode requires the root to be a JSON Schema\n * object type (`{ type: \"object\", properties: ... }`). Anything else\n * (top-level arrays, primitives, unknown shapes) is rejected with a 400\n * before a token is sampled. Checked structurally here so the first call\n * doesn't crash on a malformed extraction.\n */\nexport function isStrictCompatible(schema: Record<string, unknown>): boolean {\n return (\n schema.type === \"object\" &&\n typeof schema.properties === \"object\" &&\n schema.properties !== null &&\n isStrictSafeNode(schema)\n );\n}\n\n/**\n * Recursively check the one strict-mode rule schemas most often trip on:\n * every object must list ALL of its `properties` in `required` (OpenAI\n * strict has no notion of optional - optional fields must be expressed as\n * nullable, e.g. `type: [\"string\", \"null\"]`, and still appear in\n * `required`). A schema that violates this anywhere in the tree is NOT sent\n * in strict mode, so a hand-built or optional-bearing schema can't 400 the\n * call (\"'required' ... must include every key in properties\").\n */\nfunction isStrictSafeNode(node: unknown): boolean {\n if (!node || typeof node !== \"object\") {\n return true;\n }\n\n const record = node as Record<string, unknown>;\n\n if (record.type === \"object\" && record.properties && typeof record.properties === \"object\") {\n const properties = record.properties as Record<string, unknown>;\n const keys = Object.keys(properties);\n const required = Array.isArray(record.required) ? (record.required as unknown[]) : [];\n\n if (keys.some((key) => !required.includes(key))) {\n return false;\n }\n\n for (const key of keys) {\n if (!isStrictSafeNode(properties[key])) {\n return false;\n }\n }\n }\n\n if (record.items !== undefined && !isStrictSafeNode(record.items)) {\n return false;\n }\n\n for (const branch of [\"anyOf\", \"allOf\", \"oneOf\"] as const) {\n const value = record[branch];\n\n if (Array.isArray(value) && value.some((sub) => !isStrictSafeNode(sub))) {\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;AAqBA,SAAgB,sBAAsB,gBAA2D;CAC/F,IAAI,mBAAmB,iBAAiB,mBAAmB,QACzD,OAAO;CAGT,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,qBACd,gBACA,UACsB;CACtB,IAAI,CAAC,kBAAkB,aAAa,QAClC,OAAO,EAAE,MAAM,OAAO;CAGxB,IAAI,aAAa,eACf,OAAO,EAAE,MAAM,cAAc;CAM/B,IAAI,mBAAmB,cAAc,GACnC,OAAO;EAAE,MAAM;EAAe,QAAQ;CAAe;CAGvD,OAAO,EAAE,MAAM,cAAc;AAC/B;;;;;;;;AASA,SAAgB,mBAAmB,QAA0C;CAC3E,OACE,OAAO,SAAS,YAChB,OAAO,OAAO,eAAe,YAC7B,OAAO,eAAe,QACtB,iBAAiB,MAAM;AAE3B;;;;;;;;;;AAWA,SAAS,iBAAiB,MAAwB;CAChD,IAAI,CAAC,QAAQ,OAAO,SAAS,UAC3B,OAAO;CAGT,MAAM,SAAS;CAEf,IAAI,OAAO,SAAS,YAAY,OAAO,cAAc,OAAO,OAAO,eAAe,UAAU;EAC1F,MAAM,aAAa,OAAO;EAC1B,MAAM,OAAO,OAAO,KAAK,UAAU;EACnC,MAAM,WAAW,MAAM,QAAQ,OAAO,QAAQ,IAAK,OAAO,WAAyB,CAAC;EAEpF,IAAI,KAAK,MAAM,QAAQ,CAAC,SAAS,SAAS,GAAG,CAAC,GAC5C,OAAO;EAGT,KAAK,MAAM,OAAO,MAChB,IAAI,CAAC,iBAAiB,WAAW,IAAI,GACnC,OAAO;CAGb;CAEA,IAAI,OAAO,UAAU,UAAa,CAAC,iBAAiB,OAAO,KAAK,GAC9D,OAAO;CAGT,KAAK,MAAM,UAAU;EAAC;EAAS;EAAS;CAAO,GAAY;EACzD,MAAM,QAAQ,OAAO;EAErB,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAM,QAAQ,CAAC,iBAAiB,GAAG,CAAC,GACpE,OAAO;CAEX;CAEA,OAAO;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { InvalidRequestError } from "@warlock.js/ai";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region ../../packages/ai-openai/src/utils/to-openai-messages.ts
|
|
4
4
|
/**
|
|
5
5
|
* Convert vendor-neutral Message[] to OpenAI's chat message shape.
|
|
6
6
|
* Handles the `tool` role (requires `tool_call_id`) and assistant messages
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"to-openai-messages.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"to-openai-messages.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/to-openai-messages.ts"],"sourcesContent":["import { InvalidRequestError, type ContentPart, type Message } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\n\n/**\n * Convert vendor-neutral Message[] to OpenAI's chat message shape.\n * Handles the `tool` role (requires `tool_call_id`) and assistant messages\n * that carry `toolCalls` from a prior model response.\n *\n * Multipart `content` (a `ContentPart[]`) is mapped into OpenAI's user-message\n * content-parts shape: text becomes `{ type: \"text\", text }`, images become\n * `{ type: \"image_url\", image_url: { url } }` — with base64 sources rendered\n * as `data:` URLs inline.\n *\n * @example\n * const openaiMessages = toOpenAIMessages([\n * { role: \"user\", content: \"Hi\" },\n * { role: \"tool\", toolCallId: \"call_1\", content: '{\"ok\":true}' },\n * ]);\n *\n * @example\n * toOpenAIMessages([\n * { role: \"user\", content: [\n * { type: \"text\", text: \"What is this?\" },\n * { type: \"image\", source: { url: \"https://example.com/cat.jpg\" } },\n * ]},\n * ]);\n */\nexport function toOpenAIMessages(\n messages: Message[],\n cacheBreakpoints: number = 0,\n): OpenAI.Chat.Completions.ChatCompletionMessageParam[] {\n const mapped = messages.map((m) => {\n if (m.role === \"tool\") {\n return {\n role: \"tool\",\n content: stringifyContent(m.content),\n tool_call_id: m.toolCallId ?? \"\",\n } satisfies OpenAI.Chat.Completions.ChatCompletionToolMessageParam;\n }\n if (m.role === \"assistant\" && m.toolCalls && m.toolCalls.length > 0) {\n return {\n role: \"assistant\",\n content: stringifyContent(m.content),\n tool_calls: m.toolCalls.map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: { name: tc.name, arguments: JSON.stringify(tc.input ?? {}) },\n })),\n } satisfies OpenAI.Chat.Completions.ChatCompletionAssistantMessageParam;\n }\n\n if (m.role === \"user\" && Array.isArray(m.content)) {\n return {\n role: \"user\",\n content: m.content.map(toOpenAIContentPart),\n } satisfies OpenAI.Chat.Completions.ChatCompletionUserMessageParam;\n }\n\n return { role: m.role, content: stringifyContent(m.content) } as\n | OpenAI.Chat.Completions.ChatCompletionUserMessageParam\n | OpenAI.Chat.Completions.ChatCompletionSystemMessageParam\n | OpenAI.Chat.Completions.ChatCompletionAssistantMessageParam;\n });\n\n return addPromptCacheBreakpoints(mapped, cacheBreakpoints);\n}\n\n/** Place explicit markers on the last requested user-content parts (maximum four). */\nfunction addPromptCacheBreakpoints(\n messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],\n requested: number,\n): OpenAI.Chat.Completions.ChatCompletionMessageParam[] {\n let remaining = Math.min(4, Math.max(0, Math.floor(requested)));\n if (remaining === 0) return messages;\n\n const marked = [...messages];\n for (let index = marked.length - 1; index >= 0 && remaining > 0; index--) {\n const message = marked[index];\n if (message === undefined || message.role !== \"user\") continue;\n\n if (typeof message.content === \"string\") {\n marked[index] = {\n ...message,\n content: [\n { type: \"text\", text: message.content, prompt_cache_breakpoint: { mode: \"explicit\" } },\n ],\n };\n remaining--;\n continue;\n }\n\n const content = [...message.content];\n for (let partIndex = content.length - 1; partIndex >= 0 && remaining > 0; partIndex--) {\n const part = content[partIndex];\n if (part === undefined) continue;\n content[partIndex] = { ...part, prompt_cache_breakpoint: { mode: \"explicit\" } };\n remaining--;\n }\n marked[index] = { ...message, content };\n }\n\n return marked;\n}\n\n/**\n * Multipart content is only meaningful on user messages — for any other\n * role (system / assistant text / tool), collapse a `ContentPart[]` to\n * its concatenated text so OpenAI's wire format stays valid. Plain\n * strings pass through unchanged.\n */\nexport function stringifyContent(content: string | ContentPart[]): string {\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .filter((part): part is { type: \"text\"; text: string } => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n}\n\n/**\n * Map a resolved `ContentPart` to an OpenAI chat content part — one\n * branch per modality, each to its real wire shape:\n *\n * - `text` → `{ type: \"text\" }`.\n * - `image` → `{ type: \"image_url\" }` (remote URL, or a `data:` URL for\n * inlined base64 bytes).\n * - `pdf` → `{ type: \"file\", file: { file_data } }` (OpenAI document\n * input; base64 only — there is no remote-URL file source).\n * - `audio` → `{ type: \"input_audio\", input_audio: { data, format } }`\n * (base64 only; `wav` / `mp3` are the only formats OpenAI accepts).\n *\n * PDF and audio reach this point ONLY when the model declared the\n * matching capability (`openai.model({ name, pdf: true })` /\n * `{ audio: true }`) — the agent's modality gate throws upfront\n * otherwise, so capability and behavior stay in lockstep. A remote-URL\n * pdf/audio source raises a typed `InvalidRequestError` here rather\n * than a downstream provider fault.\n */\nfunction toOpenAIContentPart(part: ContentPart): OpenAI.Chat.Completions.ChatCompletionContentPart {\n if (part.type === \"text\") {\n return { type: \"text\", text: part.text };\n }\n\n if (part.type === \"image\") {\n return { type: \"image_url\", image_url: { url: toImageUrl(part.source) } };\n }\n\n if (part.type === \"pdf\") {\n if (\"url\" in part.source) {\n throw new InvalidRequestError(\n \"OpenAI chat completions cannot fetch a remote-URL PDF; supply base64 document bytes instead.\",\n );\n }\n\n return {\n type: \"file\",\n file: {\n filename: \"document.pdf\",\n file_data: `data:${part.source.mediaType};base64,${part.source.base64}`,\n },\n };\n }\n\n // Audio — the remaining `ContentPart` variant.\n if (\"url\" in part.source) {\n throw new InvalidRequestError(\n \"OpenAI chat completions cannot fetch remote-URL audio; supply base64 audio bytes instead.\",\n );\n }\n\n return {\n type: \"input_audio\",\n input_audio: {\n data: part.source.base64,\n format: toOpenAIAudioFormat(part.source.mediaType),\n },\n };\n}\n\n/**\n * Render an image source as a URL: a remote URL passes through, inlined\n * base64 bytes become a `data:` URL. Shared with the Responses adapter.\n */\nexport function toImageUrl(source: Extract<ContentPart, { type: \"image\" }>[\"source\"]): string {\n return \"url\" in source ? source.url : `data:${source.mediaType};base64,${source.base64}`;\n}\n\n/**\n * Narrow a neutral audio media type to the two formats OpenAI's\n * `input_audio` accepts (`wav` / `mp3`). An unsupported type raises a\n * typed `InvalidRequestError` up front rather than a provider 400.\n */\nfunction toOpenAIAudioFormat(mediaType: string): \"wav\" | \"mp3\" {\n if (mediaType === \"audio/wav\" || mediaType === \"audio/x-wav\" || mediaType === \"audio/wave\") {\n return \"wav\";\n }\n\n if (mediaType === \"audio/mp3\" || mediaType === \"audio/mpeg\" || mediaType === \"audio/mpga\") {\n return \"mp3\";\n }\n\n throw new InvalidRequestError(\n `OpenAI input_audio supports only \"wav\" and \"mp3\"; got \"${mediaType}\".`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,iBACd,UACA,mBAA2B,GAC2B;CAkCtD,OAAO,0BAjCQ,SAAS,KAAK,MAAM;EACjC,IAAI,EAAE,SAAS,QACb,OAAO;GACL,MAAM;GACN,SAAS,iBAAiB,EAAE,OAAO;GACnC,cAAc,EAAE,cAAc;EAChC;EAEF,IAAI,EAAE,SAAS,eAAe,EAAE,aAAa,EAAE,UAAU,SAAS,GAChE,OAAO;GACL,MAAM;GACN,SAAS,iBAAiB,EAAE,OAAO;GACnC,YAAY,EAAE,UAAU,KAAK,QAAQ;IACnC,IAAI,GAAG;IACP,MAAM;IACN,UAAU;KAAE,MAAM,GAAG;KAAM,WAAW,KAAK,UAAU,GAAG,SAAS,CAAC,CAAC;IAAE;GACvE,EAAE;EACJ;EAGF,IAAI,EAAE,SAAS,UAAU,MAAM,QAAQ,EAAE,OAAO,GAC9C,OAAO;GACL,MAAM;GACN,SAAS,EAAE,QAAQ,IAAI,mBAAmB;EAC5C;EAGF,OAAO;GAAE,MAAM,EAAE;GAAM,SAAS,iBAAiB,EAAE,OAAO;EAAE;CAI9D,CAEsC,GAAG,gBAAgB;AAC3D;;AAGA,SAAS,0BACP,UACA,WACsD;CACtD,IAAI,YAAY,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,CAAC,CAAC;CAC9D,IAAI,cAAc,GAAG,OAAO;CAE5B,MAAM,SAAS,CAAC,GAAG,QAAQ;CAC3B,KAAK,IAAI,QAAQ,OAAO,SAAS,GAAG,SAAS,KAAK,YAAY,GAAG,SAAS;EACxE,MAAM,UAAU,OAAO;EACvB,IAAI,YAAY,UAAa,QAAQ,SAAS,QAAQ;EAEtD,IAAI,OAAO,QAAQ,YAAY,UAAU;GACvC,OAAO,SAAS;IACd,GAAG;IACH,SAAS,CACP;KAAE,MAAM;KAAQ,MAAM,QAAQ;KAAS,yBAAyB,EAAE,MAAM,WAAW;IAAE,CACvF;GACF;GACA;GACA;EACF;EAEA,MAAM,UAAU,CAAC,GAAG,QAAQ,OAAO;EACnC,KAAK,IAAI,YAAY,QAAQ,SAAS,GAAG,aAAa,KAAK,YAAY,GAAG,aAAa;GACrF,MAAM,OAAO,QAAQ;GACrB,IAAI,SAAS,QAAW;GACxB,QAAQ,aAAa;IAAE,GAAG;IAAM,yBAAyB,EAAE,MAAM,WAAW;GAAE;GAC9E;EACF;EACA,OAAO,SAAS;GAAE,GAAG;GAAS;EAAQ;CACxC;CAEA,OAAO;AACT;;;;;;;AAQA,SAAgB,iBAAiB,SAAyC;CACxE,IAAI,OAAO,YAAY,UACrB,OAAO;CAGT,OAAO,QACJ,QAAQ,SAAiD,KAAK,SAAS,MAAM,CAAC,CAC9E,KAAK,SAAS,KAAK,IAAI,CAAC,CACxB,KAAK,EAAE;AACZ;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,oBAAoB,MAAsE;CACjG,IAAI,KAAK,SAAS,QAChB,OAAO;EAAE,MAAM;EAAQ,MAAM,KAAK;CAAK;CAGzC,IAAI,KAAK,SAAS,SAChB,OAAO;EAAE,MAAM;EAAa,WAAW,EAAE,KAAK,WAAW,KAAK,MAAM,EAAE;CAAE;CAG1E,IAAI,KAAK,SAAS,OAAO;EACvB,IAAI,SAAS,KAAK,QAChB,MAAM,IAAI,oBACR,8FACF;EAGF,OAAO;GACL,MAAM;GACN,MAAM;IACJ,UAAU;IACV,WAAW,QAAQ,KAAK,OAAO,UAAU,UAAU,KAAK,OAAO;GACjE;EACF;CACF;CAGA,IAAI,SAAS,KAAK,QAChB,MAAM,IAAI,oBACR,2FACF;CAGF,OAAO;EACL,MAAM;EACN,aAAa;GACX,MAAM,KAAK,OAAO;GAClB,QAAQ,oBAAoB,KAAK,OAAO,SAAS;EACnD;CACF;AACF;;;;;AAMA,SAAgB,WAAW,QAAmE;CAC5F,OAAO,SAAS,SAAS,OAAO,MAAM,QAAQ,OAAO,UAAU,UAAU,OAAO;AAClF;;;;;;AAOA,SAAS,oBAAoB,WAAkC;CAC7D,IAAI,cAAc,eAAe,cAAc,iBAAiB,cAAc,cAC5E,OAAO;CAGT,IAAI,cAAc,eAAe,cAAc,gBAAgB,cAAc,cAC3E,OAAO;CAGT,MAAM,IAAI,oBACR,0DAA0D,UAAU,GACtE;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { extractJsonSchema } from "@warlock.js/ai";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region ../../packages/ai-openai/src/utils/to-openai-tools.ts
|
|
4
4
|
/**
|
|
5
5
|
* Convert vendor-neutral ToolConfig[] to OpenAI's tools array.
|
|
6
6
|
* Uses the shared `extractJsonSchema` helper; falls back to an empty-object
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"to-openai-tools.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"to-openai-tools.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/to-openai-tools.ts"],"sourcesContent":["import { extractJsonSchema, type ToolConfig } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\n\n/**\n * Convert vendor-neutral ToolConfig[] to OpenAI's tools array.\n * Uses the shared `extractJsonSchema` helper; falls back to an empty-object\n * schema when extraction fails so the tool still registers with the provider.\n *\n * @example\n * const tools = toOpenAITools([weatherTool, calculatorTool]);\n * await client.chat.completions.create({ model, messages, tools });\n */\nexport function toOpenAITools(\n tools: ToolConfig<unknown, unknown>[] | undefined,\n): OpenAI.Chat.Completions.ChatCompletionTool[] | undefined {\n if (!tools || tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: toToolParameters(tool.input),\n },\n }));\n}\n\n/**\n * Resolve a tool's input schema to a JSON-Schema object. OpenAI's\n * function `parameters` expects an object root; anything else (or a\n * failed extraction) degrades to an empty-object schema so the tool\n * still registers and the model simply sees no parameters.\n */\nexport function toToolParameters(\n input: ToolConfig<unknown, unknown>[\"input\"],\n): Record<string, unknown> {\n const schema = extractJsonSchema(input);\n\n if (schema && schema.type === \"object\") {\n return schema;\n }\n\n return { type: \"object\", properties: {} };\n}\n"],"mappings":";;;;;;;;;;;;AAYA,SAAgB,cACd,OAC0D;CAC1D,IAAI,CAAC,SAAS,MAAM,WAAW,GAC7B;CAGF,OAAO,MAAM,KAAK,UAAU;EAC1B,MAAM;EACN,UAAU;GACR,MAAM,KAAK;GACX,aAAa,KAAK;GAClB,YAAY,iBAAiB,KAAK,KAAK;EACzC;CACF,EAAE;AACJ;;;;;;;AAQA,SAAgB,iBACd,OACyB;CACzB,MAAM,SAAS,kBAAkB,KAAK;CAEtC,IAAI,UAAU,OAAO,SAAS,UAC5B,OAAO;CAGT,OAAO;EAAE,MAAM;EAAU,YAAY,CAAC;CAAE;AAC1C"}
|
|
@@ -2,7 +2,7 @@ import { readReasoningReplay, toReplayReasoningItem } from "./reasoning-replay.m
|
|
|
2
2
|
import { stringifyContent, toImageUrl } from "./to-openai-messages.mjs";
|
|
3
3
|
import { InvalidRequestError } from "@warlock.js/ai";
|
|
4
4
|
|
|
5
|
-
//#region
|
|
5
|
+
//#region ../../packages/ai-openai/src/utils/to-responses-input.ts
|
|
6
6
|
/**
|
|
7
7
|
* Convert vendor-neutral `Message[]` into the Responses request pieces.
|
|
8
8
|
*
|