@buildanagent/gateway 0.0.0-stage → 0.1.0-alpha.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/LICENSE +52 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +299 -2
- package/dist/adapters/anthropic/adapter.d.ts +25 -0
- package/dist/adapters/anthropic/adapter.js +183 -0
- package/dist/adapters/anthropic/adapter.js.map +1 -0
- package/dist/adapters/anthropic/failure.d.ts +20 -0
- package/dist/adapters/anthropic/failure.js +46 -0
- package/dist/adapters/anthropic/failure.js.map +1 -0
- package/dist/adapters/anthropic/index.d.ts +3 -0
- package/dist/adapters/anthropic/index.js +3 -0
- package/dist/adapters/anthropic/index.js.map +1 -0
- package/dist/adapters/anthropic/request.d.ts +53 -0
- package/dist/adapters/anthropic/request.js +250 -0
- package/dist/adapters/anthropic/request.js.map +1 -0
- package/dist/adapters/anthropic/response.d.ts +31 -0
- package/dist/adapters/anthropic/response.js +212 -0
- package/dist/adapters/anthropic/response.js.map +1 -0
- package/dist/adapters/anthropic/usage.d.ts +26 -0
- package/dist/adapters/anthropic/usage.js +39 -0
- package/dist/adapters/anthropic/usage.js.map +1 -0
- package/dist/adapters/openai-chat/adapter.d.ts +18 -0
- package/dist/adapters/openai-chat/adapter.js +86 -0
- package/dist/adapters/openai-chat/adapter.js.map +1 -0
- package/dist/adapters/openai-chat/compat.d.ts +58 -0
- package/dist/adapters/openai-chat/compat.js +19 -0
- package/dist/adapters/openai-chat/compat.js.map +1 -0
- package/dist/adapters/openai-chat/failure.d.ts +25 -0
- package/dist/adapters/openai-chat/failure.js +33 -0
- package/dist/adapters/openai-chat/failure.js.map +1 -0
- package/dist/adapters/openai-chat/index.d.ts +4 -0
- package/dist/adapters/openai-chat/index.js +3 -0
- package/dist/adapters/openai-chat/index.js.map +1 -0
- package/dist/adapters/openai-chat/request.d.ts +47 -0
- package/dist/adapters/openai-chat/request.js +227 -0
- package/dist/adapters/openai-chat/request.js.map +1 -0
- package/dist/adapters/openai-chat/response.d.ts +22 -0
- package/dist/adapters/openai-chat/response.js +203 -0
- package/dist/adapters/openai-chat/response.js.map +1 -0
- package/dist/adapters/openai-chat/usage.d.ts +19 -0
- package/dist/adapters/openai-chat/usage.js +22 -0
- package/dist/adapters/openai-chat/usage.js.map +1 -0
- package/dist/adapters/strict-schema.d.ts +67 -0
- package/dist/adapters/strict-schema.js +269 -0
- package/dist/adapters/strict-schema.js.map +1 -0
- package/dist/adapters/wire.d.ts +77 -0
- package/dist/adapters/wire.js +137 -0
- package/dist/adapters/wire.js.map +1 -0
- package/dist/catalog.d.ts +65 -0
- package/dist/catalog.js +145 -0
- package/dist/catalog.js.map +1 -0
- package/dist/catalog.json +120 -0
- package/dist/classify.d.ts +25 -0
- package/dist/classify.js +37 -0
- package/dist/classify.js.map +1 -0
- package/dist/complete.d.ts +9 -0
- package/dist/complete.js +13 -0
- package/dist/complete.js.map +1 -0
- package/dist/cost.d.ts +42 -0
- package/dist/cost.js +122 -0
- package/dist/cost.js.map +1 -0
- package/dist/create-model.d.ts +7 -0
- package/dist/create-model.js +81 -0
- package/dist/create-model.js.map +1 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +24 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +17 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware.d.ts +11 -0
- package/dist/middleware.js +22 -0
- package/dist/middleware.js.map +1 -0
- package/dist/names.d.ts +72 -0
- package/dist/names.js +175 -0
- package/dist/names.js.map +1 -0
- package/dist/provider-config.d.ts +15 -0
- package/dist/provider-config.js +23 -0
- package/dist/provider-config.js.map +1 -0
- package/dist/request-dump.d.ts +28 -0
- package/dist/request-dump.js +52 -0
- package/dist/request-dump.js.map +1 -0
- package/dist/request-policy.d.ts +18 -0
- package/dist/request-policy.js +27 -0
- package/dist/request-policy.js.map +1 -0
- package/dist/retry.d.ts +30 -0
- package/dist/retry.js +191 -0
- package/dist/retry.js.map +1 -0
- package/dist/runtime-types.d.ts +112 -0
- package/dist/runtime-types.js +2 -0
- package/dist/runtime-types.js.map +1 -0
- package/dist/spec.d.ts +67 -0
- package/dist/spec.js +2 -0
- package/dist/spec.js.map +1 -0
- package/dist/sse.d.ts +15 -0
- package/dist/sse.js +73 -0
- package/dist/sse.js.map +1 -0
- package/dist/stream-contract.d.ts +23 -0
- package/dist/stream-contract.js +101 -0
- package/dist/stream-contract.js.map +1 -0
- package/dist/testing/guards.d.ts +16 -0
- package/dist/testing/guards.js +48 -0
- package/dist/testing/guards.js.map +1 -0
- package/dist/testing/index.d.ts +12 -0
- package/dist/testing/index.js +13 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/mock-transport.d.ts +49 -0
- package/dist/testing/mock-transport.js +101 -0
- package/dist/testing/mock-transport.js.map +1 -0
- package/dist/testing/random.d.ts +3 -0
- package/dist/testing/random.js +13 -0
- package/dist/testing/random.js.map +1 -0
- package/dist/testing/setup.d.ts +1 -0
- package/dist/testing/setup.js +12 -0
- package/dist/testing/setup.js.map +1 -0
- package/dist/transform-messages.d.ts +32 -0
- package/dist/transform-messages.js +291 -0
- package/dist/transform-messages.js.map +1 -0
- package/dist/types.d.ts +130 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/usage.d.ts +8 -0
- package/dist/usage.js +20 -0
- package/dist/usage.js.map +1 -0
- package/package.json +50 -3
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const DEFAULT_COMPAT = {
|
|
2
|
+
maxTokensField: "max_completion_tokens",
|
|
3
|
+
systemRole: "system",
|
|
4
|
+
streamUsage: true,
|
|
5
|
+
strictTools: true,
|
|
6
|
+
temperature: true,
|
|
7
|
+
cacheBreakpoints: false,
|
|
8
|
+
promptCacheRetention: false,
|
|
9
|
+
};
|
|
10
|
+
/** The flags for one model: its own entry over the adapter's, over the defaults. */
|
|
11
|
+
export function compatFor(config, modelId) {
|
|
12
|
+
const own = Object.hasOwn(config.modelCompat ?? {}, modelId) ? config.modelCompat?.[modelId] : undefined;
|
|
13
|
+
return { ...DEFAULT_COMPAT, ...definedFlags(config.compat), ...definedFlags(own) };
|
|
14
|
+
}
|
|
15
|
+
/** The flags that are set, so an `undefined` flag keeps the value beneath it. */
|
|
16
|
+
function definedFlags(compat) {
|
|
17
|
+
return Object.fromEntries(Object.entries(compat ?? {}).filter(([, value]) => value !== undefined));
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=compat.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compat.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/compat.ts"],"names":[],"mappings":"AA6DA,MAAM,cAAc,GAAmB;IACrC,cAAc,EAAE,uBAAuB;IACvC,UAAU,EAAE,QAAQ;IACpB,WAAW,EAAE,IAAI;IACjB,WAAW,EAAE,IAAI;IACjB,WAAW,EAAE,IAAI;IACjB,gBAAgB,EAAE,KAAK;IACvB,oBAAoB,EAAE,KAAK;CAC5B,CAAC;AAEF,oFAAoF;AACpF,MAAM,UAAU,SAAS,CAAC,MAAsB,EAAE,OAAe;IAC/D,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACzG,OAAO,EAAE,GAAG,cAAc,EAAE,GAAG,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,YAAY,CAAC,GAAG,CAAC,EAAE,CAAC;AACrF,CAAC;AAED,iFAAiF;AACjF,SAAS,YAAY,CAAC,MAA8B;IAClD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;AACrG,CAAC","sourcesContent":["/**\n * The quirks of one OpenAI-compatible server or model, as flags (D2: one wire adapter serves many vendors, and their\n * differences live in per-model data, as Pi's `compat` objects do). Every default is what OpenAI's own Chat\n * Completions API accepts, as its parameters read in openai-node v7.49.0\n * (`src/resources/chat/completions/completions.ts`, as of November 2026).\n */\nimport type { ProviderConfig } from \"../../runtime-types.js\";\n\n/** How one OpenAI-compatible server or model differs from OpenAI's own Chat Completions API. */\nexport interface ChatCompat {\n /**\n * The body field that carries the output limit. Defaults to `\"max_completion_tokens\"`; OpenAI deprecates\n * `max_tokens` and says reasoning models do not accept it, but many compatible servers read only `max_tokens`.\n */\n readonly maxTokensField?: \"max_completion_tokens\" | \"max_tokens\";\n /** The role the system prompt is sent as. Defaults to `\"system\"`, which every compatible server reads. */\n readonly systemRole?: \"system\" | \"developer\";\n /**\n * Whether to ask for a final usage chunk with `stream_options: { include_usage: true }`. Defaults to `true`. A\n * server that rejects the field needs `false`, and its replies then report no usage.\n */\n readonly streamUsage?: boolean;\n /** Whether tools are sent with `strict: true` when their schema allows it. Defaults to `true`. */\n readonly strictTools?: boolean;\n /**\n * Whether the model accepts `temperature`. Defaults to `true`; with `false`, a `temperature` you set is not sent and\n * the call streams a warning.\n */\n readonly temperature?: boolean;\n /**\n * Whether the model takes explicit cache breakpoints (`prompt_cache_breakpoint` on content parts and\n * `prompt_cache_options`), which OpenAI supports from `gpt-5.6`. Defaults to `false`, which leaves caching to the\n * server's automatic prefix cache.\n */\n readonly cacheBreakpoints?: boolean;\n /**\n * Whether `cacheRetention: \"long\"` sends `prompt_cache_retention: \"24h\"`, for models before `gpt-5.6` that offer\n * extended caching. Defaults to `false`.\n */\n readonly promptCacheRetention?: boolean;\n}\n\n/** The configuration `openaiChat()` takes: a `ProviderConfig` plus the server's name and quirks. */\nexport interface OpenAIChatConfig extends ProviderConfig {\n /**\n * The vendor name the adapter reports, which `createModel()` looks the model up under in the price catalog.\n * Defaults to `\"openai\"`; set it for another OpenAI-compatible server.\n */\n readonly provider?: string;\n /** Quirks that hold for every model behind this adapter. */\n readonly compat?: ChatCompat;\n /** Quirks for single models, by model id, which override `compat` flag by flag. */\n readonly modelCompat?: Readonly<Record<string, ChatCompat>>;\n}\n\n/** The part of the configuration `compatFor()` reads. */\nexport type CompatSettings = Pick<OpenAIChatConfig, \"compat\" | \"modelCompat\">;\n\n/** A `ChatCompat` with every flag set. */\nexport type ResolvedCompat = Required<ChatCompat>;\n\nconst DEFAULT_COMPAT: ResolvedCompat = {\n maxTokensField: \"max_completion_tokens\",\n systemRole: \"system\",\n streamUsage: true,\n strictTools: true,\n temperature: true,\n cacheBreakpoints: false,\n promptCacheRetention: false,\n};\n\n/** The flags for one model: its own entry over the adapter's, over the defaults. */\nexport function compatFor(config: CompatSettings, modelId: string): ResolvedCompat {\n const own = Object.hasOwn(config.modelCompat ?? {}, modelId) ? config.modelCompat?.[modelId] : undefined;\n return { ...DEFAULT_COMPAT, ...definedFlags(config.compat), ...definedFlags(own) };\n}\n\n/** The flags that are set, so an `undefined` flag keeps the value beneath it. */\nfunction definedFlags(compat: ChatCompat | undefined): ChatCompat {\n return Object.fromEntries(Object.entries(compat ?? {}).filter(([, value]) => value !== undefined));\n}\n"]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Failed requests and streams, as `error` terminals. A failed response's body is
|
|
3
|
+
* `{ "error": { "message", "type", "param", "code" } }`, as openai-node v7.49.0 reads it (`src/core/error.ts`). A
|
|
4
|
+
* stream that already returned 200 reports a later error as a chunk whose `error` field holds the same object, or as
|
|
5
|
+
* an SSE event named `error` (`src/core/streaming.ts`); both as of November 2026.
|
|
6
|
+
*
|
|
7
|
+
* OpenAI sends billing, spend and usage limits as 429s, and retrying them "won't restore API access" (Error codes,
|
|
8
|
+
* https://developers.openai.com/api/docs/guides/error-codes, as of November 2026). Their `code` names the cause, such
|
|
9
|
+
* as `credit_balance_exhausted`, and their `type` can be `insufficient_quota`. `classifyError()` reads the code and
|
|
10
|
+
* the type, so these are `quota` errors even at 429, while a 429 `rate_limit_error` such as `slow_down` stays
|
|
11
|
+
* retryable. `context_length_exceeded`, which the fixtures use for
|
|
12
|
+
* an over-long prompt, is not on that page, so its wording is unverified; the classifier also matches the phrase
|
|
13
|
+
* "maximum context".
|
|
14
|
+
*/
|
|
15
|
+
import type { ModelEvent } from "../../spec.js";
|
|
16
|
+
import type { ModelRef } from "../../types.js";
|
|
17
|
+
import { type PartialReply, type WireFailure } from "../wire.js";
|
|
18
|
+
/** Reads an error object, from an HTTP error body or an error chunk in a stream. */
|
|
19
|
+
export declare function failureFrom(body: unknown, status: number | undefined, fallback: string): WireFailure;
|
|
20
|
+
/** Reads a failed HTTP response's error body; a body that is not JSON keeps its text as the message. */
|
|
21
|
+
export declare function failureFromResponse(response: Response): Promise<WireFailure>;
|
|
22
|
+
/** The `error` terminal for a failure, with any partial content and usage the attempt reached. */
|
|
23
|
+
export declare function failureEvent(model: ModelRef, failure: WireFailure, partial?: PartialReply): Extract<ModelEvent, {
|
|
24
|
+
type: "error";
|
|
25
|
+
}>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { failureTerminal, isObject, readErrorBody } from "../wire.js";
|
|
2
|
+
// The HTTP status each error type stands for, so a stream error, which has no status, classifies like the HTTP error
|
|
3
|
+
// it would have been. A type not listed here classifies as a failure in transit, which is retryable.
|
|
4
|
+
const STATUS_OF_TYPE = {
|
|
5
|
+
invalid_request_error: 400,
|
|
6
|
+
authentication_error: 401,
|
|
7
|
+
permission_error: 403,
|
|
8
|
+
not_found_error: 404,
|
|
9
|
+
insufficient_quota: 429,
|
|
10
|
+
rate_limit_error: 429,
|
|
11
|
+
server_error: 500,
|
|
12
|
+
service_unavailable_error: 503,
|
|
13
|
+
};
|
|
14
|
+
/** Reads an error object, from an HTTP error body or an error chunk in a stream. */
|
|
15
|
+
export function failureFrom(body, status, fallback) {
|
|
16
|
+
const error = isObject(body) && isObject(body.error) ? body.error : undefined;
|
|
17
|
+
return {
|
|
18
|
+
...(status === undefined ? {} : { status }),
|
|
19
|
+
...(typeof error?.type === "string" && error.type !== "" ? { type: error.type } : {}),
|
|
20
|
+
...(typeof error?.code === "string" && error.code !== "" ? { errorCode: error.code } : {}),
|
|
21
|
+
message: typeof error?.message === "string" && error.message !== "" ? error.message : fallback,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** Reads a failed HTTP response's error body; a body that is not JSON keeps its text as the message. */
|
|
25
|
+
export async function failureFromResponse(response) {
|
|
26
|
+
const { body, text } = await readErrorBody(response);
|
|
27
|
+
return failureFrom(body, response.status, text || `HTTP ${response.status}`);
|
|
28
|
+
}
|
|
29
|
+
/** The `error` terminal for a failure, with any partial content and usage the attempt reached. */
|
|
30
|
+
export function failureEvent(model, failure, partial = {}) {
|
|
31
|
+
return failureTerminal(model, failure, STATUS_OF_TYPE, partial);
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=failure.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"failure.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/failure.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAqB,aAAa,EAAoB,MAAM,YAAY,CAAC;AAE3G,qHAAqH;AACrH,qGAAqG;AACrG,MAAM,cAAc,GAAqC;IACvD,qBAAqB,EAAE,GAAG;IAC1B,oBAAoB,EAAE,GAAG;IACzB,gBAAgB,EAAE,GAAG;IACrB,eAAe,EAAE,GAAG;IACpB,kBAAkB,EAAE,GAAG;IACvB,gBAAgB,EAAE,GAAG;IACrB,YAAY,EAAE,GAAG;IACjB,yBAAyB,EAAE,GAAG;CAC/B,CAAC;AAEF,oFAAoF;AACpF,MAAM,UAAU,WAAW,CAAC,IAAa,EAAE,MAA0B,EAAE,QAAgB;IACrF,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,I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esContent":["/**\n * Failed requests and streams, as `error` terminals. A failed response's body is\n * `{ \"error\": { \"message\", \"type\", \"param\", \"code\" } }`, as openai-node v7.49.0 reads it (`src/core/error.ts`). A\n * stream that already returned 200 reports a later error as a chunk whose `error` field holds the same object, or as\n * an SSE event named `error` (`src/core/streaming.ts`); both as of November 2026.\n *\n * OpenAI sends billing, spend and usage limits as 429s, and retrying them \"won't restore API access\" (Error codes,\n * https://developers.openai.com/api/docs/guides/error-codes, as of November 2026). Their `code` names the cause, such\n * as `credit_balance_exhausted`, and their `type` can be `insufficient_quota`. `classifyError()` reads the code and\n * the type, so these are `quota` errors even at 429, while a 429 `rate_limit_error` such as `slow_down` stays\n * retryable. `context_length_exceeded`, which the fixtures use for\n * an over-long prompt, is not on that page, so its wording is unverified; the classifier also matches the phrase\n * \"maximum context\".\n */\nimport type { ModelEvent } from \"../../spec.js\";\nimport type { ModelRef } from \"../../types.js\";\nimport { failureTerminal, isObject, type PartialReply, readErrorBody, type WireFailure } from \"../wire.js\";\n\n// The HTTP status each error type stands for, so a stream error, which has no status, classifies like the HTTP error\n// it would have been. A type not listed here classifies as a failure in transit, which is retryable.\nconst STATUS_OF_TYPE: Readonly<Record<string, number>> = {\n invalid_request_error: 400,\n authentication_error: 401,\n permission_error: 403,\n not_found_error: 404,\n insufficient_quota: 429,\n rate_limit_error: 429,\n server_error: 500,\n service_unavailable_error: 503,\n};\n\n/** Reads an error object, from an HTTP error body or an error chunk in a stream. */\nexport function failureFrom(body: unknown, status: number | undefined, fallback: string): WireFailure {\n const error = isObject(body) && isObject(body.error) ? body.error : undefined;\n return {\n ...(status === undefined ? {} : { status }),\n ...(typeof error?.type === \"string\" && error.type !== \"\" ? { type: error.type } : {}),\n ...(typeof error?.code === \"string\" && error.code !== \"\" ? { errorCode: error.code } : {}),\n message: typeof error?.message === \"string\" && error.message !== \"\" ? error.message : fallback,\n };\n}\n\n/** Reads a failed HTTP response's error body; a body that is not JSON keeps its text as the message. */\nexport async function failureFromResponse(response: Response): Promise<WireFailure> {\n const { body, text } = await readErrorBody(response);\n return failureFrom(body, response.status, text || `HTTP ${response.status}`);\n}\n\n/** The `error` terminal for a failure, with any partial content and usage the attempt reached. */\nexport function failureEvent(\n model: ModelRef,\n failure: WireFailure,\n partial: PartialReply = {},\n): Extract<ModelEvent, { type: \"error\" }> {\n return failureTerminal(model, failure, STATUS_OF_TYPE, partial);\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/index.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC","sourcesContent":["/** `@buildanagent/gateway/openai-chat`: the OpenAI-compatible Chat Completions adapter. */\nexport { openaiChat } from \"./adapter.js\";\nexport type { ChatCompat, OpenAIChatConfig } from \"./compat.js\";\nexport type { OpenAIChatProviderOptions } from \"./request.js\";\n"]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds the Chat Completions request body from a `ModelContext`. Every field below follows the API reference at
|
|
3
|
+
* https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create and
|
|
4
|
+
* `ChatCompletionCreateParams` in openai-node v7.49.0 (`src/resources/chat/completions/completions.ts`), both as of
|
|
5
|
+
* November 2026.
|
|
6
|
+
*
|
|
7
|
+
* - Messages pass through `transformMessages()` first. A tool result becomes a `tool` message, whose content can hold
|
|
8
|
+
* only text, so a result's images follow in one user message after the turn's results, and a failed result's text
|
|
9
|
+
* starts with `Error: `. The transcript's reasoning
|
|
10
|
+
* is never sent, because a Chat Completions message has no field for it.
|
|
11
|
+
* - Tool names go through the run's `ToolNameMap`. A tool is sent with `strict: true` when its schema can be lowered,
|
|
12
|
+
* and the plan keeps the original schema of each, so the reply's added nulls can be stripped.
|
|
13
|
+
* - Caching follows the model's `ChatCompat` flags: explicit breakpoints on the system prompt and the newest user or
|
|
14
|
+
* tool message, with the 30-minute lifetime Chat Completions offers; `prompt_cache_retention: "24h"`; or neither,
|
|
15
|
+
* which leaves the server's automatic prefix cache.
|
|
16
|
+
*/
|
|
17
|
+
import { type ToolNameMap } from "../../names.js";
|
|
18
|
+
import type { ModelEvent, StreamOptions } from "../../spec.js";
|
|
19
|
+
import type { ModelCaps, ModelContext, ModelRef } from "../../types.js";
|
|
20
|
+
import { type Json } from "../wire.js";
|
|
21
|
+
import type { ResolvedCompat } from "./compat.js";
|
|
22
|
+
type Warning = Extract<ModelEvent, {
|
|
23
|
+
type: "warning";
|
|
24
|
+
}>;
|
|
25
|
+
/** What the adapter reads from `providerOptions.openaiChat`. */
|
|
26
|
+
export interface OpenAIChatProviderOptions {
|
|
27
|
+
/**
|
|
28
|
+
* Extra fields for the request body, such as `reasoning_effort`, `prompt_cache_key` or `parallel_tool_calls`. The
|
|
29
|
+
* fields the adapter sets itself (`model`, `stream`, `stream_options`, `messages`, `tools`, `max_completion_tokens`
|
|
30
|
+
* and `max_tokens`) win over these: an `extraBody` value for one is not sent, and the call streams an
|
|
31
|
+
* `unsupported_option` warning.
|
|
32
|
+
*/
|
|
33
|
+
readonly extraBody?: Readonly<Record<string, unknown>>;
|
|
34
|
+
}
|
|
35
|
+
/** One request's body and what reading its response needs. */
|
|
36
|
+
export interface RequestPlan {
|
|
37
|
+
readonly body: Json;
|
|
38
|
+
readonly warnings: readonly Warning[];
|
|
39
|
+
readonly names: ToolNameMap;
|
|
40
|
+
/** The original input schema of each tool sent strict, by tool name. */
|
|
41
|
+
readonly strictSchemas: ReadonlyMap<string, Json>;
|
|
42
|
+
}
|
|
43
|
+
/** Reads `providerOptions.openaiChat`, ignoring fields of the wrong type. */
|
|
44
|
+
export declare function openaiChatOptions(options: StreamOptions): OpenAIChatProviderOptions;
|
|
45
|
+
/** Builds one call's request body. */
|
|
46
|
+
export declare function buildRequest(model: ModelRef, context: ModelContext, options: StreamOptions, caps: ModelCaps, compat: ResolvedCompat): RequestPlan;
|
|
47
|
+
export {};
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds the Chat Completions request body from a `ModelContext`. Every field below follows the API reference at
|
|
3
|
+
* https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create and
|
|
4
|
+
* `ChatCompletionCreateParams` in openai-node v7.49.0 (`src/resources/chat/completions/completions.ts`), both as of
|
|
5
|
+
* November 2026.
|
|
6
|
+
*
|
|
7
|
+
* - Messages pass through `transformMessages()` first. A tool result becomes a `tool` message, whose content can hold
|
|
8
|
+
* only text, so a result's images follow in one user message after the turn's results, and a failed result's text
|
|
9
|
+
* starts with `Error: `. The transcript's reasoning
|
|
10
|
+
* is never sent, because a Chat Completions message has no field for it.
|
|
11
|
+
* - Tool names go through the run's `ToolNameMap`. A tool is sent with `strict: true` when its schema can be lowered,
|
|
12
|
+
* and the plan keeps the original schema of each, so the reply's added nulls can be stripped.
|
|
13
|
+
* - Caching follows the model's `ChatCompat` flags: explicit breakpoints on the system prompt and the newest user or
|
|
14
|
+
* tool message, with the 30-minute lifetime Chat Completions offers; `prompt_cache_retention: "24h"`; or neither,
|
|
15
|
+
* which leaves the server's automatic prefix cache.
|
|
16
|
+
*/
|
|
17
|
+
import { createToolNameMap, TOOL_NAME_RULES } from "../../names.js";
|
|
18
|
+
import { transformMessages } from "../../transform-messages.js";
|
|
19
|
+
import { lowerToStrict } from "../strict-schema.js";
|
|
20
|
+
import { isObject } from "../wire.js";
|
|
21
|
+
// Strict function calling makes every property required, so an optional one becomes nullable. The formats, the kept
|
|
22
|
+
// and rejected keywords and the limits are those of Structured model outputs, "Supported schemas"
|
|
23
|
+
// (https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas, as of November 2026), which
|
|
24
|
+
// does not list `prefixItems`, so a schema that uses it is sent without strict.
|
|
25
|
+
const STRICT_DIALECT = {
|
|
26
|
+
optional: "nullable",
|
|
27
|
+
formats: new Set(["date-time", "time", "date", "duration", "email", "hostname", "ipv4", "ipv6", "uuid"]),
|
|
28
|
+
objectRoot: true,
|
|
29
|
+
keeps: new Set(["minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", "minItems", "maxItems"]),
|
|
30
|
+
rejects: new Set(["allOf", "dependentRequired", "dependentSchemas", "if", "then", "else", "prefixItems"]),
|
|
31
|
+
limits: {
|
|
32
|
+
properties: 5000,
|
|
33
|
+
depth: 10,
|
|
34
|
+
enumValues: 1000,
|
|
35
|
+
stringLength: 120_000,
|
|
36
|
+
largeEnum: { values: 250, length: 15_000 },
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
const TOOL_IMAGES_NOTE = "The images below are part of the tool results above.";
|
|
40
|
+
/** Reads `providerOptions.openaiChat`, ignoring fields of the wrong type. */
|
|
41
|
+
export function openaiChatOptions(options) {
|
|
42
|
+
const raw = options.providerOptions?.openaiChat;
|
|
43
|
+
if (!isObject(raw))
|
|
44
|
+
return {};
|
|
45
|
+
return isObject(raw.extraBody) ? { extraBody: raw.extraBody } : {};
|
|
46
|
+
}
|
|
47
|
+
// Content -------------------------------------------------------------------------------------------------------------
|
|
48
|
+
function imagePart(block) {
|
|
49
|
+
return { type: "image_url", image_url: { url: `data:${block.mediaType};base64,${block.data}` } };
|
|
50
|
+
}
|
|
51
|
+
function contentPart(block) {
|
|
52
|
+
if (block.type === "text")
|
|
53
|
+
return block.text === "" ? [] : [{ type: "text", text: block.text }];
|
|
54
|
+
return block.type === "image" ? [imagePart(block)] : [];
|
|
55
|
+
}
|
|
56
|
+
/** A user message's content: a plain string for a single text block, which every compatible server reads. */
|
|
57
|
+
function userContent(blocks) {
|
|
58
|
+
const [only] = blocks;
|
|
59
|
+
if (blocks.length === 1 && only?.type === "text")
|
|
60
|
+
return only.text;
|
|
61
|
+
return blocks.flatMap(contentPart);
|
|
62
|
+
}
|
|
63
|
+
function assistantMessage(message, names) {
|
|
64
|
+
// Text blocks a reasoning block or a merged turn kept apart stay apart, as paragraphs.
|
|
65
|
+
const text = message.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n\n");
|
|
66
|
+
const toolCalls = message.content.flatMap((block) => {
|
|
67
|
+
if (block.type !== "tool_call")
|
|
68
|
+
return [];
|
|
69
|
+
// A call cut off by the output limit holds its partial JSON as a string; the wire needs a JSON object.
|
|
70
|
+
const input = isObject(block.input) ? block.input : {};
|
|
71
|
+
return [
|
|
72
|
+
{
|
|
73
|
+
id: block.callId,
|
|
74
|
+
type: "function",
|
|
75
|
+
function: { name: names.sanitize(block.name), arguments: JSON.stringify(input) },
|
|
76
|
+
},
|
|
77
|
+
];
|
|
78
|
+
});
|
|
79
|
+
if (text === "" && toolCalls.length === 0)
|
|
80
|
+
return undefined;
|
|
81
|
+
return {
|
|
82
|
+
role: "assistant",
|
|
83
|
+
content: text === "" ? null : text,
|
|
84
|
+
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
// A tool message has no error field, so a failed result says so in its text.
|
|
88
|
+
const TOOL_ERROR_PREFIX = "Error: ";
|
|
89
|
+
function toolMessage(message) {
|
|
90
|
+
const text = message.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n");
|
|
91
|
+
return { role: "tool", tool_call_id: message.callId, content: message.isError ? TOOL_ERROR_PREFIX + text : text };
|
|
92
|
+
}
|
|
93
|
+
/** Encodes the transcript; a run of tool results is followed by one user message with their images, if any. */
|
|
94
|
+
function encodeMessages(messages, names) {
|
|
95
|
+
const out = [];
|
|
96
|
+
let images = [];
|
|
97
|
+
const flushImages = () => {
|
|
98
|
+
if (images.length > 0)
|
|
99
|
+
out.push({ role: "user", content: [{ type: "text", text: TOOL_IMAGES_NOTE }, ...images] });
|
|
100
|
+
images = [];
|
|
101
|
+
};
|
|
102
|
+
for (const message of messages) {
|
|
103
|
+
if (message.role === "tool") {
|
|
104
|
+
out.push(toolMessage(message));
|
|
105
|
+
images.push(...message.content.flatMap((block) => (block.type === "image" ? [imagePart(block)] : [])));
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
flushImages();
|
|
109
|
+
const encoded = message.role === "user"
|
|
110
|
+
? { role: "user", content: userContent(message.content) }
|
|
111
|
+
: assistantMessage(message, names);
|
|
112
|
+
if (encoded)
|
|
113
|
+
out.push(encoded);
|
|
114
|
+
}
|
|
115
|
+
flushImages();
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
// Caching ------------------------------------------------------------------------------------------------------------
|
|
119
|
+
/** Puts the breakpoint on the last content part of a message, turning string content into one text part. */
|
|
120
|
+
function markMessage(message, breakpoint) {
|
|
121
|
+
if (typeof message.content === "string") {
|
|
122
|
+
message.content = [{ type: "text", text: message.content, prompt_cache_breakpoint: breakpoint }];
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const last = Array.isArray(message.content) ? message.content.at(-1) : undefined;
|
|
126
|
+
if (isObject(last))
|
|
127
|
+
last.prompt_cache_breakpoint = breakpoint;
|
|
128
|
+
}
|
|
129
|
+
// Chat Completions caches for 30 minutes: its `prompt_cache_options.ttl` takes only "30m", and the 12-hour lifetime
|
|
130
|
+
// is offered in the Responses API (Prompt caching, "Cache lifetime",
|
|
131
|
+
// https://developers.openai.com/api/docs/guides/prompt-caching, as of November 2026).
|
|
132
|
+
const LONG_BREAKPOINTS_NOTE = 'cacheRetention "long" asks for a 12-hour cache, which Chat Completions does not offer, ' +
|
|
133
|
+
"so the request was sent with 30-minute breakpoints.";
|
|
134
|
+
/** The caching fields for the body, after marking the messages that take a breakpoint. */
|
|
135
|
+
function applyCaching(messages, retention, compat) {
|
|
136
|
+
if (compat.cacheBreakpoints) {
|
|
137
|
+
// Explicit mode with no breakpoint turns caching off; implicit mode adds the server's own breakpoint to ours.
|
|
138
|
+
if (retention === "none")
|
|
139
|
+
return { fields: { prompt_cache_options: { mode: "explicit" } }, warnings: [] };
|
|
140
|
+
const system = messages[0]?.role === compat.systemRole ? messages[0] : undefined;
|
|
141
|
+
const newest = messages.findLast((message) => message.role === "user" || message.role === "tool");
|
|
142
|
+
for (const message of new Set([system, newest]))
|
|
143
|
+
if (message)
|
|
144
|
+
markMessage(message, { mode: "explicit" });
|
|
145
|
+
return { fields: {}, warnings: retention === "long" ? [warning(LONG_BREAKPOINTS_NOTE)] : [] };
|
|
146
|
+
}
|
|
147
|
+
const fields = retention === "long" && compat.promptCacheRetention ? { prompt_cache_retention: "24h" } : {};
|
|
148
|
+
return { fields, warnings: [] };
|
|
149
|
+
}
|
|
150
|
+
// Tools --------------------------------------------------------------------------------------------------------------
|
|
151
|
+
function encodeTools(tools, names, compat) {
|
|
152
|
+
const strictSchemas = new Map();
|
|
153
|
+
const encoded = tools.map((tool) => {
|
|
154
|
+
const strict = compat.strictTools ? lowerToStrict(tool.inputSchema, STRICT_DIALECT) : undefined;
|
|
155
|
+
if (strict)
|
|
156
|
+
strictSchemas.set(tool.name, tool.inputSchema);
|
|
157
|
+
const definition = {
|
|
158
|
+
name: names.sanitize(tool.name),
|
|
159
|
+
...(tool.description ? { description: tool.description } : {}),
|
|
160
|
+
parameters: strict ? strict.schema : tool.inputSchema,
|
|
161
|
+
...(strict ? { strict: true } : {}),
|
|
162
|
+
};
|
|
163
|
+
return { type: "function", function: definition };
|
|
164
|
+
});
|
|
165
|
+
return { encoded, strictSchemas };
|
|
166
|
+
}
|
|
167
|
+
// The body -----------------------------------------------------------------------------------------------------------
|
|
168
|
+
function toolNames(context, messages) {
|
|
169
|
+
const called = messages.flatMap((message) => message.role === "assistant" ? message.content.flatMap((b) => (b.type === "tool_call" ? [b.name] : [])) : []);
|
|
170
|
+
return [...context.tools.map((tool) => tool.name), ...called];
|
|
171
|
+
}
|
|
172
|
+
function warning(message) {
|
|
173
|
+
return { type: "warning", code: "unsupported_option", message };
|
|
174
|
+
}
|
|
175
|
+
/** The adapter's own fields over the caller's extras, with a warning naming any extra they overrode. */
|
|
176
|
+
function mergeExtras(own, extras, owned) {
|
|
177
|
+
const overridden = owned.filter((key) => key in extras);
|
|
178
|
+
const body = { ...extras, ...own };
|
|
179
|
+
for (const key of owned)
|
|
180
|
+
if (!(key in own))
|
|
181
|
+
delete body[key];
|
|
182
|
+
const warnings = overridden.length === 0
|
|
183
|
+
? []
|
|
184
|
+
: [
|
|
185
|
+
warning(`providerOptions.openaiChat.extraBody cannot set ${overridden.join(", ")}, ` +
|
|
186
|
+
"which the adapter sets itself, so those extraBody values were not sent."),
|
|
187
|
+
];
|
|
188
|
+
return { body, warnings };
|
|
189
|
+
}
|
|
190
|
+
function samplingFields(options, model, compat) {
|
|
191
|
+
if (options.temperature === undefined)
|
|
192
|
+
return { fields: {}, warnings: [] };
|
|
193
|
+
if (compat.temperature)
|
|
194
|
+
return { fields: { temperature: options.temperature }, warnings: [] };
|
|
195
|
+
const text = `${model.id} does not accept temperature, so the request was sent without it.`;
|
|
196
|
+
return { fields: {}, warnings: [warning(text)] };
|
|
197
|
+
}
|
|
198
|
+
/** Builds one call's request body. */
|
|
199
|
+
export function buildRequest(model, context, options, caps, compat) {
|
|
200
|
+
const messages = transformMessages(context.messages, model, caps);
|
|
201
|
+
const names = createToolNameMap(TOOL_NAME_RULES.openaiChat, toolNames(context, messages));
|
|
202
|
+
const system = context.system === "" ? [] : [{ role: compat.systemRole, content: context.system }];
|
|
203
|
+
const wireMessages = [...system, ...encodeMessages(messages, names)];
|
|
204
|
+
const caching = applyCaching(wireMessages, options.cacheRetention, compat);
|
|
205
|
+
const tools = encodeTools(context.tools, names, compat);
|
|
206
|
+
const sampling = samplingFields(options, model, compat);
|
|
207
|
+
const own = {
|
|
208
|
+
model: model.id,
|
|
209
|
+
stream: true,
|
|
210
|
+
...(compat.streamUsage ? { stream_options: { include_usage: true } } : {}),
|
|
211
|
+
messages: wireMessages,
|
|
212
|
+
...(tools.encoded.length > 0 ? { tools: tools.encoded } : {}),
|
|
213
|
+
[compat.maxTokensField]: options.maxOutputTokens ?? caps.maxOutputTokens,
|
|
214
|
+
...sampling.fields,
|
|
215
|
+
...caching.fields,
|
|
216
|
+
};
|
|
217
|
+
// Both output-limit fields, so an extra cannot send a second limit beside the adapter's.
|
|
218
|
+
const owned = ["model", "stream", "stream_options", "messages", "tools", "max_completion_tokens", "max_tokens"];
|
|
219
|
+
const { body, warnings } = mergeExtras(own, openaiChatOptions(options).extraBody ?? {}, owned);
|
|
220
|
+
return {
|
|
221
|
+
body,
|
|
222
|
+
warnings: [...sampling.warnings, ...caching.warnings, ...warnings],
|
|
223
|
+
names,
|
|
224
|
+
strictSchemas: tools.strictSchemas,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
//# sourceMappingURL=request.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/request.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAoB,MAAM,gBAAgB,CAAC;AAEtF,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAEhE,OAAO,EAAE,aAAa,EAAsB,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAa,MAAM,YAAY,CAAC;AAyBjD,oHAAoH;AACpH,kGAAkG;AAClG,mHAAmH;AACnH,gFAAgF;AAChF,MAAM,cAAc,GAAkB;IACpC,QAAQ,EAAE,UAAU;IACpB,OAAO,EAAE,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACxG,UAAU,EAAE,IAAI;IAChB,KAAK,EAAE,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,SAAS,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,YAAY,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC;IACpH,OAAO,EAAE,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,mBAAmB,EAAE,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AC,aAAa;KACnC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Builds the Chat Completions request body from a `ModelContext`. Every field below follows the API reference at\n * https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create and\n * `ChatCompletionCreateParams` in openai-node v7.49.0 (`src/resources/chat/completions/completions.ts`), both as of\n * November 2026.\n *\n * - Messages pass through `transformMessages()` first. A tool result becomes a `tool` message, whose content can hold\n * only text, so a result's images follow in one user message after the turn's results, and a failed result's text\n * starts with `Error: `. The transcript's reasoning\n * is never sent, because a Chat Completions message has no field for it.\n * - Tool names go through the run's `ToolNameMap`. A tool is sent with `strict: true` when its schema can be lowered,\n * and the plan keeps the original schema of each, so the reply's added nulls can be stripped.\n * - Caching follows the model's `ChatCompat` flags: explicit breakpoints on the system prompt and the newest user or\n * tool message, with the 30-minute lifetime Chat Completions offers; `prompt_cache_retention: \"24h\"`; or neither,\n * which leaves the server's automatic prefix cache.\n */\nimport { createToolNameMap, TOOL_NAME_RULES, type ToolNameMap } from \"../../names.js\";\nimport type { ModelEvent, StreamOptions } from \"../../spec.js\";\nimport { transformMessages } from \"../../transform-messages.js\";\nimport type { ContentBlock, Message, ModelCaps, ModelContext, ModelRef, WireTool } from \"../../types.js\";\nimport { lowerToStrict, type StrictDialect } from \"../strict-schema.js\";\nimport { isObject, type Json } from \"../wire.js\";\nimport type { ResolvedCompat } from \"./compat.js\";\n\ntype Warning = Extract<ModelEvent, { type: \"warning\" }>;\n\n/** What the adapter reads from `providerOptions.openaiChat`. */\nexport interface OpenAIChatProviderOptions {\n /**\n * Extra fields for the request body, such as `reasoning_effort`, `prompt_cache_key` or `parallel_tool_calls`. The\n * fields the adapter sets itself (`model`, `stream`, `stream_options`, `messages`, `tools`, `max_completion_tokens`\n * and `max_tokens`) win over these: an `extraBody` value for one is not sent, and the call streams an\n * `unsupported_option` warning.\n */\n readonly extraBody?: Readonly<Record<string, unknown>>;\n}\n\n/** One request's body and what reading its response needs. */\nexport interface RequestPlan {\n readonly body: Json;\n readonly warnings: readonly Warning[];\n readonly names: ToolNameMap;\n /** The original input schema of each tool sent strict, by tool name. */\n readonly strictSchemas: ReadonlyMap<string, Json>;\n}\n\n// Strict function calling makes every property required, so an optional one becomes nullable. The formats, the kept\n// and rejected keywords and the limits are those of Structured model outputs, \"Supported schemas\"\n// (https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas, as of November 2026), which\n// does not list `prefixItems`, so a schema that uses it is sent without strict.\nconst STRICT_DIALECT: StrictDialect = {\n optional: \"nullable\",\n formats: new Set([\"date-time\", \"time\", \"date\", \"duration\", \"email\", \"hostname\", \"ipv4\", \"ipv6\", \"uuid\"]),\n objectRoot: true,\n keeps: new Set([\"minimum\", \"maximum\", \"exclusiveMinimum\", \"exclusiveMaximum\", \"multipleOf\", \"minItems\", \"maxItems\"]),\n rejects: new Set([\"allOf\", \"dependentRequired\", \"dependentSchemas\", \"if\", \"then\", \"else\", \"prefixItems\"]),\n limits: {\n properties: 5000,\n depth: 10,\n enumValues: 1000,\n stringLength: 120_000,\n largeEnum: { values: 250, length: 15_000 },\n },\n};\n\nconst TOOL_IMAGES_NOTE = \"The images below are part of the tool results above.\";\n\n/** Reads `providerOptions.openaiChat`, ignoring fields of the wrong type. */\nexport function openaiChatOptions(options: StreamOptions): OpenAIChatProviderOptions {\n const raw = options.providerOptions?.openaiChat;\n if (!isObject(raw)) return {};\n return isObject(raw.extraBody) ? { extraBody: raw.extraBody } : {};\n}\n\n// Content -------------------------------------------------------------------------------------------------------------\n\nfunction imagePart(block: Extract<ContentBlock, { type: \"image\" }>): Json {\n return { type: \"image_url\", image_url: { url: `data:${block.mediaType};base64,${block.data}` } };\n}\n\nfunction contentPart(block: ContentBlock): Json[] {\n if (block.type === \"text\") return block.text === \"\" ? [] : [{ type: \"text\", text: block.text }];\n return block.type === \"image\" ? [imagePart(block)] : [];\n}\n\n/** A user message's content: a plain string for a single text block, which every compatible server reads. */\nfunction userContent(blocks: readonly ContentBlock[]): string | Json[] {\n const [only] = blocks;\n if (blocks.length === 1 && only?.type === \"text\") return only.text;\n return blocks.flatMap(contentPart);\n}\n\nfunction assistantMessage(message: Extract<Message, { role: \"assistant\" }>, names: ToolNameMap): Json | undefined {\n // Text blocks a reasoning block or a merged turn kept apart stay apart, as paragraphs.\n const text = message.content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\"\\n\\n\");\n const toolCalls = message.content.flatMap((block): Json[] => {\n if (block.type !== \"tool_call\") return [];\n // A call cut off by the output limit holds its partial JSON as a string; the wire needs a JSON object.\n const input = isObject(block.input) ? block.input : {};\n return [\n {\n id: block.callId,\n type: \"function\",\n function: { name: names.sanitize(block.name), arguments: JSON.stringify(input) },\n },\n ];\n });\n if (text === \"\" && toolCalls.length === 0) return undefined;\n return {\n role: \"assistant\",\n content: text === \"\" ? null : text,\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),\n };\n}\n\n// A tool message has no error field, so a failed result says so in its text.\nconst TOOL_ERROR_PREFIX = \"Error: \";\n\nfunction toolMessage(message: Extract<Message, { role: \"tool\" }>): Json {\n const text = message.content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\"\\n\");\n return { role: \"tool\", tool_call_id: message.callId, content: message.isError ? TOOL_ERROR_PREFIX + text : text };\n}\n\n/** Encodes the transcript; a run of tool results is followed by one user message with their images, if any. */\nfunction encodeMessages(messages: readonly Message[], names: ToolNameMap): Json[] {\n const out: Json[] = [];\n let images: Json[] = [];\n const flushImages = () => {\n if (images.length > 0) out.push({ role: \"user\", content: [{ type: \"text\", text: TOOL_IMAGES_NOTE }, ...images] });\n images = [];\n };\n for (const message of messages) {\n if (message.role === \"tool\") {\n out.push(toolMessage(message));\n images.push(...message.content.flatMap((block) => (block.type === \"image\" ? [imagePart(block)] : [])));\n continue;\n }\n flushImages();\n const encoded =\n message.role === \"user\"\n ? { role: \"user\", content: userContent(message.content) }\n : assistantMessage(message, names);\n if (encoded) out.push(encoded);\n }\n flushImages();\n return out;\n}\n\n// Caching ------------------------------------------------------------------------------------------------------------\n\n/** Puts the breakpoint on the last content part of a message, turning string content into one text part. */\nfunction markMessage(message: Json, breakpoint: Json): void {\n if (typeof message.content === \"string\") {\n message.content = [{ type: \"text\", text: message.content, prompt_cache_breakpoint: breakpoint }];\n return;\n }\n const last = Array.isArray(message.content) ? message.content.at(-1) : undefined;\n if (isObject(last)) last.prompt_cache_breakpoint = breakpoint;\n}\n\n// Chat Completions caches for 30 minutes: its `prompt_cache_options.ttl` takes only \"30m\", and the 12-hour lifetime\n// is offered in the Responses API (Prompt caching, \"Cache lifetime\",\n// https://developers.openai.com/api/docs/guides/prompt-caching, as of November 2026).\nconst LONG_BREAKPOINTS_NOTE =\n 'cacheRetention \"long\" asks for a 12-hour cache, which Chat Completions does not offer, ' +\n \"so the request was sent with 30-minute breakpoints.\";\n\n/** The caching fields for the body, after marking the messages that take a breakpoint. */\nfunction applyCaching(\n messages: Json[],\n retention: StreamOptions[\"cacheRetention\"],\n compat: ResolvedCompat,\n): { fields: Json; warnings: Warning[] } {\n if (compat.cacheBreakpoints) {\n // Explicit mode with no breakpoint turns caching off; implicit mode adds the server's own breakpoint to ours.\n if (retention === \"none\") return { fields: { prompt_cache_options: { mode: \"explicit\" } }, warnings: [] };\n const system = messages[0]?.role === compat.systemRole ? messages[0] : undefined;\n const newest = messages.findLast((message) => message.role === \"user\" || message.role === \"tool\");\n for (const message of new Set([system, newest])) if (message) markMessage(message, { mode: \"explicit\" });\n return { fields: {}, warnings: retention === \"long\" ? [warning(LONG_BREAKPOINTS_NOTE)] : [] };\n }\n const fields = retention === \"long\" && compat.promptCacheRetention ? { prompt_cache_retention: \"24h\" } : {};\n return { fields, warnings: [] };\n}\n\n// Tools --------------------------------------------------------------------------------------------------------------\n\nfunction encodeTools(tools: readonly WireTool[], names: ToolNameMap, compat: ResolvedCompat) {\n const strictSchemas = new Map<string, Json>();\n const encoded = tools.map((tool): Json => {\n const strict = compat.strictTools ? lowerToStrict(tool.inputSchema, STRICT_DIALECT) : undefined;\n if (strict) strictSchemas.set(tool.name, tool.inputSchema);\n const definition: Json = {\n name: names.sanitize(tool.name),\n ...(tool.description ? { description: tool.description } : {}),\n parameters: strict ? strict.schema : tool.inputSchema,\n ...(strict ? { strict: true } : {}),\n };\n return { type: \"function\", function: definition };\n });\n return { encoded, strictSchemas };\n}\n\n// The body -----------------------------------------------------------------------------------------------------------\n\nfunction toolNames(context: ModelContext, messages: readonly Message[]): string[] {\n const called = messages.flatMap((message) =>\n message.role === \"assistant\" ? message.content.flatMap((b) => (b.type === \"tool_call\" ? [b.name] : [])) : [],\n );\n return [...context.tools.map((tool) => tool.name), ...called];\n}\n\nfunction warning(message: string): Warning {\n return { type: \"warning\", code: \"unsupported_option\", message };\n}\n\n/** The adapter's own fields over the caller's extras, with a warning naming any extra they overrode. */\nfunction mergeExtras(own: Json, extras: Readonly<Json>, owned: readonly string[]): { body: Json; warnings: Warning[] } {\n const overridden = owned.filter((key) => key in extras);\n const body: Json = { ...extras, ...own };\n for (const key of owned) if (!(key in own)) delete body[key];\n const warnings =\n overridden.length === 0\n ? []\n : [\n warning(\n `providerOptions.openaiChat.extraBody cannot set ${overridden.join(\", \")}, ` +\n \"which the adapter sets itself, so those extraBody values were not sent.\",\n ),\n ];\n return { body, warnings };\n}\n\nfunction samplingFields(options: StreamOptions, model: ModelRef, compat: ResolvedCompat) {\n if (options.temperature === undefined) return { fields: {}, warnings: [] };\n if (compat.temperature) return { fields: { temperature: options.temperature }, warnings: [] };\n const text = `${model.id} does not accept temperature, so the request was sent without it.`;\n return { fields: {}, warnings: [warning(text)] };\n}\n\n/** Builds one call's request body. */\nexport function buildRequest(\n model: ModelRef,\n context: ModelContext,\n options: StreamOptions,\n caps: ModelCaps,\n compat: ResolvedCompat,\n): RequestPlan {\n const messages = transformMessages(context.messages, model, caps);\n const names = createToolNameMap(TOOL_NAME_RULES.openaiChat, toolNames(context, messages));\n const system = context.system === \"\" ? [] : [{ role: compat.systemRole, content: context.system }];\n const wireMessages = [...system, ...encodeMessages(messages, names)];\n const caching = applyCaching(wireMessages, options.cacheRetention, compat);\n const tools = encodeTools(context.tools, names, compat);\n const sampling = samplingFields(options, model, compat);\n const own: Json = {\n model: model.id,\n stream: true,\n ...(compat.streamUsage ? { stream_options: { include_usage: true } } : {}),\n messages: wireMessages,\n ...(tools.encoded.length > 0 ? { tools: tools.encoded } : {}),\n [compat.maxTokensField]: options.maxOutputTokens ?? caps.maxOutputTokens,\n ...sampling.fields,\n ...caching.fields,\n };\n // Both output-limit fields, so an extra cannot send a second limit beside the adapter's.\n const owned = [\"model\", \"stream\", \"stream_options\", \"messages\", \"tools\", \"max_completion_tokens\", \"max_tokens\"];\n const { body, warnings } = mergeExtras(own, openaiChatOptions(options).extraBody ?? {}, owned);\n return {\n body,\n warnings: [...sampling.warnings, ...caching.warnings, ...warnings],\n names,\n strictSchemas: tools.strictSchemas,\n };\n}\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ModelEvent } from "../../spec.js";
|
|
2
|
+
import type { ServerSentEvent } from "../../sse.js";
|
|
3
|
+
import type { ContentBlock, ModelRef, Usage } from "../../types.js";
|
|
4
|
+
import { type StreamReader } from "../wire.js";
|
|
5
|
+
import type { RequestPlan } from "./request.js";
|
|
6
|
+
/** One stream's state: the blocks so far, the usage and the finish reason. */
|
|
7
|
+
export declare class ChunkAssembler implements StreamReader {
|
|
8
|
+
#private;
|
|
9
|
+
constructor(model: ModelRef, plan: Pick<RequestPlan, "names" | "strictSchemas">);
|
|
10
|
+
/** The events one server-sent event produces. The last one is the terminal when the stream has ended. */
|
|
11
|
+
handle(sse: ServerSentEvent): ModelEvent[];
|
|
12
|
+
/**
|
|
13
|
+
* A stream that closed without `[DONE]`. One that already sent its finish reason ends as it would have, because
|
|
14
|
+
* some compatible servers never send `[DONE]`; any other is a retryable failure.
|
|
15
|
+
*/
|
|
16
|
+
ended(): ModelEvent[];
|
|
17
|
+
/** The content and usage so far, open blocks included, for an `error` terminal. */
|
|
18
|
+
partial(): {
|
|
19
|
+
content: ContentBlock[];
|
|
20
|
+
usage: Usage;
|
|
21
|
+
};
|
|
22
|
+
}
|