llm-large-files 0.4.1 → 0.7.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 (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
@@ -0,0 +1,613 @@
1
+ // Any Chat Completions endpoint as a model of `askWithFiles`: OpenAI, Azure OpenAI, DeepSeek,
2
+ // LiteLLM, vLLM, Ollama, OpenRouter, Gemini's OpenAI layer. No SDK: the caller gives the URL.
3
+ import { randomUUID } from "node:crypto";
4
+ import { base64, idleWatch, noteCutReply, notJsonMessage, parseArguments, readArguments, readJson, replyEnd, resolveHeaderSource, resolveSecret, streamedReply, unreachableReason, type HeaderSource, type IdleWatch, type SecretSource } from "../http.js";
5
+ import { laterResult, ModelRequestError, type ChatMessage, type ModelAdapter, type ModelMessage, type ModelReply, type ModelRequest, type ModelTextMessage, type ModelToolRound, type SendHooks, type ToolCall, type ToolTurn } from "../model.js";
6
+ import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
7
+ import { retryAfterMs } from "../retry.js";
8
+ import { eventTooLongMessage, parseSseJson, SseEventTooLongError } from "../sse.js";
9
+ import type { GenerateText, GenerateUsage, ToolDeclaration, ToolResult } from "../types.js";
10
+
11
+ /** The endpoint answered with an HTTP error, or could not be reached (`status` 0). */
12
+ export class OpenAiRequestError extends ModelRequestError {
13
+ /** The request field the error is about, when the server named it (`error.param`): "max_tokens". */
14
+ readonly param?: string;
15
+ /** The server's own word for the error (`error.code`): "unsupported_parameter". */
16
+ readonly code?: string;
17
+ constructor(message: string, status: number, options: ConstructorParameters<typeof ModelRequestError>[2] & { param?: string } = {}) {
18
+ super(message, status, options);
19
+ this.name = "OpenAiRequestError";
20
+ if (options.param) this.param = options.param;
21
+ if (options.code) this.code = options.code;
22
+ }
23
+ }
24
+
25
+ /** A Chat Completions message, as the API takes and returns it. */
26
+ export type OpenAiMessage = { role: string; [key: string]: unknown };
27
+
28
+ export type OpenAiCompatibleOptions = {
29
+ /** The model name the endpoint knows: "gpt-5.5", "deepseek-v4-pro", a deployment name. */
30
+ model: string;
31
+ /**
32
+ * The base of the API: `/chat/completions` is added to it. Defaults to https://api.openai.com/v1.
33
+ * DeepSeek: https://api.deepseek.com/v1. Gemini: https://generativelanguage.googleapis.com/v1beta/openai.
34
+ */
35
+ baseUrl?: string | undefined;
36
+ /** The whole Chat Completions URL, when it is not `baseUrl` + `/chat/completions` (Azure OpenAI, a gateway). */
37
+ url?: string | undefined;
38
+ /** Sent as `Authorization: Bearer …`. A function is called for each request. */
39
+ apiKey?: SecretSource | undefined;
40
+ /** More headers, or all of them (Azure's `api-key`). A function is called for each request. */
41
+ headers?: HeaderSource | undefined;
42
+ /** More fields for the body of every chat request: `temperature`, `reasoning_effort`, `max_completion_tokens`, and so on. */
43
+ body?: Record<string, unknown> | undefined;
44
+ /** More fields for the body of a whole-document part read, given the output limit it is sent with. */
45
+ analysisBody?: ((maxOutputTokens: number) => Record<string, unknown>) | undefined;
46
+ /**
47
+ * The name of the output limit in a part read. `max_completion_tokens` for api.openai.com and
48
+ * Azure OpenAI (`*.openai.azure.com`, and the `/openai/` paths of `*.cognitiveservices.azure.com`
49
+ * and `*.services.ai.azure.com`), whose newer models refuse the other; `max_tokens` anywhere
50
+ * else, where it is the one every server knows. Left out, a server that refuses the one sent
51
+ * (HTTP 400 naming it) is sent the other, which is then kept for this adapter.
52
+ */
53
+ maxTokensField?: "max_tokens" | "max_completion_tokens" | undefined;
54
+ /** "system" (the default), or "developer" for an endpoint that wants the newer name. */
55
+ systemRole?: "system" | "developer" | undefined;
56
+ /**
57
+ * How the request that must be answered in text says so. "tool_choice" (the default) keeps the
58
+ * tools and sends `tool_choice: "none"`. "omit" leaves the tools out, for a server that does not
59
+ * know `tool_choice`.
60
+ */
61
+ answerWithoutTools?: "tool_choice" | "omit" | undefined;
62
+ /**
63
+ * Send the pages of `view_pages` to the model, as a `file` part in a user message after the tool
64
+ * results. Off by default: a tool message holds text only, and many servers behind this API
65
+ * take no PDF at all. Turn it on for a model that reads PDF input.
66
+ */
67
+ pdfInput?: boolean | undefined;
68
+ /** Stream the answer when the caller listens for text. Defaults to true. False for a server without streaming. */
69
+ stream?: boolean | undefined;
70
+ /** The model's context window in tokens, when the budget of a question should follow it. */
71
+ contextTokens?: number | undefined;
72
+ /** The largest request body the endpoint takes, in bytes. */
73
+ maxRequestBytes?: number | undefined;
74
+ /** Tokens billed for one PDF page, when `pdfInput` is on. Defaults to 1,000. */
75
+ pageTokens?: number | undefined;
76
+ /** This model's tokens for one token of the library's estimate. Defaults to 1. */
77
+ tokenScale?: number | undefined;
78
+ /** Milliseconds a part read may take. Defaults to 180,000. */
79
+ timeoutMs?: number | undefined;
80
+ /**
81
+ * The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count:
82
+ * a model that thinks sends nothing until it has thought, and a reply that is not streamed comes
83
+ * whole at the end. A request that gets nothing for that long is aborted and sent again, once.
84
+ * Defaults to 600,000. 0 waits without end.
85
+ */
86
+ firstByteTimeoutMs?: number | undefined;
87
+ /**
88
+ * The longest wait, in milliseconds, between two pieces of a chat reply once it has started to
89
+ * arrive (keep-alives count). A request that gets nothing for that long is aborted and sent
90
+ * again, once, unless text of it was shown. Defaults to 300,000. 0 waits without end.
91
+ */
92
+ idleTimeoutMs?: number | undefined;
93
+ /** Names the model in usage totals. Defaults to `model`. */
94
+ id?: string | undefined;
95
+ fetch?: typeof fetch | undefined;
96
+ };
97
+
98
+ type Json = Record<string, any>;
99
+
100
+ const contentText = (content: unknown): string => {
101
+ if (typeof content === "string") return content;
102
+ if (!Array.isArray(content)) return "";
103
+ return content.map((part: Json) => (part?.type === "text" && typeof part.text === "string" ? part.text : "")).join("");
104
+ };
105
+
106
+ const asFunction = (declaration: ToolDeclaration) => ({ type: "function", function: declaration });
107
+
108
+ function usageOf(usage: Json | undefined): GenerateUsage {
109
+ const number = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : 0);
110
+ return {
111
+ inputTokens: number(usage?.prompt_tokens),
112
+ cachedInputTokens: number(usage?.prompt_tokens_details?.cached_tokens ?? usage?.prompt_cache_hit_tokens),
113
+ outputTokens: number(usage?.completion_tokens),
114
+ thoughtTokens: number(usage?.completion_tokens_details?.reasoning_tokens),
115
+ };
116
+ }
117
+
118
+ /** The status of an error event in a stream that began with 200: from its code, or from its type. */
119
+ const STATUS_OF_ERROR: Record<string, number> = {
120
+ server_error: 500, api_error: 500, internal_error: 500, internal_server_error: 500, service_unavailable: 503,
121
+ rate_limit_exceeded: 429, rate_limit_error: 429, tokens_exceeded: 429, timeout: 408, invalid_request_error: 400,
122
+ context_length_exceeded: 400, insufficient_quota: 429,
123
+ };
124
+
125
+ /**
126
+ * The HTTP status of an error that arrived inside a stream. The response itself was 200, which says
127
+ * nothing of the error: OpenAI's own is `{ type: "server_error", code: null }`. A failure the server
128
+ * did not name is its own, 500, and is sent again like one (when no text of it was shown).
129
+ */
130
+ export function streamErrorStatus(failed: unknown): number {
131
+ if (failed && typeof failed === "object") {
132
+ const { code, type } = failed as { code?: unknown; type?: unknown };
133
+ const numeric = typeof code === "number" ? code : typeof code === "string" && /^\d{3}$/.test(code) ? Number(code) : Number.NaN;
134
+ if (numeric >= 400 && numeric <= 599) return numeric;
135
+ for (const word of [type, code]) if (typeof word === "string" && STATUS_OF_ERROR[word] !== undefined) return STATUS_OF_ERROR[word]!;
136
+ }
137
+ return 500;
138
+ }
139
+
140
+ /**
141
+ * Whether a server refused the name of the output limit (`max_tokens` or `max_completion_tokens`),
142
+ * rather than its number: "Unsupported parameter: 'max_tokens' ... Use 'max_completion_tokens'
143
+ * instead", "Unrecognized request argument supplied: max_completion_tokens". Not "max_tokens is
144
+ * too large", which can name the other field too.
145
+ */
146
+ function refusesField(error: unknown, field: string): boolean {
147
+ if (!(error instanceof OpenAiRequestError) || error.status !== 400) return false;
148
+ // A server that names the field it refuses says it plainly.
149
+ if (error.param !== undefined) return error.param === field && (error.code === "unsupported_parameter" || REFUSED.test(error.message));
150
+ const message = error.message;
151
+ if (/too large|too many|maximum|at most|exceed|must be (less|at most|<)/i.test(message) || !REFUSED.test(message)) return false;
152
+ // "Unsupported parameter: 'max_tokens' ... Use 'max_completion_tokens' instead" names both: the
153
+ // one it refuses comes first. Azure's "Could not finish the message because max_tokens or model
154
+ // output limit was reached" refuses nothing.
155
+ const named = /max_completion_tokens|max_tokens/.exec(message)?.[0];
156
+ return named === field;
157
+ }
158
+
159
+ /** Words of a server that refuses a field of the request, rather than its value. */
160
+ const REFUSED = /unsupported|unrecognized|not supported|unknown (parameter|field|argument)|not permitted|not allowed|extra (inputs|fields)/i;
161
+
162
+ /**
163
+ * Adds a piece of OpenRouter's streamed `reasoning_details` to those of the turn. Pieces of one
164
+ * detail share its `index` and type: their text is joined, and their other fields (a signature, an
165
+ * ID, the encrypted data) are kept. The details stay in the order they came, and are not changed
166
+ * otherwise: they go back to the model as they were written.
167
+ */
168
+ function addReasoningDetail(details: Json[], detail: unknown): void {
169
+ if (!detail || typeof detail !== "object") return;
170
+ const piece = detail as Json;
171
+ const same = typeof piece.index === "number" ? details.find((known) => known.index === piece.index && known.type === piece.type) : undefined;
172
+ if (!same) {
173
+ details.push({ ...piece });
174
+ return;
175
+ }
176
+ for (const [key, value] of Object.entries(piece)) {
177
+ if (value === null || value === undefined) continue;
178
+ if ((key === "text" || key === "summary") && typeof value === "string" && typeof same[key] === "string") same[key] += value;
179
+ else same[key] = value;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * The error of a response that is not OK. Gemini's layer wraps its error in an array. Most servers
185
+ * put it in `error`; vLLM before its OpenAI-shaped errors, SGLang and FastChat put `message`, and
186
+ * servers built on FastAPI `detail`, at the top of the body.
187
+ */
188
+ async function failure(response: Response): Promise<OpenAiRequestError> {
189
+ const data = await response.json().catch(() => null) as Json | Json[] | null;
190
+ const body = Array.isArray(data) ? data[0] : data;
191
+ const nested = body?.error && typeof body.error === "object" ? body.error as Json : undefined;
192
+ const message = [typeof body?.error === "string" ? body.error : nested?.message, body?.message, detailText(body?.detail)]
193
+ .find((text): text is string => typeof text === "string" && text.length > 0);
194
+ const wait = retryAfterMs(response.headers, body);
195
+ const own = nested ?? (body && typeof body === "object" ? body : undefined);
196
+ const param = typeof own?.param === "string" ? own.param as string : undefined;
197
+ const code = typeof own?.code === "string" ? own.code as string : undefined;
198
+ return new OpenAiRequestError(message ?? `The model returned HTTP ${response.status}.`, response.status, {
199
+ ...(wait === undefined ? {} : { retryAfterMs: wait }),
200
+ ...(param ? { param } : {}),
201
+ ...(code ? { code } : {}),
202
+ });
203
+ }
204
+
205
+ /** FastAPI's `detail`: a message, or a list of problems, each with its own `msg`. */
206
+ function detailText(detail: unknown): string | undefined {
207
+ if (typeof detail === "string") return detail;
208
+ if (!Array.isArray(detail)) return undefined;
209
+ return detail.map((problem) => (typeof (problem as Json | null)?.msg === "string" ? (problem as Json).msg as string : "")).filter(Boolean).join("; ") || undefined;
210
+ }
211
+
212
+ /** An error event inside a stream that began with 200, with the server's own word for it. */
213
+ function streamFailure(failed: unknown): OpenAiRequestError {
214
+ const named = failed && typeof failed === "object" ? failed as Json : {};
215
+ return new OpenAiRequestError(typeof failed === "string" ? failed : String(named.message ?? "The model reported an error."), streamErrorStatus(failed), {
216
+ ...(typeof named.code === "string" && named.code ? { code: named.code } : {}),
217
+ ...(typeof named.param === "string" && named.param ? { param: named.param } : {}),
218
+ });
219
+ }
220
+
221
+ const textOf = (message: ModelTextMessage): string => message.parts.map((part) => part.text ?? "").filter(Boolean).join("\n\n");
222
+
223
+ /** A turn of text. One with nothing but text is a string, which every server takes; native parts make it a list. */
224
+ function textMessage(message: ModelTextMessage): OpenAiMessage {
225
+ if (message.parts.every((part) => part.native === undefined)) return { role: message.role, content: textOf(message) };
226
+ return { role: message.role, content: message.parts.map((part) => (part.native !== undefined ? part.native : { type: "text", text: part.text })) };
227
+ }
228
+
229
+ /**
230
+ * Turns of the user that follow each other, made one. The loop can send the question and the
231
+ * request for an answer after it with no turn between them, and some servers (DeepSeek's reasoner,
232
+ * the chat templates of Mistral and Gemma models) refuse two user turns in a row.
233
+ */
234
+ function joinUserTurns(messages: OpenAiMessage[]): OpenAiMessage[] {
235
+ const parts = (content: unknown): unknown[] => (typeof content === "string" ? (content ? [{ type: "text", text: content }] : []) : Array.isArray(content) ? content : []);
236
+ const out: OpenAiMessage[] = [];
237
+ for (const message of messages) {
238
+ const last = out.at(-1);
239
+ if (last?.role !== "user" || message.role !== "user") {
240
+ out.push(message);
241
+ continue;
242
+ }
243
+ out[out.length - 1] = {
244
+ role: "user",
245
+ content: typeof last.content === "string" && typeof message.content === "string"
246
+ ? [last.content, message.content].filter(Boolean).join("\n\n")
247
+ : [...parts(last.content), ...parts(message.content)],
248
+ };
249
+ }
250
+ return out;
251
+ }
252
+
253
+ /** The messages of one tool round. `number` makes the IDs of calls that came without one. */
254
+ function roundMessages(round: ModelToolRound, number: number, pdfInput: boolean): OpenAiMessage[] {
255
+ const idOf = (call: ToolCall, index: number) => call.id ?? `call_${number}_${index + 1}`;
256
+ // Its own turn goes back as it came: a server may want what it put there (reasoning, signatures).
257
+ const asked: OpenAiMessage = round.raw !== undefined ? round.raw as OpenAiMessage : {
258
+ role: "assistant",
259
+ content: null,
260
+ tool_calls: round.calls.map((call, index) => ({ id: idOf(call, index), type: "function", function: { name: call.name, arguments: JSON.stringify(call.args) } })),
261
+ };
262
+ const results = round.answers.map((answer, index): OpenAiMessage => ({ role: "tool", tool_call_id: idOf(answer.call, index), content: JSON.stringify(answer.result) }));
263
+ // A tool message holds text. Files follow in a user turn, each after a line that names it.
264
+ const files = pdfInput ? round.answers.flatMap((answer) => (answer.files ?? []).flatMap((file) => [
265
+ { type: "text", text: `${file.name} (returned by ${answer.call.name}):` },
266
+ { type: "file", file: { filename: file.name, file_data: `data:${file.mimeType};base64,${base64(file.bytes)}` } },
267
+ ])) : [];
268
+ return [asked, ...results, ...(files.length > 0 ? [{ role: "user", content: files }] : [])];
269
+ }
270
+
271
+ /**
272
+ * Chat Completions messages as the conversation of `askWithFiles`. System messages are returned
273
+ * apart, as `system`. An assistant turn of tool calls and the tool messages that answer it become
274
+ * one stored tool round.
275
+ */
276
+ export function fromOpenAiMessages(history: OpenAiMessage[]): { system: string; messages: ChatMessage[] } {
277
+ const system: string[] = [];
278
+ const messages: ChatMessage[] = [];
279
+ const open = new Map<string, { result: ToolResult }>();
280
+ for (const message of history) {
281
+ if (message.role === "system" || message.role === "developer") {
282
+ const text = contentText(message.content);
283
+ if (text) system.push(text);
284
+ } else if (message.role === "tool") {
285
+ const call = open.get(String(message.tool_call_id));
286
+ if (!call) continue;
287
+ const text = contentText(message.content);
288
+ const parsed = parseArguments(text);
289
+ call.result = Object.keys(parsed).length > 0 || text.trim() === "{}" ? parsed : { text };
290
+ } else if (message.role === "assistant" && Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {
291
+ const calls = (message.tool_calls as Json[]).map((call, index) => ({
292
+ id: typeof call.id === "string" ? call.id : `call_${messages.length}_${index + 1}`,
293
+ name: String(call.function?.name ?? ""),
294
+ args: parseArguments(call.function?.arguments),
295
+ result: { error: "No result was kept for this call." } as ToolResult,
296
+ }));
297
+ for (const call of calls) open.set(call.id, call);
298
+ messages.push({ role: "tools", calls });
299
+ } else if (message.role === "user" || message.role === "assistant") {
300
+ const parts = typeof message.content === "string" || !Array.isArray(message.content)
301
+ ? [{ text: contentText(message.content) }]
302
+ : (message.content as Json[]).map((part) => (part?.type === "text" && typeof part.text === "string" ? { text: part.text as string } : { native: part }));
303
+ messages.push({ role: message.role, parts });
304
+ }
305
+ }
306
+ return { system: system.join("\n\n"), messages };
307
+ }
308
+
309
+ /**
310
+ * The tool rounds a question returned (`AskResult.toolTurns`) as Chat Completions messages, for an
311
+ * application that keeps its history in that form: put them between the question and its answer.
312
+ */
313
+ export function openAiToolTurns(turns: ToolTurn[]): OpenAiMessage[] {
314
+ return turns.flatMap((turn, index) => {
315
+ // A call that came without an ID is given one that no round of another question has: these
316
+ // messages are kept, and sent again next to those of later questions.
317
+ const answers = turn.calls.map(({ result, ...call }) => ({ call: call.id ? call : { ...call, id: `call_${randomUUID().replaceAll("-", "").slice(0, 24)}` }, result: laterResult(result) }));
318
+ return roundMessages({ role: "tools", calls: answers.map((answer) => answer.call), answers }, index + 1, false);
319
+ });
320
+ }
321
+
322
+ /** A model behind a Chat Completions endpoint, for `askWithFiles`. */
323
+ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter {
324
+ const fetchImpl = options.fetch ?? fetch;
325
+ const url = options.url ?? `${(options.baseUrl ?? "https://api.openai.com/v1").replace(/\/+$/, "")}/chat/completions`;
326
+ const { hostname, pathname } = (() => {
327
+ try {
328
+ return new URL(url);
329
+ } catch {
330
+ return { hostname: "", pathname: "" };
331
+ }
332
+ })();
333
+ // Azure OpenAI answers on three kinds of host. On the two it shares with other models, only its `/openai/` paths are OpenAI's.
334
+ const official = /(^|\.)openai\.com$|\.openai\.azure\.com$/.test(hostname)
335
+ || (/\.(cognitiveservices\.azure\.com|services\.ai\.azure\.com)$/.test(hostname) && pathname.includes("/openai/"));
336
+ /** The name of the output limit in a part read: changed once when the server refuses it and no name was given. */
337
+ let maxTokensField = options.maxTokensField ?? (official ? "max_completion_tokens" : "max_tokens");
338
+ const systemRole = options.systemRole ?? "system";
339
+ const pdfInput = options.pdfInput === true;
340
+
341
+ const headersNow = async (): Promise<Record<string, string>> => {
342
+ const key = await resolveSecret(options.apiKey);
343
+ return { "Content-Type": "application/json", ...(key ? { Authorization: `Bearer ${key}` } : {}), ...await resolveHeaderSource(options.headers) };
344
+ };
345
+
346
+ const built = new WeakMap<ModelToolRound, { number: number; messages: OpenAiMessage[] }>();
347
+ const toMessages = (messages: ModelMessage[]): OpenAiMessage[] => {
348
+ let rounds = 0;
349
+ return joinUserTurns(messages.flatMap((message) => {
350
+ if (message.role !== "tools") return [textMessage(message)];
351
+ const number = ++rounds;
352
+ let known = built.get(message);
353
+ if (!known || known.number !== number) {
354
+ known = { number, messages: roundMessages(message, number, pdfInput) };
355
+ built.set(message, known);
356
+ }
357
+ return known.messages;
358
+ }));
359
+ };
360
+ const bodyOf = (request: ModelRequest, stream: boolean): Json => {
361
+ const mustAnswer = request.toolChoice === "none";
362
+ const listTools = Boolean(request.tools?.length) && !(mustAnswer && options.answerWithoutTools === "omit");
363
+ return {
364
+ model: options.model,
365
+ messages: [...(request.system ? [{ role: systemRole, content: request.system }] : []), ...toMessages(request.messages)],
366
+ ...(listTools ? { tools: request.tools!.map(asFunction), ...(mustAnswer ? { tool_choice: "none" } : {}) } : {}),
367
+ ...(stream ? { stream: true, stream_options: { include_usage: true } } : {}),
368
+ ...options.body,
369
+ };
370
+ };
371
+
372
+ const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean, lost: (error: unknown) => OpenAiRequestError = unreachable, headers?: Record<string, string>): Promise<Response> => {
373
+ let response: Response;
374
+ try {
375
+ response = await fetchImpl(url, { method: "POST", headers: headers ?? await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
376
+ } catch (error) {
377
+ if (stopped()) throw error;
378
+ throw lost(error);
379
+ }
380
+ if (!response.ok) throw await failure(response);
381
+ return response;
382
+ };
383
+
384
+ const generateText: GenerateText = ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
385
+ const send = async (limit: number): Promise<LimitedReply> => {
386
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
387
+ const stopped = () => Boolean(signal?.aborted) || timeout.aborted;
388
+ const body = (field: string): Json => ({
389
+ model: options.model,
390
+ messages: [{ role: systemRole, content: system }, { role: "user", content: prompt }],
391
+ [field]: limit,
392
+ ...options.analysisBody?.(limit),
393
+ });
394
+ let response: Response;
395
+ // The name this request is sent with: part reads run together, and another may learn the other name meanwhile.
396
+ const sent = maxTokensField;
397
+ try {
398
+ response = await post(body(sent), signal ? AbortSignal.any([signal, timeout]) : timeout, stopped);
399
+ } catch (error) {
400
+ // A server that knows only the other name of the output limit: it is sent that one, now and from now on.
401
+ if (options.maxTokensField !== undefined || !refusesField(error, sent)) throw error;
402
+ const other = sent === "max_tokens" ? "max_completion_tokens" : "max_tokens";
403
+ if (maxTokensField === sent) maxTokensField = other;
404
+ response = await post(body(other), signal ? AbortSignal.any([signal, timeout]) : timeout, stopped);
405
+ }
406
+ const data = await readJson<Json>(response, stopped, unreachable, undefined, (error) => new OpenAiRequestError(notJsonMessage("The model's", response), response.status, { kind: "invalid", cause: error }));
407
+ const used = usageOf(data.usage);
408
+ onUsage?.(used);
409
+ const choice = data.choices?.[0];
410
+ // DeepSeek stops a reply when its servers run short: that is the server's failure, sent again.
411
+ if (choice?.finish_reason === "insufficient_system_resource") throw interrupted();
412
+ return {
413
+ text: contentText(choice?.message?.content),
414
+ cutOff: choice?.finish_reason === "length",
415
+ // Stopped by the content filter before its end: what it wrote is not all there is.
416
+ stopped: choice?.finish_reason === "content_filter",
417
+ ...(typeof choice?.finish_reason === "string" ? { reason: choice.finish_reason } : {}),
418
+ thoughts: used.thoughtTokens ?? 0,
419
+ };
420
+ };
421
+ return completeWithinLimit(`${url}|${options.model}`, maxOutputTokens, send, { signal, onTruncated });
422
+ };
423
+
424
+ return {
425
+ id: options.id ?? options.model,
426
+ capabilities: {
427
+ ...(options.contextTokens ? { contextTokens: options.contextTokens } : {}),
428
+ ...(options.maxRequestBytes ? { maxRequestBytes: options.maxRequestBytes } : {}),
429
+ toolFiles: pdfInput ? "beside" : "none",
430
+ pageTokens: options.pageTokens ?? 1_000,
431
+ ...(options.tokenScale ? { tokenScale: options.tokenScale } : {}),
432
+ },
433
+ requestBytes: (request) => Buffer.byteLength(JSON.stringify(bodyOf(request, false))),
434
+ generateText,
435
+
436
+ async send(request: ModelRequest, hooks: SendHooks = {}): Promise<ModelReply> {
437
+ const stream = Boolean(hooks.onText) && options.stream !== false;
438
+ // A key or token is fetched before the watch starts: the time that takes is not the model's.
439
+ const headers = await headersNow();
440
+ const watch = idleWatch(hooks.signal, { firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs });
441
+ // A request the watch aborted got nothing back for the whole wait: that is no failed connection.
442
+ const lost = (error: unknown) => (watch.expired ? silent(watch.waitedMs) : unreachable(error));
443
+ try {
444
+ // The headers are no piece of the reply: a server may send them at once and then think.
445
+ const response = await post(bodyOf(request, stream), watch.signal, () => Boolean(hooks.signal?.aborted), lost, headers);
446
+ return await readReply(response, stream, hooks, watch, lost);
447
+ } finally {
448
+ watch.stop();
449
+ }
450
+ },
451
+ };
452
+
453
+ /** The reply of a request that was answered: streamed, or in one piece. */
454
+ async function readReply(answer: Response, stream: boolean, hooks: SendHooks, watch: IdleWatch, lost: (error: unknown) => OpenAiRequestError): Promise<ModelReply> {
455
+ {
456
+ let message: Json;
457
+ let finish: unknown;
458
+ let usage: Json | undefined;
459
+ let text = "";
460
+ // A body that is no JSON (a gateway's page) is not the model's reply, and is not sent again.
461
+ const notJson = (error: unknown) => new OpenAiRequestError(notJsonMessage("The model's", answer), answer.status, { kind: "invalid", cause: error });
462
+ let response = answer;
463
+ let events = false;
464
+ if (stream && answer.body) {
465
+ try {
466
+ ({ events, response } = await streamedReply(answer, watch));
467
+ } catch (error) {
468
+ if (hooks.signal?.aborted) throw error;
469
+ throw noteCutReply(lost(error));
470
+ }
471
+ }
472
+ if (events && response.body) {
473
+ let reasoning = "";
474
+ let reasoningText = "";
475
+ let refusal = "";
476
+ const details: Json[] = [];
477
+ const toolCalls: Json[] = [];
478
+ let ended = false;
479
+ // "[DONE]" ends the reply: a server that leaves the connection open after it is not waited for.
480
+ const end = replyEnd(watch);
481
+ try {
482
+ for await (const chunk of parseSseJson<Json>(response.body, { onData: watch.pulse, onDone: () => { ended = true; end.reached(); }, signal: end.signal })) {
483
+ const failed = (Array.isArray(chunk) ? chunk[0] : chunk)?.error;
484
+ if (failed) throw streamFailure(failed);
485
+ if (chunk.usage) usage = chunk.usage as Json;
486
+ const choice = chunk.choices?.[0] as Json | undefined;
487
+ if (!choice) continue;
488
+ const delta = (choice.delta ?? {}) as Json;
489
+ const piece = contentText(delta.content);
490
+ if (piece) {
491
+ text += piece;
492
+ hooks.onText?.(piece);
493
+ }
494
+ if (typeof delta.reasoning_content === "string") reasoning += delta.reasoning_content;
495
+ // What a non-streamed reply holds in fields of its own: a refusal, and the reasoning of
496
+ // OpenRouter, whose details (a thought signature among them) must go back with the turn.
497
+ if (typeof delta.refusal === "string") refusal += delta.refusal;
498
+ if (typeof delta.reasoning === "string") reasoningText += delta.reasoning;
499
+ if (Array.isArray(delta.reasoning_details)) for (const detail of delta.reasoning_details as unknown[]) addReasoningDetail(details, detail);
500
+ for (const part of (Array.isArray(delta.tool_calls) ? delta.tool_calls : []) as Json[]) {
501
+ // A call arrives in pieces under its index: first its ID and name, then its arguments, a few characters at a time.
502
+ const at = typeof part.index === "number" ? part.index : part.id || toolCalls.length === 0 ? toolCalls.length : toolCalls.length - 1;
503
+ const call = (toolCalls[at] ??= { type: "function", function: { name: "", arguments: "" } });
504
+ for (const [key, value] of Object.entries(part)) {
505
+ if (key !== "index" && key !== "function" && value !== undefined && value !== null && !(key === "id" && call.id)) call[key] = value;
506
+ }
507
+ // The name comes whole in the first piece of a call. A server that sends it again with
508
+ // each piece does not make it longer; one that sends it in pieces does.
509
+ const name = part.function?.name;
510
+ if (typeof name === "string" && name !== call.function.name) call.function.name += name;
511
+ if (typeof part.function?.arguments === "string") call.function.arguments += part.function.arguments;
512
+ }
513
+ finish = choice.finish_reason ?? finish;
514
+ }
515
+ } catch (error) {
516
+ // The reply ended with "[DONE]", and the connection then stayed open, or broke rather than
517
+ // end: what came before it is whole.
518
+ const whole = end.left(error) || (end.whole && !hooks.signal?.aborted && !(error instanceof OpenAiRequestError));
519
+ if (!whole) {
520
+ if (hooks.signal?.aborted || error instanceof OpenAiRequestError) throw error;
521
+ // An event too long to read would come again: it is not sent again, like a page in the reply's place.
522
+ if (error instanceof SseEventTooLongError) throw new OpenAiRequestError(eventTooLongMessage("The model's", error), answer.status, { kind: "invalid", cause: error });
523
+ // The connection went while the answer was on its way, or nothing came for the whole wait.
524
+ throw noteCutReply(lost(error));
525
+ }
526
+ } finally {
527
+ end.dispose();
528
+ }
529
+ // A stream ends with a reason for its end, and with "[DONE]". One that closed with neither
530
+ // was cut off on its way (a proxy, a dropped connection): it is not a whole reply, and is
531
+ // sent again like a connection that failed, unless text of it was shown.
532
+ if (finish === undefined && !ended) throw noteCutReply(new OpenAiRequestError("The model's reply ended before it was complete.", 0));
533
+ const calls = toolCalls.filter(Boolean);
534
+ message = {
535
+ role: "assistant",
536
+ content: text || null,
537
+ ...(refusal ? { refusal } : {}),
538
+ ...(reasoning ? { reasoning_content: reasoning } : {}),
539
+ ...(reasoningText ? { reasoning: reasoningText } : {}),
540
+ ...(details.length > 0 ? { reasoning_details: details } : {}),
541
+ ...(calls.length > 0 ? { tool_calls: calls } : {}),
542
+ };
543
+ // A refusal is what the model has to say to the user, as it is without streaming.
544
+ if (!text && refusal) {
545
+ text = refusal;
546
+ hooks.onText?.(refusal);
547
+ }
548
+ } else {
549
+ // In one piece: no streaming was asked for, or the server answered without it.
550
+ const data = await readJson<Json>(response, () => Boolean(hooks.signal?.aborted), lost, watch, notJson);
551
+ const choice = data.choices?.[0] as Json | undefined;
552
+ message = (choice?.message ?? { role: "assistant", content: null }) as Json;
553
+ finish = choice?.finish_reason;
554
+ usage = data.usage as Json | undefined;
555
+ // The whole reply is in hand: one that the server stopped is sent again before any of it is shown.
556
+ if (finish === "insufficient_system_resource") throw interrupted();
557
+ // A refusal is what the model has to say to the user, in a field of its own.
558
+ text = contentText(message.content) || (typeof message.refusal === "string" ? message.refusal : "");
559
+ if (text) hooks.onText?.(text);
560
+ }
561
+ // DeepSeek stops a reply when its servers run short: what came of it is not the model's whole
562
+ // turn. That is the server's failure, sent again unless text of it was shown.
563
+ if (finish === "insufficient_system_resource") throw interrupted();
564
+ // Cut off at the output limit with a call half-written: the call is answered, not run.
565
+ const cutOff = finish === "length" ? "This call was cut off at the output limit before its arguments were complete, and was not run. Send it again." : undefined;
566
+ const calls: ToolCall[] = (Array.isArray(message.tool_calls) ? message.tool_calls as Json[] : [])
567
+ .filter((call) => typeof call?.function?.name === "string" && call.function.name)
568
+ .map((call) => {
569
+ const read = readArguments(call.function.arguments);
570
+ // Arguments that are not a JSON object go back as none, and so do arguments that are
571
+ // empty: a server that reads every call of the conversation (vLLM before 0.29) refuses
572
+ // the next request when one is not JSON.
573
+ const written = call.function.arguments;
574
+ if (read.problem || typeof written !== "string" || !written.trim()) call.function = { ...call.function, arguments: read.problem ? "{}" : JSON.stringify(read.args) };
575
+ const problem = read.problem ?? cutOff;
576
+ return { ...(typeof call.id === "string" && call.id ? { id: call.id } : {}), name: call.function.name as string, args: read.args, ...(problem ? { problem } : {}) };
577
+ });
578
+ const kind = finishOfOpenAi(finish);
579
+ return {
580
+ text,
581
+ calls,
582
+ raw: message,
583
+ ...(typeof finish === "string" ? { finishReason: finish } : {}),
584
+ ...(kind ? { finish: kind } : {}),
585
+ ...(finish === "content_filter" && !text && calls.length === 0 ? { blockReason: "content_filter" } : {}),
586
+ ...(usage ? { usage: usageOf(usage), providerUsage: usage } : {}),
587
+ };
588
+ }
589
+ }
590
+ }
591
+
592
+ /** A request that got no answer: the reason, without the stack of the HTTP client. */
593
+ function unreachable(error: unknown): OpenAiRequestError {
594
+ return new OpenAiRequestError(`The model could not be reached${unreachableReason(error)}.`, 0, { cause: error });
595
+ }
596
+
597
+ /** A request that got nothing back for the whole wait of its `IdleWatch`. */
598
+ function silent(waitMs: number): OpenAiRequestError {
599
+ return new OpenAiRequestError(`The model sent nothing for ${Math.round(waitMs / 1_000)} s.`, 0, { kind: "timeout" });
600
+ }
601
+
602
+ /** A reply the server stopped because it ran short (DeepSeek's `insufficient_system_resource`). */
603
+ function interrupted(): OpenAiRequestError {
604
+ return new OpenAiRequestError("The model's server stopped the reply: it ran short of resources.", 503);
605
+ }
606
+
607
+ /** `finish_reason` in the terms of `ModelReply.finish`. Undefined for a reason it does not know. */
608
+ function finishOfOpenAi(reason: unknown): ModelReply["finish"] {
609
+ if (reason === "stop" || reason === "tool_calls" || reason === "function_call") return "complete";
610
+ if (reason === "length") return "cut";
611
+ if (reason === "content_filter") return "filtered";
612
+ return undefined;
613
+ }
@@ -0,0 +1,2 @@
1
+ export { fromOpenAiMessages, openAiCompatible, openAiToolTurns, OpenAiRequestError } from "./adapter.js";
2
+ export type { OpenAiCompatibleOptions, OpenAiMessage } from "./adapter.js";