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/docs/security.md CHANGED
@@ -120,6 +120,24 @@ A slice is synchronous, so a slow pattern still holds the event loop for up to a
120
120
  second at a time, and twice that at the start of a search. If that matters for your latency, run
121
121
  the document tools in a worker thread.
122
122
 
123
+ ## What a question can cost
124
+
125
+ A file can ask a model to do expensive things, and a model can decide to on its own. These bound
126
+ one question, whatever the model:
127
+
128
+ - `limits.toolTurns` (12) chat requests, with at most `limits.callsPerTurn` (8) tool calls run in
129
+ each.
130
+ - One whole-file read of each document (`limits.wholeDocumentReads`). A read is up to
131
+ `maxMapChunks` requests of up to `mapChunkTokens` each: 3M input tokens with the defaults. In a
132
+ probe a model asked for the same file to be read whole six times in one question.
133
+ - `limits.inputTokens` and `limits.requests`, unset by default, are ceilings for the whole
134
+ question, part reads included. Set them if a question must not pass a cost.
135
+ - The request is kept inside the model's window ([Room in the request](configuration.md#room-in-the-request)),
136
+ so a turn of many large reads cannot build a request that the model refuses.
137
+
138
+ `result.usage` is what the question used: every request that was answered, for each model. Log it
139
+ per user to see who spends what.
140
+
123
141
  ## Storage errors
124
142
 
125
143
  A file-system error names the path it failed on, and a database error its host. Neither is shown
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "llm-large-files",
3
- "version": "0.4.1",
4
- "description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, map-reduce, and a look at the pages of a PDF. Gemini and Vertex AI helpers included.",
3
+ "version": "0.5.0",
4
+ "description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, map-reduce, a look at the pages of a PDF, and one tool loop for any model. Adapters for Gemini and Vertex AI, OpenAI-compatible endpoints, and Claude.",
5
5
  "keywords": [
6
6
  "llm",
7
7
  "gemini",
@@ -15,7 +15,11 @@
15
15
  "logs",
16
16
  "pdf",
17
17
  "rag",
18
- "chatbot"
18
+ "chatbot",
19
+ "openai",
20
+ "anthropic",
21
+ "claude",
22
+ "deepseek"
19
23
  ],
20
24
  "license": "MIT",
21
25
  "author": "renanbazinin",
@@ -43,6 +47,14 @@
43
47
  "types": "./dist/gemini/index.d.ts",
44
48
  "default": "./dist/gemini/index.js"
45
49
  },
50
+ "./openai": {
51
+ "types": "./dist/openai/index.d.ts",
52
+ "default": "./dist/openai/index.js"
53
+ },
54
+ "./anthropic": {
55
+ "types": "./dist/anthropic/index.d.ts",
56
+ "default": "./dist/anthropic/index.js"
57
+ },
46
58
  "./node": {
47
59
  "types": "./dist/node/index.d.ts",
48
60
  "default": "./dist/node/index.js"
@@ -54,6 +66,12 @@
54
66
  "gemini": [
55
67
  "./dist/gemini/index.d.ts"
56
68
  ],
69
+ "openai": [
70
+ "./dist/openai/index.d.ts"
71
+ ],
72
+ "anthropic": [
73
+ "./dist/anthropic/index.d.ts"
74
+ ],
57
75
  "node": [
58
76
  "./dist/node/index.d.ts"
59
77
  ]
@@ -0,0 +1,454 @@
1
+ // Claude (the Messages API) as a model of `askWithFiles`. No SDK, like the other adapters: the
2
+ // caller gives a key or a token, and may give the URL of a gateway that speaks the same API.
3
+ import { base64, resolveHeaderSource, resolveSecret, unreachableReason, type HeaderSource, type SecretSource } from "../http.js";
4
+ import { ModelRequestError, type ChatMessage, type ModelAdapter, type ModelMessage, type ModelReply, type ModelRequest, 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 API answered with an HTTP error, or could not be reached (`status` 0). `type` is the API's own word: "rate_limit_error". */
11
+ export class AnthropicRequestError extends ModelRequestError {
12
+ readonly type?: string;
13
+ constructor(message: string, status: number, options: { retryAfterMs?: number; cause?: unknown; type?: string } = {}) {
14
+ super(message, status, options);
15
+ this.name = "AnthropicRequestError";
16
+ if (options.type) this.type = options.type;
17
+ }
18
+ }
19
+
20
+ /** A message of the Messages API, as it takes and returns it. */
21
+ export type AnthropicMessage = { role: "user" | "assistant"; content: string | Array<Record<string, unknown>> };
22
+
23
+ /** The API version the requests are written for. */
24
+ export const ANTHROPIC_VERSION = "2026-10-21";
25
+ /** The beta that `fallbacks` needs. */
26
+ const FALLBACK_BETA = "server-side-fallback-2026-07-01";
27
+ const DEFAULT_MAX_TOKENS = 64_000;
28
+
29
+ export type AnthropicOptions = {
30
+ /** The model ID: "claude-opus-5-5". */
31
+ model: string;
32
+ /** Sent as `x-api-key`. A function is called for each request. */
33
+ apiKey?: SecretSource | undefined;
34
+ /** Sent as `Authorization: Bearer …`, for an OAuth token or a gateway. A function is called for each request. */
35
+ authToken?: SecretSource | undefined;
36
+ /** The base of the API: `/v1/messages` is added to it. Defaults to https://api.anthropic.com. */
37
+ baseUrl?: string | undefined;
38
+ /** The whole Messages URL, when it is not `baseUrl` + `/v1/messages`. */
39
+ url?: string | undefined;
40
+ /** More headers. A function is called for each request. */
41
+ headers?: HeaderSource | undefined;
42
+ /** The `anthropic-version` header. Defaults to `ANTHROPIC_VERSION`. */
43
+ version?: string | undefined;
44
+ /** Values for the `anthropic-beta` header. */
45
+ betas?: string[] | undefined;
46
+ /**
47
+ * `max_tokens` of a chat request: the most the model may write, thoughts included. Defaults to
48
+ * 64,000. It comes out of the context window, so the budget of a question keeps it free.
49
+ */
50
+ maxTokens?: number | undefined;
51
+ /** More fields for the body of every chat request: `thinking`, `output_config`, `context_management`, `metadata`, and so on. */
52
+ body?: Record<string, unknown> | undefined;
53
+ /** More fields for the body of a whole-document part read, given the `max_tokens` it is sent with. */
54
+ analysisBody?: ((maxOutputTokens: number) => Record<string, unknown>) | undefined;
55
+ /**
56
+ * Have another model answer when this one's safety classifiers decline a request: "default", or
57
+ * a list of `{ model }`. It adds the `fallbacks` field and its beta header. Off unless set: it
58
+ * is offered on the Claude API, not on Amazon Bedrock, Vertex AI or Microsoft Foundry, and not
59
+ * for every model.
60
+ */
61
+ fallbacks?: "default" | Array<Record<string, unknown> & { model: string }> | undefined;
62
+ /**
63
+ * Prompt caching: a top-level `cache_control`, which caches the request up to its last block, so
64
+ * each request of a tool loop, and a follow-up question, reads what the one before wrote.
65
+ * `true` (the default) keeps it five minutes, "1h" an hour, `false` sends none.
66
+ */
67
+ cache?: boolean | "5m" | "1h" | undefined;
68
+ /**
69
+ * Where the pages of `view_pages` go: "inside" the tool result as a document block (the
70
+ * default), "beside" it as a document block after the tool results, or "none" to not offer
71
+ * `view_pages`.
72
+ */
73
+ toolFilePlacement?: "inside" | "beside" | "none" | undefined;
74
+ /** Chat requests are streamed, which keeps a long reply from timing out. False for a gateway without streaming. */
75
+ stream?: boolean | undefined;
76
+ /**
77
+ * Set `eager_input_streaming` on the tools of a streamed request, so tool input arrives as it
78
+ * is written. Defaults to true for api.anthropic.com and false for any other URL, which may
79
+ * refuse the field.
80
+ */
81
+ eagerInputStreaming?: boolean | undefined;
82
+ /** The model's context window in tokens, when the budget of a question should follow it. */
83
+ contextTokens?: number | undefined;
84
+ /** The largest request body in bytes. Defaults to 32 MB, the limit of the Claude API. */
85
+ maxRequestBytes?: number | undefined;
86
+ /** Tokens billed for one PDF page: its text and its picture. Defaults to 3,500. */
87
+ pageTokens?: number | undefined;
88
+ /**
89
+ * This model's tokens for one token of the library's estimate, which is fitted to Gemini.
90
+ * Defaults to 1.35, a cautious guess for the tokenizer of the current models: the count the API
91
+ * reports with each reply corrects it during a question.
92
+ */
93
+ tokenScale?: number | undefined;
94
+ /** Milliseconds a part read may take. Defaults to 180,000. */
95
+ timeoutMs?: number | undefined;
96
+ /** Names the model in usage totals. Defaults to `model`. */
97
+ id?: string | undefined;
98
+ fetch?: typeof fetch | undefined;
99
+ };
100
+
101
+ type Json = Record<string, any>;
102
+ type Block = Record<string, any>;
103
+
104
+ const STATUS_OF_TYPE: Record<string, number> = { overloaded_error: 529, rate_limit_error: 429, api_error: 500, timeout_error: 408 };
105
+
106
+ /** Blocks of a model that declined part-way must not go back: only what came after the last switch to another model does. */
107
+ const INTERNAL_BEFORE_FALLBACK = new Set(["thinking", "redacted_thinking", "tool_use", "server_tool_use"]);
108
+
109
+ /** The content of a reply as it goes back in the next request. */
110
+ function echoable(content: Block[]): Block[] {
111
+ const boundary = content.map((block) => block?.type).lastIndexOf("fallback");
112
+ if (boundary < 0) return content;
113
+ return content.filter((block, index) => index >= boundary || !INTERNAL_BEFORE_FALLBACK.has(block?.type));
114
+ }
115
+
116
+ function usageOf(usage: Json | undefined): GenerateUsage {
117
+ const number = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : 0);
118
+ // With fallbacks, each attempt is an entry of `iterations`, and the top-level numbers are the last attempt's alone.
119
+ const attempts: Json[] = Array.isArray(usage?.iterations) && usage.iterations.length > 0 ? usage.iterations : [usage ?? {}];
120
+ const sum = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, thoughtTokens: 0 };
121
+ for (const attempt of attempts) {
122
+ const read = number(attempt?.cache_read_input_tokens);
123
+ // `input_tokens` is what was not cached: the prompt is the three together.
124
+ sum.inputTokens += number(attempt?.input_tokens) + number(attempt?.cache_creation_input_tokens) + read;
125
+ sum.cachedInputTokens += read;
126
+ sum.outputTokens += number(attempt?.output_tokens);
127
+ }
128
+ return sum;
129
+ }
130
+
131
+ async function failure(response: Response): Promise<AnthropicRequestError> {
132
+ const data = await response.json().catch(() => null) as Json | null;
133
+ const wait = retryAfterMs(response.headers, data);
134
+ const type = typeof data?.error?.type === "string" ? data.error.type as string : undefined;
135
+ return new AnthropicRequestError(typeof data?.error?.message === "string" && data.error.message ? data.error.message : `Claude returned HTTP ${response.status}.`, response.status, {
136
+ ...(wait === undefined ? {} : { retryAfterMs: wait }),
137
+ ...(type ? { type } : {}),
138
+ });
139
+ }
140
+
141
+ const toolResultOf = (id: string, result: ToolResult, documents: Block[]): Block => ({
142
+ type: "tool_result",
143
+ tool_use_id: id,
144
+ content: documents.length > 0 ? [{ type: "text", text: JSON.stringify(result) }, ...documents] : JSON.stringify(result),
145
+ // Says to the model that the call failed, so it tries another way instead of reading the message as data.
146
+ ...(typeof result.error === "string" ? { is_error: true } : {}),
147
+ });
148
+
149
+ /** The two messages of one tool round. `number` makes the IDs of calls that came without one. */
150
+ function roundMessages(round: ModelToolRound, number: number, files: "inside" | "beside" | "none"): AnthropicMessage[] {
151
+ const idOf = (call: ToolCall, index: number) => call.id ?? `toolu_${number}_${index + 1}`;
152
+ // Its own turn goes back exactly as it came: Claude checks its thinking blocks against the conversation they were written in.
153
+ const asked: AnthropicMessage = {
154
+ role: "assistant",
155
+ content: round.raw !== undefined ? round.raw as Block[] : round.calls.map((call, index) => ({ type: "tool_use", id: idOf(call, index), name: call.name, input: call.args })),
156
+ };
157
+ if (round.answers.length === 0) return [asked];
158
+ const document = (file: { mimeType: string; bytes: Uint8Array }): Block => ({ type: "document", source: { type: "base64", media_type: file.mimeType, data: base64(file.bytes) } });
159
+ const results = round.answers.map((answer, index) => toolResultOf(idOf(answer.call, index), answer.result, files === "inside" ? (answer.files ?? []).map(document) : []));
160
+ // Anything else in the turn comes after every tool result: the API refuses text before one.
161
+ const beside = files === "beside" ? round.answers.flatMap((answer) => (answer.files ?? []).flatMap((file) => [
162
+ { type: "text", text: `${file.name} (returned by ${answer.call.name}):` },
163
+ document(file),
164
+ ])) : [];
165
+ return [asked, { role: "user", content: [...results, ...beside] }];
166
+ }
167
+
168
+ /** Turns that follow each other with the same role, made one: tool results and the text after them belong to one user turn. */
169
+ function joined(messages: AnthropicMessage[]): AnthropicMessage[] {
170
+ const out: AnthropicMessage[] = [];
171
+ for (const message of messages) {
172
+ const content = typeof message.content === "string" ? (message.content ? [{ type: "text", text: message.content }] : []) : message.content;
173
+ if (content.length === 0) continue;
174
+ const last = out.at(-1);
175
+ if (last && last.role === message.role) last.content = [...last.content as Block[], ...content];
176
+ else out.push({ role: message.role, content: [...content] });
177
+ }
178
+ return out;
179
+ }
180
+
181
+ /**
182
+ * Messages of the Messages API as the conversation of `askWithFiles`: text blocks as text, a turn
183
+ * of `tool_use` blocks and the `tool_result` blocks that answer it as one stored tool round, and
184
+ * every other block (an image, a document) as it is. Thinking blocks are left out: they belong to
185
+ * the conversation they were written in.
186
+ */
187
+ export function fromAnthropicMessages(history: AnthropicMessage[]): ChatMessage[] {
188
+ const messages: ChatMessage[] = [];
189
+ const open = new Map<string, { result: ToolResult }>();
190
+ for (const message of history) {
191
+ const content: Block[] = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
192
+ const calls: Array<ToolCall & { result: ToolResult }> = [];
193
+ const parts: Array<{ text: string } | { native: unknown }> = [];
194
+ for (const block of content) {
195
+ if (block.type === "thinking" || block.type === "redacted_thinking") continue;
196
+ if (block.type === "text" && typeof block.text === "string") {
197
+ if (block.text) parts.push({ text: block.text });
198
+ } else if (block.type === "tool_use" && message.role === "assistant") {
199
+ calls.push({ id: String(block.id), name: String(block.name), args: block.input && typeof block.input === "object" ? block.input as Record<string, unknown> : {}, result: { error: "No result was kept for this call." } });
200
+ } else if (block.type === "tool_result" && message.role === "user") {
201
+ const call = open.get(String(block.tool_use_id));
202
+ if (!call) continue;
203
+ const text = typeof block.content === "string" ? block.content : (Array.isArray(block.content) ? block.content as Block[] : []).map((part) => (part.type === "text" ? String(part.text ?? "") : "")).join("");
204
+ try {
205
+ const parsed = JSON.parse(text) as unknown;
206
+ call.result = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as ToolResult : { text };
207
+ } catch {
208
+ call.result = { text };
209
+ }
210
+ } else {
211
+ parts.push({ native: block });
212
+ }
213
+ }
214
+ if (parts.length > 0) messages.push({ role: message.role, parts });
215
+ if (calls.length > 0) {
216
+ for (const call of calls) open.set(call.id!, call);
217
+ messages.push({ role: "tools", calls });
218
+ }
219
+ }
220
+ return messages;
221
+ }
222
+
223
+ /**
224
+ * The tool rounds a question returned (`AskResult.toolTurns`) as messages of the Messages API, for
225
+ * an application that keeps its history in that form: put them between the question and its answer.
226
+ */
227
+ export function anthropicToolTurns(turns: ToolTurn[]): AnthropicMessage[] {
228
+ return turns.flatMap((turn, index) => {
229
+ const answers = turn.calls.map(({ result, ...call }) => ({ call, result }));
230
+ return roundMessages({ role: "tools", calls: answers.map((answer) => answer.call), answers }, index + 1, "none");
231
+ });
232
+ }
233
+
234
+ /** A Claude model for `askWithFiles`. */
235
+ export function anthropic(options: AnthropicOptions): ModelAdapter {
236
+ const fetchImpl = options.fetch ?? fetch;
237
+ const url = options.url ?? `${(options.baseUrl ?? "https://api.anthropic.com").replace(/\/+$/, "")}/v1/messages`;
238
+ const firstParty = (() => {
239
+ try {
240
+ return new URL(url).hostname === "api.anthropic.com";
241
+ } catch {
242
+ return false;
243
+ }
244
+ })();
245
+ const files = options.toolFilePlacement ?? "inside";
246
+ const maxTokens = Math.max(1, Math.trunc(options.maxTokens ?? DEFAULT_MAX_TOKENS));
247
+ const streaming = options.stream !== false;
248
+ const eager = options.eagerInputStreaming ?? firstParty;
249
+ const cache = options.cache === false ? undefined : { type: "ephemeral", ...(options.cache === "1h" ? { ttl: "1h" } : {}) };
250
+ const betas = [...new Set([...(options.betas ?? []), ...(options.fallbacks ? [FALLBACK_BETA] : [])])];
251
+
252
+ const headersNow = async (): Promise<Record<string, string>> => {
253
+ const [key, token] = await Promise.all([resolveSecret(options.apiKey), resolveSecret(options.authToken)]);
254
+ return {
255
+ "Content-Type": "application/json",
256
+ "anthropic-version": options.version ?? ANTHROPIC_VERSION,
257
+ ...(betas.length > 0 ? { "anthropic-beta": betas.join(",") } : {}),
258
+ ...(key ? { "x-api-key": key } : {}),
259
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
260
+ ...await resolveHeaderSource(options.headers),
261
+ };
262
+ };
263
+
264
+ const built = new WeakMap<ModelToolRound, { number: number; messages: AnthropicMessage[] }>();
265
+ const toMessages = (messages: ModelMessage[]): AnthropicMessage[] => {
266
+ let rounds = 0;
267
+ return joined(messages.flatMap((message): AnthropicMessage[] => {
268
+ if (message.role !== "tools") {
269
+ // The API refuses an empty text block.
270
+ return [{ role: message.role, content: message.parts.flatMap((part): Block[] => (part.native !== undefined ? [part.native as Block] : part.text ? [{ type: "text", text: part.text }] : [])) }];
271
+ }
272
+ const number = ++rounds;
273
+ let known = built.get(message);
274
+ if (!known || known.number !== number) {
275
+ known = { number, messages: roundMessages(message, number, files) };
276
+ built.set(message, known);
277
+ }
278
+ return known.messages;
279
+ }));
280
+ };
281
+ const asTool = (declaration: ToolDeclaration, stream: boolean): Block => ({
282
+ name: declaration.name,
283
+ description: declaration.description,
284
+ input_schema: declaration.parameters,
285
+ ...(stream && eager ? { eager_input_streaming: true } : {}),
286
+ });
287
+ const bodyOf = (request: ModelRequest, stream: boolean): Json => ({
288
+ model: options.model,
289
+ max_tokens: maxTokens,
290
+ ...(request.system ? { system: request.system } : {}),
291
+ messages: toMessages(request.messages),
292
+ // The tools stay listed in the request that must be answered in text: Claude ties its thinking
293
+ // to the tools of the conversation, and wants them declared next to earlier calls.
294
+ ...(request.tools?.length ? { tools: request.tools.map((tool) => asTool(tool, stream)), ...(request.toolChoice === "none" ? { tool_choice: { type: "none" } } : {}) } : {}),
295
+ ...(stream ? { stream: true } : {}),
296
+ ...(cache ? { cache_control: cache } : {}),
297
+ ...(options.fallbacks ? { fallbacks: options.fallbacks } : {}),
298
+ ...options.body,
299
+ });
300
+
301
+ const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean): Promise<Response> => {
302
+ let response: Response;
303
+ try {
304
+ response = await fetchImpl(url, { method: "POST", headers: await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
305
+ } catch (error) {
306
+ if (stopped()) throw error;
307
+ throw new AnthropicRequestError(`Claude could not be reached${unreachableReason(error)}.`, 0, { cause: error });
308
+ }
309
+ if (!response.ok) throw await failure(response);
310
+ return response;
311
+ };
312
+
313
+ /** The reply, from the content of a finished message. */
314
+ const replyOf = (content: Block[], stopReason: unknown, stopDetails: Json | undefined, usage: Json | undefined, problems: Map<number, string>, text: string): ModelReply => {
315
+ const boundary = content.map((block) => block?.type).lastIndexOf("fallback");
316
+ const refused = stopReason === "refusal";
317
+ // Cut off at the output limit with a call half-written: the call is answered, not run.
318
+ const cutOff = stopReason === "max_tokens";
319
+ const calls: ToolCall[] = refused ? [] : content.flatMap((block, index): ToolCall[] => {
320
+ if (block?.type !== "tool_use" || index < boundary || typeof block.name !== "string") return [];
321
+ const problem = problems.get(index) ?? (cutOff ? "This call was cut off at the output limit before its arguments were complete, and was not run. Send it again." : undefined);
322
+ return [{
323
+ ...(typeof block.id === "string" ? { id: block.id } : {}),
324
+ name: block.name,
325
+ args: block.input && typeof block.input === "object" && !Array.isArray(block.input) ? block.input as Record<string, unknown> : {},
326
+ ...(problem ? { problem } : {}),
327
+ }];
328
+ });
329
+ const category = typeof stopDetails?.category === "string" ? `: ${stopDetails.category as string}` : "";
330
+ return {
331
+ text,
332
+ calls,
333
+ raw: echoable(content),
334
+ ...(typeof stopReason === "string" ? { finishReason: stopReason } : {}),
335
+ ...(refused ? { blockReason: `refusal${category}` } : {}),
336
+ ...(usage ? { usage: usageOf(usage), providerUsage: usage } : {}),
337
+ };
338
+ };
339
+
340
+ const generateText: GenerateText = ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
341
+ const send = async (limit: number): Promise<LimitedReply> => {
342
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
343
+ const response = await post({
344
+ model: options.model,
345
+ max_tokens: limit,
346
+ system,
347
+ messages: [{ role: "user", content: prompt }],
348
+ ...options.analysisBody?.(limit),
349
+ }, signal ? AbortSignal.any([signal, timeout]) : timeout, () => Boolean(signal?.aborted) || timeout.aborted);
350
+ const data = await response.json() as Json;
351
+ onUsage?.(usageOf(data.usage as Json | undefined));
352
+ const content: Block[] = Array.isArray(data.content) ? data.content : [];
353
+ return {
354
+ text: content.map((block) => (block?.type === "text" && typeof block.text === "string" ? block.text : "")).join(""),
355
+ cutOff: data.stop_reason === "max_tokens",
356
+ ...(typeof data.stop_reason === "string" ? { reason: data.stop_reason } : {}),
357
+ thoughts: 0,
358
+ };
359
+ };
360
+ return completeWithinLimit(`${url}|${options.model}`, maxOutputTokens, send, { signal, onTruncated });
361
+ };
362
+
363
+ return {
364
+ id: options.id ?? options.model,
365
+ capabilities: {
366
+ ...(options.contextTokens ? { contextTokens: options.contextTokens } : {}),
367
+ maxRequestBytes: options.maxRequestBytes ?? 32_000_000,
368
+ toolFiles: files,
369
+ pageTokens: options.pageTokens ?? 3_500,
370
+ tokenScale: options.tokenScale ?? 1.35,
371
+ outputTokens: maxTokens,
372
+ // Claude checks its thinking blocks against the conversation they were written in: an
373
+ // earlier turn that is rewritten makes the later ones invalid.
374
+ appendOnly: true,
375
+ },
376
+ requestBytes: (request) => Buffer.byteLength(JSON.stringify(bodyOf(request, streaming))),
377
+ generateText,
378
+
379
+ async send(request: ModelRequest, hooks: SendHooks = {}): Promise<ModelReply> {
380
+ const response = await post(bodyOf(request, streaming), hooks.signal, () => Boolean(hooks.signal?.aborted));
381
+ const problems = new Map<number, string>();
382
+ if (!(streaming && response.body && (response.headers.get("content-type") ?? "").includes("text/event-stream"))) {
383
+ // In one piece: streaming is off, or the gateway answered without it.
384
+ const data = await response.json() as Json;
385
+ const content: Block[] = Array.isArray(data.content) ? data.content : [];
386
+ const text = content.map((block) => (block?.type === "text" && typeof block.text === "string" ? block.text : "")).join("");
387
+ if (text) hooks.onText?.(text);
388
+ return replyOf(content, data.stop_reason, data.stop_details as Json | undefined, data.usage as Json | undefined, problems, text);
389
+ }
390
+ const content: Block[] = [];
391
+ const inputs = new Map<number, string>();
392
+ let text = "";
393
+ let stopReason: unknown;
394
+ let stopDetails: Json | undefined;
395
+ let usage: Json | undefined;
396
+ try {
397
+ for await (const event of parseSseJson<Json>(response.body)) {
398
+ if (event.type === "error") {
399
+ const type = typeof event.error?.type === "string" ? event.error.type as string : undefined;
400
+ throw new AnthropicRequestError(String(event.error?.message ?? "Claude reported an error."), (type && STATUS_OF_TYPE[type]) || response.status, type ? { type } : {});
401
+ }
402
+ if (event.type === "message_start") {
403
+ usage = { ...event.message?.usage };
404
+ } else if (event.type === "content_block_start" && typeof event.index === "number") {
405
+ content[event.index] = { ...event.content_block };
406
+ } else if (event.type === "content_block_delta" && typeof event.index === "number") {
407
+ const block = (content[event.index] ??= {});
408
+ const delta = (event.delta ?? {}) as Json;
409
+ if (delta.type === "text_delta" && typeof delta.text === "string") {
410
+ block.text = `${block.text ?? ""}${delta.text}`;
411
+ text += delta.text;
412
+ if (delta.text) hooks.onText?.(delta.text);
413
+ } else if (delta.type === "thinking_delta" && typeof delta.thinking === "string") {
414
+ block.thinking = `${block.thinking ?? ""}${delta.thinking}`;
415
+ } else if (delta.type === "signature_delta") {
416
+ block.signature = delta.signature;
417
+ } else if (delta.type === "input_json_delta" && typeof delta.partial_json === "string") {
418
+ inputs.set(event.index, `${inputs.get(event.index) ?? ""}${delta.partial_json}`);
419
+ } else if (delta.type === "citations_delta") {
420
+ (block.citations ??= []).push(delta.citation);
421
+ }
422
+ } else if (event.type === "content_block_stop" && typeof event.index === "number") {
423
+ const written = inputs.get(event.index);
424
+ const block = content[event.index];
425
+ if (block?.type === "tool_use" && written !== undefined && written.trim()) {
426
+ // The pieces of the input are JSON only when they are all there: read them strictly.
427
+ try {
428
+ const input = JSON.parse(written) as unknown;
429
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("not an object");
430
+ block.input = input;
431
+ } catch {
432
+ block.input = {};
433
+ problems.set(event.index, `The arguments of this call were not valid JSON, and it was not run: ${written.slice(0, 300)}. Send the call again.`);
434
+ }
435
+ }
436
+ } else if (event.type === "message_delta") {
437
+ stopReason = event.delta?.stop_reason ?? stopReason;
438
+ stopDetails = (event.delta?.stop_details as Json | undefined) ?? stopDetails;
439
+ usage = { ...usage, ...event.usage };
440
+ }
441
+ }
442
+ } catch (error) {
443
+ if (hooks.signal?.aborted || error instanceof AnthropicRequestError) throw error;
444
+ // The connection went while the answer was on its way.
445
+ throw new AnthropicRequestError(`Claude could not be reached${unreachableReason(error)}.`, 0, { cause: error });
446
+ }
447
+ const blocks = content.filter(Boolean);
448
+ // The problems were noted by the place of the block in the stream: the same place, with no gaps, in what is kept.
449
+ const placed = new Map<number, string>();
450
+ for (const [index, problem] of problems) placed.set(blocks.indexOf(content[index]!), problem);
451
+ return replyOf(blocks, stopReason, stopDetails, usage, placed, text);
452
+ },
453
+ };
454
+ }
@@ -0,0 +1,2 @@
1
+ export { anthropic, ANTHROPIC_VERSION, anthropicToolTurns, AnthropicRequestError, fromAnthropicMessages } from "./adapter.js";
2
+ export type { AnthropicMessage, AnthropicOptions } from "./adapter.js";