llm-large-files 0.4.1 → 0.5.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 (121) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +48 -8
  3. package/dist/anthropic/adapter.d.ts +106 -0
  4. package/dist/anthropic/adapter.d.ts.map +1 -0
  5. package/dist/anthropic/adapter.js +391 -0
  6. package/dist/anthropic/adapter.js.map +1 -0
  7. package/dist/anthropic/index.d.ts +3 -0
  8. package/dist/anthropic/index.d.ts.map +1 -0
  9. package/dist/anthropic/index.js +2 -0
  10. package/dist/anthropic/index.js.map +1 -0
  11. package/dist/ask.d.ts +144 -0
  12. package/dist/ask.d.ts.map +1 -0
  13. package/dist/ask.js +540 -0
  14. package/dist/ask.js.map +1 -0
  15. package/dist/budget.d.ts +23 -0
  16. package/dist/budget.d.ts.map +1 -0
  17. package/dist/budget.js +64 -0
  18. package/dist/budget.js.map +1 -0
  19. package/dist/evidence.d.ts +40 -0
  20. package/dist/evidence.d.ts.map +1 -0
  21. package/dist/evidence.js +137 -0
  22. package/dist/evidence.js.map +1 -0
  23. package/dist/gemini/adapter.d.ts +50 -0
  24. package/dist/gemini/adapter.d.ts.map +1 -0
  25. package/dist/gemini/adapter.js +179 -0
  26. package/dist/gemini/adapter.js.map +1 -0
  27. package/dist/gemini/chat.d.ts +31 -75
  28. package/dist/gemini/chat.d.ts.map +1 -1
  29. package/dist/gemini/chat.js +38 -300
  30. package/dist/gemini/chat.js.map +1 -1
  31. package/dist/gemini/errors.d.ts +11 -0
  32. package/dist/gemini/errors.d.ts.map +1 -0
  33. package/dist/gemini/errors.js +14 -0
  34. package/dist/gemini/errors.js.map +1 -0
  35. package/dist/gemini/generate.d.ts +9 -20
  36. package/dist/gemini/generate.d.ts.map +1 -1
  37. package/dist/gemini/generate.js +43 -92
  38. package/dist/gemini/generate.js.map +1 -1
  39. package/dist/gemini/index.d.ts +3 -1
  40. package/dist/gemini/index.d.ts.map +1 -1
  41. package/dist/gemini/index.js +2 -1
  42. package/dist/gemini/index.js.map +1 -1
  43. package/dist/gemini/sse.d.ts +1 -2
  44. package/dist/gemini/sse.d.ts.map +1 -1
  45. package/dist/gemini/sse.js +1 -38
  46. package/dist/gemini/sse.js.map +1 -1
  47. package/dist/http.d.ts +20 -0
  48. package/dist/http.d.ts.map +1 -0
  49. package/dist/http.js +55 -0
  50. package/dist/http.js.map +1 -0
  51. package/dist/index.d.ts +13 -2
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +11 -4
  54. package/dist/index.js.map +1 -1
  55. package/dist/library.d.ts +29 -3
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +10 -12
  58. package/dist/library.js.map +1 -1
  59. package/dist/map-reduce.d.ts +9 -0
  60. package/dist/map-reduce.d.ts.map +1 -1
  61. package/dist/map-reduce.js +25 -19
  62. package/dist/map-reduce.js.map +1 -1
  63. package/dist/model.d.ts +196 -0
  64. package/dist/model.d.ts.map +1 -0
  65. package/dist/model.js +41 -0
  66. package/dist/model.js.map +1 -0
  67. package/dist/openai/adapter.d.ts +85 -0
  68. package/dist/openai/adapter.d.ts.map +1 -0
  69. package/dist/openai/adapter.js +293 -0
  70. package/dist/openai/adapter.js.map +1 -0
  71. package/dist/openai/index.d.ts +3 -0
  72. package/dist/openai/index.d.ts.map +1 -0
  73. package/dist/openai/index.js +2 -0
  74. package/dist/openai/index.js.map +1 -0
  75. package/dist/output-limit.d.ts +30 -0
  76. package/dist/output-limit.d.ts.map +1 -0
  77. package/dist/output-limit.js +92 -0
  78. package/dist/output-limit.js.map +1 -0
  79. package/dist/retry.d.ts +54 -0
  80. package/dist/retry.d.ts.map +1 -0
  81. package/dist/retry.js +111 -0
  82. package/dist/retry.js.map +1 -0
  83. package/dist/sse.d.ts +3 -0
  84. package/dist/sse.d.ts.map +1 -0
  85. package/dist/sse.js +39 -0
  86. package/dist/sse.js.map +1 -0
  87. package/dist/tools.d.ts +11 -0
  88. package/dist/tools.d.ts.map +1 -1
  89. package/dist/tools.js +85 -31
  90. package/dist/tools.js.map +1 -1
  91. package/dist/types.d.ts +28 -3
  92. package/dist/types.d.ts.map +1 -1
  93. package/docs/api.md +245 -27
  94. package/docs/configuration.md +83 -9
  95. package/docs/getting-started.md +67 -16
  96. package/docs/how-it-works.md +38 -2
  97. package/docs/security.md +18 -0
  98. package/package.json +21 -3
  99. package/src/anthropic/adapter.ts +454 -0
  100. package/src/anthropic/index.ts +2 -0
  101. package/src/ask.ts +675 -0
  102. package/src/budget.ts +71 -0
  103. package/src/evidence.ts +162 -0
  104. package/src/gemini/adapter.ts +218 -0
  105. package/src/gemini/chat.ts +61 -353
  106. package/src/gemini/errors.ts +15 -0
  107. package/src/gemini/generate.ts +50 -90
  108. package/src/gemini/index.ts +3 -1
  109. package/src/gemini/sse.ts +1 -34
  110. package/src/http.ts +59 -0
  111. package/src/index.ts +33 -4
  112. package/src/library.ts +39 -13
  113. package/src/map-reduce.ts +22 -16
  114. package/src/model.ts +200 -0
  115. package/src/openai/adapter.ts +345 -0
  116. package/src/openai/index.ts +2 -0
  117. package/src/output-limit.ts +99 -0
  118. package/src/retry.ts +132 -0
  119. package/src/sse.ts +34 -0
  120. package/src/tools.ts +91 -34
  121. package/src/types.ts +24 -3
package/src/model.ts ADDED
@@ -0,0 +1,200 @@
1
+ // The contract between the tool loop (`askWithFiles`) and a model provider. An adapter turns a
2
+ // neutral request into the provider's own, sends it, and reads the reply back. Everything else
3
+ // (planning, tools, limits, retries, usage, the forced answer) is the loop's, once, for every provider.
4
+ import type { GenerateText, ToolDeclaration, ToolFile, ToolResult } from "./types.js";
5
+
6
+ /**
7
+ * A tool call a model made. `id` is the provider's own, where it gives one. `problem` says why
8
+ * the call cannot be run as it came (its arguments were not JSON, or it was cut off): the loop
9
+ * then answers it with that message, and the model can send it again.
10
+ */
11
+ export type ToolCall = { id?: string; name: string; args: Record<string, unknown>; problem?: string };
12
+
13
+ /** A tool call with what the tool returned for it. */
14
+ export type ToolAnswer = { call: ToolCall; result: ToolResult; files?: ToolFile[] };
15
+
16
+ /**
17
+ * One piece of a message: plain text, or something in the provider's own form (an image, an inline
18
+ * PDF) that only its adapter reads. A native part may carry the text it holds, to be sized by.
19
+ */
20
+ export type ModelPart = { text: string; native?: undefined } | { native: unknown; text?: string };
21
+
22
+ /** A turn of the user or of the model, as text and native parts. */
23
+ export type ModelTextMessage = { role: "user" | "assistant"; parts: ModelPart[] };
24
+
25
+ /**
26
+ * One round of tool use: the calls of a model turn, and what the tools returned for them, in call
27
+ * order. `raw` is that model turn in its provider's own form. The loop sets it only for the
28
+ * adapter that received it, which sends it back unchanged (Gemini wants its thought signatures,
29
+ * Claude its thinking blocks). Without `raw` the turn is built from `calls`. A round whose
30
+ * `answers` is empty is a model turn that has not been answered yet.
31
+ */
32
+ export type ModelToolRound = { role: "tools"; calls: ToolCall[]; answers: ToolAnswer[]; raw?: unknown };
33
+
34
+ export type ModelMessage = ModelTextMessage | ModelToolRound;
35
+
36
+ /** A plain chat turn. "model" is accepted as an alias for "assistant". */
37
+ export type ChatTurn = { role: "user" | "assistant" | "model"; text: string };
38
+
39
+ /**
40
+ * A round of tool use as an application stores it between a question and its answer
41
+ * (`AskResult.toolTurns`): plain JSON. Passed back in `messages`, the model sees in a later
42
+ * question what its tools returned in an earlier one, and does not have to search again.
43
+ */
44
+ export type ToolTurn = { role: "tools"; calls: Array<ToolCall & { result: ToolResult }> };
45
+
46
+ /** What `askWithFiles` takes as conversation: plain turns, stored tool rounds, and turns with native parts. */
47
+ export type ChatMessage = ChatTurn | ToolTurn | ModelTextMessage;
48
+
49
+ export type ModelRequest = {
50
+ /** The system instruction: the application's, then the guide to the document tools. May be empty. */
51
+ system: string;
52
+ /** The conversation, oldest first. The last message is the user's, or a tool round. */
53
+ messages: ModelMessage[];
54
+ /** The tools on offer. Left out when the conversation needs none. */
55
+ tools?: ToolDeclaration[];
56
+ /**
57
+ * "none": the model must answer in text. The tools are still listed, for a provider that wants
58
+ * them declared next to the tool calls already in the conversation.
59
+ */
60
+ toolChoice?: "auto" | "none";
61
+ };
62
+
63
+ /** Tokens of one request, or summed over several. */
64
+ export type ModelUsage = {
65
+ /** Every token of the prompt, those read from a cache included. */
66
+ inputTokens: number;
67
+ /** The part of `inputTokens` that was read from the provider's prompt cache. */
68
+ cachedInputTokens: number;
69
+ /** Every token the model produced, thoughts included. */
70
+ outputTokens: number;
71
+ /** The part of `outputTokens` that went on thinking, where the provider says. */
72
+ thoughtTokens: number;
73
+ };
74
+
75
+ export type ModelReply = {
76
+ /** What the model wrote for the user in this reply. Thoughts are not part of it. */
77
+ text: string;
78
+ calls: ToolCall[];
79
+ /** This turn in the provider's own form, to send back unchanged with the tool results. */
80
+ raw?: unknown;
81
+ finishReason?: string;
82
+ /** Why the provider refused the prompt, when it did. Nothing more is asked after it. */
83
+ blockReason?: string;
84
+ usage?: Partial<ModelUsage>;
85
+ /** The provider's own usage object, as it came. */
86
+ providerUsage?: Record<string, unknown>;
87
+ };
88
+
89
+ export type SendHooks = {
90
+ /**
91
+ * Called with the answer text as it arrives. When it is given the adapter streams if it can; one
92
+ * that cannot calls it once with the whole text. The text is in the reply either way.
93
+ */
94
+ onText?: (delta: string) => void;
95
+ signal?: AbortSignal;
96
+ };
97
+
98
+ /** What a model can take, as far as its adapter knows. */
99
+ export type ModelCapabilities = {
100
+ /** The context window in tokens. When set, the budget of a question is no larger than this. */
101
+ contextTokens?: number;
102
+ /** The largest request body in bytes. When set, the budget of a question is no larger than this. */
103
+ maxRequestBytes?: number;
104
+ /**
105
+ * Where a file that a tool returned (the pages of `view_pages`) goes: "inside" the tool result,
106
+ * "beside" it in a user turn of its own, or "none" for a model that cannot be sent one. With
107
+ * "none", `view_pages` is not offered.
108
+ */
109
+ toolFiles: "inside" | "beside" | "none";
110
+ /** About what the model bills for one PDF page it is shown, in tokens. */
111
+ pageTokens: number;
112
+ /**
113
+ * How many of this model's tokens one token of the library's estimate comes to. The estimate
114
+ * (`estimateTokens`) is fitted to Gemini, so that is 1, the default. A model whose tokenizer
115
+ * counts a third more for the same text says 1.33, and its documents are planned for a window
116
+ * that much smaller.
117
+ */
118
+ tokenScale?: number;
119
+ /**
120
+ * Tokens set aside for the model's reply, when they come out of the same window as the prompt
121
+ * (Claude's `max_tokens`). The budget of a question leaves them free.
122
+ */
123
+ outputTokens?: number;
124
+ /**
125
+ * True for a model whose conversation may only grow: an earlier turn that is rewritten makes
126
+ * the request invalid (Claude ties its thinking blocks to the conversation they were written
127
+ * in). Old tool results are then not shortened to make room: when the room runs out, the
128
+ * question is answered with what it has.
129
+ */
130
+ appendOnly?: boolean;
131
+ };
132
+
133
+ /** A model provider, as the tool loop sees it. */
134
+ export interface ModelAdapter {
135
+ /** Names the model in usage totals and messages: "gemini-3.8-flash". */
136
+ readonly id: string;
137
+ readonly capabilities: ModelCapabilities;
138
+ /** How many tokens a text is for this model. Defaults to the library's estimate. */
139
+ estimateTokens?(text: string): number;
140
+ /**
141
+ * One chat request. Throw a `ModelRequestError` for an HTTP error or a connection that failed:
142
+ * the loop retries the ones worth retrying.
143
+ */
144
+ send(request: ModelRequest, hooks?: SendHooks): Promise<ModelReply>;
145
+ /**
146
+ * The size in bytes of the body `send` would post. With it, the room left for the pages of a PDF
147
+ * is exact; without it, it is estimated.
148
+ */
149
+ requestBytes?(request: ModelRequest): number;
150
+ /** A plain completion, for whole-file reads. Without it `analyze_whole_document` is not offered. */
151
+ generateText?: GenerateText;
152
+ }
153
+
154
+ /**
155
+ * A model request that failed: the provider answered with an HTTP error, or could not be reached
156
+ * (`status` 0). `retryAfterMs` is the wait the provider asked for, when it named one.
157
+ */
158
+ export class ModelRequestError extends Error {
159
+ readonly status: number;
160
+ readonly retryAfterMs?: number;
161
+ constructor(message: string, status: number, options: { retryAfterMs?: number; cause?: unknown } = {}) {
162
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
163
+ this.name = "ModelRequestError";
164
+ this.status = status;
165
+ if (options.retryAfterMs !== undefined) this.retryAfterMs = options.retryAfterMs;
166
+ }
167
+ }
168
+
169
+ /** Some document IDs were never uploaded, have expired, or belong to another owner. */
170
+ export class DocumentsNotFoundError extends Error {
171
+ constructor(readonly ids: string[]) {
172
+ super(`${ids.length === 1 ? "A document is" : `${ids.length} documents are`} no longer available: ${ids.join(", ")}. Upload ${ids.length === 1 ? "it" : "them"} again.`);
173
+ this.name = "DocumentsNotFoundError";
174
+ }
175
+ }
176
+
177
+ const EMPTY_USAGE: ModelUsage = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, thoughtTokens: 0 };
178
+
179
+ /** Usage of one question: every request it made, whole-file part reads included, in all and by model. */
180
+ export type UsageTotals = ModelUsage & {
181
+ /** Requests that were answered. One that failed and was sent again counts once. */
182
+ requests: number;
183
+ byModel: Record<string, ModelUsage & { requests: number }>;
184
+ };
185
+
186
+ /** Sums the usage of the requests of one question. */
187
+ export class UsageMeter {
188
+ readonly totals: UsageTotals = { requests: 0, ...EMPTY_USAGE, byModel: {} };
189
+
190
+ add(model: string, usage: Partial<ModelUsage> | undefined): void {
191
+ const of = (this.totals.byModel[model] ??= { requests: 0, ...EMPTY_USAGE });
192
+ for (const sum of [this.totals, of]) {
193
+ sum.requests++;
194
+ for (const key of Object.keys(EMPTY_USAGE) as Array<keyof ModelUsage>) {
195
+ const value = usage?.[key];
196
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) sum[key] += value;
197
+ }
198
+ }
199
+ }
200
+ }
@@ -0,0 +1,345 @@
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 { base64, parseArguments, readArguments, resolveHeaderSource, resolveSecret, unreachableReason, type HeaderSource, type SecretSource } from "../http.js";
4
+ import { ModelRequestError, type ChatMessage, type ModelAdapter, type ModelMessage, type ModelReply, type ModelRequest, type ModelTextMessage, type ModelToolRound, type SendHooks, type ToolCall, type ToolTurn } from "../model.js";
5
+ import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
6
+ import { retryAfterMs } from "../retry.js";
7
+ import { parseSseJson } from "../sse.js";
8
+ import type { GenerateText, GenerateUsage, ToolDeclaration, ToolResult } from "../types.js";
9
+
10
+ /** The endpoint answered with an HTTP error, or could not be reached (`status` 0). */
11
+ export class OpenAiRequestError extends ModelRequestError {
12
+ constructor(message: string, status: number, options: { retryAfterMs?: number; cause?: unknown } = {}) {
13
+ super(message, status, options);
14
+ this.name = "OpenAiRequestError";
15
+ }
16
+ }
17
+
18
+ /** A Chat Completions message, as the API takes and returns it. */
19
+ export type OpenAiMessage = { role: string; [key: string]: unknown };
20
+
21
+ export type OpenAiCompatibleOptions = {
22
+ /** The model name the endpoint knows: "gpt-5.5", "deepseek-v4-pro", a deployment name. */
23
+ model: string;
24
+ /**
25
+ * The base of the API: `/chat/completions` is added to it. Defaults to https://api.openai.com/v1.
26
+ * DeepSeek: https://api.deepseek.com/v1. Gemini: https://generativelanguage.googleapis.com/v1beta/openai.
27
+ */
28
+ baseUrl?: string | undefined;
29
+ /** The whole Chat Completions URL, when it is not `baseUrl` + `/chat/completions` (Azure OpenAI, a gateway). */
30
+ url?: string | undefined;
31
+ /** Sent as `Authorization: Bearer …`. A function is called for each request. */
32
+ apiKey?: SecretSource | undefined;
33
+ /** More headers, or all of them (Azure's `api-key`). A function is called for each request. */
34
+ headers?: HeaderSource | undefined;
35
+ /** More fields for the body of every chat request: `temperature`, `reasoning_effort`, `max_completion_tokens`, and so on. */
36
+ body?: Record<string, unknown> | undefined;
37
+ /** More fields for the body of a whole-document part read, given the output limit it is sent with. */
38
+ analysisBody?: ((maxOutputTokens: number) => Record<string, unknown>) | undefined;
39
+ /**
40
+ * The name of the output limit in a part read. `max_completion_tokens` for api.openai.com and
41
+ * Azure OpenAI, whose newer models refuse the other; `max_tokens` anywhere else, where it is the
42
+ * one every server knows.
43
+ */
44
+ maxTokensField?: "max_tokens" | "max_completion_tokens" | undefined;
45
+ /** "system" (the default), or "developer" for an endpoint that wants the newer name. */
46
+ systemRole?: "system" | "developer" | undefined;
47
+ /**
48
+ * How the request that must be answered in text says so. "tool_choice" (the default) keeps the
49
+ * tools and sends `tool_choice: "none"`. "omit" leaves the tools out, for a server that does not
50
+ * know `tool_choice`.
51
+ */
52
+ answerWithoutTools?: "tool_choice" | "omit" | undefined;
53
+ /**
54
+ * Send the pages of `view_pages` to the model, as a `file` part in a user message after the tool
55
+ * results. Off by default: a tool message holds text only, and many servers behind this API
56
+ * take no PDF at all. Turn it on for a model that reads PDF input.
57
+ */
58
+ pdfInput?: boolean | undefined;
59
+ /** Stream the answer when the caller listens for text. Defaults to true. False for a server without streaming. */
60
+ stream?: boolean | undefined;
61
+ /** The model's context window in tokens, when the budget of a question should follow it. */
62
+ contextTokens?: number | undefined;
63
+ /** The largest request body the endpoint takes, in bytes. */
64
+ maxRequestBytes?: number | undefined;
65
+ /** Tokens billed for one PDF page, when `pdfInput` is on. Defaults to 1,000. */
66
+ pageTokens?: number | undefined;
67
+ /** This model's tokens for one token of the library's estimate. Defaults to 1. */
68
+ tokenScale?: number | undefined;
69
+ /** Milliseconds a part read may take. Defaults to 180,000. */
70
+ timeoutMs?: number | undefined;
71
+ /** Names the model in usage totals. Defaults to `model`. */
72
+ id?: string | undefined;
73
+ fetch?: typeof fetch | undefined;
74
+ };
75
+
76
+ type Json = Record<string, any>;
77
+
78
+ const contentText = (content: unknown): string => {
79
+ if (typeof content === "string") return content;
80
+ if (!Array.isArray(content)) return "";
81
+ return content.map((part: Json) => (part?.type === "text" && typeof part.text === "string" ? part.text : "")).join("");
82
+ };
83
+
84
+ const asFunction = (declaration: ToolDeclaration) => ({ type: "function", function: declaration });
85
+
86
+ function usageOf(usage: Json | undefined): GenerateUsage {
87
+ const number = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : 0);
88
+ return {
89
+ inputTokens: number(usage?.prompt_tokens),
90
+ cachedInputTokens: number(usage?.prompt_tokens_details?.cached_tokens ?? usage?.prompt_cache_hit_tokens),
91
+ outputTokens: number(usage?.completion_tokens),
92
+ thoughtTokens: number(usage?.completion_tokens_details?.reasoning_tokens),
93
+ };
94
+ }
95
+
96
+ /** The error of a response that is not OK. Gemini's layer wraps its error in an array. */
97
+ async function failure(response: Response): Promise<OpenAiRequestError> {
98
+ const data = await response.json().catch(() => null) as Json | Json[] | null;
99
+ const body = Array.isArray(data) ? data[0] : data;
100
+ const message = typeof body?.error === "string" ? body.error : body?.error?.message;
101
+ const wait = retryAfterMs(response.headers, body);
102
+ return new OpenAiRequestError(typeof message === "string" && message ? message : `The model returned HTTP ${response.status}.`, response.status, wait === undefined ? {} : { retryAfterMs: wait });
103
+ }
104
+
105
+ const textOf = (message: ModelTextMessage): string => message.parts.map((part) => part.text ?? "").filter(Boolean).join("\n\n");
106
+
107
+ /** A turn of text. One with nothing but text is a string, which every server takes; native parts make it a list. */
108
+ function textMessage(message: ModelTextMessage): OpenAiMessage {
109
+ if (message.parts.every((part) => part.native === undefined)) return { role: message.role, content: textOf(message) };
110
+ return { role: message.role, content: message.parts.map((part) => (part.native !== undefined ? part.native : { type: "text", text: part.text })) };
111
+ }
112
+
113
+ /** The messages of one tool round. `number` makes the IDs of calls that came without one. */
114
+ function roundMessages(round: ModelToolRound, number: number, pdfInput: boolean): OpenAiMessage[] {
115
+ const idOf = (call: ToolCall, index: number) => call.id ?? `call_${number}_${index + 1}`;
116
+ // Its own turn goes back as it came: a server may want what it put there (reasoning, signatures).
117
+ const asked: OpenAiMessage = round.raw !== undefined ? round.raw as OpenAiMessage : {
118
+ role: "assistant",
119
+ content: null,
120
+ tool_calls: round.calls.map((call, index) => ({ id: idOf(call, index), type: "function", function: { name: call.name, arguments: JSON.stringify(call.args) } })),
121
+ };
122
+ const results = round.answers.map((answer, index): OpenAiMessage => ({ role: "tool", tool_call_id: idOf(answer.call, index), content: JSON.stringify(answer.result) }));
123
+ // A tool message holds text. Files follow in a user turn, each after a line that names it.
124
+ const files = pdfInput ? round.answers.flatMap((answer) => (answer.files ?? []).flatMap((file) => [
125
+ { type: "text", text: `${file.name} (returned by ${answer.call.name}):` },
126
+ { type: "file", file: { filename: file.name, file_data: `data:${file.mimeType};base64,${base64(file.bytes)}` } },
127
+ ])) : [];
128
+ return [asked, ...results, ...(files.length > 0 ? [{ role: "user", content: files }] : [])];
129
+ }
130
+
131
+ /**
132
+ * Chat Completions messages as the conversation of `askWithFiles`. System messages are returned
133
+ * apart, as `system`. An assistant turn of tool calls and the tool messages that answer it become
134
+ * one stored tool round.
135
+ */
136
+ export function fromOpenAiMessages(history: OpenAiMessage[]): { system: string; messages: ChatMessage[] } {
137
+ const system: string[] = [];
138
+ const messages: ChatMessage[] = [];
139
+ const open = new Map<string, { result: ToolResult }>();
140
+ for (const message of history) {
141
+ if (message.role === "system" || message.role === "developer") {
142
+ const text = contentText(message.content);
143
+ if (text) system.push(text);
144
+ } else if (message.role === "tool") {
145
+ const call = open.get(String(message.tool_call_id));
146
+ if (!call) continue;
147
+ const text = contentText(message.content);
148
+ const parsed = parseArguments(text);
149
+ call.result = Object.keys(parsed).length > 0 || text.trim() === "{}" ? parsed : { text };
150
+ } else if (message.role === "assistant" && Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {
151
+ const calls = (message.tool_calls as Json[]).map((call, index) => ({
152
+ id: typeof call.id === "string" ? call.id : `call_${messages.length}_${index + 1}`,
153
+ name: String(call.function?.name ?? ""),
154
+ args: parseArguments(call.function?.arguments),
155
+ result: { error: "No result was kept for this call." } as ToolResult,
156
+ }));
157
+ for (const call of calls) open.set(call.id, call);
158
+ messages.push({ role: "tools", calls });
159
+ } else if (message.role === "user" || message.role === "assistant") {
160
+ const parts = typeof message.content === "string" || !Array.isArray(message.content)
161
+ ? [{ text: contentText(message.content) }]
162
+ : (message.content as Json[]).map((part) => (part?.type === "text" && typeof part.text === "string" ? { text: part.text as string } : { native: part }));
163
+ messages.push({ role: message.role, parts });
164
+ }
165
+ }
166
+ return { system: system.join("\n\n"), messages };
167
+ }
168
+
169
+ /**
170
+ * The tool rounds a question returned (`AskResult.toolTurns`) as Chat Completions messages, for an
171
+ * application that keeps its history in that form: put them between the question and its answer.
172
+ */
173
+ export function openAiToolTurns(turns: ToolTurn[]): OpenAiMessage[] {
174
+ return turns.flatMap((turn, index) => {
175
+ const answers = turn.calls.map(({ result, ...call }) => ({ call, result }));
176
+ return roundMessages({ role: "tools", calls: answers.map((answer) => answer.call), answers }, index + 1, false);
177
+ });
178
+ }
179
+
180
+ /** A model behind a Chat Completions endpoint, for `askWithFiles`. */
181
+ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter {
182
+ const fetchImpl = options.fetch ?? fetch;
183
+ const url = options.url ?? `${(options.baseUrl ?? "https://api.openai.com/v1").replace(/\/+$/, "")}/chat/completions`;
184
+ const official = /(^|\.)openai\.com$|\.openai\.azure\.com$/.test((() => {
185
+ try {
186
+ return new URL(url).hostname;
187
+ } catch {
188
+ return "";
189
+ }
190
+ })());
191
+ const maxTokensField = options.maxTokensField ?? (official ? "max_completion_tokens" : "max_tokens");
192
+ const systemRole = options.systemRole ?? "system";
193
+ const pdfInput = options.pdfInput === true;
194
+
195
+ const headersNow = async (): Promise<Record<string, string>> => {
196
+ const key = await resolveSecret(options.apiKey);
197
+ return { "Content-Type": "application/json", ...(key ? { Authorization: `Bearer ${key}` } : {}), ...await resolveHeaderSource(options.headers) };
198
+ };
199
+
200
+ const built = new WeakMap<ModelToolRound, { number: number; messages: OpenAiMessage[] }>();
201
+ const toMessages = (messages: ModelMessage[]): OpenAiMessage[] => {
202
+ let rounds = 0;
203
+ return messages.flatMap((message) => {
204
+ if (message.role !== "tools") return [textMessage(message)];
205
+ const number = ++rounds;
206
+ let known = built.get(message);
207
+ if (!known || known.number !== number) {
208
+ known = { number, messages: roundMessages(message, number, pdfInput) };
209
+ built.set(message, known);
210
+ }
211
+ return known.messages;
212
+ });
213
+ };
214
+ const bodyOf = (request: ModelRequest, stream: boolean): Json => {
215
+ const mustAnswer = request.toolChoice === "none";
216
+ const listTools = Boolean(request.tools?.length) && !(mustAnswer && options.answerWithoutTools === "omit");
217
+ return {
218
+ model: options.model,
219
+ messages: [...(request.system ? [{ role: systemRole, content: request.system }] : []), ...toMessages(request.messages)],
220
+ ...(listTools ? { tools: request.tools!.map(asFunction), ...(mustAnswer ? { tool_choice: "none" } : {}) } : {}),
221
+ ...(stream ? { stream: true, stream_options: { include_usage: true } } : {}),
222
+ ...options.body,
223
+ };
224
+ };
225
+
226
+ const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean): Promise<Response> => {
227
+ let response: Response;
228
+ try {
229
+ response = await fetchImpl(url, { method: "POST", headers: await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
230
+ } catch (error) {
231
+ if (stopped()) throw error;
232
+ throw new OpenAiRequestError(`The model could not be reached${unreachableReason(error)}.`, 0, { cause: error });
233
+ }
234
+ if (!response.ok) throw await failure(response);
235
+ return response;
236
+ };
237
+
238
+ const generateText: GenerateText = ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
239
+ const send = async (limit: number): Promise<LimitedReply> => {
240
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
241
+ const response = await post({
242
+ model: options.model,
243
+ messages: [{ role: systemRole, content: system }, { role: "user", content: prompt }],
244
+ [maxTokensField]: limit,
245
+ ...options.analysisBody?.(limit),
246
+ }, signal ? AbortSignal.any([signal, timeout]) : timeout, () => Boolean(signal?.aborted) || timeout.aborted);
247
+ const data = await response.json() as Json;
248
+ const used = usageOf(data.usage);
249
+ onUsage?.(used);
250
+ const choice = data.choices?.[0];
251
+ return {
252
+ text: contentText(choice?.message?.content),
253
+ cutOff: choice?.finish_reason === "length",
254
+ ...(typeof choice?.finish_reason === "string" ? { reason: choice.finish_reason } : {}),
255
+ thoughts: used.thoughtTokens ?? 0,
256
+ };
257
+ };
258
+ return completeWithinLimit(`${url}|${options.model}`, maxOutputTokens, send, { signal, onTruncated });
259
+ };
260
+
261
+ return {
262
+ id: options.id ?? options.model,
263
+ capabilities: {
264
+ ...(options.contextTokens ? { contextTokens: options.contextTokens } : {}),
265
+ ...(options.maxRequestBytes ? { maxRequestBytes: options.maxRequestBytes } : {}),
266
+ toolFiles: pdfInput ? "beside" : "none",
267
+ pageTokens: options.pageTokens ?? 1_000,
268
+ ...(options.tokenScale ? { tokenScale: options.tokenScale } : {}),
269
+ },
270
+ requestBytes: (request) => Buffer.byteLength(JSON.stringify(bodyOf(request, false))),
271
+ generateText,
272
+
273
+ async send(request: ModelRequest, hooks: SendHooks = {}): Promise<ModelReply> {
274
+ const stream = Boolean(hooks.onText) && options.stream !== false;
275
+ const response = await post(bodyOf(request, stream), hooks.signal, () => Boolean(hooks.signal?.aborted));
276
+ let message: Json;
277
+ let finish: unknown;
278
+ let usage: Json | undefined;
279
+ let text = "";
280
+ if (stream && response.body && (response.headers.get("content-type") ?? "").includes("text/event-stream")) {
281
+ let reasoning = "";
282
+ const toolCalls: Json[] = [];
283
+ try {
284
+ for await (const chunk of parseSseJson<Json>(response.body)) {
285
+ const failed = (Array.isArray(chunk) ? chunk[0] : chunk)?.error;
286
+ if (failed) throw new OpenAiRequestError(typeof failed === "string" ? failed : String(failed.message ?? "The model reported an error."), typeof failed.code === "number" ? failed.code : response.status);
287
+ if (chunk.usage) usage = chunk.usage as Json;
288
+ const choice = chunk.choices?.[0] as Json | undefined;
289
+ if (!choice) continue;
290
+ const delta = (choice.delta ?? {}) as Json;
291
+ const piece = contentText(delta.content);
292
+ if (piece) {
293
+ text += piece;
294
+ hooks.onText?.(piece);
295
+ }
296
+ if (typeof delta.reasoning_content === "string") reasoning += delta.reasoning_content;
297
+ for (const part of (Array.isArray(delta.tool_calls) ? delta.tool_calls : []) as Json[]) {
298
+ // A call arrives in pieces under its index: first its ID and name, then its arguments, a few characters at a time.
299
+ const at = typeof part.index === "number" ? part.index : part.id || toolCalls.length === 0 ? toolCalls.length : toolCalls.length - 1;
300
+ const call = (toolCalls[at] ??= { type: "function", function: { name: "", arguments: "" } });
301
+ for (const [key, value] of Object.entries(part)) {
302
+ if (key !== "index" && key !== "function" && value !== undefined && value !== null && !(key === "id" && call.id)) call[key] = value;
303
+ }
304
+ if (typeof part.function?.name === "string") call.function.name += part.function.name;
305
+ if (typeof part.function?.arguments === "string") call.function.arguments += part.function.arguments;
306
+ }
307
+ finish = choice.finish_reason ?? finish;
308
+ }
309
+ } catch (error) {
310
+ if (hooks.signal?.aborted || error instanceof OpenAiRequestError) throw error;
311
+ // The connection went while the answer was on its way.
312
+ throw new OpenAiRequestError(`The model could not be reached${unreachableReason(error)}.`, 0, { cause: error });
313
+ }
314
+ const calls = toolCalls.filter(Boolean);
315
+ message = { role: "assistant", content: text || null, ...(reasoning ? { reasoning_content: reasoning } : {}), ...(calls.length > 0 ? { tool_calls: calls } : {}) };
316
+ } else {
317
+ // In one piece: no streaming was asked for, or the server answered without it.
318
+ const data = await response.json() as Json;
319
+ const choice = data.choices?.[0] as Json | undefined;
320
+ message = (choice?.message ?? { role: "assistant", content: null }) as Json;
321
+ finish = choice?.finish_reason;
322
+ usage = data.usage as Json | undefined;
323
+ // A refusal is what the model has to say to the user, in a field of its own.
324
+ text = contentText(message.content) || (typeof message.refusal === "string" ? message.refusal : "");
325
+ if (text) hooks.onText?.(text);
326
+ }
327
+ // Cut off at the output limit with a call half-written: the call is answered, not run.
328
+ 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;
329
+ const calls: ToolCall[] = (Array.isArray(message.tool_calls) ? message.tool_calls as Json[] : [])
330
+ .filter((call) => typeof call?.function?.name === "string" && call.function.name)
331
+ .map((call) => {
332
+ const { args, problem = cutOff } = readArguments(call.function.arguments);
333
+ return { ...(typeof call.id === "string" && call.id ? { id: call.id } : {}), name: call.function.name as string, args, ...(problem ? { problem } : {}) };
334
+ });
335
+ return {
336
+ text,
337
+ calls,
338
+ raw: message,
339
+ ...(typeof finish === "string" ? { finishReason: finish } : {}),
340
+ ...(finish === "content_filter" && !text && calls.length === 0 ? { blockReason: "content_filter" } : {}),
341
+ ...(usage ? { usage: usageOf(usage), providerUsage: usage } : {}),
342
+ };
343
+ },
344
+ };
345
+ }
@@ -0,0 +1,2 @@
1
+ export { fromOpenAiMessages, openAiCompatible, openAiToolTurns, OpenAiRequestError } from "./adapter.js";
2
+ export type { OpenAiCompatibleOptions, OpenAiMessage } from "./adapter.js";
@@ -0,0 +1,99 @@
1
+ // A plain completion on a model that may think its output limit away: shared by the part readers
2
+ // of every adapter.
3
+
4
+ /**
5
+ * A model that thinks counts its thoughts in its output limit. Asked for 4,096 tokens of notes on
6
+ * a part of a log, Gemini 3.8 Flash spent 3,931 of them thinking and wrote two lines, and Gemini 4
7
+ * wrote nothing at all (November 2026). A reply that was cut off that way is asked for again with
8
+ * this limit, the least Google recommends for a Gemini 4 model. OpenAI says to keep at least
9
+ * 25,000 for its reasoning models.
10
+ */
11
+ export const THINKING_OUTPUT_TOKENS = 32_768;
12
+
13
+ /**
14
+ * What has been learned about a model, so that a whole-file read does not pay for the wasted
15
+ * request with every part: the output limit it needs, or 0 when it refused that limit.
16
+ */
17
+ const learnedLimits = new Map<string, number>();
18
+ /** The first request to a model that is still on its way. Others wait for what it learns. */
19
+ const firstRequests = new Map<string, Promise<void>>();
20
+ /** Models that have answered at least once. */
21
+ const answered = new Set<string>();
22
+ const MOST_REMEMBERED = 200;
23
+
24
+ function remember(model: string, limit: number): void {
25
+ if (learnedLimits.size >= MOST_REMEMBERED && !learnedLimits.has(model)) learnedLimits.clear();
26
+ learnedLimits.set(model, limit);
27
+ }
28
+
29
+ /** A reply to a plain completion. */
30
+ export type LimitedReply = {
31
+ text: string;
32
+ /** True when the model stopped because it reached the output limit. */
33
+ cutOff: boolean;
34
+ /** Why it stopped, in the provider's word, for the message when there is no text. */
35
+ reason?: string;
36
+ /** Tokens the model spent thinking, when the provider says. */
37
+ thoughts: number;
38
+ };
39
+
40
+ /**
41
+ * Sends a completion with an output limit, and once more with `THINKING_OUTPUT_TOKENS` when the
42
+ * reply was cut off with nothing written, or with half the limit or more gone on thoughts. What
43
+ * was learned is kept under `model` (a URL, or a URL and a model name): later requests start with
44
+ * the larger limit, and a model that refused it (HTTP 400) is not asked for it again. Requests
45
+ * that arrive while the first one to a model is on its way wait for it.
46
+ */
47
+ export async function completeWithinLimit(model: string, maxOutputTokens: number, send: (limit: number) => Promise<LimitedReply>, options: {
48
+ signal?: AbortSignal | undefined;
49
+ onTruncated?: (() => void) | undefined;
50
+ } = {}): Promise<string> {
51
+ const { signal } = options;
52
+ // The first request to a model finds out whether it thinks its limit away. The parts of a
53
+ // whole-file read are sent four at a time: the others wait for it, and one request is wasted
54
+ // on such a model, not four.
55
+ let learned = () => undefined as void;
56
+ if (!answered.has(model)) {
57
+ const first = firstRequests.get(model);
58
+ if (first) {
59
+ await first;
60
+ signal?.throwIfAborted();
61
+ } else {
62
+ firstRequests.set(model, new Promise<void>((resolve) => {
63
+ learned = () => {
64
+ if (answered.size >= MOST_REMEMBERED) answered.clear();
65
+ answered.add(model);
66
+ firstRequests.delete(model);
67
+ resolve();
68
+ };
69
+ }));
70
+ }
71
+ }
72
+ try {
73
+ const known = learnedLimits.get(model);
74
+ const limit = Math.max(maxOutputTokens, known ?? 0);
75
+ let reply = await send(limit);
76
+ // Cut off, with nothing written or with at least half of the limit gone on thoughts: the
77
+ // limit was too low for this model, not the notes too long.
78
+ const starved = reply.cutOff && (!reply.text.trim() || reply.thoughts >= limit / 2);
79
+ if (starved && known !== 0 && limit < THINKING_OUTPUT_TOKENS) {
80
+ remember(model, THINKING_OUTPUT_TOKENS);
81
+ try {
82
+ reply = await send(THINKING_OUTPUT_TOKENS);
83
+ } catch (error) {
84
+ if (signal?.aborted) throw error;
85
+ // A model or a gateway that refuses the larger limit (HTTP 400) is not asked for it again.
86
+ // Any other failure says nothing about the limit: the next request starts with it. What
87
+ // the first reply had is kept; with nothing in it, this error is the one to report.
88
+ if ((error as { status?: unknown } | null)?.status === 400) remember(model, 0);
89
+ if (!reply.text.trim()) throw error;
90
+ }
91
+ }
92
+ if (!reply.text.trim()) throw new Error(`The model returned no text${reply.reason ? ` (${reply.reason})` : ""}.`);
93
+ // The text stops mid-list when the output limit is reached. Say so instead of passing it off as complete.
94
+ if (reply.cutOff) options.onTruncated?.();
95
+ return reply.text;
96
+ } finally {
97
+ learned();
98
+ }
99
+ }