@warlock.js/ai-openai 5.30.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 +24 -1
- package/README.md +3 -3
- package/cjs/index.cjs +416 -48
- package/cjs/index.cjs.map +1 -1
- package/esm/config.type.d.mts +5 -3
- package/esm/config.type.d.mts.map +1 -1
- package/esm/embedder.d.mts.map +1 -1
- package/esm/embedder.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/model.mjs +75 -23
- 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 +116 -17
- package/esm/responses-model.mjs.map +1 -1
- package/esm/sdk.d.mts +3 -2
- package/esm/sdk.d.mts.map +1 -1
- package/esm/sdk.mjs +5 -3
- package/esm/sdk.mjs.map +1 -1
- package/esm/transcription.mjs.map +1 -1
- package/esm/utils/build-usage.mjs +14 -2
- package/esm/utils/build-usage.mjs.map +1 -1
- package/esm/utils/index.mjs +1 -1
- package/esm/utils/map-responses-status.mjs.map +1 -1
- package/esm/utils/prompt-cache-params.mjs +25 -6
- package/esm/utils/prompt-cache-params.mjs.map +1 -1
- package/esm/utils/reasoning-replay.mjs +23 -1
- package/esm/utils/reasoning-replay.mjs.map +1 -1
- package/esm/utils/structured-output.mjs.map +1 -1
- package/esm/utils/to-openai-messages.mjs.map +1 -1
- package/esm/utils/to-openai-tools.mjs.map +1 -1
- package/esm/utils/wrap-openai-error.mjs +6 -1
- package/esm/utils/wrap-openai-error.mjs.map +1 -1
- package/llms-full.txt +128 -37
- package/llms.txt +1 -1
- package/package.json +3 -3
- package/skills/setup-openai/SKILL.md +128 -37
package/esm/config.type.d.mts
CHANGED
|
@@ -138,9 +138,11 @@ type OpenAIModelConfig = ModelConfig & {
|
|
|
138
138
|
*/
|
|
139
139
|
reasoning?: boolean;
|
|
140
140
|
/**
|
|
141
|
-
* Stable request bucket used
|
|
142
|
-
* Sent
|
|
143
|
-
*
|
|
141
|
+
* Stable request bucket used to improve prompt-cache matching, sent as
|
|
142
|
+
* `prompt_cache_key`. Sent when the SDK provider label is `"openai"`,
|
|
143
|
+
* `"xai"` or `"mistral"` — the endpoints that document the field. Other
|
|
144
|
+
* labels (Groq and DeepSeek cache automatically; custom gateways) never
|
|
145
|
+
* receive it.
|
|
144
146
|
*/
|
|
145
147
|
promptCacheKey?: string;
|
|
146
148
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.type.d.mts","names":[],"sources":["../../../../../../../packages/ai-openai/src/config.type.ts"],"mappings":";;;;;AAyCA;;;;;;;;;;;;;;;;AAeuC;AAiBvC;;;;AAAgC;AAahC;;;;AAAqB;AAcrB;;KA3DY,eAAA,GAAkB,IAAA,CAAK,aAAA;EA2DH;;;;;;;;EAlD9B,QAAA;EAwDM;;;;;EAlDN,OAAA,GAAU,MAAA,SAAe,YAAA;AAAA;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"config.type.d.mts","names":[],"sources":["../../../../../../../packages/ai-openai/src/config.type.ts"],"mappings":";;;;;AAyCA;;;;;;;;;;;;;;;;AAeuC;AAiBvC;;;;AAAgC;AAahC;;;;AAAqB;AAcrB;;KA3DY,eAAA,GAAkB,IAAA,CAAK,aAAA;EA2DH;;;;;;;;EAlD9B,QAAA;EAwDM;;;;;EAlDN,OAAA,GAAU,MAAA,SAAe,YAAA;AAAA;;;;;;;;;;AA8HpB;AAaP;;;;KA1HY,oBAAA;AAwIZ;;;;AAAgD;AAahD;;;;AAAkD;AAalD;AA1BA,KA3HY,SAAA;;;AAqJoD;;;;;;;;;;KAvIpD,iBAAA,GAAoB,WAAA;;;;;;EAM9B,GAAA,GAAM,SAAA;;;;;;;;EAQN,MAAA;;;;;;;;;;;;;;EAcA,cAAA,GAAiB,oBAAA;;;;;;;;;EASjB,gBAAA;;;;;;;;;;;EAWA,SAAA;;;;;;;;EAQA,cAAA;;;;;;EAMA,oBAAA,GAAuB,OAAA,CACrB,MAAA,CAAO,IAAA,CAAK,WAAA,CAAY,0BAAA;;;;;;;;;EAW1B,GAAA;;;;;;;;EAQA,KAAA;AAAA;;;;;;;;;;;KAaU,oBAAA,GAAuB,cAAc;;;;;;;;;;;;;KAcrC,iBAAA,GAAoB,gBAAgB;;;;;;;;;;;;KAapC,kBAAA,GAAqB,iBAAiB;;;;;;;;;;;;KAatC,yBAAA,GAA4B,wBAAwB"}
|
package/esm/embedder.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"embedder.d.mts","names":[],"sources":["../../../../../../../packages/ai-openai/src/embedder.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"embedder.d.mts","names":[],"sources":["../../../../../../../packages/ai-openai/src/embedder.ts"],"mappings":";;;;;;;AAyCA;;;;;;;;;;;;;;;;;;;;;;;cAAa,cAAA,YAA0B,gBAAA;EAAA,SACrB,IAAA;EAAA,SACA,QAAA;EACT,UAAA;EAAA,iBAEU,MAAA;EA8CJ;;;;;EAAA,iBAvCI,oBAAA;EAAA,iBACA,MAAA;cAEE,MAAA,EAAQ,MAAA,EAAQ,MAAA,EAAQ,oBAAA;EAO9B,KAAA,CAAM,KAAA,WAAgB,OAAA,CAAQ,eAAA;EA6B9B,SAAA,CAAU,MAAA,aAAmB,OAAA,CAAQ,oBAAA;;;;;;;UAgBpC,OAAA;AAAA"}
|
package/esm/embedder.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"embedder.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/embedder.ts"],"sourcesContent":["import {\n EmbeddingVectorCountMismatchError,\n type EmbeddingBatchResult,\n type EmbeddingResult,\n type EmbeddingUsage,\n type EmbedderContract,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type OpenAI from \"openai\";\nimport type { OpenAIEmbedderConfig } from \"./config.type\";\nimport { wrapOpenAIError } from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\ntype EmbeddingsResponse = Awaited
|
|
1
|
+
{"version":3,"file":"embedder.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/embedder.ts"],"sourcesContent":["import {\n EmbeddingVectorCountMismatchError,\n type EmbeddingBatchResult,\n type EmbeddingResult,\n type EmbeddingUsage,\n type EmbedderContract,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type OpenAI from \"openai\";\nimport type { OpenAIEmbedderConfig } from \"./config.type\";\nimport { wrapOpenAIError } from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\ntype EmbeddingsResponse = Awaited<ReturnType<OpenAI[\"embeddings\"][\"create\"]>>;\n\n/**\n * OpenAI-backed implementation of `EmbedderContract`.\n *\n * **Role.** Converts text (or a batch of texts) into floating-point\n * vectors via OpenAI's Embeddings API. Standalone primitive — no\n * relationship to chat completions, tools, or the agent loop.\n *\n * **Dimensions.** When no `dimensions` override is supplied in config,\n * `this.dimensions` starts at `0` and is populated from the first\n * response's vector length, then cached for all subsequent calls —\n * even if a later response were to return a different length, the\n * first value wins so batches stay dimensionally consistent. Passing\n * `dimensions` in config both forwards the truncation hint to the API\n * (for models like `text-embedding-3-*`) and sets the initial value.\n *\n * **Error handling.** Raw OpenAI SDK errors are wrapped into the\n * typed `@warlock.js/ai` `AIError` hierarchy via `wrapOpenAIError` —\n * callers catch `AIError` subclasses (`ProviderRateLimitError`,\n * `ProviderAuthError`, etc.) instead of OpenAI's own classes.\n *\n * @example\n * const embedder = new OpenAIEmbedder(client, { name: \"text-embedding-3-small\" });\n * const { vector, dimensions, usage } = await embedder.embed(\"Hello world\");\n * const { vectors } = await embedder.embedMany([\"doc 1\", \"doc 2\"]);\n */\nexport class OpenAIEmbedder implements EmbedderContract {\n public readonly name: string;\n public readonly provider = \"openai\";\n public dimensions: number;\n\n private readonly client: OpenAI;\n\n /**\n * User-specified truncation hint, or `undefined` if omitted.\n * Forwarded to the API on every call so OpenAI can truncate the\n * embedding server-side for models that support it.\n */\n private readonly configuredDimensions: number | undefined;\n private readonly logger: Logger = log;\n\n public constructor(client: OpenAI, config: OpenAIEmbedderConfig) {\n this.client = client;\n this.name = config.name;\n this.configuredDimensions = config.dimensions;\n this.dimensions = config.dimensions ?? 0;\n }\n\n public async embed(input: string): Promise<EmbeddingResult> {\n const { response, usage } = await this.request(input);\n\n const [first] = response.data;\n\n if (first === undefined) {\n // A 200 whose `data` array is empty. Before this guard the next line\n // read `.embedding` off `undefined` and the caller got a bare\n // `TypeError: Cannot read properties of undefined`, naming neither the\n // provider nor what it actually returned.\n //\n // Same typed error the RAG and skill-catalog paths raise for this\n // contract violation, so one shortfall has one name wherever it\n // surfaces. Expected 1, received 0.\n throw new EmbeddingVectorCountMismatchError({\n provider: this.provider,\n expectedCount: 1,\n receivedCount: response.data.length,\n record: input,\n });\n }\n\n return {\n vector: first.embedding,\n dimensions: this.dimensions,\n usage,\n };\n }\n\n public async embedMany(inputs: string[]): Promise<EmbeddingBatchResult> {\n const { response, usage } = await this.request(inputs);\n\n return {\n vectors: response.data.map((d) => d.embedding),\n dimensions: this.dimensions,\n usage,\n };\n }\n\n /**\n * Shared transport for both `embed()` and `embedMany()` — issues the\n * `embeddings.create` call, wraps provider errors, caches dimensions\n * on the first successful response, and returns the raw response\n * plus a camelCase usage object for the caller to shape.\n */\n private async request(input: string | string[]): Promise<{\n response: EmbeddingsResponse;\n usage: EmbeddingUsage;\n }> {\n this.logger.debug(LOG_MODULE, \"embedder.request\", \"embeddings.create\", {\n model: this.name,\n batch: Array.isArray(input),\n count: Array.isArray(input) ? input.length : 1,\n });\n\n let response: EmbeddingsResponse;\n\n try {\n response = await this.client.embeddings.create({\n model: this.name,\n input,\n ...(this.configuredDimensions !== undefined\n ? { dimensions: this.configuredDimensions }\n : {}),\n });\n } catch (thrown) {\n const wrapped = wrapOpenAIError(thrown);\n\n this.logger.error(LOG_MODULE, \"embedder.error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n throw wrapped;\n }\n\n this.logger.debug(LOG_MODULE, \"embedder.response\", \"embeddings.create returned\", {\n dimensions: response.data[0]?.embedding.length,\n usage: {\n promptTokens: response.usage.prompt_tokens,\n totalTokens: response.usage.total_tokens,\n },\n });\n\n // Cache dimensions on the first response. Once set, stays set —\n // we trust the first call to define the shape for this embedder.\n //\n // Reads the first entry optionally rather than asserting it: this runs for\n // BOTH embed() and embedMany(), and an empty `data` array is a real\n // provider response, not an impossible one. Leaving `dimensions` at 0 for\n // an empty response is correct — the callers each raise their own typed\n // error about the shortfall, and cacheing a dimension off a response that\n // carried no vectors would be inventing a shape from nothing.\n if (this.dimensions === 0) {\n const firstEmbedding = response.data[0]?.embedding;\n\n if (firstEmbedding !== undefined) {\n this.dimensions = firstEmbedding.length;\n }\n }\n\n const usage: EmbeddingUsage = {\n promptTokens: response.usage.prompt_tokens,\n totalTokens: response.usage.total_tokens,\n };\n\n return { response, usage };\n }\n}\n"],"mappings":";;;;;;AAYA,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BnB,IAAa,iBAAb,MAAwD;CAetD,AAAO,YAAY,QAAgB,QAA8B;kBAbtC;gBAWO;EAGhC,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,uBAAuB,OAAO;EACnC,KAAK,aAAa,OAAO,cAAc;CACzC;CAEA,MAAa,MAAM,OAAyC;EAC1D,MAAM,EAAE,UAAU,UAAU,MAAM,KAAK,QAAQ,KAAK;EAEpD,MAAM,CAAC,SAAS,SAAS;EAEzB,IAAI,UAAU,QASZ,MAAM,IAAI,kCAAkC;GAC1C,UAA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;EAAM;CAC3B;AACF"}
|
package/esm/index.d.mts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { OpenAIEmbedderConfig, OpenAIImageConfig, OpenAISDKConfig, OpenAISpeechConfig, OpenAITranscriptionConfig } from "./config.type.mjs";
|
|
2
2
|
import { OpenAISDK } from "./sdk.mjs";
|
|
3
|
+
import { OPENAI_MODEL_PRICING, openAIPricingFor } from "./known-pricing.mjs";
|
|
3
4
|
import { OpenAIEmbedder } from "./embedder.mjs";
|
|
4
5
|
import { OpenAIImageModel } from "./image.mjs";
|
|
5
6
|
import { OpenAISpeechModel } from "./speech.mjs";
|
|
6
7
|
import { OpenAITranscriptionModel } from "./transcription.mjs";
|
|
7
|
-
|
|
8
|
+
import { OpenAICallOptions } from "./provider-options.mjs";
|
|
9
|
+
export { OPENAI_MODEL_PRICING, type OpenAICallOptions, OpenAIEmbedder, type OpenAIEmbedderConfig, type OpenAIImageConfig, OpenAIImageModel, OpenAISDK, type OpenAISDKConfig, type OpenAISpeechConfig, OpenAISpeechModel, type OpenAITranscriptionConfig, OpenAITranscriptionModel, openAIPricingFor };
|
package/esm/index.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { OPENAI_MODEL_PRICING, openAIPricingFor } from "./known-pricing.mjs";
|
|
1
2
|
import { OpenAIEmbedder } from "./embedder.mjs";
|
|
2
3
|
import { OpenAIImageModel } from "./image.mjs";
|
|
3
4
|
import { OpenAISpeechModel } from "./speech.mjs";
|
|
4
5
|
import { OpenAITranscriptionModel } from "./transcription.mjs";
|
|
5
6
|
import { OpenAISDK } from "./sdk.mjs";
|
|
6
7
|
|
|
7
|
-
export { OpenAIEmbedder, OpenAIImageModel, OpenAISDK, OpenAISpeechModel, OpenAITranscriptionModel };
|
|
8
|
+
export { OPENAI_MODEL_PRICING, OpenAIEmbedder, OpenAIImageModel, OpenAISDK, OpenAISpeechModel, OpenAITranscriptionModel, openAIPricingFor };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { ModelPricing } from "@warlock.js/ai";
|
|
2
|
+
|
|
3
|
+
//#region ../../packages/ai-openai/src/known-pricing.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Built-in OpenAI API list prices, USD per 1,000,000 tokens, keyed by
|
|
6
|
+
* exact model id. `cachedInput` is the cached-input rate. None of these
|
|
7
|
+
* models charges for cache writes.
|
|
8
|
+
*
|
|
9
|
+
* Source: https://developers.openai.com/api/docs/pricing (the target of
|
|
10
|
+
* platform.openai.com/docs/pricing), Standard tier, fetched 2026-10-17.
|
|
11
|
+
*
|
|
12
|
+
* Applied only when the SDK's provider label is `"openai"`, and only on
|
|
13
|
+
* an exact id match — dated snapshots can carry other prices. Left out on
|
|
14
|
+
* purpose, so pass `pricing` yourself for them:
|
|
15
|
+
*
|
|
16
|
+
* - Models priced by prompt length (a higher rate above 272K input
|
|
17
|
+
* tokens): the gpt-6 / gpt-5.6 / gpt-5.5 / gpt-5.4 families and the
|
|
18
|
+
* `-pro` models. A flat `ModelPricing` cannot express the tiers.
|
|
19
|
+
* - Promotional, Batch, Flex and Priority pricing, and the regional
|
|
20
|
+
* (data-residency) uplift.
|
|
21
|
+
*/
|
|
22
|
+
declare const OPENAI_MODEL_PRICING: Readonly<Record<string, ModelPricing>>;
|
|
23
|
+
/**
|
|
24
|
+
* Look up the built-in list price for an OpenAI model id (exact match).
|
|
25
|
+
* Returns `undefined` for unknown ids, so cost stays unknown rather than
|
|
26
|
+
* wrong.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* openAIPricingFor("gpt-4o-mini"); // { input: 0.15, output: 0.6, cachedInput: 0.075 }
|
|
30
|
+
* openAIPricingFor("gpt-5.5"); // undefined — priced by prompt length
|
|
31
|
+
*/
|
|
32
|
+
declare function openAIPricingFor(modelName: string): ModelPricing | undefined;
|
|
33
|
+
//#endregion
|
|
34
|
+
export { OPENAI_MODEL_PRICING, openAIPricingFor };
|
|
35
|
+
//# sourceMappingURL=known-pricing.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"known-pricing.d.mts","names":[],"sources":["../../../../../../../packages/ai-openai/src/known-pricing.ts"],"mappings":";;;;;AAoBA;;;;;;;;;;;;AAAuE;AA4BvE;;;cA5Ba,oBAAA,EAAsB,QAAA,CAAS,MAAA,SAAe,YAAA;AA4BM;;;;;;;;;AAAA,iBAAjD,gBAAA,CAAiB,SAAA,WAAoB,YAAY"}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
//#region ../../packages/ai-openai/src/known-pricing.ts
|
|
2
|
+
/**
|
|
3
|
+
* Built-in OpenAI API list prices, USD per 1,000,000 tokens, keyed by
|
|
4
|
+
* exact model id. `cachedInput` is the cached-input rate. None of these
|
|
5
|
+
* models charges for cache writes.
|
|
6
|
+
*
|
|
7
|
+
* Source: https://developers.openai.com/api/docs/pricing (the target of
|
|
8
|
+
* platform.openai.com/docs/pricing), Standard tier, fetched 2026-10-17.
|
|
9
|
+
*
|
|
10
|
+
* Applied only when the SDK's provider label is `"openai"`, and only on
|
|
11
|
+
* an exact id match — dated snapshots can carry other prices. Left out on
|
|
12
|
+
* purpose, so pass `pricing` yourself for them:
|
|
13
|
+
*
|
|
14
|
+
* - Models priced by prompt length (a higher rate above 272K input
|
|
15
|
+
* tokens): the gpt-6 / gpt-5.6 / gpt-5.5 / gpt-5.4 families and the
|
|
16
|
+
* `-pro` models. A flat `ModelPricing` cannot express the tiers.
|
|
17
|
+
* - Promotional, Batch, Flex and Priority pricing, and the regional
|
|
18
|
+
* (data-residency) uplift.
|
|
19
|
+
*/
|
|
20
|
+
const OPENAI_MODEL_PRICING = {
|
|
21
|
+
"gpt-5.4-mini": {
|
|
22
|
+
input: .75,
|
|
23
|
+
output: 4.5,
|
|
24
|
+
cachedInput: .075
|
|
25
|
+
},
|
|
26
|
+
"gpt-5.4-nano": {
|
|
27
|
+
input: .2,
|
|
28
|
+
output: 1.25,
|
|
29
|
+
cachedInput: .02
|
|
30
|
+
},
|
|
31
|
+
"gpt-5.2": {
|
|
32
|
+
input: 1.75,
|
|
33
|
+
output: 14,
|
|
34
|
+
cachedInput: .175
|
|
35
|
+
},
|
|
36
|
+
"gpt-5.1": {
|
|
37
|
+
input: 1.25,
|
|
38
|
+
output: 10,
|
|
39
|
+
cachedInput: .125
|
|
40
|
+
},
|
|
41
|
+
"gpt-5": {
|
|
42
|
+
input: 1.25,
|
|
43
|
+
output: 10,
|
|
44
|
+
cachedInput: .125
|
|
45
|
+
},
|
|
46
|
+
"gpt-5-mini": {
|
|
47
|
+
input: .25,
|
|
48
|
+
output: 2,
|
|
49
|
+
cachedInput: .025
|
|
50
|
+
},
|
|
51
|
+
"gpt-5-nano": {
|
|
52
|
+
input: .05,
|
|
53
|
+
output: .4,
|
|
54
|
+
cachedInput: .005
|
|
55
|
+
},
|
|
56
|
+
"gpt-4.1": {
|
|
57
|
+
input: 2,
|
|
58
|
+
output: 8,
|
|
59
|
+
cachedInput: .5
|
|
60
|
+
},
|
|
61
|
+
"gpt-4.1-mini": {
|
|
62
|
+
input: .4,
|
|
63
|
+
output: 1.6,
|
|
64
|
+
cachedInput: .1
|
|
65
|
+
},
|
|
66
|
+
"gpt-4.1-nano": {
|
|
67
|
+
input: .1,
|
|
68
|
+
output: .4,
|
|
69
|
+
cachedInput: .025
|
|
70
|
+
},
|
|
71
|
+
"gpt-4o": {
|
|
72
|
+
input: 2.5,
|
|
73
|
+
output: 10,
|
|
74
|
+
cachedInput: 1.25
|
|
75
|
+
},
|
|
76
|
+
"gpt-4o-mini": {
|
|
77
|
+
input: .15,
|
|
78
|
+
output: .6,
|
|
79
|
+
cachedInput: .075
|
|
80
|
+
},
|
|
81
|
+
o3: {
|
|
82
|
+
input: 2,
|
|
83
|
+
output: 8,
|
|
84
|
+
cachedInput: .5
|
|
85
|
+
},
|
|
86
|
+
"o4-mini": {
|
|
87
|
+
input: 1.1,
|
|
88
|
+
output: 4.4,
|
|
89
|
+
cachedInput: .275
|
|
90
|
+
},
|
|
91
|
+
"o3-mini": {
|
|
92
|
+
input: 1.1,
|
|
93
|
+
output: 4.4,
|
|
94
|
+
cachedInput: .55
|
|
95
|
+
},
|
|
96
|
+
o1: {
|
|
97
|
+
input: 15,
|
|
98
|
+
output: 60,
|
|
99
|
+
cachedInput: 7.5
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
/**
|
|
103
|
+
* Look up the built-in list price for an OpenAI model id (exact match).
|
|
104
|
+
* Returns `undefined` for unknown ids, so cost stays unknown rather than
|
|
105
|
+
* wrong.
|
|
106
|
+
*
|
|
107
|
+
* @example
|
|
108
|
+
* openAIPricingFor("gpt-4o-mini"); // { input: 0.15, output: 0.6, cachedInput: 0.075 }
|
|
109
|
+
* openAIPricingFor("gpt-5.5"); // undefined — priced by prompt length
|
|
110
|
+
*/
|
|
111
|
+
function openAIPricingFor(modelName) {
|
|
112
|
+
return OPENAI_MODEL_PRICING[modelName];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
//#endregion
|
|
116
|
+
export { OPENAI_MODEL_PRICING, openAIPricingFor };
|
|
117
|
+
//# sourceMappingURL=known-pricing.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"known-pricing.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/known-pricing.ts"],"sourcesContent":["import type { ModelPricing } from \"@warlock.js/ai\";\n\n/**\n * Built-in OpenAI API list prices, USD per 1,000,000 tokens, keyed by\n * exact model id. `cachedInput` is the cached-input rate. None of these\n * models charges for cache writes.\n *\n * Source: https://developers.openai.com/api/docs/pricing (the target of\n * platform.openai.com/docs/pricing), Standard tier, fetched 2026-10-17.\n *\n * Applied only when the SDK's provider label is `\"openai\"`, and only on\n * an exact id match — dated snapshots can carry other prices. Left out on\n * purpose, so pass `pricing` yourself for them:\n *\n * - Models priced by prompt length (a higher rate above 272K input\n * tokens): the gpt-6 / gpt-5.6 / gpt-5.5 / gpt-5.4 families and the\n * `-pro` models. A flat `ModelPricing` cannot express the tiers.\n * - Promotional, Batch, Flex and Priority pricing, and the regional\n * (data-residency) uplift.\n */\nexport const OPENAI_MODEL_PRICING: Readonly<Record<string, ModelPricing>> = {\n \"gpt-5.4-mini\": { input: 0.75, output: 4.5, cachedInput: 0.075 },\n \"gpt-5.4-nano\": { input: 0.2, output: 1.25, cachedInput: 0.02 },\n \"gpt-5.2\": { input: 1.75, output: 14, cachedInput: 0.175 },\n \"gpt-5.1\": { input: 1.25, output: 10, cachedInput: 0.125 },\n \"gpt-5\": { input: 1.25, output: 10, cachedInput: 0.125 },\n \"gpt-5-mini\": { input: 0.25, output: 2, cachedInput: 0.025 },\n \"gpt-5-nano\": { input: 0.05, output: 0.4, cachedInput: 0.005 },\n \"gpt-4.1\": { input: 2, output: 8, cachedInput: 0.5 },\n \"gpt-4.1-mini\": { input: 0.4, output: 1.6, cachedInput: 0.1 },\n \"gpt-4.1-nano\": { input: 0.1, output: 0.4, cachedInput: 0.025 },\n \"gpt-4o\": { input: 2.5, output: 10, cachedInput: 1.25 },\n \"gpt-4o-mini\": { input: 0.15, output: 0.6, cachedInput: 0.075 },\n o3: { input: 2, output: 8, cachedInput: 0.5 },\n \"o4-mini\": { input: 1.1, output: 4.4, cachedInput: 0.275 },\n \"o3-mini\": { input: 1.1, output: 4.4, cachedInput: 0.55 },\n o1: { input: 15, output: 60, cachedInput: 7.5 },\n};\n\n/**\n * Look up the built-in list price for an OpenAI model id (exact match).\n * Returns `undefined` for unknown ids, so cost stays unknown rather than\n * wrong.\n *\n * @example\n * openAIPricingFor(\"gpt-4o-mini\"); // { input: 0.15, output: 0.6, cachedInput: 0.075 }\n * openAIPricingFor(\"gpt-5.5\"); // undefined — priced by prompt length\n */\nexport function openAIPricingFor(modelName: string): ModelPricing | undefined {\n return OPENAI_MODEL_PRICING[modelName];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBA,MAAa,uBAA+D;CAC1E,gBAAgB;EAAE,OAAO;EAAM,QAAQ;EAAK,aAAa;CAAM;CAC/D,gBAAgB;EAAE,OAAO;EAAK,QAAQ;EAAM,aAAa;CAAK;CAC9D,WAAW;EAAE,OAAO;EAAM,QAAQ;EAAI,aAAa;CAAM;CACzD,WAAW;EAAE,OAAO;EAAM,QAAQ;EAAI,aAAa;CAAM;CACzD,SAAS;EAAE,OAAO;EAAM,QAAQ;EAAI,aAAa;CAAM;CACvD,cAAc;EAAE,OAAO;EAAM,QAAQ;EAAG,aAAa;CAAM;CAC3D,cAAc;EAAE,OAAO;EAAM,QAAQ;EAAK,aAAa;CAAM;CAC7D,WAAW;EAAE,OAAO;EAAG,QAAQ;EAAG,aAAa;CAAI;CACnD,gBAAgB;EAAE,OAAO;EAAK,QAAQ;EAAK,aAAa;CAAI;CAC5D,gBAAgB;EAAE,OAAO;EAAK,QAAQ;EAAK,aAAa;CAAM;CAC9D,UAAU;EAAE,OAAO;EAAK,QAAQ;EAAI,aAAa;CAAK;CACtD,eAAe;EAAE,OAAO;EAAM,QAAQ;EAAK,aAAa;CAAM;CAC9D,IAAI;EAAE,OAAO;EAAG,QAAQ;EAAG,aAAa;CAAI;CAC5C,WAAW;EAAE,OAAO;EAAK,QAAQ;EAAK,aAAa;CAAM;CACzD,WAAW;EAAE,OAAO;EAAK,QAAQ;EAAK,aAAa;CAAK;CACxD,IAAI;EAAE,OAAO;EAAI,QAAQ;EAAI,aAAa;CAAI;AAChD;;;;;;;;;;AAWA,SAAgB,iBAAiB,WAA6C;CAC5E,OAAO,qBAAqB;AAC9B"}
|
package/esm/model.mjs
CHANGED
|
@@ -7,9 +7,10 @@ import { inferStructuredOutput, planStructuredOutput } from "./utils/structured-
|
|
|
7
7
|
import { toOpenAIMessages } from "./utils/to-openai-messages.mjs";
|
|
8
8
|
import { toOpenAITools } from "./utils/to-openai-tools.mjs";
|
|
9
9
|
import "./utils/index.mjs";
|
|
10
|
+
import { mergeProviderBody } from "./provider-options.mjs";
|
|
10
11
|
import { inferReasoningCapability } from "./known-reasoning-models.mjs";
|
|
11
12
|
import { inferVisionCapability } from "./known-vision-models.mjs";
|
|
12
|
-
import { InvalidRequestError, ProviderError, safeJsonParse } from "@warlock.js/ai";
|
|
13
|
+
import { InvalidRequestError, ProviderError, resolveStreamChunks, safeJsonParse, selectProviderTools } from "@warlock.js/ai";
|
|
13
14
|
import { log } from "@warlock.js/logger";
|
|
14
15
|
|
|
15
16
|
//#region ../../packages/ai-openai/src/model.ts
|
|
@@ -88,15 +89,15 @@ var OpenAIModel = class {
|
|
|
88
89
|
});
|
|
89
90
|
let response;
|
|
90
91
|
try {
|
|
91
|
-
response = await this.client.chat.completions.create({
|
|
92
|
+
response = await this.client.chat.completions.create(mergeProviderBody({
|
|
92
93
|
model: this.name,
|
|
93
94
|
messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),
|
|
94
95
|
...this.buildSamplingParams(options),
|
|
95
96
|
...buildPromptCacheParams(this.provider, this.config),
|
|
96
|
-
|
|
97
|
+
...this.buildTools(options),
|
|
97
98
|
...this.buildResponseFormat(options?.responseSchema),
|
|
98
99
|
...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length))
|
|
99
|
-
}, options?.signal ? { signal: options.signal } : void 0);
|
|
100
|
+
}, options), options?.signal ? { signal: options.signal } : void 0);
|
|
100
101
|
} catch (thrown) {
|
|
101
102
|
const wrapped = wrapOpenAIError(thrown);
|
|
102
103
|
this.logger.error(LOG_MODULE, "error", wrapped.message, {
|
|
@@ -129,6 +130,11 @@ var OpenAIModel = class {
|
|
|
129
130
|
* `delta` for text tokens, `tool-call` when the model requests a tool,
|
|
130
131
|
* and a terminal `done` carrying the final finish reason + usage totals.
|
|
131
132
|
* Callers consume it with `for await`.
|
|
133
|
+
*
|
|
134
|
+
* With `options.streamChunks` it also yields `tool-args` for each
|
|
135
|
+
* `tool_calls[].function.arguments` fragment and `reasoning` for a
|
|
136
|
+
* vendor's `reasoning_content` / `reasoning` delta field. Usage arrives
|
|
137
|
+
* only on the final chunk here, so no `usage` chunk is emitted.
|
|
132
138
|
*/
|
|
133
139
|
async *stream(messages, options) {
|
|
134
140
|
this.logger.debug(LOG_MODULE, "request", "Starting streaming call to chat.completions", {
|
|
@@ -139,17 +145,17 @@ var OpenAIModel = class {
|
|
|
139
145
|
});
|
|
140
146
|
let stream;
|
|
141
147
|
try {
|
|
142
|
-
stream = await this.client.chat.completions.create({
|
|
148
|
+
stream = await this.client.chat.completions.create(mergeProviderBody({
|
|
143
149
|
model: this.name,
|
|
144
150
|
messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),
|
|
145
151
|
...this.buildSamplingParams(options),
|
|
146
152
|
...buildPromptCacheParams(this.provider, this.config),
|
|
147
|
-
|
|
153
|
+
...this.buildTools(options),
|
|
148
154
|
stream: true,
|
|
149
155
|
stream_options: { include_usage: true },
|
|
150
156
|
...this.buildResponseFormat(options?.responseSchema),
|
|
151
157
|
...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length))
|
|
152
|
-
}, options?.signal ? { signal: options.signal } : void 0);
|
|
158
|
+
}, options), options?.signal ? { signal: options.signal } : void 0);
|
|
153
159
|
} catch (thrown) {
|
|
154
160
|
const wrapped = wrapOpenAIError(thrown);
|
|
155
161
|
this.logger.error(LOG_MODULE, "error", wrapped.message, {
|
|
@@ -159,16 +165,24 @@ var OpenAIModel = class {
|
|
|
159
165
|
throw wrapped;
|
|
160
166
|
}
|
|
161
167
|
let rawFinishReason = "stop";
|
|
162
|
-
|
|
168
|
+
let usage = {
|
|
163
169
|
input: 0,
|
|
164
170
|
output: 0,
|
|
165
171
|
total: 0
|
|
166
172
|
};
|
|
173
|
+
const want = resolveStreamChunks(options);
|
|
167
174
|
const toolCallAccum = /* @__PURE__ */ new Map();
|
|
168
175
|
try {
|
|
169
176
|
for await (const chunk of stream) {
|
|
170
177
|
const delta = chunk.choices[0]?.delta;
|
|
171
178
|
const finish = chunk.choices[0]?.finish_reason;
|
|
179
|
+
if (want.reasoning && delta) {
|
|
180
|
+
const reasoning = readReasoningDelta(delta);
|
|
181
|
+
if (reasoning) yield {
|
|
182
|
+
type: "reasoning",
|
|
183
|
+
delta: reasoning
|
|
184
|
+
};
|
|
185
|
+
}
|
|
172
186
|
if (delta?.content) yield {
|
|
173
187
|
type: "delta",
|
|
174
188
|
content: delta.content
|
|
@@ -178,23 +192,25 @@ var OpenAIModel = class {
|
|
|
178
192
|
if (!toolCallAccum.has(idx)) toolCallAccum.set(idx, {
|
|
179
193
|
id: "",
|
|
180
194
|
name: "",
|
|
181
|
-
arguments: ""
|
|
195
|
+
arguments: "",
|
|
196
|
+
streamed: 0
|
|
182
197
|
});
|
|
183
198
|
const acc = toolCallAccum.get(idx);
|
|
184
199
|
if (toolCall.id) acc.id = toolCall.id;
|
|
185
200
|
if (toolCall.function?.name) acc.name = toolCall.function.name;
|
|
186
201
|
if (toolCall.function?.arguments) acc.arguments += toolCall.function.arguments;
|
|
202
|
+
if (want.toolArgs && acc.name && acc.arguments.length > acc.streamed) {
|
|
203
|
+
yield {
|
|
204
|
+
type: "tool-args",
|
|
205
|
+
callId: acc.id,
|
|
206
|
+
name: acc.name,
|
|
207
|
+
delta: acc.arguments.slice(acc.streamed)
|
|
208
|
+
};
|
|
209
|
+
acc.streamed = acc.arguments.length;
|
|
210
|
+
}
|
|
187
211
|
}
|
|
188
212
|
if (finish) rawFinishReason = finish;
|
|
189
|
-
if (chunk.usage)
|
|
190
|
-
usage.input = chunk.usage.prompt_tokens ?? 0;
|
|
191
|
-
usage.output = chunk.usage.completion_tokens ?? 0;
|
|
192
|
-
usage.total = chunk.usage.total_tokens ?? 0;
|
|
193
|
-
const cached = chunk.usage.prompt_tokens_details?.cached_tokens;
|
|
194
|
-
if (cached !== void 0 && cached > 0) usage.cachedTokens = cached;
|
|
195
|
-
const reasoning = chunk.usage.completion_tokens_details?.reasoning_tokens;
|
|
196
|
-
if (reasoning !== void 0 && reasoning > 0) usage.reasoningTokens = reasoning;
|
|
197
|
-
}
|
|
213
|
+
if (chunk.usage) usage = this.extractUsage(chunk.usage);
|
|
198
214
|
}
|
|
199
215
|
for (const acc of toolCallAccum.values()) {
|
|
200
216
|
if (!acc.name) continue;
|
|
@@ -224,6 +240,25 @@ var OpenAIModel = class {
|
|
|
224
240
|
usage
|
|
225
241
|
};
|
|
226
242
|
}
|
|
243
|
+
/**
|
|
244
|
+
* Spread-friendly `tools` fragment: the function tools, then the
|
|
245
|
+
* provider-defined entries whose `provider` equals this model's
|
|
246
|
+
* provider label (`"openai"`, or the vendor label an OpenAI-compatible
|
|
247
|
+
* wrapper sets, e.g. `"groq"`), sent verbatim. Chat Completions only
|
|
248
|
+
* accepts `function` and `custom` tool types from OpenAI itself; its
|
|
249
|
+
* hosted tools (`web_search`, `file_search`, …) need `api: "responses"`
|
|
250
|
+
* and OpenAI rejects them here with a 400.
|
|
251
|
+
*/
|
|
252
|
+
buildTools(options) {
|
|
253
|
+
const { tools, definitions } = selectProviderTools(options, {
|
|
254
|
+
accepts: [this.provider],
|
|
255
|
+
module: LOG_MODULE,
|
|
256
|
+
model: this.name,
|
|
257
|
+
logger: this.logger
|
|
258
|
+
});
|
|
259
|
+
const mapped = [...toOpenAITools(tools) ?? [], ...definitions];
|
|
260
|
+
return mapped.length > 0 ? { tools: mapped } : {};
|
|
261
|
+
}
|
|
227
262
|
/** Map the neutral cache hint only for the direct OpenAI provider. */
|
|
228
263
|
promptCacheBreakpoints(options) {
|
|
229
264
|
return this.provider === "openai" ? options?.cacheControl?.breakpoints ?? 0 : 0;
|
|
@@ -262,7 +297,9 @@ var OpenAIModel = class {
|
|
|
262
297
|
* (the hidden reasoning channel on o-series / gpt-5 models, already
|
|
263
298
|
* counted within `output`). Both are emitted only when the provider
|
|
264
299
|
* reports a positive value, so non-reasoning / uncached calls keep the
|
|
265
|
-
* lean `{ input, output, total }` shape.
|
|
300
|
+
* lean `{ input, output, total }` shape. `cacheWriteTokens` mirrors
|
|
301
|
+
* `prompt_tokens_details.cache_write_tokens` (billed writes on the
|
|
302
|
+
* models that charge for them). `cost` is attached when priced.
|
|
266
303
|
*/
|
|
267
304
|
extractUsage(raw) {
|
|
268
305
|
if (!raw) return {
|
|
@@ -271,12 +308,13 @@ var OpenAIModel = class {
|
|
|
271
308
|
total: 0
|
|
272
309
|
};
|
|
273
310
|
return buildUsage({
|
|
274
|
-
input: raw.prompt_tokens,
|
|
275
|
-
output: raw.completion_tokens,
|
|
276
|
-
total: raw.total_tokens,
|
|
311
|
+
input: raw.prompt_tokens ?? 0,
|
|
312
|
+
output: raw.completion_tokens ?? 0,
|
|
313
|
+
total: raw.total_tokens ?? 0,
|
|
277
314
|
cachedTokens: raw.prompt_tokens_details?.cached_tokens,
|
|
315
|
+
cacheWriteTokens: raw.prompt_tokens_details?.cache_write_tokens,
|
|
278
316
|
reasoningTokens: raw.completion_tokens_details?.reasoning_tokens
|
|
279
|
-
});
|
|
317
|
+
}, this.pricing);
|
|
280
318
|
}
|
|
281
319
|
/**
|
|
282
320
|
* Translate the neutral `ModelCallOptions.reasoning` hint into OpenAI's
|
|
@@ -352,6 +390,20 @@ var OpenAIModel = class {
|
|
|
352
390
|
}));
|
|
353
391
|
}
|
|
354
392
|
};
|
|
393
|
+
/**
|
|
394
|
+
* Reasoning text an OpenAI-compatible vendor puts on a Chat Completions
|
|
395
|
+
* stream delta. OpenAI itself streams none on this API. DeepSeek documents
|
|
396
|
+
* `delta.reasoning_content` (API reference, chat completion chunk); Groq
|
|
397
|
+
* documents the parsed reasoning under a `reasoning` field. Neither is in
|
|
398
|
+
* the OpenAI SDK's delta type, so the delta is read as a plain record.
|
|
399
|
+
*/
|
|
400
|
+
function readReasoningDelta(delta) {
|
|
401
|
+
const record = delta;
|
|
402
|
+
for (const key of ["reasoning_content", "reasoning"]) {
|
|
403
|
+
const value = record[key];
|
|
404
|
+
if (typeof value === "string" && value !== "") return value;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
355
407
|
|
|
356
408
|
//#endregion
|
|
357
409
|
export { OpenAIModel };
|
package/esm/model.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.mjs","names":[],"sources":["../../../../../../../packages/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,OAA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;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,kBAAk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AI,2BAA2B;EAClD,GACA,KAAK,OACP;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;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"}
|