@warlock.js/ai-openai 5.39.2 → 5.40.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 +12 -0
- package/cjs/index.cjs +799 -623
- package/cjs/index.cjs.map +1 -1
- package/esm/index.d.mts +2 -1
- package/esm/index.mjs +2 -1
- package/esm/list-models.mjs +54 -0
- package/esm/list-models.mjs.map +1 -0
- package/esm/model.mjs +31 -1
- package/esm/model.mjs.map +1 -1
- package/esm/native-search.mjs +47 -0
- package/esm/native-search.mjs.map +1 -0
- package/esm/provider-options.d.mts +1 -1
- package/esm/responses-model.d.mts +155 -0
- package/esm/responses-model.d.mts.map +1 -0
- package/esm/responses-model.mjs +15 -6
- package/esm/responses-model.mjs.map +1 -1
- package/esm/sdk.d.mts +28 -1
- package/esm/sdk.d.mts.map +1 -1
- package/esm/sdk.mjs +49 -1
- package/esm/sdk.mjs.map +1 -1
- package/esm/utils/hosted-output.mjs +2 -2
- package/esm/utils/hosted-output.mjs.map +1 -1
- package/llms-full.txt +8 -0
- package/package.json +3 -3
- package/skills/SKILL.md +8 -0
package/cjs/index.cjs
CHANGED
|
@@ -149,6 +149,56 @@ function openAIPricingFor(modelName) {
|
|
|
149
149
|
* https://developers.openai.com/api/docs/pricing#built-in-tools — verified 2026-10-18. */
|
|
150
150
|
const OPENAI_SERVER_TOOL_PRICING = { webSearch: .01 };
|
|
151
151
|
|
|
152
|
+
//#endregion
|
|
153
|
+
//#region ../../packages/ai-openai/src/list-models.ts
|
|
154
|
+
/**
|
|
155
|
+
* Map one entry of an OpenAI-style `GET /models` listing to {@link ModelInfo}.
|
|
156
|
+
*
|
|
157
|
+
* OpenAI's own entries carry `id`, `created` and `owned_by` only. The
|
|
158
|
+
* compatible vendors add fields on top of that shape, and this reads the ones
|
|
159
|
+
* that are documented: Groq `context_window` and `active`, Mistral `name`,
|
|
160
|
+
* `description`, `max_context_length` and `capabilities`, and a `created_at`
|
|
161
|
+
* date string. Returns `undefined` for an entry that should not be offered
|
|
162
|
+
* (an id-less row, or one the vendor marks inactive).
|
|
163
|
+
*/
|
|
164
|
+
function toModelInfo(entry, provider) {
|
|
165
|
+
if (typeof entry !== "object" || entry === null) return;
|
|
166
|
+
const row = entry;
|
|
167
|
+
const id = row.id;
|
|
168
|
+
if (typeof id !== "string" || id === "" || row.active === false) return;
|
|
169
|
+
const created = numberOf(row.created) ?? secondsOf(row.created_at);
|
|
170
|
+
const contextWindow = numberOf(row.context_window) ?? numberOf(row.max_context_length);
|
|
171
|
+
const maxOutputTokens = numberOf(row.max_completion_tokens);
|
|
172
|
+
return {
|
|
173
|
+
id,
|
|
174
|
+
label: typeof row.name === "string" && row.name !== "" ? row.name : id,
|
|
175
|
+
provider,
|
|
176
|
+
kind: kindOf(id, row.capabilities),
|
|
177
|
+
...created !== void 0 ? { created } : {},
|
|
178
|
+
...contextWindow !== void 0 ? { contextWindow } : {},
|
|
179
|
+
...maxOutputTokens !== void 0 ? { maxOutputTokens } : {},
|
|
180
|
+
...typeof row.description === "string" && row.description !== "" ? { description: row.description } : {}
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
/** Mistral reports `capabilities.completion_chat`; everything else is classified by id. */
|
|
184
|
+
function kindOf(id, capabilities) {
|
|
185
|
+
const inferred = (0, _warlock_js_ai.inferModelKind)(id);
|
|
186
|
+
if (typeof capabilities === "object" && capabilities !== null) {
|
|
187
|
+
const flags = capabilities;
|
|
188
|
+
if (flags.completion_chat === true) return "chat";
|
|
189
|
+
if (flags.completion_chat === false && inferred === "chat") return "other";
|
|
190
|
+
}
|
|
191
|
+
return inferred;
|
|
192
|
+
}
|
|
193
|
+
function numberOf(value) {
|
|
194
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
195
|
+
}
|
|
196
|
+
function secondsOf(value) {
|
|
197
|
+
if (typeof value !== "string") return;
|
|
198
|
+
const milliseconds = Date.parse(value);
|
|
199
|
+
return Number.isNaN(milliseconds) ? void 0 : Math.floor(milliseconds / 1e3);
|
|
200
|
+
}
|
|
201
|
+
|
|
152
202
|
//#endregion
|
|
153
203
|
//#region ../../packages/ai-openai/src/utils/build-usage.ts
|
|
154
204
|
/**
|
|
@@ -1240,6 +1290,67 @@ var OpenAIImageModel = class {
|
|
|
1240
1290
|
}
|
|
1241
1291
|
};
|
|
1242
1292
|
|
|
1293
|
+
//#endregion
|
|
1294
|
+
//#region ../../packages/ai-openai/src/native-search.ts
|
|
1295
|
+
/** Hosted web-search tool types the Responses API accepts. */
|
|
1296
|
+
const HOSTED_SEARCH_TYPES = /* @__PURE__ */ new Set([
|
|
1297
|
+
"web_search",
|
|
1298
|
+
"web_search_2025_08_26",
|
|
1299
|
+
"web_search_preview",
|
|
1300
|
+
"web_search_preview_2025_03_11"
|
|
1301
|
+
]);
|
|
1302
|
+
/**
|
|
1303
|
+
* Models the OpenAI web-search tool is documented as unavailable on, plus
|
|
1304
|
+
* ids that are not conversational at all. Everything else is attempted:
|
|
1305
|
+
* an id the list does not know still reaches OpenAI, which is the authority.
|
|
1306
|
+
* https://developers.openai.com/api/docs/guides/tools-web-search
|
|
1307
|
+
*/
|
|
1308
|
+
const UNSUPPORTED_SEARCH_MODELS = /^(?:gpt-3\.5|gpt-4(?:-\d|-turbo|-32k|$)|gpt-4\.1-nano|o1-mini|o1-preview|o3-mini|text-embedding|whisper|tts|dall-e|gpt-image|omni-moderation)/u;
|
|
1309
|
+
/** The provider-defined entries on a call that belong to `provider`. */
|
|
1310
|
+
function providerToolsOf(options, provider) {
|
|
1311
|
+
return [...options?.providerTools ?? [], ...(options?.tools ?? []).filter(_warlock_js_ai.isProviderTool)].filter((entry) => entry.provider === provider).map((entry) => entry);
|
|
1312
|
+
}
|
|
1313
|
+
/** `true` when the call carries OpenAI's hosted web-search tool. */
|
|
1314
|
+
function requestsHostedSearch(options, provider) {
|
|
1315
|
+
return providerToolsOf(options, provider).some((entry) => typeof entry.definition.type === "string" && HOSTED_SEARCH_TYPES.has(entry.definition.type));
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* Throw a capability error, before any request, when a model cannot run
|
|
1319
|
+
* OpenAI's hosted web search. Nothing falls back silently: the caller picks
|
|
1320
|
+
* another model or drops the tool.
|
|
1321
|
+
*/
|
|
1322
|
+
function assertHostedSearchSupported(model, options) {
|
|
1323
|
+
if (UNSUPPORTED_SEARCH_MODELS.test(model)) throw new _warlock_js_ai.InvalidRequestError(`OpenAI's hosted web_search tool is not available on "${model}". Use a model that supports it (for example gpt-4.1, gpt-4.1-mini, gpt-4o, gpt-5), or remove the web_search tool.`, { context: {
|
|
1324
|
+
provider: "openai",
|
|
1325
|
+
model,
|
|
1326
|
+
tool: "web_search"
|
|
1327
|
+
} });
|
|
1328
|
+
if (/^gpt-5/u.test(model) && options?.reasoning?.effort === "minimal") throw new _warlock_js_ai.InvalidRequestError(`OpenAI's hosted web_search tool is not available on "${model}" with minimal reasoning. Use a higher reasoning effort or remove the web_search tool.`, { context: {
|
|
1329
|
+
provider: "openai",
|
|
1330
|
+
model,
|
|
1331
|
+
tool: "web_search",
|
|
1332
|
+
effort: "minimal"
|
|
1333
|
+
} });
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
//#endregion
|
|
1337
|
+
//#region ../../packages/ai-openai/src/utils/hosted-output.ts
|
|
1338
|
+
/** Installed openai 7.23.0 ResponseFunctionWebSearch (action includes search/open_page/find).
|
|
1339
|
+
* https://developers.openai.com/api/docs/guides/tools-web-search
|
|
1340
|
+
* Count output items, never URLs, sources, answer text, or function calls.
|
|
1341
|
+
* Fees and search content tokens are separate; preview pricing varies:
|
|
1342
|
+
* https://developers.openai.com/api/docs/pricing#built-in-tools */
|
|
1343
|
+
function hostedOutput(usage, output, pricing, key = "openai") {
|
|
1344
|
+
const hosted = output.filter((item) => item.type !== "message" && item.type !== "reasoning" && item.type !== "function_call");
|
|
1345
|
+
const searches = hosted.filter((item) => item.type === "web_search_call");
|
|
1346
|
+
if (searches.length) usage.serverToolUse = {
|
|
1347
|
+
...usage.serverToolUse,
|
|
1348
|
+
webSearchRequests: searches.length
|
|
1349
|
+
};
|
|
1350
|
+
(0, _warlock_js_ai.attachCost)(usage, pricing);
|
|
1351
|
+
return hosted.length ? { [key]: { output: hosted } } : void 0;
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1243
1354
|
//#endregion
|
|
1244
1355
|
//#region ../../packages/ai-openai/src/provider-options.ts
|
|
1245
1356
|
const RESERVED_FIELDS = /* @__PURE__ */ new Set([
|
|
@@ -1378,52 +1489,75 @@ function inferVisionCapability(modelName) {
|
|
|
1378
1489
|
}
|
|
1379
1490
|
|
|
1380
1491
|
//#endregion
|
|
1381
|
-
//#region ../../packages/ai-openai/src/model.ts
|
|
1492
|
+
//#region ../../packages/ai-openai/src/responses-model.ts
|
|
1382
1493
|
const LOG_MODULE$3 = "ai.openai";
|
|
1383
1494
|
/**
|
|
1384
|
-
*
|
|
1495
|
+
* Responses output item types of built-in tools the CALLER must execute
|
|
1496
|
+
* (installed SDK `ResponseOutputItem` union). The adapter maps only
|
|
1497
|
+
* `function_call` to a neutral tool call, so these fail closed.
|
|
1498
|
+
*/
|
|
1499
|
+
const CLIENT_RUN_ITEM_TYPES = /* @__PURE__ */ new Set([
|
|
1500
|
+
"computer_call",
|
|
1501
|
+
"custom_tool_call",
|
|
1502
|
+
"local_shell_call",
|
|
1503
|
+
"shell_call",
|
|
1504
|
+
"apply_patch_call",
|
|
1505
|
+
"mcp_approval_request"
|
|
1506
|
+
]);
|
|
1507
|
+
/**
|
|
1508
|
+
* OpenAI Responses API implementation of `ModelContract` (`api: "responses"`).
|
|
1385
1509
|
*
|
|
1386
|
-
* **Role.**
|
|
1387
|
-
*
|
|
1388
|
-
*
|
|
1389
|
-
* `
|
|
1390
|
-
* any OpenAI-compatible endpoint (OpenAI, Azure OpenAI, OpenRouter, local
|
|
1391
|
-
* gateways that speak the Chat Completions protocol).
|
|
1510
|
+
* **Role.** A sibling of `OpenAIModel` that speaks `POST /v1/responses`
|
|
1511
|
+
* instead of Chat Completions. Its point is letting a tool-using agent run a
|
|
1512
|
+
* reasoning model with reasoning ON: the Chat path has to force
|
|
1513
|
+
* `reasoning_effort: "none"` whenever tools are attached, Responses does not.
|
|
1392
1514
|
*
|
|
1393
|
-
* **
|
|
1394
|
-
*
|
|
1395
|
-
*
|
|
1396
|
-
*
|
|
1397
|
-
*
|
|
1398
|
-
* translating OpenAI's response (content, finish reason, tool calls,
|
|
1399
|
-
* usage) back into the neutral shapes on the way in.
|
|
1400
|
-
* - Does NOT own: dispatching tools, deciding whether to loop, tracking
|
|
1401
|
-
* conversation history, or retrying on failure — those are agent
|
|
1402
|
-
* concerns. The model is a stateless (per-call) protocol adapter.
|
|
1515
|
+
* **Why a separate class.** Only `OpenAISDK.model()` constructs it, and only
|
|
1516
|
+
* for the direct `"openai"` provider. The wrapper packages (deepseek, groq,
|
|
1517
|
+
* xai, mistral) build `OpenAIModel` and cannot reach this class, so an
|
|
1518
|
+
* endpoint that does not implement `/v1/responses` is never sent there. The
|
|
1519
|
+
* constructor re-checks the provider label as a second lock.
|
|
1403
1520
|
*
|
|
1404
|
-
*
|
|
1405
|
-
*
|
|
1521
|
+
* **Stateless.** Every request sends `store: false`; nothing is kept on the
|
|
1522
|
+
* server and no `previous_response_id` is used. Full history is re-sent each
|
|
1523
|
+
* call, exactly like the Chat path.
|
|
1406
1524
|
*
|
|
1407
|
-
*
|
|
1408
|
-
*
|
|
1409
|
-
*
|
|
1410
|
-
*
|
|
1525
|
+
* **Reasoning replay.** Every request asks for
|
|
1526
|
+
* `include: ["reasoning.encrypted_content"]`. The `reasoning` items of a
|
|
1527
|
+
* tool-calling turn are stored on the FIRST tool call as
|
|
1528
|
+
* `providerMetadata.openaiResponses = { model, reasoningItems }` and sent back
|
|
1529
|
+
* before that turn's `function_call` items on the next request (only when the
|
|
1530
|
+
* stored model equals the current one). Text-only turns are not replayed.
|
|
1411
1531
|
*
|
|
1412
|
-
*
|
|
1413
|
-
*
|
|
1414
|
-
*
|
|
1415
|
-
*
|
|
1416
|
-
*
|
|
1532
|
+
* **Streaming.** `stream()` uses `responses.create({ stream: true })` and yields
|
|
1533
|
+
* the same chunk sequence as the Chat path: text `delta`s, then the
|
|
1534
|
+
* `tool-call`s, then one `done`. With `streamChunks` it also yields
|
|
1535
|
+
* `reasoning` (reasoning summary / reasoning text deltas) and `tool-args`
|
|
1536
|
+
* (`response.function_call_arguments.delta`).
|
|
1417
1537
|
*
|
|
1418
|
-
*
|
|
1538
|
+
* **Provider-defined tools.** `ai.providerTool({ provider: "openai" })`
|
|
1539
|
+
* definitions are appended to `tools` verbatim. Hosted tools run inside the
|
|
1540
|
+
* response; their output items (`web_search_call`, …) are retained in
|
|
1541
|
+
* `providerMetadata.openai.output` for inspection and are not replayed
|
|
1542
|
+
* (with `store: false` the next turn only needs the answer text), and a
|
|
1543
|
+
* reasoning item that led into one is not replayed either (see
|
|
1544
|
+
* `pickTurnReasoning`).
|
|
1419
1545
|
*/
|
|
1420
|
-
var
|
|
1421
|
-
|
|
1546
|
+
var OpenAIResponsesModel = class {
|
|
1547
|
+
/**
|
|
1548
|
+
* `options.compatible` lets a vendor package that implements `/v1/responses`
|
|
1549
|
+
* (xAI) reuse this adapter under its own provider label. It is accepted
|
|
1550
|
+
* only from those packages' own code: it drops the OpenAI-only request
|
|
1551
|
+
* fields (`include` of encrypted reasoning and search sources), so no
|
|
1552
|
+
* reasoning replay happens and no field unknown to the vendor is sent.
|
|
1553
|
+
*/
|
|
1554
|
+
constructor(client, config, provider = "openai", options = {}) {
|
|
1422
1555
|
this.logger = _warlock_js_logger.log;
|
|
1423
|
-
|
|
1556
|
+
this.compatible = options.compatible === true;
|
|
1557
|
+
if (provider !== "openai" && !this.compatible) throw new _warlock_js_ai.InvalidRequestError(`api: "responses" is supported only on the direct "openai" provider; got provider "${provider}".`, { context: {
|
|
1424
1558
|
provider,
|
|
1425
1559
|
model: config.name,
|
|
1426
|
-
api:
|
|
1560
|
+
api: "responses"
|
|
1427
1561
|
} });
|
|
1428
1562
|
this.client = client;
|
|
1429
1563
|
this.config = config;
|
|
@@ -1434,19 +1568,19 @@ var OpenAIModel = class {
|
|
|
1434
1568
|
structuredOutput: config.structuredOutput ?? inferStructuredOutput(config.responseFormat),
|
|
1435
1569
|
vision: config.vision ?? inferVisionCapability(config.name),
|
|
1436
1570
|
reasoning: config.reasoning ?? inferReasoningCapability(config.name),
|
|
1437
|
-
promptCaching:
|
|
1438
|
-
pdf:
|
|
1439
|
-
audio:
|
|
1571
|
+
promptCaching: true,
|
|
1572
|
+
pdf: false,
|
|
1573
|
+
audio: false
|
|
1440
1574
|
};
|
|
1441
1575
|
}
|
|
1442
1576
|
/**
|
|
1443
|
-
* Single-shot completion. Sends the full
|
|
1444
|
-
*
|
|
1445
|
-
* into a vendor-neutral `ModelResponse`. Per-call `options` override the
|
|
1446
|
-
* instance
|
|
1577
|
+
* Single-shot completion against `client.responses.create`. Sends the full
|
|
1578
|
+
* history as Responses `input` items, walks `response.output`, and reshapes
|
|
1579
|
+
* it into a vendor-neutral `ModelResponse`. Per-call `options` override the
|
|
1580
|
+
* instance defaults for this call only.
|
|
1447
1581
|
*/
|
|
1448
1582
|
async complete(messages, options) {
|
|
1449
|
-
this.logger.debug(LOG_MODULE$3, "request", "Starting call to
|
|
1583
|
+
this.logger.debug(LOG_MODULE$3, "request", "Starting call to responses.create", {
|
|
1450
1584
|
model: this.name,
|
|
1451
1585
|
messageCount: messages.length,
|
|
1452
1586
|
streaming: false,
|
|
@@ -1454,167 +1588,216 @@ var OpenAIModel = class {
|
|
|
1454
1588
|
});
|
|
1455
1589
|
let response;
|
|
1456
1590
|
try {
|
|
1457
|
-
response = await this.client.
|
|
1458
|
-
model: this.name,
|
|
1459
|
-
...compatibleSearchParams(this.provider, options),
|
|
1460
|
-
messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),
|
|
1461
|
-
...this.buildSamplingParams(options),
|
|
1462
|
-
...buildPromptCacheParams(this.provider, this.config),
|
|
1463
|
-
...this.buildTools(options),
|
|
1464
|
-
...this.buildResponseFormat(options?.responseSchema),
|
|
1465
|
-
...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length))
|
|
1466
|
-
}, options), options?.signal ? { signal: options.signal } : void 0);
|
|
1591
|
+
response = await this.client.responses.create(this.buildRequest(messages, options), options?.signal ? { signal: options.signal } : void 0);
|
|
1467
1592
|
} catch (thrown) {
|
|
1468
|
-
|
|
1469
|
-
this.logger.error(LOG_MODULE$3, "error", wrapped.message, {
|
|
1470
|
-
code: wrapped.code,
|
|
1471
|
-
context: wrapped.context
|
|
1472
|
-
});
|
|
1473
|
-
throw wrapped;
|
|
1593
|
+
throw this.logAndWrap(thrown);
|
|
1474
1594
|
}
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1595
|
+
if (response.status === "failed") throw this.logAndWrap(toResponseFailure(response, this.name));
|
|
1596
|
+
const output = Array.isArray(response.output) ? response.output : [];
|
|
1597
|
+
const { content, toolCalls } = this.readOutput(output);
|
|
1598
|
+
const finishReason = mapResponsesFinishReason({
|
|
1599
|
+
status: response.status,
|
|
1600
|
+
incomplete_details: response.incomplete_details,
|
|
1601
|
+
hasToolCalls: toolCalls !== void 0
|
|
1602
|
+
});
|
|
1482
1603
|
const usage = this.extractUsage(response.usage);
|
|
1483
|
-
|
|
1604
|
+
const providerMetadata = hostedOutput(usage, output, this.pricing, this.compatible ? this.provider : "openai");
|
|
1605
|
+
this.logger.debug(LOG_MODULE$3, "response", "call to responses.create succeeded", {
|
|
1484
1606
|
finishReason,
|
|
1485
1607
|
usage
|
|
1486
1608
|
});
|
|
1487
1609
|
return {
|
|
1488
|
-
content
|
|
1610
|
+
content,
|
|
1489
1611
|
finishReason,
|
|
1490
1612
|
usage,
|
|
1491
|
-
|
|
1613
|
+
...providerMetadata ? { providerMetadata } : {},
|
|
1614
|
+
...toolCalls ? { toolCalls } : {}
|
|
1492
1615
|
};
|
|
1493
1616
|
}
|
|
1617
|
+
/** Count native Responses input tokens using the same converted input and tools. */
|
|
1618
|
+
async countTokens(messages, options) {
|
|
1619
|
+
const request = this.buildRequest(messages, options);
|
|
1620
|
+
const body = {
|
|
1621
|
+
model: request.model,
|
|
1622
|
+
input: request.input,
|
|
1623
|
+
instructions: request.instructions,
|
|
1624
|
+
tools: request.tools,
|
|
1625
|
+
tool_choice: request.tool_choice,
|
|
1626
|
+
reasoning: request.reasoning,
|
|
1627
|
+
text: request.text,
|
|
1628
|
+
parallel_tool_calls: request.parallel_tool_calls,
|
|
1629
|
+
truncation: request.truncation ?? void 0
|
|
1630
|
+
};
|
|
1631
|
+
try {
|
|
1632
|
+
return (await this.client.responses.inputTokens.count(body, options?.signal ? { signal: options.signal } : void 0)).input_tokens;
|
|
1633
|
+
} catch (thrown) {
|
|
1634
|
+
throw this.logAndWrap(thrown);
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1494
1637
|
/**
|
|
1495
|
-
* Incremental streaming completion.
|
|
1496
|
-
*
|
|
1497
|
-
*
|
|
1498
|
-
* Callers consume it with `for await`.
|
|
1638
|
+
* Incremental streaming completion via `responses.create({ stream: true })`
|
|
1639
|
+
* (the SDK's `Stream<ResponseStreamEvent>`, `responses.d.ts:55`). Yields the
|
|
1640
|
+
* same neutral `ModelStreamChunk` sequence as the Chat path:
|
|
1499
1641
|
*
|
|
1500
|
-
*
|
|
1501
|
-
* `
|
|
1502
|
-
*
|
|
1503
|
-
*
|
|
1642
|
+
* - `response.output_text.delta` / `response.refusal.delta` -> `delta`.
|
|
1643
|
+
* - `response.output_item.done` with a completed `function_call` item ->
|
|
1644
|
+
* buffered; `reasoning` items are captured for replay. The `done` copy is
|
|
1645
|
+
* used because the `added` copy may be incomplete (`responses.d.ts:5711`).
|
|
1646
|
+
* - After the loop: the buffered `tool-call`s (the first carries the
|
|
1647
|
+
* replay metadata), then a single `done` with the finish reason and usage
|
|
1648
|
+
* from `response.completed` / `response.incomplete`.
|
|
1649
|
+
* - `response.failed` and `error` events throw a typed `AIError`; a stream
|
|
1650
|
+
* that ends with no terminal event throws `ProviderError`.
|
|
1651
|
+
* - Abort goes through the request `signal`; the SDK rejects the read and
|
|
1652
|
+
* the error is wrapped like any other.
|
|
1504
1653
|
*/
|
|
1505
1654
|
async *stream(messages, options) {
|
|
1506
|
-
this.logger.debug(LOG_MODULE$3, "request", "Starting streaming call to
|
|
1655
|
+
this.logger.debug(LOG_MODULE$3, "request", "Starting streaming call to responses.create", {
|
|
1507
1656
|
model: this.name,
|
|
1508
1657
|
messageCount: messages.length,
|
|
1509
1658
|
streaming: true,
|
|
1510
1659
|
toolCount: options?.tools?.length ?? 0
|
|
1511
1660
|
});
|
|
1512
|
-
let
|
|
1661
|
+
let events;
|
|
1513
1662
|
try {
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
...this.buildSamplingParams(options),
|
|
1519
|
-
...buildPromptCacheParams(this.provider, this.config),
|
|
1520
|
-
...this.buildTools(options),
|
|
1521
|
-
stream: true,
|
|
1522
|
-
stream_options: { include_usage: true },
|
|
1523
|
-
...this.buildResponseFormat(options?.responseSchema),
|
|
1524
|
-
...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length))
|
|
1525
|
-
}, options), options?.signal ? { signal: options.signal } : void 0);
|
|
1663
|
+
events = await this.client.responses.create({
|
|
1664
|
+
...this.buildRequest(messages, options),
|
|
1665
|
+
stream: true
|
|
1666
|
+
}, options?.signal ? { signal: options.signal } : void 0);
|
|
1526
1667
|
} catch (thrown) {
|
|
1527
|
-
|
|
1528
|
-
this.logger.error(LOG_MODULE$3, "error", wrapped.message, {
|
|
1529
|
-
code: wrapped.code,
|
|
1530
|
-
context: wrapped.context
|
|
1531
|
-
});
|
|
1532
|
-
throw wrapped;
|
|
1668
|
+
throw this.logAndWrap(thrown);
|
|
1533
1669
|
}
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
input: 0,
|
|
1537
|
-
output: 0,
|
|
1538
|
-
total: 0
|
|
1539
|
-
};
|
|
1670
|
+
const toolCalls = [];
|
|
1671
|
+
const outputItems = [];
|
|
1540
1672
|
const want = (0, _warlock_js_ai.resolveStreamChunks)(options);
|
|
1541
|
-
const
|
|
1673
|
+
const streamingCalls = /* @__PURE__ */ new Map();
|
|
1674
|
+
let terminal;
|
|
1542
1675
|
try {
|
|
1543
|
-
for await (const
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1676
|
+
for await (const event of events) {
|
|
1677
|
+
if (event.type === "response.output_text.delta" || event.type === "response.refusal.delta") {
|
|
1678
|
+
if (event.delta) yield {
|
|
1679
|
+
type: "delta",
|
|
1680
|
+
content: event.delta
|
|
1681
|
+
};
|
|
1682
|
+
continue;
|
|
1683
|
+
}
|
|
1684
|
+
if (event.type === "response.reasoning_summary_text.delta" || event.type === "response.reasoning_text.delta") {
|
|
1685
|
+
if (want.reasoning && event.delta) yield {
|
|
1549
1686
|
type: "reasoning",
|
|
1550
|
-
delta:
|
|
1687
|
+
delta: event.delta
|
|
1551
1688
|
};
|
|
1689
|
+
continue;
|
|
1552
1690
|
}
|
|
1553
|
-
if (
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
const idx = toolCall.index ?? 0;
|
|
1559
|
-
if (!toolCallAccum.has(idx)) toolCallAccum.set(idx, {
|
|
1560
|
-
id: "",
|
|
1561
|
-
name: "",
|
|
1562
|
-
arguments: "",
|
|
1563
|
-
streamed: 0
|
|
1691
|
+
if (event.type === "response.output_item.added") {
|
|
1692
|
+
const { item } = event;
|
|
1693
|
+
if (item.type === "function_call" && item.id) streamingCalls.set(item.id, {
|
|
1694
|
+
callId: item.call_id,
|
|
1695
|
+
name: item.name
|
|
1564
1696
|
});
|
|
1565
|
-
|
|
1566
|
-
if (toolCall.id) acc.id = toolCall.id;
|
|
1567
|
-
if (toolCall.function?.name) acc.name = toolCall.function.name;
|
|
1568
|
-
if (toolCall.function?.arguments) acc.arguments += toolCall.function.arguments;
|
|
1569
|
-
if (want.toolArgs && acc.name && acc.arguments.length > acc.streamed) {
|
|
1570
|
-
yield {
|
|
1571
|
-
type: "tool-args",
|
|
1572
|
-
callId: acc.id,
|
|
1573
|
-
name: acc.name,
|
|
1574
|
-
delta: acc.arguments.slice(acc.streamed)
|
|
1575
|
-
};
|
|
1576
|
-
acc.streamed = acc.arguments.length;
|
|
1577
|
-
}
|
|
1697
|
+
continue;
|
|
1578
1698
|
}
|
|
1579
|
-
if (
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1699
|
+
if (event.type === "response.function_call_arguments.delta") {
|
|
1700
|
+
const call = streamingCalls.get(event.item_id);
|
|
1701
|
+
if (want.toolArgs && call && event.delta) yield {
|
|
1702
|
+
type: "tool-args",
|
|
1703
|
+
callId: call.callId,
|
|
1704
|
+
name: call.name,
|
|
1705
|
+
delta: event.delta
|
|
1706
|
+
};
|
|
1707
|
+
continue;
|
|
1708
|
+
}
|
|
1709
|
+
if (event.type === "response.output_item.done") {
|
|
1710
|
+
const { item } = event;
|
|
1711
|
+
this.assertServerRunItem(item);
|
|
1712
|
+
outputItems.push(item);
|
|
1713
|
+
if (item.type === "function_call" && item.status !== "incomplete") toolCalls.push(this.toToolCall(item));
|
|
1714
|
+
continue;
|
|
1715
|
+
}
|
|
1716
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
1717
|
+
terminal = event.response;
|
|
1718
|
+
continue;
|
|
1719
|
+
}
|
|
1720
|
+
if (event.type === "response.failed") throw toResponseFailure(event.response, this.name);
|
|
1721
|
+
if (event.type === "error") throw wrapOpenAIError({
|
|
1722
|
+
code: event.code,
|
|
1723
|
+
message: event.message,
|
|
1724
|
+
param: event.param
|
|
1725
|
+
});
|
|
1590
1726
|
}
|
|
1727
|
+
if (terminal === void 0) throw new _warlock_js_ai.ProviderError("OpenAI Responses stream ended before response.completed.", { context: {
|
|
1728
|
+
provider: this.provider,
|
|
1729
|
+
model: this.name
|
|
1730
|
+
} });
|
|
1591
1731
|
} catch (thrown) {
|
|
1592
|
-
|
|
1593
|
-
this.logger.error(LOG_MODULE$3, "error", wrapped.message, {
|
|
1594
|
-
code: wrapped.code,
|
|
1595
|
-
context: wrapped.context
|
|
1596
|
-
});
|
|
1597
|
-
throw wrapped;
|
|
1732
|
+
throw this.logAndWrap(thrown);
|
|
1598
1733
|
}
|
|
1599
|
-
const
|
|
1600
|
-
|
|
1734
|
+
for (const call of attachReasoningReplay(toolCalls, this.name, pickTurnReasoning(outputItems))) yield {
|
|
1735
|
+
type: "tool-call",
|
|
1736
|
+
id: call.id,
|
|
1737
|
+
name: call.name,
|
|
1738
|
+
input: call.input,
|
|
1739
|
+
...call.providerMetadata ? { providerMetadata: call.providerMetadata } : {}
|
|
1740
|
+
};
|
|
1741
|
+
const finishReason = mapResponsesFinishReason({
|
|
1742
|
+
status: terminal.status,
|
|
1743
|
+
incomplete_details: terminal.incomplete_details,
|
|
1744
|
+
hasToolCalls: toolCalls.length > 0
|
|
1745
|
+
});
|
|
1746
|
+
const usage = this.extractUsage(terminal.usage);
|
|
1747
|
+
const output = terminal.output?.length ? terminal.output : outputItems;
|
|
1748
|
+
const providerMetadata = hostedOutput(usage, output, this.pricing, this.compatible ? this.provider : "openai");
|
|
1749
|
+
this.logger.debug(LOG_MODULE$3, "response", "Streaming call to responses.create succeeded", {
|
|
1601
1750
|
finishReason,
|
|
1602
1751
|
usage
|
|
1603
1752
|
});
|
|
1604
1753
|
yield {
|
|
1605
1754
|
type: "done",
|
|
1606
1755
|
finishReason,
|
|
1607
|
-
usage
|
|
1756
|
+
usage,
|
|
1757
|
+
...providerMetadata ? { providerMetadata } : {}
|
|
1608
1758
|
};
|
|
1609
1759
|
}
|
|
1610
1760
|
/**
|
|
1611
|
-
*
|
|
1612
|
-
*
|
|
1613
|
-
*
|
|
1614
|
-
*
|
|
1615
|
-
*
|
|
1616
|
-
*
|
|
1617
|
-
*
|
|
1761
|
+
* Assemble the `responses.create` body.
|
|
1762
|
+
*
|
|
1763
|
+
* - System prompt -> `instructions`; history -> `input` items.
|
|
1764
|
+
* - `store: false` always (the API default is `true` when omitted), plus
|
|
1765
|
+
* `include: ["reasoning.encrypted_content"]` for stateless reasoning replay.
|
|
1766
|
+
* - `max_output_tokens` caps reasoning and visible output together.
|
|
1767
|
+
* - `temperature` only for non-reasoning models (same rule as Chat).
|
|
1768
|
+
* - `tools` flat with `strict: false`; `tool_choice` only with tools.
|
|
1769
|
+
* - `reasoning.effort` only when the caller gave one, through the same
|
|
1770
|
+
* clamp table as Chat. With no explicit effort the provider default
|
|
1771
|
+
* applies EVEN with tools attached - that is the point of this API.
|
|
1772
|
+
*/
|
|
1773
|
+
buildRequest(messages, options) {
|
|
1774
|
+
const { instructions, input } = toResponsesInput(messages, this.name);
|
|
1775
|
+
const tools = this.buildTools(options);
|
|
1776
|
+
const toolChoice = tools ? toResponsesToolChoice(options?.toolChoice) : void 0;
|
|
1777
|
+
const maxTokens = options?.maxTokens ?? this.config.maxTokens;
|
|
1778
|
+
const temperature = options?.temperature ?? this.config.temperature;
|
|
1779
|
+
const include = this.compatible ? [] : ["reasoning.encrypted_content", ...tools?.some((tool) => tool.type === "web_search" || tool.type === "web_search_2025_08_26" || tool.type === "web_search_preview" || tool.type === "web_search_preview_2025_03_11") ? ["web_search_call.action.sources"] : []];
|
|
1780
|
+
return mergeProviderBody({
|
|
1781
|
+
model: this.name,
|
|
1782
|
+
...instructions !== void 0 ? { instructions } : {},
|
|
1783
|
+
input,
|
|
1784
|
+
store: false,
|
|
1785
|
+
...include.length > 0 ? { include } : {},
|
|
1786
|
+
...maxTokens !== void 0 ? { max_output_tokens: maxTokens } : {},
|
|
1787
|
+
...!this.capabilities.reasoning && temperature !== void 0 ? { temperature } : {},
|
|
1788
|
+
...tools ? { tools } : {},
|
|
1789
|
+
...toolChoice !== void 0 ? { tool_choice: toolChoice } : {},
|
|
1790
|
+
...this.buildTextFormat(options?.responseSchema),
|
|
1791
|
+
...this.buildReasoningParams(options?.reasoning),
|
|
1792
|
+
...buildPromptCacheParams(this.provider, this.config)
|
|
1793
|
+
}, options);
|
|
1794
|
+
}
|
|
1795
|
+
/**
|
|
1796
|
+
* The request `tools`: function tools (flat, `strict: false`), then the
|
|
1797
|
+
* `ai.providerTool({ provider: "openai" })` definitions verbatim — the
|
|
1798
|
+
* Responses built-in tools (`web_search`, `file_search`,
|
|
1799
|
+
* `code_interpreter`, `image_generation`, `mcp`, …). Other providers'
|
|
1800
|
+
* definitions are skipped with a warning. `undefined` when there are none.
|
|
1618
1801
|
*/
|
|
1619
1802
|
buildTools(options) {
|
|
1620
1803
|
const { tools, definitions } = (0, _warlock_js_ai.selectProviderTools)(options, {
|
|
@@ -1623,240 +1806,160 @@ var OpenAIModel = class {
|
|
|
1623
1806
|
model: this.name,
|
|
1624
1807
|
logger: this.logger
|
|
1625
1808
|
});
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
return definition.type === "builtin_function" && typeof fn === "object" && fn !== null && "name" in fn && fn.name === "$web_search";
|
|
1629
|
-
})) throw new _warlock_js_ai.InvalidRequestError("Kimi's builtin $web_search retires on 20 October 2026. Use kimiSearchTool() / kimiFetchTool() from @warlock.js/ai-openai.");
|
|
1630
|
-
if (this.provider === "xai" && definitions.some((definition) => definition.type === "web_search" || definition.type === "x_search")) throw new _warlock_js_ai.InvalidRequestError("xAI native web_search / x_search requires POST /v1/responses. XaiSDK currently supports Chat Completions only; use xAI's Responses API with the vendor SDK for native search.");
|
|
1631
|
-
const mapped = [...toOpenAITools(tools) ?? [], ...definitions];
|
|
1632
|
-
return mapped.length > 0 ? { tools: mapped } : {};
|
|
1633
|
-
}
|
|
1634
|
-
/** Map the neutral cache hint only for the direct OpenAI provider. */
|
|
1635
|
-
promptCacheBreakpoints(options) {
|
|
1636
|
-
return this.provider === "openai" ? options?.cacheControl?.breakpoints ?? 0 : 0;
|
|
1809
|
+
const mapped = [...toResponsesTools(tools) ?? [], ...definitions];
|
|
1810
|
+
return mapped.length > 0 ? mapped : void 0;
|
|
1637
1811
|
}
|
|
1638
1812
|
/**
|
|
1639
|
-
*
|
|
1640
|
-
* `
|
|
1641
|
-
* strict-
|
|
1642
|
-
* `planStructuredOutput
|
|
1643
|
-
*
|
|
1644
|
-
* Returns an empty spread when no schema was supplied, so the caller
|
|
1645
|
-
* can unconditionally `...buildResponseFormat(...)` into the request.
|
|
1813
|
+
* Structured output on Responses lives in `text.format`, and `name` /
|
|
1814
|
+
* `schema` / `strict` sit directly on the format object (Chat nests them
|
|
1815
|
+
* under `json_schema`). The strict-or-downgrade decision is the shared
|
|
1816
|
+
* `planStructuredOutput`.
|
|
1646
1817
|
*/
|
|
1647
|
-
|
|
1818
|
+
buildTextFormat(responseSchema) {
|
|
1648
1819
|
const plan = planStructuredOutput(responseSchema, this.config.responseFormat);
|
|
1649
|
-
if (plan.mode === "json_schema") return {
|
|
1820
|
+
if (plan.mode === "json_schema") return { text: { format: {
|
|
1650
1821
|
type: "json_schema",
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
} };
|
|
1657
|
-
if (plan.mode === "json_object") return { response_format: { type: "json_object" } };
|
|
1822
|
+
name: "response",
|
|
1823
|
+
schema: plan.schema,
|
|
1824
|
+
strict: true
|
|
1825
|
+
} } };
|
|
1826
|
+
if (plan.mode === "json_object") return { text: { format: { type: "json_object" } } };
|
|
1658
1827
|
return {};
|
|
1659
1828
|
}
|
|
1829
|
+
/** `reasoning.effort` for reasoning-capable models, only when the caller set one. */
|
|
1830
|
+
buildReasoningParams(reasoning) {
|
|
1831
|
+
if (!this.capabilities.reasoning || !reasoning?.effort) return {};
|
|
1832
|
+
return { reasoning: { effort: toOpenAIReasoningEffort(reasoning.effort) } };
|
|
1833
|
+
}
|
|
1660
1834
|
/**
|
|
1661
|
-
*
|
|
1662
|
-
*
|
|
1663
|
-
*
|
|
1664
|
-
*
|
|
1665
|
-
*
|
|
1666
|
-
*
|
|
1667
|
-
*
|
|
1668
|
-
*
|
|
1669
|
-
* (the hidden reasoning channel on o-series / gpt-5 models, already
|
|
1670
|
-
* counted within `output`). Both are emitted only when the provider
|
|
1671
|
-
* reports a positive value, so non-reasoning / uncached calls keep the
|
|
1672
|
-
* lean `{ input, output, total }` shape. `cacheWriteTokens` mirrors
|
|
1673
|
-
* `prompt_tokens_details.cache_write_tokens` (billed writes on the
|
|
1674
|
-
* models that charge for them). `cost` is attached when priced.
|
|
1835
|
+
* Walk `response.output`: `message` items contribute their `output_text`
|
|
1836
|
+
* text and any `refusal` text (surfaced as ordinary content, decision 5);
|
|
1837
|
+
* each completed `function_call` item becomes one tool call with
|
|
1838
|
+
* `id = call_id`. `reasoning` items carry no visible content and are
|
|
1839
|
+
* not content. A `function_call` the API marked `incomplete` (truncated
|
|
1840
|
+
* arguments) is skipped rather than dispatched with empty input.
|
|
1841
|
+
* `reasoning` items are captured and attached to the first tool call for
|
|
1842
|
+
* replay (see `attachReasoningReplay`).
|
|
1675
1843
|
*/
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1844
|
+
readOutput(output) {
|
|
1845
|
+
let content = "";
|
|
1846
|
+
const toolCalls = [];
|
|
1847
|
+
for (const item of output) {
|
|
1848
|
+
this.assertServerRunItem(item);
|
|
1849
|
+
if (item.type === "message") {
|
|
1850
|
+
for (const part of item.content) content += part.type === "refusal" ? part.refusal : part.text;
|
|
1851
|
+
continue;
|
|
1852
|
+
}
|
|
1853
|
+
if (item.type === "function_call" && item.status !== "incomplete") toolCalls.push(this.toToolCall(item));
|
|
1854
|
+
}
|
|
1855
|
+
return {
|
|
1856
|
+
content,
|
|
1857
|
+
toolCalls: toolCalls.length > 0 ? attachReasoningReplay(toolCalls, this.name, pickTurnReasoning(output)) : void 0
|
|
1681
1858
|
};
|
|
1682
|
-
return buildUsage({
|
|
1683
|
-
input: raw.prompt_tokens ?? 0,
|
|
1684
|
-
output: raw.completion_tokens ?? 0,
|
|
1685
|
-
total: raw.total_tokens ?? 0,
|
|
1686
|
-
cachedTokens: raw.prompt_tokens_details?.cached_tokens,
|
|
1687
|
-
cacheWriteTokens: raw.prompt_tokens_details?.cache_write_tokens,
|
|
1688
|
-
reasoningTokens: raw.completion_tokens_details?.reasoning_tokens
|
|
1689
|
-
}, this.pricing);
|
|
1690
1859
|
}
|
|
1691
1860
|
/**
|
|
1692
|
-
*
|
|
1693
|
-
* `
|
|
1694
|
-
*
|
|
1695
|
-
* so
|
|
1696
|
-
*
|
|
1697
|
-
*
|
|
1698
|
-
* The neutral `ReasoningEffort` (`"low" | "medium" | "high" | "none"`)
|
|
1699
|
-
* is a subset of OpenAI's accepted values, so it forwards verbatim —
|
|
1700
|
-
* `"none"` included. `"none"` is load-bearing: gpt-5 / o-series models
|
|
1701
|
-
* **reject function tools** on Chat Completions while reasoning is
|
|
1702
|
-
* active, and the endpoint accepts tools only when `reasoning_effort`
|
|
1703
|
-
* is `"none"` (the alternative is the Responses API). This is why the
|
|
1704
|
-
* param is EMITTED for `"none"` rather than omitted — omitting it
|
|
1705
|
-
* leaves the model reasoning server-side by default, so tools would
|
|
1706
|
-
* still be rejected.
|
|
1707
|
-
*
|
|
1708
|
-
* No-ops when the model is not reasoning-capable
|
|
1709
|
-
* (`capabilities.reasoning` is false — e.g. `gpt-4o`, which 400s on any
|
|
1710
|
-
* `reasoning_effort`).
|
|
1711
|
-
*
|
|
1712
|
-
* When the caller gave no explicit `effort`: defaults to `"none"` IF
|
|
1713
|
-
* `hasTools` is true, else omits the param (provider default — the
|
|
1714
|
-
* pre-existing behavior for a tool-less call). The default exists
|
|
1715
|
-
* because, on a reasoning-capable model, there is no working alternative
|
|
1716
|
-
* to `"none"` when tools are attached — omitting `reasoning_effort`
|
|
1717
|
-
* leaves reasoning on server-side, which Chat Completions rejects tools
|
|
1718
|
-
* for (empty replies on some model generations, a hard 400 — "Function
|
|
1719
|
-
* tools with reasoning_effort are not supported ... in
|
|
1720
|
-
* /v1/chat/completions" — on newer ones). An explicit `effort` from the
|
|
1721
|
-
* caller always wins over this default, in either direction.
|
|
1722
|
-
*
|
|
1723
|
-
* Returns an empty spread when nothing applies, so the caller can
|
|
1724
|
-
* unconditionally `...buildReasoningParams(...)` into the request.
|
|
1725
|
-
*/
|
|
1726
|
-
/**
|
|
1727
|
-
* Output-length and sampling params, in current Chat Completions shapes only.
|
|
1728
|
-
*
|
|
1729
|
-
* - `max_completion_tokens`, never the legacy `max_tokens`: current
|
|
1730
|
-
* models (the gpt-5 family and later) answer `400 unsupported_parameter`
|
|
1731
|
-
* to `max_tokens`, and `max_completion_tokens` is accepted everywhere.
|
|
1732
|
-
* - No `temperature` for a reasoning-capable model: those accept only the
|
|
1733
|
-
* default value and reject any other with a 400.
|
|
1861
|
+
* Fail closed on a built-in tool call that YOUR code would have to run
|
|
1862
|
+
* (`shell_call`, `apply_patch_call`, `computer_call`, …, from a
|
|
1863
|
+
* provider-defined client tool). These items have their own output item
|
|
1864
|
+
* types that this adapter does not map, so the turn would otherwise end
|
|
1865
|
+
* silently with the call dropped. Hosted (server-run) tool items pass.
|
|
1734
1866
|
*/
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1867
|
+
assertServerRunItem(item) {
|
|
1868
|
+
if (!CLIENT_RUN_ITEM_TYPES.has(item.type)) return;
|
|
1869
|
+
throw new _warlock_js_ai.InvalidRequestError(`OpenAI returned a "${item.type}" item: that built-in tool is executed by the caller, which the Responses adapter does not support. Use OpenAI's server-run built-in tools (web_search, file_search, code_interpreter, image_generation, mcp without approval) with ai.providerTool(), or a function tool from ai.tool().`, { context: {
|
|
1870
|
+
provider: this.provider,
|
|
1871
|
+
model: this.name,
|
|
1872
|
+
itemType: item.type
|
|
1873
|
+
} });
|
|
1874
|
+
}
|
|
1875
|
+
/** One completed `function_call` item as a neutral tool call (`call_id` -> `id`). */
|
|
1876
|
+
toToolCall(item) {
|
|
1738
1877
|
return {
|
|
1739
|
-
|
|
1740
|
-
|
|
1878
|
+
id: item.call_id,
|
|
1879
|
+
name: item.name,
|
|
1880
|
+
input: (0, _warlock_js_ai.safeJsonParse)(item.arguments, {})
|
|
1741
1881
|
};
|
|
1742
1882
|
}
|
|
1743
|
-
buildReasoningParams(reasoning, hasTools) {
|
|
1744
|
-
if (!this.capabilities.reasoning) return {};
|
|
1745
|
-
if (!reasoning?.effort) return hasTools ? { reasoning_effort: "none" } : {};
|
|
1746
|
-
return { reasoning_effort: toOpenAIReasoningEffort(reasoning.effort) };
|
|
1747
|
-
}
|
|
1748
1883
|
/**
|
|
1749
|
-
*
|
|
1750
|
-
* `
|
|
1751
|
-
*
|
|
1752
|
-
*
|
|
1753
|
-
*
|
|
1754
|
-
* can branch on presence.
|
|
1884
|
+
* Normalize `usage` (absent on some partials) into the neutral `Usage`.
|
|
1885
|
+
* `input_tokens_details.cached_tokens` -> `cachedTokens`,
|
|
1886
|
+
* `cache_write_tokens` -> `cacheWriteTokens`,
|
|
1887
|
+
* `output_tokens_details.reasoning_tokens` -> `reasoningTokens`. The
|
|
1888
|
+
* detail blocks are typed non-optional but read defensively.
|
|
1755
1889
|
*/
|
|
1756
|
-
|
|
1757
|
-
if (!
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1890
|
+
extractUsage(raw) {
|
|
1891
|
+
if (!raw) return {
|
|
1892
|
+
input: 0,
|
|
1893
|
+
output: 0,
|
|
1894
|
+
total: 0
|
|
1895
|
+
};
|
|
1896
|
+
return buildUsage({
|
|
1897
|
+
input: raw.input_tokens,
|
|
1898
|
+
output: raw.output_tokens,
|
|
1899
|
+
total: raw.total_tokens,
|
|
1900
|
+
cachedTokens: raw.input_tokens_details?.cached_tokens,
|
|
1901
|
+
cacheWriteTokens: raw.input_tokens_details?.cache_write_tokens,
|
|
1902
|
+
reasoningTokens: raw.output_tokens_details?.reasoning_tokens
|
|
1903
|
+
}, this.pricing);
|
|
1763
1904
|
}
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
function readReasoningDelta(delta) {
|
|
1773
|
-
const record = delta;
|
|
1774
|
-
for (const key of ["reasoning_content", "reasoning"]) {
|
|
1775
|
-
const value = record[key];
|
|
1776
|
-
if (typeof value === "string" && value !== "") return value;
|
|
1905
|
+
/** Wrap (idempotently), log and return a failure for the caller to throw. */
|
|
1906
|
+
logAndWrap(thrown) {
|
|
1907
|
+
const wrapped = wrapOpenAIError(thrown);
|
|
1908
|
+
this.logger.error(LOG_MODULE$3, "error", wrapped.message, {
|
|
1909
|
+
code: wrapped.code,
|
|
1910
|
+
context: wrapped.context
|
|
1911
|
+
});
|
|
1912
|
+
return wrapped;
|
|
1777
1913
|
}
|
|
1778
|
-
}
|
|
1779
|
-
|
|
1780
|
-
//#endregion
|
|
1781
|
-
//#region ../../packages/ai-openai/src/utils/hosted-output.ts
|
|
1782
|
-
/** Installed openai 7.23.0 ResponseFunctionWebSearch (action includes search/open_page/find).
|
|
1783
|
-
* https://developers.openai.com/api/docs/guides/tools-web-search
|
|
1784
|
-
* Count output items, never URLs, sources, answer text, or function calls.
|
|
1785
|
-
* Fees and search content tokens are separate; preview pricing varies:
|
|
1786
|
-
* https://developers.openai.com/api/docs/pricing#built-in-tools */
|
|
1787
|
-
function hostedOutput(usage, output, pricing) {
|
|
1788
|
-
const hosted = output.filter((item) => item.type !== "message" && item.type !== "reasoning" && item.type !== "function_call");
|
|
1789
|
-
const searches = hosted.filter((item) => item.type === "web_search_call");
|
|
1790
|
-
if (searches.length) usage.serverToolUse = {
|
|
1791
|
-
...usage.serverToolUse,
|
|
1792
|
-
webSearchRequests: searches.length
|
|
1793
|
-
};
|
|
1794
|
-
(0, _warlock_js_ai.attachCost)(usage, pricing);
|
|
1795
|
-
return hosted.length ? { openai: { output: hosted } } : void 0;
|
|
1796
|
-
}
|
|
1914
|
+
};
|
|
1797
1915
|
|
|
1798
1916
|
//#endregion
|
|
1799
|
-
//#region ../../packages/ai-openai/src/
|
|
1917
|
+
//#region ../../packages/ai-openai/src/model.ts
|
|
1800
1918
|
const LOG_MODULE$2 = "ai.openai";
|
|
1801
1919
|
/**
|
|
1802
|
-
*
|
|
1803
|
-
* (installed SDK `ResponseOutputItem` union). The adapter maps only
|
|
1804
|
-
* `function_call` to a neutral tool call, so these fail closed.
|
|
1805
|
-
*/
|
|
1806
|
-
const CLIENT_RUN_ITEM_TYPES = /* @__PURE__ */ new Set([
|
|
1807
|
-
"computer_call",
|
|
1808
|
-
"custom_tool_call",
|
|
1809
|
-
"local_shell_call",
|
|
1810
|
-
"shell_call",
|
|
1811
|
-
"apply_patch_call",
|
|
1812
|
-
"mcp_approval_request"
|
|
1813
|
-
]);
|
|
1814
|
-
/**
|
|
1815
|
-
* OpenAI Responses API implementation of `ModelContract` (`api: "responses"`).
|
|
1920
|
+
* OpenAI-backed implementation of `ModelContract`.
|
|
1816
1921
|
*
|
|
1817
|
-
* **Role.**
|
|
1818
|
-
*
|
|
1819
|
-
*
|
|
1820
|
-
* `
|
|
1922
|
+
* **Role.** The provider-facing bridge between the vendor-neutral
|
|
1923
|
+
* `@warlock.js/ai` agent runtime and the official `openai` SDK. Agents,
|
|
1924
|
+
* workflows, and supervisors never talk to OpenAI directly — they hold a
|
|
1925
|
+
* `ModelContract`, and this class is what makes that contract concrete for
|
|
1926
|
+
* any OpenAI-compatible endpoint (OpenAI, Azure OpenAI, OpenRouter, local
|
|
1927
|
+
* gateways that speak the Chat Completions protocol).
|
|
1821
1928
|
*
|
|
1822
|
-
* **
|
|
1823
|
-
*
|
|
1824
|
-
*
|
|
1825
|
-
*
|
|
1826
|
-
*
|
|
1929
|
+
* **Responsibility.**
|
|
1930
|
+
* - Owns: a long-lived `OpenAI` client + frozen `ModelConfig` (name,
|
|
1931
|
+
* temperature, maxTokens) used as defaults for every call.
|
|
1932
|
+
* - Owns: translating vendor-neutral `Message[]` and
|
|
1933
|
+
* `ToolContract[]` into OpenAI wire shapes on the way out, and
|
|
1934
|
+
* translating OpenAI's response (content, finish reason, tool calls,
|
|
1935
|
+
* usage) back into the neutral shapes on the way in.
|
|
1936
|
+
* - Does NOT own: dispatching tools, deciding whether to loop, tracking
|
|
1937
|
+
* conversation history, or retrying on failure — those are agent
|
|
1938
|
+
* concerns. The model is a stateless (per-call) protocol adapter.
|
|
1827
1939
|
*
|
|
1828
|
-
*
|
|
1829
|
-
*
|
|
1830
|
-
* call, exactly like the Chat path.
|
|
1940
|
+
* Because it holds a live client and shared defaults, it is modeled as a
|
|
1941
|
+
* class (see §4.2 of code-style.md — "long-lived state across calls").
|
|
1831
1942
|
*
|
|
1832
|
-
*
|
|
1833
|
-
*
|
|
1834
|
-
*
|
|
1835
|
-
*
|
|
1836
|
-
* before that turn's `function_call` items on the next request (only when the
|
|
1837
|
-
* stored model equals the current one). Text-only turns are not replayed.
|
|
1943
|
+
* @example
|
|
1944
|
+
* import OpenAI from "openai";
|
|
1945
|
+
* const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
|
|
1946
|
+
* const model = new OpenAIModel(client, { name: "gpt-4o", temperature: 0.3 });
|
|
1838
1947
|
*
|
|
1839
|
-
*
|
|
1840
|
-
*
|
|
1841
|
-
*
|
|
1842
|
-
*
|
|
1843
|
-
*
|
|
1948
|
+
* const myAgent = agent({
|
|
1949
|
+
* model,
|
|
1950
|
+
* systemPrompt: "You are a helpful assistant.",
|
|
1951
|
+
* tools: [searchTool],
|
|
1952
|
+
* });
|
|
1844
1953
|
*
|
|
1845
|
-
*
|
|
1846
|
-
* definitions are appended to `tools` verbatim. Hosted tools run inside the
|
|
1847
|
-
* response; their output items (`web_search_call`, …) are retained in
|
|
1848
|
-
* `providerMetadata.openai.output` for inspection and are not replayed
|
|
1849
|
-
* (with `store: false` the next turn only needs the answer text), and a
|
|
1850
|
-
* reasoning item that led into one is not replayed either (see
|
|
1851
|
-
* `pickTurnReasoning`).
|
|
1954
|
+
* const result = await myAgent.execute("Summarize today's news.");
|
|
1852
1955
|
*/
|
|
1853
|
-
var
|
|
1956
|
+
var OpenAIModel = class {
|
|
1854
1957
|
constructor(client, config, provider = "openai") {
|
|
1855
1958
|
this.logger = _warlock_js_logger.log;
|
|
1856
|
-
if (
|
|
1959
|
+
if (config.api === "responses") throw new _warlock_js_ai.InvalidRequestError("OpenAIModel speaks Chat Completions only and cannot serve api: \"responses\". Use OpenAISDK.model({ api: \"responses\" }) on the direct OpenAI provider.", { context: {
|
|
1857
1960
|
provider,
|
|
1858
1961
|
model: config.name,
|
|
1859
|
-
api:
|
|
1962
|
+
api: config.api
|
|
1860
1963
|
} });
|
|
1861
1964
|
this.client = client;
|
|
1862
1965
|
this.config = config;
|
|
@@ -1867,19 +1970,21 @@ var OpenAIResponsesModel = class {
|
|
|
1867
1970
|
structuredOutput: config.structuredOutput ?? inferStructuredOutput(config.responseFormat),
|
|
1868
1971
|
vision: config.vision ?? inferVisionCapability(config.name),
|
|
1869
1972
|
reasoning: config.reasoning ?? inferReasoningCapability(config.name),
|
|
1870
|
-
promptCaching:
|
|
1871
|
-
pdf: false,
|
|
1872
|
-
audio: false
|
|
1973
|
+
promptCaching: this.provider === "openai",
|
|
1974
|
+
pdf: config.pdf ?? false,
|
|
1975
|
+
audio: config.audio ?? false
|
|
1873
1976
|
};
|
|
1874
1977
|
}
|
|
1875
1978
|
/**
|
|
1876
|
-
* Single-shot completion
|
|
1877
|
-
*
|
|
1878
|
-
*
|
|
1879
|
-
* instance defaults for this call only.
|
|
1979
|
+
* Single-shot completion. Sends the full message list to the Chat
|
|
1980
|
+
* Completions endpoint, waits for the terminal response, and reshapes it
|
|
1981
|
+
* into a vendor-neutral `ModelResponse`. Per-call `options` override the
|
|
1982
|
+
* instance's `ModelConfig` defaults for this call only.
|
|
1880
1983
|
*/
|
|
1881
1984
|
async complete(messages, options) {
|
|
1882
|
-
|
|
1985
|
+
const searchRoute = this.hostedSearchRoute(options);
|
|
1986
|
+
if (searchRoute) return searchRoute.complete(messages, options);
|
|
1987
|
+
this.logger.debug(LOG_MODULE$2, "request", "Starting call to chat.completions", {
|
|
1883
1988
|
model: this.name,
|
|
1884
1989
|
messageCount: messages.length,
|
|
1885
1990
|
streaming: false,
|
|
@@ -1887,215 +1992,193 @@ var OpenAIResponsesModel = class {
|
|
|
1887
1992
|
});
|
|
1888
1993
|
let response;
|
|
1889
1994
|
try {
|
|
1890
|
-
response = await this.client.
|
|
1995
|
+
response = await this.client.chat.completions.create(mergeProviderBody({
|
|
1996
|
+
model: this.name,
|
|
1997
|
+
...compatibleSearchParams(this.provider, options),
|
|
1998
|
+
messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),
|
|
1999
|
+
...this.buildSamplingParams(options),
|
|
2000
|
+
...buildPromptCacheParams(this.provider, this.config),
|
|
2001
|
+
...this.buildTools(options),
|
|
2002
|
+
...this.buildResponseFormat(options?.responseSchema),
|
|
2003
|
+
...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length))
|
|
2004
|
+
}, options), options?.signal ? { signal: options.signal } : void 0);
|
|
1891
2005
|
} catch (thrown) {
|
|
1892
|
-
|
|
2006
|
+
const wrapped = wrapOpenAIError(thrown);
|
|
2007
|
+
this.logger.error(LOG_MODULE$2, "error", wrapped.message, {
|
|
2008
|
+
code: wrapped.code,
|
|
2009
|
+
context: wrapped.context
|
|
2010
|
+
});
|
|
2011
|
+
throw wrapped;
|
|
1893
2012
|
}
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
});
|
|
2013
|
+
const [choice] = response.choices;
|
|
2014
|
+
if (choice === void 0) throw new _warlock_js_ai.ProviderError("OpenAI returned a response with no choices.", { context: {
|
|
2015
|
+
provider: "openai",
|
|
2016
|
+
model: this.name,
|
|
2017
|
+
choices: response.choices.length
|
|
2018
|
+
} });
|
|
2019
|
+
const finishReason = mapFinishReason(choice.finish_reason);
|
|
1902
2020
|
const usage = this.extractUsage(response.usage);
|
|
1903
|
-
|
|
1904
|
-
this.logger.debug(LOG_MODULE$2, "response", "call to responses.create succeeded", {
|
|
2021
|
+
this.logger.debug(LOG_MODULE$2, "response", "call to chat.completions succeeded", {
|
|
1905
2022
|
finishReason,
|
|
1906
2023
|
usage
|
|
1907
2024
|
});
|
|
1908
2025
|
return {
|
|
1909
|
-
content,
|
|
2026
|
+
content: choice.message.content ?? "",
|
|
1910
2027
|
finishReason,
|
|
1911
2028
|
usage,
|
|
1912
|
-
|
|
1913
|
-
...toolCalls ? { toolCalls } : {}
|
|
1914
|
-
};
|
|
1915
|
-
}
|
|
1916
|
-
/** Count native Responses input tokens using the same converted input and tools. */
|
|
1917
|
-
async countTokens(messages, options) {
|
|
1918
|
-
const request = this.buildRequest(messages, options);
|
|
1919
|
-
const body = {
|
|
1920
|
-
model: request.model,
|
|
1921
|
-
input: request.input,
|
|
1922
|
-
instructions: request.instructions,
|
|
1923
|
-
tools: request.tools,
|
|
1924
|
-
tool_choice: request.tool_choice,
|
|
1925
|
-
reasoning: request.reasoning,
|
|
1926
|
-
text: request.text,
|
|
1927
|
-
parallel_tool_calls: request.parallel_tool_calls,
|
|
1928
|
-
truncation: request.truncation ?? void 0
|
|
2029
|
+
toolCalls: this.extractToolCalls(choice.message.tool_calls)
|
|
1929
2030
|
};
|
|
1930
|
-
try {
|
|
1931
|
-
return (await this.client.responses.inputTokens.count(body, options?.signal ? { signal: options.signal } : void 0)).input_tokens;
|
|
1932
|
-
} catch (thrown) {
|
|
1933
|
-
throw this.logAndWrap(thrown);
|
|
1934
|
-
}
|
|
1935
2031
|
}
|
|
1936
2032
|
/**
|
|
1937
|
-
* Incremental streaming completion
|
|
1938
|
-
*
|
|
1939
|
-
*
|
|
2033
|
+
* Incremental streaming completion. Yields neutral `ModelStreamChunk`s —
|
|
2034
|
+
* `delta` for text tokens, `tool-call` when the model requests a tool,
|
|
2035
|
+
* and a terminal `done` carrying the final finish reason + usage totals.
|
|
2036
|
+
* Callers consume it with `for await`.
|
|
1940
2037
|
*
|
|
1941
|
-
*
|
|
1942
|
-
*
|
|
1943
|
-
*
|
|
1944
|
-
*
|
|
1945
|
-
* - After the loop: the buffered `tool-call`s (the first carries the
|
|
1946
|
-
* replay metadata), then a single `done` with the finish reason and usage
|
|
1947
|
-
* from `response.completed` / `response.incomplete`.
|
|
1948
|
-
* - `response.failed` and `error` events throw a typed `AIError`; a stream
|
|
1949
|
-
* that ends with no terminal event throws `ProviderError`.
|
|
1950
|
-
* - Abort goes through the request `signal`; the SDK rejects the read and
|
|
1951
|
-
* the error is wrapped like any other.
|
|
2038
|
+
* With `options.streamChunks` it also yields `tool-args` for each
|
|
2039
|
+
* `tool_calls[].function.arguments` fragment and `reasoning` for a
|
|
2040
|
+
* vendor's `reasoning_content` / `reasoning` delta field. Usage arrives
|
|
2041
|
+
* only on the final chunk here, so no `usage` chunk is emitted.
|
|
1952
2042
|
*/
|
|
1953
2043
|
async *stream(messages, options) {
|
|
1954
|
-
|
|
2044
|
+
const searchRoute = this.hostedSearchRoute(options);
|
|
2045
|
+
if (searchRoute) {
|
|
2046
|
+
yield* searchRoute.stream(messages, options);
|
|
2047
|
+
return;
|
|
2048
|
+
}
|
|
2049
|
+
this.logger.debug(LOG_MODULE$2, "request", "Starting streaming call to chat.completions", {
|
|
1955
2050
|
model: this.name,
|
|
1956
2051
|
messageCount: messages.length,
|
|
1957
2052
|
streaming: true,
|
|
1958
2053
|
toolCount: options?.tools?.length ?? 0
|
|
1959
2054
|
});
|
|
1960
|
-
let
|
|
2055
|
+
let stream;
|
|
1961
2056
|
try {
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
2057
|
+
stream = await this.client.chat.completions.create(mergeProviderBody({
|
|
2058
|
+
model: this.name,
|
|
2059
|
+
...compatibleSearchParams(this.provider, options),
|
|
2060
|
+
messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),
|
|
2061
|
+
...this.buildSamplingParams(options),
|
|
2062
|
+
...buildPromptCacheParams(this.provider, this.config),
|
|
2063
|
+
...this.buildTools(options),
|
|
2064
|
+
stream: true,
|
|
2065
|
+
stream_options: { include_usage: true },
|
|
2066
|
+
...this.buildResponseFormat(options?.responseSchema),
|
|
2067
|
+
...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length))
|
|
2068
|
+
}, options), options?.signal ? { signal: options.signal } : void 0);
|
|
1966
2069
|
} catch (thrown) {
|
|
1967
|
-
|
|
2070
|
+
const wrapped = wrapOpenAIError(thrown);
|
|
2071
|
+
this.logger.error(LOG_MODULE$2, "error", wrapped.message, {
|
|
2072
|
+
code: wrapped.code,
|
|
2073
|
+
context: wrapped.context
|
|
2074
|
+
});
|
|
2075
|
+
throw wrapped;
|
|
1968
2076
|
}
|
|
1969
|
-
|
|
1970
|
-
|
|
2077
|
+
let rawFinishReason = "stop";
|
|
2078
|
+
let usage = {
|
|
2079
|
+
input: 0,
|
|
2080
|
+
output: 0,
|
|
2081
|
+
total: 0
|
|
2082
|
+
};
|
|
1971
2083
|
const want = (0, _warlock_js_ai.resolveStreamChunks)(options);
|
|
1972
|
-
const
|
|
1973
|
-
let terminal;
|
|
2084
|
+
const toolCallAccum = /* @__PURE__ */ new Map();
|
|
1974
2085
|
try {
|
|
1975
|
-
for await (const
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
continue;
|
|
1982
|
-
}
|
|
1983
|
-
if (event.type === "response.reasoning_summary_text.delta" || event.type === "response.reasoning_text.delta") {
|
|
1984
|
-
if (want.reasoning && event.delta) yield {
|
|
2086
|
+
for await (const chunk of stream) {
|
|
2087
|
+
const delta = chunk.choices[0]?.delta;
|
|
2088
|
+
const finish = chunk.choices[0]?.finish_reason;
|
|
2089
|
+
if (want.reasoning && delta) {
|
|
2090
|
+
const reasoning = readReasoningDelta(delta);
|
|
2091
|
+
if (reasoning) yield {
|
|
1985
2092
|
type: "reasoning",
|
|
1986
|
-
delta:
|
|
2093
|
+
delta: reasoning
|
|
1987
2094
|
};
|
|
1988
|
-
continue;
|
|
1989
2095
|
}
|
|
1990
|
-
if (
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
2096
|
+
if (delta?.content) yield {
|
|
2097
|
+
type: "delta",
|
|
2098
|
+
content: delta.content
|
|
2099
|
+
};
|
|
2100
|
+
if (delta?.tool_calls) for (const toolCall of delta.tool_calls) {
|
|
2101
|
+
const idx = toolCall.index ?? 0;
|
|
2102
|
+
if (!toolCallAccum.has(idx)) toolCallAccum.set(idx, {
|
|
2103
|
+
id: "",
|
|
2104
|
+
name: "",
|
|
2105
|
+
arguments: "",
|
|
2106
|
+
streamed: 0
|
|
1995
2107
|
});
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
if (want.toolArgs &&
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
const { item } = event;
|
|
2010
|
-
this.assertServerRunItem(item);
|
|
2011
|
-
outputItems.push(item);
|
|
2012
|
-
if (item.type === "function_call" && item.status !== "incomplete") toolCalls.push(this.toToolCall(item));
|
|
2013
|
-
continue;
|
|
2014
|
-
}
|
|
2015
|
-
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
2016
|
-
terminal = event.response;
|
|
2017
|
-
continue;
|
|
2108
|
+
const acc = toolCallAccum.get(idx);
|
|
2109
|
+
if (toolCall.id) acc.id = toolCall.id;
|
|
2110
|
+
if (toolCall.function?.name) acc.name = toolCall.function.name;
|
|
2111
|
+
if (toolCall.function?.arguments) acc.arguments += toolCall.function.arguments;
|
|
2112
|
+
if (want.toolArgs && acc.name && acc.arguments.length > acc.streamed) {
|
|
2113
|
+
yield {
|
|
2114
|
+
type: "tool-args",
|
|
2115
|
+
callId: acc.id,
|
|
2116
|
+
name: acc.name,
|
|
2117
|
+
delta: acc.arguments.slice(acc.streamed)
|
|
2118
|
+
};
|
|
2119
|
+
acc.streamed = acc.arguments.length;
|
|
2120
|
+
}
|
|
2018
2121
|
}
|
|
2019
|
-
if (
|
|
2020
|
-
if (
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2122
|
+
if (finish) rawFinishReason = finish;
|
|
2123
|
+
if (chunk.usage) usage = this.extractUsage(chunk.usage);
|
|
2124
|
+
}
|
|
2125
|
+
for (const acc of toolCallAccum.values()) {
|
|
2126
|
+
if (!acc.name) continue;
|
|
2127
|
+
yield {
|
|
2128
|
+
type: "tool-call",
|
|
2129
|
+
id: acc.id,
|
|
2130
|
+
name: acc.name,
|
|
2131
|
+
input: (0, _warlock_js_ai.safeJsonParse)(acc.arguments, {})
|
|
2132
|
+
};
|
|
2025
2133
|
}
|
|
2026
|
-
if (terminal === void 0) throw new _warlock_js_ai.ProviderError("OpenAI Responses stream ended before response.completed.", { context: {
|
|
2027
|
-
provider: this.provider,
|
|
2028
|
-
model: this.name
|
|
2029
|
-
} });
|
|
2030
2134
|
} catch (thrown) {
|
|
2031
|
-
|
|
2135
|
+
const wrapped = wrapOpenAIError(thrown);
|
|
2136
|
+
this.logger.error(LOG_MODULE$2, "error", wrapped.message, {
|
|
2137
|
+
code: wrapped.code,
|
|
2138
|
+
context: wrapped.context
|
|
2139
|
+
});
|
|
2140
|
+
throw wrapped;
|
|
2032
2141
|
}
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
id: call.id,
|
|
2036
|
-
name: call.name,
|
|
2037
|
-
input: call.input,
|
|
2038
|
-
...call.providerMetadata ? { providerMetadata: call.providerMetadata } : {}
|
|
2039
|
-
};
|
|
2040
|
-
const finishReason = mapResponsesFinishReason({
|
|
2041
|
-
status: terminal.status,
|
|
2042
|
-
incomplete_details: terminal.incomplete_details,
|
|
2043
|
-
hasToolCalls: toolCalls.length > 0
|
|
2044
|
-
});
|
|
2045
|
-
const usage = this.extractUsage(terminal.usage);
|
|
2046
|
-
const output = terminal.output?.length ? terminal.output : outputItems;
|
|
2047
|
-
const providerMetadata = hostedOutput(usage, output, this.pricing);
|
|
2048
|
-
this.logger.debug(LOG_MODULE$2, "response", "Streaming call to responses.create succeeded", {
|
|
2142
|
+
const finishReason = mapFinishReason(rawFinishReason);
|
|
2143
|
+
this.logger.debug(LOG_MODULE$2, "response", "Streaming call to chat.completions succeeded", {
|
|
2049
2144
|
finishReason,
|
|
2050
2145
|
usage
|
|
2051
2146
|
});
|
|
2052
2147
|
yield {
|
|
2053
2148
|
type: "done",
|
|
2054
|
-
finishReason,
|
|
2055
|
-
usage
|
|
2056
|
-
|
|
2057
|
-
};
|
|
2058
|
-
}
|
|
2059
|
-
/**
|
|
2060
|
-
* Assemble the `responses.create` body.
|
|
2061
|
-
*
|
|
2062
|
-
* - System prompt -> `instructions`; history -> `input` items.
|
|
2063
|
-
* - `store: false` always (the API default is `true` when omitted), plus
|
|
2064
|
-
* `include: ["reasoning.encrypted_content"]` for stateless reasoning replay.
|
|
2065
|
-
* - `max_output_tokens` caps reasoning and visible output together.
|
|
2066
|
-
* - `temperature` only for non-reasoning models (same rule as Chat).
|
|
2067
|
-
* - `tools` flat with `strict: false`; `tool_choice` only with tools.
|
|
2068
|
-
* - `reasoning.effort` only when the caller gave one, through the same
|
|
2069
|
-
* clamp table as Chat. With no explicit effort the provider default
|
|
2070
|
-
* applies EVEN with tools attached - that is the point of this API.
|
|
2071
|
-
*/
|
|
2072
|
-
buildRequest(messages, options) {
|
|
2073
|
-
const { instructions, input } = toResponsesInput(messages, this.name);
|
|
2074
|
-
const tools = this.buildTools(options);
|
|
2075
|
-
const toolChoice = tools ? toResponsesToolChoice(options?.toolChoice) : void 0;
|
|
2076
|
-
const maxTokens = options?.maxTokens ?? this.config.maxTokens;
|
|
2077
|
-
const temperature = options?.temperature ?? this.config.temperature;
|
|
2078
|
-
return mergeProviderBody({
|
|
2079
|
-
model: this.name,
|
|
2080
|
-
...instructions !== void 0 ? { instructions } : {},
|
|
2081
|
-
input,
|
|
2082
|
-
store: false,
|
|
2083
|
-
include: ["reasoning.encrypted_content", ...tools?.some((tool) => tool.type === "web_search" || tool.type === "web_search_2025_08_26" || tool.type === "web_search_preview" || tool.type === "web_search_preview_2025_03_11") ? ["web_search_call.action.sources"] : []],
|
|
2084
|
-
...maxTokens !== void 0 ? { max_output_tokens: maxTokens } : {},
|
|
2085
|
-
...!this.capabilities.reasoning && temperature !== void 0 ? { temperature } : {},
|
|
2086
|
-
...tools ? { tools } : {},
|
|
2087
|
-
...toolChoice !== void 0 ? { tool_choice: toolChoice } : {},
|
|
2088
|
-
...this.buildTextFormat(options?.responseSchema),
|
|
2089
|
-
...this.buildReasoningParams(options?.reasoning),
|
|
2090
|
-
...buildPromptCacheParams(this.provider, this.config)
|
|
2091
|
-
}, options);
|
|
2149
|
+
finishReason,
|
|
2150
|
+
usage
|
|
2151
|
+
};
|
|
2092
2152
|
}
|
|
2093
2153
|
/**
|
|
2094
|
-
*
|
|
2095
|
-
*
|
|
2096
|
-
*
|
|
2097
|
-
*
|
|
2098
|
-
*
|
|
2154
|
+
* OpenAI's hosted `web_search` tool exists only on the Responses API, and
|
|
2155
|
+
* Chat Completions answers it with a 400. When a call on the direct
|
|
2156
|
+
* `"openai"` provider carries it, the call is served by the Responses
|
|
2157
|
+
* adapter instead (same client, same pricing, same model name), unless the
|
|
2158
|
+
* model was pinned to `api: "chat"` or cannot search at all: both throw a
|
|
2159
|
+
* clear error before any request, never a silent fallback to something
|
|
2160
|
+
* else. Every other call stays on Chat Completions.
|
|
2161
|
+
*/
|
|
2162
|
+
hostedSearchRoute(options) {
|
|
2163
|
+
if (this.provider !== "openai" || !requestsHostedSearch(options, this.provider)) return;
|
|
2164
|
+
if (this.config.api === "chat") throw new _warlock_js_ai.InvalidRequestError(`OpenAI's hosted web_search tool needs the Responses API, but "${this.name}" is pinned to api: "chat". Remove api: "chat" (the call is then routed to the Responses API) or use api: "responses".`, { context: {
|
|
2165
|
+
provider: this.provider,
|
|
2166
|
+
model: this.name,
|
|
2167
|
+
api: "chat",
|
|
2168
|
+
tool: "web_search"
|
|
2169
|
+
} });
|
|
2170
|
+
assertHostedSearchSupported(this.name, options);
|
|
2171
|
+
this.searchModel ??= new OpenAIResponsesModel(this.client, this.config, this.provider);
|
|
2172
|
+
return this.searchModel;
|
|
2173
|
+
}
|
|
2174
|
+
/**
|
|
2175
|
+
* Spread-friendly `tools` fragment: the function tools, then the
|
|
2176
|
+
* provider-defined entries whose `provider` equals this model's
|
|
2177
|
+
* provider label (`"openai"`, or the vendor label an OpenAI-compatible
|
|
2178
|
+
* wrapper sets, e.g. `"groq"`), sent verbatim. Chat Completions only
|
|
2179
|
+
* accepts `function` and `custom` tool types from OpenAI itself; its
|
|
2180
|
+
* hosted tools (`web_search`, `file_search`, …) need `api: "responses"`
|
|
2181
|
+
* and OpenAI rejects them here with a 400.
|
|
2099
2182
|
*/
|
|
2100
2183
|
buildTools(options) {
|
|
2101
2184
|
const { tools, definitions } = (0, _warlock_js_ai.selectProviderTools)(options, {
|
|
@@ -2104,86 +2187,55 @@ var OpenAIResponsesModel = class {
|
|
|
2104
2187
|
model: this.name,
|
|
2105
2188
|
logger: this.logger
|
|
2106
2189
|
});
|
|
2107
|
-
|
|
2108
|
-
|
|
2190
|
+
if ((this.provider === "moonshot" || this.provider === "kimi") && definitions.some((definition) => {
|
|
2191
|
+
const fn = definition.function;
|
|
2192
|
+
return definition.type === "builtin_function" && typeof fn === "object" && fn !== null && "name" in fn && fn.name === "$web_search";
|
|
2193
|
+
})) throw new _warlock_js_ai.InvalidRequestError("Kimi's builtin $web_search retires on 20 October 2026. Use kimiSearchTool() / kimiFetchTool() from @warlock.js/ai-openai.");
|
|
2194
|
+
if (this.provider === "xai" && definitions.some((definition) => definition.type === "web_search" || definition.type === "x_search")) throw new _warlock_js_ai.InvalidRequestError("xAI native web_search / x_search requires POST /v1/responses. Build the model with XaiSDK from @warlock.js/ai-xai, which routes those calls to the Responses API.");
|
|
2195
|
+
const mapped = [...toOpenAITools(tools) ?? [], ...definitions];
|
|
2196
|
+
return mapped.length > 0 ? { tools: mapped } : {};
|
|
2197
|
+
}
|
|
2198
|
+
/** Map the neutral cache hint only for the direct OpenAI provider. */
|
|
2199
|
+
promptCacheBreakpoints(options) {
|
|
2200
|
+
return this.provider === "openai" ? options?.cacheControl?.breakpoints ?? 0 : 0;
|
|
2109
2201
|
}
|
|
2110
2202
|
/**
|
|
2111
|
-
*
|
|
2112
|
-
* `
|
|
2113
|
-
*
|
|
2114
|
-
* `planStructuredOutput
|
|
2203
|
+
* Translate the neutral `responseSchema` option into OpenAI's
|
|
2204
|
+
* `response_format` parameter. The mode decision (override handling,
|
|
2205
|
+
* strict-compatibility downgrade to `json_object`) lives in
|
|
2206
|
+
* `planStructuredOutput`, shared with the Responses adapter.
|
|
2207
|
+
*
|
|
2208
|
+
* Returns an empty spread when no schema was supplied, so the caller
|
|
2209
|
+
* can unconditionally `...buildResponseFormat(...)` into the request.
|
|
2115
2210
|
*/
|
|
2116
|
-
|
|
2211
|
+
buildResponseFormat(responseSchema) {
|
|
2117
2212
|
const plan = planStructuredOutput(responseSchema, this.config.responseFormat);
|
|
2118
|
-
if (plan.mode === "json_schema") return {
|
|
2213
|
+
if (plan.mode === "json_schema") return { response_format: {
|
|
2119
2214
|
type: "json_schema",
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
if (plan.mode === "json_object") return { text: { format: { type: "json_object" } } };
|
|
2125
|
-
return {};
|
|
2126
|
-
}
|
|
2127
|
-
/** `reasoning.effort` for reasoning-capable models, only when the caller set one. */
|
|
2128
|
-
buildReasoningParams(reasoning) {
|
|
2129
|
-
if (!this.capabilities.reasoning || !reasoning?.effort) return {};
|
|
2130
|
-
return { reasoning: { effort: toOpenAIReasoningEffort(reasoning.effort) } };
|
|
2131
|
-
}
|
|
2132
|
-
/**
|
|
2133
|
-
* Walk `response.output`: `message` items contribute their `output_text`
|
|
2134
|
-
* text and any `refusal` text (surfaced as ordinary content, decision 5);
|
|
2135
|
-
* each completed `function_call` item becomes one tool call with
|
|
2136
|
-
* `id = call_id`. `reasoning` items carry no visible content and are
|
|
2137
|
-
* not content. A `function_call` the API marked `incomplete` (truncated
|
|
2138
|
-
* arguments) is skipped rather than dispatched with empty input.
|
|
2139
|
-
* `reasoning` items are captured and attached to the first tool call for
|
|
2140
|
-
* replay (see `attachReasoningReplay`).
|
|
2141
|
-
*/
|
|
2142
|
-
readOutput(output) {
|
|
2143
|
-
let content = "";
|
|
2144
|
-
const toolCalls = [];
|
|
2145
|
-
for (const item of output) {
|
|
2146
|
-
this.assertServerRunItem(item);
|
|
2147
|
-
if (item.type === "message") {
|
|
2148
|
-
for (const part of item.content) content += part.type === "refusal" ? part.refusal : part.text;
|
|
2149
|
-
continue;
|
|
2215
|
+
json_schema: {
|
|
2216
|
+
name: "response",
|
|
2217
|
+
schema: plan.schema,
|
|
2218
|
+
strict: true
|
|
2150
2219
|
}
|
|
2151
|
-
|
|
2152
|
-
}
|
|
2153
|
-
return {
|
|
2154
|
-
content,
|
|
2155
|
-
toolCalls: toolCalls.length > 0 ? attachReasoningReplay(toolCalls, this.name, pickTurnReasoning(output)) : void 0
|
|
2156
|
-
};
|
|
2157
|
-
}
|
|
2158
|
-
/**
|
|
2159
|
-
* Fail closed on a built-in tool call that YOUR code would have to run
|
|
2160
|
-
* (`shell_call`, `apply_patch_call`, `computer_call`, …, from a
|
|
2161
|
-
* provider-defined client tool). These items have their own output item
|
|
2162
|
-
* types that this adapter does not map, so the turn would otherwise end
|
|
2163
|
-
* silently with the call dropped. Hosted (server-run) tool items pass.
|
|
2164
|
-
*/
|
|
2165
|
-
assertServerRunItem(item) {
|
|
2166
|
-
if (!CLIENT_RUN_ITEM_TYPES.has(item.type)) return;
|
|
2167
|
-
throw new _warlock_js_ai.InvalidRequestError(`OpenAI returned a "${item.type}" item: that built-in tool is executed by the caller, which the Responses adapter does not support. Use OpenAI's server-run built-in tools (web_search, file_search, code_interpreter, image_generation, mcp without approval) with ai.providerTool(), or a function tool from ai.tool().`, { context: {
|
|
2168
|
-
provider: this.provider,
|
|
2169
|
-
model: this.name,
|
|
2170
|
-
itemType: item.type
|
|
2171
|
-
} });
|
|
2172
|
-
}
|
|
2173
|
-
/** One completed `function_call` item as a neutral tool call (`call_id` -> `id`). */
|
|
2174
|
-
toToolCall(item) {
|
|
2175
|
-
return {
|
|
2176
|
-
id: item.call_id,
|
|
2177
|
-
name: item.name,
|
|
2178
|
-
input: (0, _warlock_js_ai.safeJsonParse)(item.arguments, {})
|
|
2179
|
-
};
|
|
2220
|
+
} };
|
|
2221
|
+
if (plan.mode === "json_object") return { response_format: { type: "json_object" } };
|
|
2222
|
+
return {};
|
|
2180
2223
|
}
|
|
2181
2224
|
/**
|
|
2182
|
-
* Normalize `usage` (absent on some
|
|
2183
|
-
* `
|
|
2184
|
-
*
|
|
2185
|
-
*
|
|
2186
|
-
*
|
|
2225
|
+
* Normalize OpenAI's `usage` block (which may be absent on some responses
|
|
2226
|
+
* or partials) into the neutral `Usage` shape. Missing usage collapses to
|
|
2227
|
+
* zeros rather than propagating `undefined`, so downstream aggregation
|
|
2228
|
+
* math stays safe.
|
|
2229
|
+
*
|
|
2230
|
+
* `cachedTokens` mirrors `prompt_tokens_details.cached_tokens` (the
|
|
2231
|
+
* subset of the prompt served from OpenAI's automatic prompt cache);
|
|
2232
|
+
* `reasoningTokens` mirrors `completion_tokens_details.reasoning_tokens`
|
|
2233
|
+
* (the hidden reasoning channel on o-series / gpt-5 models, already
|
|
2234
|
+
* counted within `output`). Both are emitted only when the provider
|
|
2235
|
+
* reports a positive value, so non-reasoning / uncached calls keep the
|
|
2236
|
+
* lean `{ input, output, total }` shape. `cacheWriteTokens` mirrors
|
|
2237
|
+
* `prompt_tokens_details.cache_write_tokens` (billed writes on the
|
|
2238
|
+
* models that charge for them). `cost` is attached when priced.
|
|
2187
2239
|
*/
|
|
2188
2240
|
extractUsage(raw) {
|
|
2189
2241
|
if (!raw) return {
|
|
@@ -2192,24 +2244,102 @@ var OpenAIResponsesModel = class {
|
|
|
2192
2244
|
total: 0
|
|
2193
2245
|
};
|
|
2194
2246
|
return buildUsage({
|
|
2195
|
-
input: raw.
|
|
2196
|
-
output: raw.
|
|
2197
|
-
total: raw.total_tokens,
|
|
2198
|
-
cachedTokens: raw.
|
|
2199
|
-
cacheWriteTokens: raw.
|
|
2200
|
-
reasoningTokens: raw.
|
|
2247
|
+
input: raw.prompt_tokens ?? 0,
|
|
2248
|
+
output: raw.completion_tokens ?? 0,
|
|
2249
|
+
total: raw.total_tokens ?? 0,
|
|
2250
|
+
cachedTokens: raw.prompt_tokens_details?.cached_tokens,
|
|
2251
|
+
cacheWriteTokens: raw.prompt_tokens_details?.cache_write_tokens,
|
|
2252
|
+
reasoningTokens: raw.completion_tokens_details?.reasoning_tokens
|
|
2201
2253
|
}, this.pricing);
|
|
2202
2254
|
}
|
|
2203
|
-
/**
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2255
|
+
/**
|
|
2256
|
+
* Translate the neutral `ModelCallOptions.reasoning` hint into OpenAI's
|
|
2257
|
+
* `reasoning_effort` request param. Only `effort` maps — OpenAI's Chat
|
|
2258
|
+
* Completions API exposes a discrete effort knob, not a token budget,
|
|
2259
|
+
* so `reasoning.maxTokens` (the Anthropic extended-thinking cap) has no
|
|
2260
|
+
* wire equivalent here and is silently ignored.
|
|
2261
|
+
*
|
|
2262
|
+
* The neutral `ReasoningEffort` (`"low" | "medium" | "high" | "none"`)
|
|
2263
|
+
* is a subset of OpenAI's accepted values, so it forwards verbatim —
|
|
2264
|
+
* `"none"` included. `"none"` is load-bearing: gpt-5 / o-series models
|
|
2265
|
+
* **reject function tools** on Chat Completions while reasoning is
|
|
2266
|
+
* active, and the endpoint accepts tools only when `reasoning_effort`
|
|
2267
|
+
* is `"none"` (the alternative is the Responses API). This is why the
|
|
2268
|
+
* param is EMITTED for `"none"` rather than omitted — omitting it
|
|
2269
|
+
* leaves the model reasoning server-side by default, so tools would
|
|
2270
|
+
* still be rejected.
|
|
2271
|
+
*
|
|
2272
|
+
* No-ops when the model is not reasoning-capable
|
|
2273
|
+
* (`capabilities.reasoning` is false — e.g. `gpt-4o`, which 400s on any
|
|
2274
|
+
* `reasoning_effort`).
|
|
2275
|
+
*
|
|
2276
|
+
* When the caller gave no explicit `effort`: defaults to `"none"` IF
|
|
2277
|
+
* `hasTools` is true, else omits the param (provider default — the
|
|
2278
|
+
* pre-existing behavior for a tool-less call). The default exists
|
|
2279
|
+
* because, on a reasoning-capable model, there is no working alternative
|
|
2280
|
+
* to `"none"` when tools are attached — omitting `reasoning_effort`
|
|
2281
|
+
* leaves reasoning on server-side, which Chat Completions rejects tools
|
|
2282
|
+
* for (empty replies on some model generations, a hard 400 — "Function
|
|
2283
|
+
* tools with reasoning_effort are not supported ... in
|
|
2284
|
+
* /v1/chat/completions" — on newer ones). An explicit `effort` from the
|
|
2285
|
+
* caller always wins over this default, in either direction.
|
|
2286
|
+
*
|
|
2287
|
+
* Returns an empty spread when nothing applies, so the caller can
|
|
2288
|
+
* unconditionally `...buildReasoningParams(...)` into the request.
|
|
2289
|
+
*/
|
|
2290
|
+
/**
|
|
2291
|
+
* Output-length and sampling params, in current Chat Completions shapes only.
|
|
2292
|
+
*
|
|
2293
|
+
* - `max_completion_tokens`, never the legacy `max_tokens`: current
|
|
2294
|
+
* models (the gpt-5 family and later) answer `400 unsupported_parameter`
|
|
2295
|
+
* to `max_tokens`, and `max_completion_tokens` is accepted everywhere.
|
|
2296
|
+
* - No `temperature` for a reasoning-capable model: those accept only the
|
|
2297
|
+
* default value and reject any other with a 400.
|
|
2298
|
+
*/
|
|
2299
|
+
buildSamplingParams(options) {
|
|
2300
|
+
const maxTokens = options?.maxTokens ?? this.config.maxTokens;
|
|
2301
|
+
const temperature = options?.temperature ?? this.config.temperature;
|
|
2302
|
+
return {
|
|
2303
|
+
max_completion_tokens: maxTokens,
|
|
2304
|
+
...!this.capabilities.reasoning && { temperature }
|
|
2305
|
+
};
|
|
2306
|
+
}
|
|
2307
|
+
buildReasoningParams(reasoning, hasTools) {
|
|
2308
|
+
if (!this.capabilities.reasoning) return {};
|
|
2309
|
+
if (!reasoning?.effort) return hasTools ? { reasoning_effort: "none" } : {};
|
|
2310
|
+
return { reasoning_effort: toOpenAIReasoningEffort(reasoning.effort) };
|
|
2311
|
+
}
|
|
2312
|
+
/**
|
|
2313
|
+
* Reshape OpenAI's `tool_calls` array into the neutral
|
|
2314
|
+
* `ModelToolCallRequest[]`. The raw `arguments` field is a JSON string
|
|
2315
|
+
* per OpenAI's protocol — we parse it defensively via `safeJsonParse` so
|
|
2316
|
+
* malformed or empty arguments yield an empty object instead of crashing
|
|
2317
|
+
* the trip. Returns `undefined` when no tools were requested so callers
|
|
2318
|
+
* can branch on presence.
|
|
2319
|
+
*/
|
|
2320
|
+
extractToolCalls(rawToolCalls) {
|
|
2321
|
+
if (!rawToolCalls || rawToolCalls.length === 0) return;
|
|
2322
|
+
return rawToolCalls.map((toolCall) => ({
|
|
2323
|
+
id: toolCall.id,
|
|
2324
|
+
name: toolCall.function.name,
|
|
2325
|
+
input: (0, _warlock_js_ai.safeJsonParse)(toolCall.function.arguments, {})
|
|
2326
|
+
}));
|
|
2211
2327
|
}
|
|
2212
2328
|
};
|
|
2329
|
+
/**
|
|
2330
|
+
* Reasoning text an OpenAI-compatible vendor puts on a Chat Completions
|
|
2331
|
+
* stream delta. OpenAI itself streams none on this API. DeepSeek documents
|
|
2332
|
+
* `delta.reasoning_content` (API reference, chat completion chunk); Groq
|
|
2333
|
+
* documents the parsed reasoning under a `reasoning` field. Neither is in
|
|
2334
|
+
* the OpenAI SDK's delta type, so the delta is read as a plain record.
|
|
2335
|
+
*/
|
|
2336
|
+
function readReasoningDelta(delta) {
|
|
2337
|
+
const record = delta;
|
|
2338
|
+
for (const key of ["reasoning_content", "reasoning"]) {
|
|
2339
|
+
const value = record[key];
|
|
2340
|
+
if (typeof value === "string" && value !== "") return value;
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2213
2343
|
|
|
2214
2344
|
//#endregion
|
|
2215
2345
|
//#region ../../packages/ai-openai/src/speech.ts
|
|
@@ -2453,6 +2583,23 @@ var OpenAISDK = class {
|
|
|
2453
2583
|
return new OpenAIModel(this.client, resolvedConfig, this.provider);
|
|
2454
2584
|
}
|
|
2455
2585
|
/**
|
|
2586
|
+
* Build the Responses-API model for an OpenAI-compatible vendor that serves
|
|
2587
|
+
* `POST /v1/responses` itself (xAI). For vendor wrapper packages: the direct
|
|
2588
|
+
* OpenAI provider reaches the same adapter through `model({ api:
|
|
2589
|
+
* "responses" })`, and every other label is refused there on purpose. The
|
|
2590
|
+
* returned model keeps this SDK's provider label, sends `store: false`, and
|
|
2591
|
+
* leaves out the OpenAI-only `include` fields (encrypted reasoning, search
|
|
2592
|
+
* sources), so nothing the vendor does not know is sent.
|
|
2593
|
+
*/
|
|
2594
|
+
compatibleResponses(config) {
|
|
2595
|
+
const resolvedPricing = config.pricing ?? this.pricing?.[config.name];
|
|
2596
|
+
const resolvedConfig = resolvedPricing === config.pricing ? config : {
|
|
2597
|
+
...config,
|
|
2598
|
+
pricing: resolvedPricing
|
|
2599
|
+
};
|
|
2600
|
+
return new OpenAIResponsesModel(this.client, resolvedConfig, this.provider, { compatible: true });
|
|
2601
|
+
}
|
|
2602
|
+
/**
|
|
2456
2603
|
* Rough token-count estimate for a given text. Uses a
|
|
2457
2604
|
* character-heuristic (`approximateTokenCount`) from the core package
|
|
2458
2605
|
* — good enough for budgeting and quota guards, not for billing.
|
|
@@ -2463,6 +2610,34 @@ var OpenAISDK = class {
|
|
|
2463
2610
|
return (0, _warlock_js_ai.approximateTokenCount)(text);
|
|
2464
2611
|
}
|
|
2465
2612
|
/**
|
|
2613
|
+
* List the models this account can use, live from `GET /models`, mapped to
|
|
2614
|
+
* {@link ModelInfo}. Works for OpenAI and for every OpenAI-compatible vendor
|
|
2615
|
+
* that implements the listing (the wrapper packages for xAI, Groq,
|
|
2616
|
+
* DeepSeek and Mistral call this). Follows pagination to the end; a
|
|
2617
|
+
* vendor-marked inactive model is left out. Failures are thrown as the
|
|
2618
|
+
* adapter's usual provider errors, never an empty list.
|
|
2619
|
+
*
|
|
2620
|
+
* `kind` comes from the vendor's own flags when it has them (Mistral
|
|
2621
|
+
* `capabilities`) and from the model id otherwise, so treat it as a filter
|
|
2622
|
+
* hint for ids OpenAI does not describe.
|
|
2623
|
+
*
|
|
2624
|
+
* @example
|
|
2625
|
+
* const models = await openai.models();
|
|
2626
|
+
* const chat = models.filter((model) => model.kind === "chat");
|
|
2627
|
+
*/
|
|
2628
|
+
async models(options) {
|
|
2629
|
+
const found = /* @__PURE__ */ new Map();
|
|
2630
|
+
try {
|
|
2631
|
+
for await (const entry of this.client.models.list(options?.signal ? { signal: options.signal } : void 0)) {
|
|
2632
|
+
const info = toModelInfo(entry, this.provider);
|
|
2633
|
+
if (info) found.set(info.id, info);
|
|
2634
|
+
}
|
|
2635
|
+
} catch (thrown) {
|
|
2636
|
+
throw wrapOpenAIError(thrown);
|
|
2637
|
+
}
|
|
2638
|
+
return [...found.values()];
|
|
2639
|
+
}
|
|
2640
|
+
/**
|
|
2466
2641
|
* Build an `OpenAIEmbedder` bound to this SDK's client. Each call
|
|
2467
2642
|
* returns a fresh embedder instance sharing the same underlying
|
|
2468
2643
|
* `OpenAI` client — connection pools and authentication stay unified
|
|
@@ -2786,6 +2961,7 @@ exports.OPENAI_MODEL_PRICING = OPENAI_MODEL_PRICING;
|
|
|
2786
2961
|
exports.OPENAI_SERVER_TOOL_PRICING = OPENAI_SERVER_TOOL_PRICING;
|
|
2787
2962
|
exports.OpenAIEmbedder = OpenAIEmbedder;
|
|
2788
2963
|
exports.OpenAIImageModel = OpenAIImageModel;
|
|
2964
|
+
exports.OpenAIResponsesModel = OpenAIResponsesModel;
|
|
2789
2965
|
exports.OpenAISDK = OpenAISDK;
|
|
2790
2966
|
exports.OpenAISpeechModel = OpenAISpeechModel;
|
|
2791
2967
|
exports.OpenAITranscriptionModel = OpenAITranscriptionModel;
|