taugraph 0.2.0 → 0.4.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.
Files changed (94) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +283 -22
  3. package/README.zh-CN.md +283 -22
  4. package/dist/agent/index.d.ts +74 -0
  5. package/dist/agent/index.d.ts.map +1 -0
  6. package/dist/agent/index.js +254 -0
  7. package/dist/agent/index.js.map +1 -0
  8. package/dist/agent/state.d.ts +30 -0
  9. package/dist/agent/state.d.ts.map +1 -0
  10. package/dist/agent/state.js +135 -0
  11. package/dist/agent/state.js.map +1 -0
  12. package/dist/agent/util.d.ts +19 -0
  13. package/dist/agent/util.d.ts.map +1 -0
  14. package/dist/agent/util.js +59 -0
  15. package/dist/agent/util.js.map +1 -0
  16. package/dist/core/engine.d.ts +1 -1
  17. package/dist/core/engine.d.ts.map +1 -1
  18. package/dist/core/engine.js +237 -35
  19. package/dist/core/engine.js.map +1 -1
  20. package/dist/core/errors.d.ts +2 -0
  21. package/dist/core/errors.d.ts.map +1 -1
  22. package/dist/core/errors.js.map +1 -1
  23. package/dist/core/graph.d.ts.map +1 -1
  24. package/dist/core/graph.js +9 -1
  25. package/dist/core/graph.js.map +1 -1
  26. package/dist/core/node.d.ts +6 -1
  27. package/dist/core/node.d.ts.map +1 -1
  28. package/dist/core/node.js +55 -6
  29. package/dist/core/node.js.map +1 -1
  30. package/dist/core/patch.d.ts +26 -0
  31. package/dist/core/patch.d.ts.map +1 -0
  32. package/dist/core/patch.js +192 -0
  33. package/dist/core/patch.js.map +1 -0
  34. package/dist/core/retry.d.ts +20 -0
  35. package/dist/core/retry.d.ts.map +1 -0
  36. package/dist/core/retry.js +79 -0
  37. package/dist/core/retry.js.map +1 -0
  38. package/dist/core/trace.d.ts +39 -8
  39. package/dist/core/trace.d.ts.map +1 -1
  40. package/dist/core/trace.js +222 -29
  41. package/dist/core/trace.js.map +1 -1
  42. package/dist/core/types.d.ts +35 -4
  43. package/dist/core/types.d.ts.map +1 -1
  44. package/dist/core/util.d.ts +5 -1
  45. package/dist/core/util.d.ts.map +1 -1
  46. package/dist/core/util.js +41 -9
  47. package/dist/core/util.js.map +1 -1
  48. package/dist/file/index.d.ts +26 -0
  49. package/dist/file/index.d.ts.map +1 -0
  50. package/dist/file/index.js +373 -0
  51. package/dist/file/index.js.map +1 -0
  52. package/dist/index.d.ts +4 -3
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +2 -1
  55. package/dist/index.js.map +1 -1
  56. package/dist/nodes/code.d.ts +5 -0
  57. package/dist/nodes/code.d.ts.map +1 -1
  58. package/dist/nodes/code.js.map +1 -1
  59. package/dist/nodes/content.d.ts +18 -0
  60. package/dist/nodes/content.d.ts.map +1 -0
  61. package/dist/nodes/content.js +88 -0
  62. package/dist/nodes/content.js.map +1 -0
  63. package/dist/nodes/index.d.ts +2 -1
  64. package/dist/nodes/index.d.ts.map +1 -1
  65. package/dist/nodes/index.js +1 -0
  66. package/dist/nodes/index.js.map +1 -1
  67. package/dist/nodes/llm.d.ts +100 -4
  68. package/dist/nodes/llm.d.ts.map +1 -1
  69. package/dist/nodes/llm.js +5 -1
  70. package/dist/nodes/llm.js.map +1 -1
  71. package/dist/openai/index.d.ts +55 -0
  72. package/dist/openai/index.d.ts.map +1 -0
  73. package/dist/openai/index.js +208 -0
  74. package/dist/openai/index.js.map +1 -0
  75. package/package.json +20 -4
  76. package/src/agent/index.ts +359 -0
  77. package/src/agent/state.ts +147 -0
  78. package/src/agent/util.ts +74 -0
  79. package/src/core/engine.ts +241 -34
  80. package/src/core/errors.ts +2 -0
  81. package/src/core/graph.ts +7 -1
  82. package/src/core/node.ts +55 -6
  83. package/src/core/patch.ts +173 -0
  84. package/src/core/retry.ts +89 -0
  85. package/src/core/trace.ts +222 -29
  86. package/src/core/types.ts +37 -4
  87. package/src/core/util.ts +43 -10
  88. package/src/file/index.ts +408 -0
  89. package/src/index.ts +5 -1
  90. package/src/nodes/code.ts +5 -0
  91. package/src/nodes/content.ts +100 -0
  92. package/src/nodes/index.ts +10 -0
  93. package/src/nodes/llm.ts +109 -7
  94. package/src/openai/index.ts +286 -0
package/src/nodes/llm.ts CHANGED
@@ -2,14 +2,92 @@ import { defineNode, type MaybePromise, type Node, type RetryPolicy, type Standa
2
2
  import { andThen, issuesMessage } from "./util.js";
3
3
 
4
4
  // ---------------------------------------------------------------------------
5
- // Model contract. taugraph ships no provider; adapt any SDK or HTTP API to this.
5
+ // Model contract. Adapt any SDK or HTTP API to this; taugraph/openai covers OpenAI-compatible endpoints.
6
6
  // ---------------------------------------------------------------------------
7
7
 
8
- export interface ChatMessage {
9
- readonly role: "system" | "user" | "assistant";
10
- readonly content: string;
8
+ /** A tool the model may call. Field names follow MCP; `inputSchema` is JSON Schema for the arguments object. */
9
+ export interface ToolSpec {
10
+ /** Letters, digits, `_` and `-`, at most 64 characters: what every major provider accepts. */
11
+ readonly name: string;
12
+ readonly description?: string;
13
+ readonly inputSchema: Readonly<Record<string, unknown>>;
14
+ }
15
+
16
+ /** A call the model asked for. Arguments are parsed JSON, as in MCP and Anthropic; adapters convert OpenAI's string. */
17
+ export interface ToolCall {
18
+ readonly id: string;
19
+ readonly name: string;
20
+ readonly arguments: Readonly<Record<string, unknown>>;
21
+ /** Set by an adapter that could not read the arguments as a JSON object; `arguments` is then `{}`. */
22
+ readonly parseError?: string;
23
+ /** The provider's opaque proof for this call (Gemini's thought signature). Send it back to the same model only. */
24
+ readonly signature?: string;
25
+ }
26
+
27
+ /** How the model may use tools: freely, not at all, at least one, or this one. */
28
+ export type ToolChoice = "auto" | "none" | "required" | { readonly name: string };
29
+
30
+ /**
31
+ * How much a model should think before it answers. Adapters map it to the provider's setting; an adapter that knows
32
+ * which levels a model has rounds to the nearest one.
33
+ */
34
+ export type ReasoningLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
35
+
36
+ /**
37
+ * What a model thought before answering, in the order it gave. `signature` is the provider's opaque proof and is only
38
+ * valid for the model that wrote it: adapters send it back when the assistant message's `model` is their own `id`.
39
+ */
40
+ export interface ReasoningPart {
41
+ readonly text: string;
42
+ readonly signature?: string;
43
+ /** The provider hid the text (a safety filter); `signature` holds the encrypted payload. */
44
+ readonly redacted?: boolean;
45
+ }
46
+
47
+ /** Text in a message. */
48
+ export interface TextPart {
49
+ readonly type: "text";
50
+ readonly text: string;
11
51
  }
12
52
 
53
+ /**
54
+ * An image in a message: its bytes in base64 (`data`, without a `data:` prefix), or a URL. A URL may be `https:`,
55
+ * `data:`, or a reference of your own such as `media:abc` that the adapter reads when it calls the model, which keeps
56
+ * traces and snapshots small. Field names follow MCP. If both `data` and `url` are present, `data` wins; narrow with
57
+ * `"data" in image`.
58
+ */
59
+ export type ImagePart =
60
+ | { readonly type: "image"; readonly data: string; readonly mimeType: string }
61
+ | { readonly type: "image"; readonly url: string; readonly mimeType?: string };
62
+
63
+ export type ContentPart = TextPart | ImagePart;
64
+
65
+ /** What a user message or a tool result carries: plain text, or text and images in order. */
66
+ export type MessageContent = string | readonly ContentPart[];
67
+
68
+ /** One message of a conversation. User messages and tool results may carry images; the others are text. */
69
+ export type ChatMessage =
70
+ | { readonly role: "system"; readonly content: string }
71
+ | { readonly role: "user"; readonly content: MessageContent }
72
+ | {
73
+ readonly role: "assistant";
74
+ readonly content: string;
75
+ readonly toolCalls?: readonly ToolCall[];
76
+ /** What the model thought first. */
77
+ readonly reasoning?: readonly ReasoningPart[];
78
+ /**
79
+ * The `LLMModel.id` that wrote this message (not `LLMResponse.model`). Adapters send reasoning signatures,
80
+ * `redacted` parts and `ToolCall.signature` back only when it equals their own `id`.
81
+ */
82
+ readonly model?: string;
83
+ }
84
+ | {
85
+ readonly role: "tool";
86
+ readonly toolCallId: string;
87
+ readonly content: MessageContent;
88
+ readonly isError?: boolean;
89
+ };
90
+
13
91
  /** Everything in a request is recorded in the trace, so keep it plain JSON. */
14
92
  export interface LLMRequest {
15
93
  readonly messages: readonly ChatMessage[];
@@ -19,17 +97,35 @@ export interface LLMRequest {
19
97
  readonly responseFormat?: "text" | "json";
20
98
  /** Provider-specific options, passed through by the adapter. */
21
99
  readonly extra?: Readonly<Record<string, unknown>>;
100
+ /** Tools the model may call; adapters translate them to the provider's format. */
101
+ readonly tools?: readonly ToolSpec[];
102
+ readonly toolChoice?: ToolChoice;
103
+ /** How much the model should think first. Unset: the adapter sends nothing and the model uses its default. */
104
+ readonly reasoning?: ReasoningLevel;
22
105
  }
23
106
 
24
107
  export interface LLMResponse {
25
108
  readonly content: string;
109
+ /** The provider's name for the model that answered, e.g. "gpt-4o-mini-2024-07-18". Not the `LLMModel.id`. */
26
110
  readonly model?: string;
27
111
  readonly finishReason?: string;
28
- readonly usage?: { readonly inputTokens?: number; readonly outputTokens?: number };
112
+ readonly usage?: {
113
+ readonly inputTokens?: number;
114
+ readonly outputTokens?: number;
115
+ /** Tokens spent thinking; already counted in `outputTokens`. */
116
+ readonly reasoningTokens?: number;
117
+ };
118
+ /** Tool calls the model asked for, in order. */
119
+ readonly toolCalls?: readonly ToolCall[];
120
+ /** What the model thought before answering, in order. */
121
+ readonly reasoning?: readonly ReasoningPart[];
29
122
  }
30
123
 
31
124
  export interface LLMModel {
32
- /** Recorded in every `llm_call` event, e.g. "openai:gpt-4o-mini" or "ollama:qwen3". */
125
+ /**
126
+ * Recorded in every `llm_call` event, e.g. "openai:gpt-4o-mini" or "ollama:qwen3". It also decides which assistant
127
+ * messages count as this model's own for reasoning passback, so keep it stable and different for each model.
128
+ */
33
129
  readonly id: string;
34
130
  complete(request: LLMRequest, options: { readonly signal: AbortSignal }): MaybePromise<LLMResponse>;
35
131
  }
@@ -44,6 +140,8 @@ interface LLMNodeBase<S> {
44
140
  readonly prompt: (state: S) => LLMRequest | string;
45
141
  /** Retries the whole call, including output parsing. */
46
142
  readonly retry?: RetryPolicy;
143
+ /** Milliseconds each attempt may take; then the request's signal aborts and the attempt fails with TIMEOUT. */
144
+ readonly timeoutMs?: number;
47
145
  }
48
146
 
49
147
  export interface LLMTextNodeConfig<S> extends LLMNodeBase<S> {
@@ -100,7 +198,11 @@ export function LLMNode<S, T>(config: LLMTextNodeConfig<S> | LLMStructuredNodeCo
100
198
  );
101
199
  });
102
200
  },
103
- { kind: "llm", ...(config.retry && { retry: config.retry }) },
201
+ {
202
+ kind: "llm",
203
+ ...(config.retry && { retry: config.retry }),
204
+ ...(config.timeoutMs !== undefined && { timeoutMs: config.timeoutMs }),
205
+ },
104
206
  );
105
207
  }
106
208
 
@@ -0,0 +1,286 @@
1
+ // taugraph/openai: the LLMModel contract on any OpenAI-compatible /chat/completions endpoint (OpenAI, DeepSeek, Qwen,
2
+ // Kimi, Ollama, vLLM, LM Studio, ...), with tool calling, images and reasoning. A plugin like taugraph/agent: it uses
3
+ // the global fetch, or the one you pass, and adds no dependencies.
4
+ import type { MaybePromise } from "../index.js";
5
+ import {
6
+ type ChatMessage,
7
+ type ImagePart,
8
+ type ImageResolver,
9
+ type LLMModel,
10
+ type MessageContent,
11
+ type ReasoningLevel,
12
+ resolveImages,
13
+ type ToolCall,
14
+ type ToolChoice,
15
+ type ToolSpec,
16
+ textOf,
17
+ } from "../nodes/index.js";
18
+
19
+ export interface OpenAICompatibleOptions {
20
+ /** e.g. "https://api.openai.com/v1" or "http://localhost:11434/v1" for Ollama */
21
+ readonly baseURL: string;
22
+ readonly model: string;
23
+ readonly apiKey?: string | undefined;
24
+ /** Reads image URLs OpenAI cannot fetch, e.g. `media:abc` from your store. http(s) and data: URLs go as they are. */
25
+ readonly resolveImage?: ImageResolver | undefined;
26
+ /** Request parameters for a reasoning level, merged before `extra`. Default: `{ reasoning_effort }`, "off" as "none". */
27
+ readonly reasoningParams?: ((level: ReasoningLevel) => Record<string, unknown>) | undefined;
28
+ /**
29
+ * Send a model's own reasoning back as `reasoning_content`. Default true: DeepSeek V4 and Kimi refuse a tool loop
30
+ * without it. Set false for endpoints that refuse the field in input messages, such as Groq and Cerebras.
31
+ */
32
+ readonly sendReasoning?: boolean | undefined;
33
+ /**
34
+ * The request field that carries `maxTokens`. Default `"max_tokens"`; OpenAI's reasoning models (o-series, GPT-5)
35
+ * want `"max_completion_tokens"`.
36
+ */
37
+ readonly tokenLimit?: "max_tokens" | "max_completion_tokens" | undefined;
38
+ /** Used instead of the global `fetch`, e.g. for a proxy or tests. */
39
+ readonly fetch?: typeof fetch | undefined;
40
+ }
41
+
42
+ /** A tool call as OpenAI sends it: arguments are a JSON string. */
43
+ export interface OpenAIToolCall {
44
+ readonly id?: string;
45
+ readonly type?: string;
46
+ readonly function?: { readonly name?: string; readonly arguments?: string };
47
+ }
48
+
49
+ /** A response outside 200-299. `status` and `retryAfterMs` let `isRetryable` and the retry wait act on it. */
50
+ export class HTTPError extends Error {
51
+ override readonly name = "HTTPError";
52
+ constructor(
53
+ message: string,
54
+ readonly status: number,
55
+ readonly url: string,
56
+ /** From `Retry-After`, given in seconds or as an HTTP date; undefined when missing or unreadable. */
57
+ readonly retryAfterMs: number | undefined,
58
+ ) {
59
+ super(message);
60
+ }
61
+ }
62
+
63
+ /** `Retry-After` in milliseconds: a number of seconds, or an HTTP date (0 once it has passed). */
64
+ function retryAfter(header: string | null): number | undefined {
65
+ if (header === null) return undefined;
66
+ const text = header.trim();
67
+ if (/^\d+(\.\d+)?$/.test(text)) return Math.round(Number(text) * 1000);
68
+ const date = Date.parse(text);
69
+ return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
70
+ }
71
+
72
+ interface ChatCompletion {
73
+ model?: string;
74
+ choices?: {
75
+ message?: {
76
+ content?: string | null;
77
+ tool_calls?: OpenAIToolCall[];
78
+ /** DeepSeek, Qwen, Kimi */
79
+ reasoning_content?: string | null;
80
+ /** OpenRouter, Ollama */
81
+ reasoning?: string | null;
82
+ };
83
+ finish_reason?: string;
84
+ }[];
85
+ usage?: {
86
+ prompt_tokens?: number;
87
+ completion_tokens?: number;
88
+ completion_tokens_details?: { reasoning_tokens?: number };
89
+ };
90
+ }
91
+
92
+ const defaultReasoningParams = (level: ReasoningLevel): Record<string, unknown> => ({
93
+ reasoning_effort: level === "off" ? "none" : level,
94
+ });
95
+
96
+ /** A model's own reasoning as `reasoning_content`, which DeepSeek V4 requires back in tool loops. Never another model's. */
97
+ function reasoningOf(
98
+ m: Extract<ChatMessage, { role: "assistant" }>,
99
+ modelId: string | undefined,
100
+ ): Record<string, unknown> {
101
+ if (modelId === undefined || m.model !== modelId || !m.reasoning?.length) return {};
102
+ const text = m.reasoning
103
+ .filter((r) => !r.redacted)
104
+ .map((r) => r.text)
105
+ .join("\n");
106
+ return text === "" ? {} : { reasoning_content: text };
107
+ }
108
+
109
+ /** URLs OpenAI takes as they are. */
110
+ const SENDABLE = /^(https?|data):/i;
111
+ const shown = (url: string): string => (url.length > 100 ? `${url.slice(0, 100)}…` : url);
112
+
113
+ function imageURL(image: ImagePart): string {
114
+ if ("data" in image) return `data:${image.mimeType};base64,${image.data}`;
115
+ if (!SENDABLE.test(image.url)) {
116
+ throw new TypeError(
117
+ `Image "${shown(image.url)}" cannot be sent as a URL; make resolveImage return { data, mimeType } or an http(s) URL`,
118
+ );
119
+ }
120
+ return image.url;
121
+ }
122
+
123
+ const imageOf = (image: ImagePart) => ({ type: "image_url", image_url: { url: imageURL(image) } });
124
+
125
+ const imagesIn = (content: MessageContent): ImagePart[] =>
126
+ typeof content === "string" ? [] : content.filter((p): p is ImagePart => p.type === "image");
127
+
128
+ /** OpenAI's tool messages take text only, and have no error flag: errors say so in the text. */
129
+ function toolText(m: Extract<ChatMessage, { role: "tool" }>): string {
130
+ const text = textOf(m.content, { imagePlaceholder: "" }) || (imagesIn(m.content).length > 0 ? "(image)" : "");
131
+ return m.isError && !text.startsWith("Error") ? `Error: ${text}` : text;
132
+ }
133
+
134
+ /**
135
+ * taugraph messages in OpenAI's wire format. Images from tool results go into one user message right after the
136
+ * tool messages, since OpenAI's tool messages take text only. Image references must be read first (`resolveImage`).
137
+ * Pass the adapter's id as `modelId` to send that model's own reasoning back.
138
+ */
139
+ export function toOpenAIMessages(messages: readonly ChatMessage[], modelId?: string): Record<string, unknown>[] {
140
+ const out: Record<string, unknown>[] = [];
141
+ let toolImages: Record<string, unknown>[] = [];
142
+ const flush = () => {
143
+ if (toolImages.length > 0) out.push({ role: "user", content: toolImages });
144
+ toolImages = [];
145
+ };
146
+ for (const m of messages) {
147
+ if (m.role === "tool") {
148
+ out.push({ role: "tool", tool_call_id: m.toolCallId, content: toolText(m) });
149
+ const images = imagesIn(m.content);
150
+ if (images.length > 0) {
151
+ toolImages.push({ type: "text", text: `Images from tool call ${m.toolCallId}:` }, ...images.map(imageOf));
152
+ }
153
+ continue;
154
+ }
155
+ flush();
156
+ if (m.role === "assistant" && m.toolCalls?.length) {
157
+ out.push({
158
+ role: "assistant",
159
+ content: m.content === "" ? null : m.content,
160
+ tool_calls: m.toolCalls.map((c) => ({
161
+ id: c.id,
162
+ type: "function",
163
+ function: { name: c.name, arguments: JSON.stringify(c.arguments) },
164
+ })),
165
+ ...reasoningOf(m, modelId),
166
+ });
167
+ } else if (m.role === "user" && typeof m.content !== "string") {
168
+ out.push({
169
+ role: "user",
170
+ content: m.content.map((p) => (p.type === "text" ? { type: "text", text: p.text } : imageOf(p))),
171
+ });
172
+ } else {
173
+ out.push({ role: m.role, content: m.content, ...(m.role === "assistant" && reasoningOf(m, modelId)) });
174
+ }
175
+ }
176
+ flush();
177
+ return out;
178
+ }
179
+
180
+ export function toOpenAITools(tools: readonly ToolSpec[]): Record<string, unknown>[] {
181
+ return tools.map((t) => ({
182
+ type: "function",
183
+ function: { name: t.name, ...(t.description && { description: t.description }), parameters: t.inputSchema },
184
+ }));
185
+ }
186
+
187
+ export function toOpenAIToolChoice(choice: ToolChoice): unknown {
188
+ return typeof choice === "string" ? choice : { type: "function", function: { name: choice.name } };
189
+ }
190
+
191
+ /** OpenAI's tool calls as taugraph's, arguments parsed. Unreadable arguments become `{}` with a `parseError`; missing ids become `call_<round>_<index>`. */
192
+ export function fromOpenAIToolCalls(calls: readonly OpenAIToolCall[], round = 1): ToolCall[] {
193
+ return calls.flatMap((c, i) => {
194
+ const name = c.function?.name;
195
+ if (!name) return [];
196
+ const raw = c.function?.arguments ?? "";
197
+ let parsed: unknown = {};
198
+ let parseError: string | undefined;
199
+ if (raw.trim() !== "") {
200
+ try {
201
+ parsed = JSON.parse(raw);
202
+ } catch {
203
+ parseError = "arguments are not valid JSON";
204
+ }
205
+ }
206
+ const isObject = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed);
207
+ if (!parseError && !isObject) parseError = "arguments are not a JSON object";
208
+ return [
209
+ {
210
+ id: c.id || `call_${round}_${i}`,
211
+ name,
212
+ arguments: isObject && !parseError ? (parsed as Record<string, unknown>) : {},
213
+ ...(parseError && { parseError }),
214
+ },
215
+ ];
216
+ });
217
+ }
218
+
219
+ export function openAICompatible(options: OpenAICompatibleOptions): LLMModel {
220
+ const url = `${options.baseURL.replace(/\/+$/, "")}/chat/completions`;
221
+ const id = `openai-compatible:${options.model}`;
222
+ const tokenLimit = options.tokenLimit ?? "max_tokens";
223
+ if (tokenLimit !== "max_tokens" && tokenLimit !== "max_completion_tokens") {
224
+ throw new TypeError(
225
+ `openAICompatible: tokenLimit must be "max_tokens" or "max_completion_tokens", got ${String(options.tokenLimit)}`,
226
+ );
227
+ }
228
+ const readImage = (image: string): MaybePromise<ImagePart> => {
229
+ if (/^https?:/i.test(image)) return { type: "image", url: image };
230
+ if (!options.resolveImage) throw new TypeError(`Image "${shown(image)}" needs resolveImage to be read`);
231
+ return options.resolveImage(image);
232
+ };
233
+ return {
234
+ id,
235
+ async complete(request, { signal }) {
236
+ const messages = await resolveImages(request.messages, readImage);
237
+ const response = await (options.fetch ?? fetch)(url, {
238
+ method: "POST",
239
+ signal,
240
+ headers: {
241
+ "content-type": "application/json",
242
+ ...(options.apiKey && { authorization: `Bearer ${options.apiKey}` }),
243
+ },
244
+ body: JSON.stringify({
245
+ model: options.model,
246
+ messages: toOpenAIMessages(messages, options.sendReasoning === false ? undefined : id),
247
+ temperature: request.temperature,
248
+ [tokenLimit]: request.maxTokens,
249
+ ...(request.responseFormat === "json" && { response_format: { type: "json_object" } }),
250
+ ...(request.tools?.length && { tools: toOpenAITools(request.tools) }),
251
+ ...(request.toolChoice && { tool_choice: toOpenAIToolChoice(request.toolChoice) }),
252
+ ...(request.reasoning && (options.reasoningParams ?? defaultReasoningParams)(request.reasoning)),
253
+ ...request.extra,
254
+ }),
255
+ });
256
+ if (!response.ok) {
257
+ const text = await response.text().catch(() => "");
258
+ throw new HTTPError(
259
+ `${url} responded ${response.status}: ${text.slice(0, 500)}`,
260
+ response.status,
261
+ url,
262
+ retryAfter(response.headers.get("retry-after")),
263
+ );
264
+ }
265
+ const body = (await response.json()) as ChatCompletion;
266
+ const choice = body.choices?.[0];
267
+ const calls = choice?.message?.tool_calls;
268
+ const round = request.messages.filter((m) => m.role === "assistant").length + 1;
269
+ const message = choice?.message;
270
+ const thought = message?.reasoning_content || message?.reasoning;
271
+ const reasoningTokens = body.usage?.completion_tokens_details?.reasoning_tokens;
272
+ return {
273
+ content: message?.content ?? "",
274
+ ...(body.model && { model: body.model }),
275
+ ...(choice?.finish_reason && { finishReason: choice.finish_reason }),
276
+ usage: {
277
+ inputTokens: body.usage?.prompt_tokens ?? 0,
278
+ outputTokens: body.usage?.completion_tokens ?? 0,
279
+ ...(typeof reasoningTokens === "number" && { reasoningTokens }),
280
+ },
281
+ ...(thought && { reasoning: [{ text: thought }] }),
282
+ ...(calls?.length && { toolCalls: fromOpenAIToolCalls(calls, round) }),
283
+ };
284
+ },
285
+ };
286
+ }