llm-large-files 0.4.0 → 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 (156) hide show
  1. package/CHANGELOG.md +205 -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/cache.d.ts +11 -2
  20. package/dist/cache.d.ts.map +1 -1
  21. package/dist/cache.js +36 -7
  22. package/dist/cache.js.map +1 -1
  23. package/dist/errors.d.ts +21 -0
  24. package/dist/errors.d.ts.map +1 -0
  25. package/dist/errors.js +44 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/evidence.d.ts +40 -0
  28. package/dist/evidence.d.ts.map +1 -0
  29. package/dist/evidence.js +137 -0
  30. package/dist/evidence.js.map +1 -0
  31. package/dist/gemini/adapter.d.ts +50 -0
  32. package/dist/gemini/adapter.d.ts.map +1 -0
  33. package/dist/gemini/adapter.js +179 -0
  34. package/dist/gemini/adapter.js.map +1 -0
  35. package/dist/gemini/chat.d.ts +32 -71
  36. package/dist/gemini/chat.d.ts.map +1 -1
  37. package/dist/gemini/chat.js +38 -284
  38. package/dist/gemini/chat.js.map +1 -1
  39. package/dist/gemini/errors.d.ts +11 -0
  40. package/dist/gemini/errors.d.ts.map +1 -0
  41. package/dist/gemini/errors.js +14 -0
  42. package/dist/gemini/errors.js.map +1 -0
  43. package/dist/gemini/generate.d.ts +12 -13
  44. package/dist/gemini/generate.d.ts.map +1 -1
  45. package/dist/gemini/generate.js +62 -26
  46. package/dist/gemini/generate.js.map +1 -1
  47. package/dist/gemini/index.d.ts +3 -1
  48. package/dist/gemini/index.d.ts.map +1 -1
  49. package/dist/gemini/index.js +2 -1
  50. package/dist/gemini/index.js.map +1 -1
  51. package/dist/gemini/sse.d.ts +1 -2
  52. package/dist/gemini/sse.d.ts.map +1 -1
  53. package/dist/gemini/sse.js +1 -38
  54. package/dist/gemini/sse.js.map +1 -1
  55. package/dist/http.d.ts +20 -0
  56. package/dist/http.d.ts.map +1 -0
  57. package/dist/http.js +55 -0
  58. package/dist/http.js.map +1 -0
  59. package/dist/index.d.ts +14 -2
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +12 -4
  62. package/dist/index.js.map +1 -1
  63. package/dist/library.d.ts +50 -5
  64. package/dist/library.d.ts.map +1 -1
  65. package/dist/library.js +56 -26
  66. package/dist/library.js.map +1 -1
  67. package/dist/map-reduce.d.ts +15 -0
  68. package/dist/map-reduce.d.ts.map +1 -1
  69. package/dist/map-reduce.js +58 -27
  70. package/dist/map-reduce.js.map +1 -1
  71. package/dist/model.d.ts +196 -0
  72. package/dist/model.d.ts.map +1 -0
  73. package/dist/model.js +41 -0
  74. package/dist/model.js.map +1 -0
  75. package/dist/openai/adapter.d.ts +85 -0
  76. package/dist/openai/adapter.d.ts.map +1 -0
  77. package/dist/openai/adapter.js +293 -0
  78. package/dist/openai/adapter.js.map +1 -0
  79. package/dist/openai/index.d.ts +3 -0
  80. package/dist/openai/index.d.ts.map +1 -0
  81. package/dist/openai/index.js +2 -0
  82. package/dist/openai/index.js.map +1 -0
  83. package/dist/output-limit.d.ts +30 -0
  84. package/dist/output-limit.d.ts.map +1 -0
  85. package/dist/output-limit.js +92 -0
  86. package/dist/output-limit.js.map +1 -0
  87. package/dist/plan.d.ts +20 -4
  88. package/dist/plan.d.ts.map +1 -1
  89. package/dist/plan.js +44 -7
  90. package/dist/plan.js.map +1 -1
  91. package/dist/ranged.d.ts +2 -2
  92. package/dist/ranged.d.ts.map +1 -1
  93. package/dist/ranged.js +11 -4
  94. package/dist/ranged.js.map +1 -1
  95. package/dist/retry.d.ts +54 -0
  96. package/dist/retry.d.ts.map +1 -0
  97. package/dist/retry.js +111 -0
  98. package/dist/retry.js.map +1 -0
  99. package/dist/search.d.ts +16 -2
  100. package/dist/search.d.ts.map +1 -1
  101. package/dist/search.js +109 -26
  102. package/dist/search.js.map +1 -1
  103. package/dist/sse.d.ts +3 -0
  104. package/dist/sse.d.ts.map +1 -0
  105. package/dist/sse.js +39 -0
  106. package/dist/sse.js.map +1 -0
  107. package/dist/stores.d.ts +5 -1
  108. package/dist/stores.d.ts.map +1 -1
  109. package/dist/stores.js +58 -15
  110. package/dist/stores.js.map +1 -1
  111. package/dist/text.d.ts +12 -1
  112. package/dist/text.d.ts.map +1 -1
  113. package/dist/text.js +43 -15
  114. package/dist/text.js.map +1 -1
  115. package/dist/tools.d.ts +23 -0
  116. package/dist/tools.d.ts.map +1 -1
  117. package/dist/tools.js +115 -35
  118. package/dist/tools.js.map +1 -1
  119. package/dist/types.d.ts +33 -3
  120. package/dist/types.d.ts.map +1 -1
  121. package/docs/api.md +253 -28
  122. package/docs/configuration.md +89 -10
  123. package/docs/getting-started.md +69 -16
  124. package/docs/how-it-works.md +46 -4
  125. package/docs/security.md +36 -3
  126. package/package.json +21 -3
  127. package/src/anthropic/adapter.ts +454 -0
  128. package/src/anthropic/index.ts +2 -0
  129. package/src/ask.ts +675 -0
  130. package/src/budget.ts +71 -0
  131. package/src/cache.ts +32 -8
  132. package/src/errors.ts +42 -0
  133. package/src/evidence.ts +162 -0
  134. package/src/gemini/adapter.ts +218 -0
  135. package/src/gemini/chat.ts +62 -333
  136. package/src/gemini/errors.ts +15 -0
  137. package/src/gemini/generate.ts +72 -30
  138. package/src/gemini/index.ts +3 -1
  139. package/src/gemini/sse.ts +1 -34
  140. package/src/http.ts +59 -0
  141. package/src/index.ts +34 -4
  142. package/src/library.ts +102 -29
  143. package/src/map-reduce.ts +52 -23
  144. package/src/model.ts +200 -0
  145. package/src/openai/adapter.ts +345 -0
  146. package/src/openai/index.ts +2 -0
  147. package/src/output-limit.ts +99 -0
  148. package/src/plan.ts +46 -7
  149. package/src/ranged.ts +13 -6
  150. package/src/retry.ts +132 -0
  151. package/src/search.ts +116 -25
  152. package/src/sse.ts +34 -0
  153. package/src/stores.ts +51 -15
  154. package/src/text.ts +39 -12
  155. package/src/tools.ts +127 -38
  156. package/src/types.ts +29 -3
@@ -1,47 +1,17 @@
1
+ import { askWithFiles, type AskLimits, type AskResult } from "../ask.js";
1
2
  import type { LargeFiles } from "../library.js";
2
- import { REQUEST_BYTES_MARGIN } from "../plan.js";
3
- import { estimateTokens, jsonBytes } from "../text.js";
4
- import { TOOL_NAMES, toolResultSummary } from "../tools.js";
5
- import type { DocumentPlan, ToolFile, ToolFileLimits, ToolResult } from "../types.js";
6
- import { resolveHeaders, type GeminiEndpoint } from "./endpoints.js";
7
- import { createGeminiGenerateText, geminiFunctionResponseTurns, type GeminiFunctionCall, type GeminiToolFilePlacement } from "./generate.js";
8
- import { parseSseJson } from "./sse.js";
9
-
10
- export type GeminiPart = Record<string, unknown>;
11
- export type GeminiContent = { role: "user" | "model"; parts: GeminiPart[] };
12
- /** A plain chat turn. "assistant" is accepted as an alias for "model". */
13
- export type ChatTurn = { role: "user" | "model" | "assistant"; text: string };
14
-
15
- /** Sent (invisibly to the user) when the model must stop using tools and answer. */
16
- export const FINAL_ANSWER_REQUEST = "Stop using tools now. Answer my question using only what the tools returned above, with line citations. Say plainly what you could not find.";
17
- /** The same, when the only tool was `view_pages`: the text of the files is in the prompt, not in tool results. */
18
- export const FINAL_ANSWER_AFTER_PAGES = "Stop using tools now. Answer my question from the text of the files and the pages you looked at. Say plainly what you could not see or find.";
19
- /** Sent to the answering model when an explorer model used no tool, so there is no tool result to answer from. */
20
- export const FINAL_ANSWER_WITHOUT_TOOLS = "Answer my question now, from what is in this conversation. No tools are available for this reply: if the answer needs a part of a file that is not shown here, say so plainly.";
21
- /**
22
- * Added to the system instruction of an explorer model's requests: it gathers what the answer
23
- * needs, and the other model writes the answer.
24
- */
25
- export const EXPLORER_INSTRUCTION = "You only gather material in this conversation: another model writes the answer. It sees this conversation and what your tool calls returned, not what you thought or wrote. So call the tools until their results hold everything the answer needs from the files. Then, or at once if no tool is needed, reply with the single word DONE instead of an answer.";
26
-
27
- /** What Gemini bills for one PDF page it is shown (measured: 520 to 532). */
28
- const PAGE_TOKENS = 530;
29
-
30
- /** Some document IDs were never uploaded, have expired, or belong to another owner. */
31
- export class DocumentsNotFoundError extends Error {
32
- constructor(readonly ids: string[]) {
33
- super(`${ids.length === 1 ? "A document is" : `${ids.length} documents are`} no longer available: ${ids.join(", ")}. Upload ${ids.length === 1 ? "it" : "them"} again.`);
34
- this.name = "DocumentsNotFoundError";
35
- }
36
- }
37
-
38
- /** Gemini answered with an HTTP error. */
39
- export class GeminiRequestError extends Error {
40
- constructor(message: string, readonly status: number) {
41
- super(message);
42
- this.name = "GeminiRequestError";
43
- }
44
- }
3
+ import type { ChatTurn, ToolTurn } from "../model.js";
4
+ import type { RetryOptions } from "../retry.js";
5
+ import type { Budget } from "../types.js";
6
+ import { fromGeminiContents, gemini, type GeminiContent } from "./adapter.js";
7
+ import type { GeminiEndpoint } from "./endpoints.js";
8
+ import type { GeminiToolFilePlacement } from "./generate.js";
9
+
10
+ export { DocumentsNotFoundError } from "../model.js";
11
+ export { EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS } from "../ask.js";
12
+ export type { ChatTurn } from "../model.js";
13
+ export type { GeminiContent, GeminiPart } from "./adapter.js";
14
+ export { GeminiRequestError } from "./errors.js";
45
15
 
46
16
  export type AskGeminiOptions = {
47
17
  files: LargeFiles;
@@ -61,8 +31,11 @@ export type AskGeminiOptions = {
61
31
  * did; the document then moves on every turn and is billed in full each time.
62
32
  */
63
33
  documentPlacement?: "first" | "last";
64
- /** Plain chat history; the last turn must be the user's question. Use this or `contents`. */
65
- messages?: ChatTurn[];
34
+ /**
35
+ * Plain chat history; the last turn must be the user's question. It may hold the tool rounds of
36
+ * earlier questions (`toolTurns` of their results). Use this or `contents`.
37
+ */
38
+ messages?: Array<ChatTurn | ToolTurn>;
66
39
  /** Your own Gemini `contents` (with images, inline PDFs, etc.). The last turn must be the user's. */
67
40
  contents?: GeminiContent[];
68
41
  system?: string;
@@ -76,13 +49,16 @@ export type AskGeminiOptions = {
76
49
  explorerGenerationConfig?: Record<string, unknown>;
77
50
  /** The user asking. Documents ingested with a different owner are treated as missing. */
78
51
  owner?: string;
79
- /**
80
- * The most model requests for one question, counting the answer. Tools can run in all but the
81
- * last: if the model is still calling tools then, the last request is sent with no tools so it
82
- * must answer. Defaults to 12. With an explorer model the answer is always a request of its
83
- * own, the last one, so the explorer has one less than this.
84
- */
52
+ /** The limits of the question: tool turns, calls in a turn, whole-file reads, tokens and requests. */
53
+ limits?: AskLimits;
54
+ /** `limits.toolTurns`, under the name it had before 0.5.0. Defaults to 12. */
85
55
  maxToolTurns?: number;
56
+ /** `limits.callsPerTurn`, under the name it had before 0.5.0. Defaults to 8. */
57
+ maxToolCallsPerTurn?: number;
58
+ /** How a request that failed is sent again. Defaults to three more tries, with a wait that doubles. */
59
+ retry?: RetryOptions;
60
+ /** Budget fields for this question, in place of the library's. */
61
+ budget?: Partial<Budget>;
86
62
  /** Offer `analyze_whole_document`, which reads a whole file in many model calls. Defaults to true. */
87
63
  wholeDocumentAnalysis?: boolean;
88
64
  /**
@@ -113,293 +89,46 @@ export type AskGeminiOptions = {
113
89
  signal?: AbortSignal;
114
90
  };
115
91
 
116
- export type AskGeminiResult = {
117
- /**
118
- * Everything the model wrote, including any remark it made before calling a tool. With an
119
- * explorer model, only what the answering model wrote: the explorer's words are not shown.
120
- */
121
- text: string;
122
- /**
123
- * False when the model's last turn had no text: the prompt was blocked, the reply was cut off
124
- * before any text, or the model produced a malformed tool call. `text` may then be empty or
125
- * hold only an earlier remark, so show your own message instead of treating it as the answer.
126
- */
127
- answered: boolean;
128
- /** Why Gemini refused the prompt (`promptFeedback.blockReason`), when it did. */
129
- blockReason?: string;
130
- /** Every tool step taken, in order (also delivered through `onStep`). */
131
- steps: string[];
132
- /** Which documents went in whole and which were searched. */
133
- plan: DocumentPlan;
134
- /** Model requests made for the chat itself, an explorer model's among them (whole-document part reads not included). */
135
- turns: number;
136
- finishReason?: string;
137
- /** Usage metadata of the last model response. */
138
- usage?: Record<string, unknown>;
139
- };
140
-
141
- type Body = {
142
- contents: GeminiContent[];
143
- systemInstruction?: { parts: Array<{ text: string }> };
144
- generationConfig?: Record<string, unknown>;
145
- tools?: unknown[];
146
- toolConfig?: unknown;
147
- };
148
-
149
- type Chunk = {
150
- candidates?: Array<{ finishReason?: string; content?: { parts?: GeminiPart[] } }>;
151
- usageMetadata?: Record<string, unknown>;
152
- promptFeedback?: { blockReason?: string };
153
- error?: { message?: string };
154
- };
155
-
156
- function toContents(options: AskGeminiOptions): GeminiContent[] {
157
- const contents: GeminiContent[] = options.contents
158
- ? options.contents.map((content) => ({ role: content.role, parts: [...content.parts] }))
159
- : (options.messages ?? []).map((turn) => ({ role: turn.role === "user" ? "user" : "model", parts: [{ text: turn.text }] }));
160
- if (contents.at(-1)?.role !== "user") throw new Error("The last message must be the user's.");
161
- return contents;
162
- }
163
-
164
- function baseSize(contents: GeminiContent[], system: string | undefined): { tokens: number; bytes: number } {
165
- let tokens = estimateTokens(system ?? "") + 2_000;
166
- let bytes = jsonBytes(system ?? "") + 8_000;
167
- for (const content of contents) {
168
- for (const part of content.parts) {
169
- if (typeof part.text === "string") {
170
- tokens += estimateTokens(part.text);
171
- bytes += jsonBytes(part.text);
172
- } else {
173
- const size = JSON.stringify(part).length;
174
- bytes += size;
175
- // Media: Gemini bills about 258 tokens per image or PDF page; ~4 tokens/KB is a cautious stand-in.
176
- tokens += Math.ceil(size / 256);
177
- }
178
- }
179
- }
180
- return { tokens, bytes };
181
- }
92
+ /** What `askWithFiles` returns. `usage` is summed over the whole question; Gemini's own `usageMetadata` of the last response is `lastUsage`. */
93
+ export type AskGeminiResult = AskResult;
182
94
 
183
95
  /**
184
- * A turn of an explorer model as the answering model gets it: the tool calls alone. A thought
185
- * signature belongs to the model that wrote it, and the explorer's thoughts and remarks are not
186
- * what the files say.
187
- */
188
- function callsOnly(content: GeminiContent): GeminiContent {
189
- if (content.role !== "model") return content;
190
- return { role: "model", parts: content.parts.flatMap((part) => (part.functionCall ? [{ functionCall: part.functionCall }] : [])) };
191
- }
192
-
193
- /**
194
- * Answers a chat turn about large documents with Gemini (Generate Content REST).
195
- * Documents that fit go into the prompt whole; otherwise Gemini gets search/read tools and this
196
- * runs the tool loop, ending with a tool-free turn so there is always an answer.
197
- * When the endpoint names an explorer model, that model runs the tool loop and the endpoint's own
198
- * model writes the answer, in the tool-free turn.
96
+ * Answers a chat turn about large documents with Gemini (Generate Content REST): `askWithFiles`
97
+ * with a `gemini()` model for the endpoint, and a second one for its explorer model when it names
98
+ * one. Documents that fit go into the prompt whole; otherwise Gemini gets search and read tools
99
+ * and the tool loop runs, ending with a request without tools so there is always an answer.
199
100
  */
200
101
  export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiResult> {
201
- const fetchImpl = options.fetch ?? fetch;
202
- const { files, endpoint, signal } = options;
102
+ const { endpoint } = options;
203
103
  // A second model for the requests that use tools. The answering model's own URL is not one.
204
104
  const explorerUrl = endpoint.explorerUrl && endpoint.explorerUrl !== endpoint.url ? endpoint.explorerUrl : undefined;
205
- const contents = toContents(options);
206
- const prepared = await files.prepare(options.documentIds, baseSize(contents, options.system), { owner: options.owner, viewPages: options.viewPages !== false });
207
- if (prepared.missing.length) throw new DocumentsNotFoundError(prepared.missing);
208
-
209
- const blocks = [...new Set(options.documentIds)].map((id) => prepared.blocks.get(id)).filter((block): block is string => Boolean(block));
210
- if (blocks.length) {
211
- const block = { text: blocks.join("\n\n") };
212
- if (options.documentPlacement === "last") contents.at(-1)!.parts.push(block);
213
- // The last turn is the user's, so there is always a first user turn.
214
- else contents.find((content) => content.role === "user")!.parts.unshift(block);
215
- }
216
- const system = [options.system?.trim(), prepared.instruction].filter(Boolean).join("\n\n");
217
- const body: Body = {
218
- contents,
219
- ...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}),
220
- ...(options.generationConfig ? { generationConfig: options.generationConfig } : {}),
221
- };
222
- const headers = await resolveHeaders(endpoint);
223
- const streaming = Boolean(options.onText && endpoint.streamUrl);
224
-
225
- let text = "";
226
- let turns = 0;
227
- let finishReason: string | undefined;
228
- let blockReason: string | undefined;
229
- let usage: Record<string, unknown> | undefined;
230
- const steps: string[] = [];
231
- const emit = (delta: string) => {
232
- text += delta;
233
- options.onText?.(delta);
234
- };
235
-
236
- /**
237
- * One model request. Text is emitted as it arrives; parts are kept as received.
238
- * `wroteText` says whether this request produced any text of its own.
239
- * Given `exploring`, the request is the explorer model's: that body goes to its URL, in one
240
- * piece, and what it writes is not emitted, because the answer comes from the other model.
241
- */
242
- const turn = async (exploring?: Body): Promise<{ parts: GeminiPart[]; calls: GeminiFunctionCall[]; wroteText: boolean }> => {
243
- turns++;
244
- const stream = streaming && !exploring;
245
- const response = await fetchImpl(exploring ? explorerUrl! : stream ? endpoint.streamUrl! : endpoint.url, {
246
- method: "POST",
247
- headers,
248
- body: JSON.stringify(exploring ?? body),
249
- signal,
250
- });
251
- if (!response.ok) {
252
- const data = await response.json().catch(() => null) as { error?: { message?: string } } | null;
253
- throw new GeminiRequestError(data?.error?.message ?? `Gemini returned HTTP ${response.status}.`, response.status);
254
- }
255
- const parts: GeminiPart[] = [];
256
- const calls: GeminiFunctionCall[] = [];
257
- let separated = text.length === 0;
258
- let wroteText = false;
259
- const take = (chunk: Chunk) => {
260
- if (chunk.error?.message) throw new GeminiRequestError(chunk.error.message, response.status);
261
- if (chunk.promptFeedback?.blockReason) blockReason = chunk.promptFeedback.blockReason;
262
- const candidate = chunk.candidates?.[0];
263
- for (const part of candidate?.content?.parts ?? []) {
264
- // Keep every part unchanged: Gemini 3 requires its thought signatures back.
265
- parts.push(part);
266
- if (typeof part.text === "string" && part.text && part.thought !== true) {
267
- if (!exploring) {
268
- if (!separated) {
269
- emit("\n\n");
270
- separated = true;
271
- }
272
- emit(part.text);
273
- }
274
- if (part.text.trim()) wroteText = true;
275
- }
276
- const call = part.functionCall as { name?: unknown; args?: unknown; id?: unknown } | undefined;
277
- if (call && typeof call.name === "string") {
278
- const args = call.args && typeof call.args === "object" && !Array.isArray(call.args) ? call.args as Record<string, unknown> : {};
279
- calls.push({ name: call.name, args, ...(typeof call.id === "string" ? { id: call.id } : {}) });
280
- }
281
- }
282
- finishReason = candidate?.finishReason ?? finishReason;
283
- usage = chunk.usageMetadata ?? usage;
284
- };
285
- if (stream) {
286
- if (!response.body) throw new GeminiRequestError("Gemini returned an empty stream.", response.status);
287
- for await (const chunk of parseSseJson<Chunk>(response.body)) take(chunk);
288
- } else {
289
- take(await response.json() as Chunk);
290
- }
291
- return { parts, calls, wroteText };
292
- };
293
-
294
- const result = (answered: boolean): AskGeminiResult => ({
295
- text,
296
- answered,
297
- ...(blockReason ? { blockReason } : {}),
298
- steps,
299
- plan: prepared.plan,
300
- turns,
301
- ...(finishReason ? { finishReason } : {}),
302
- ...(usage ? { usage } : {}),
303
- });
304
-
305
- // Tools are needed for a file that is too large to send whole, and for a PDF whose pages can be
306
- // looked at: that one may have its whole text in the prompt and still hide a chart from the model.
307
- const { searchable } = prepared.plan;
308
- const { viewable } = prepared;
309
- if (searchable.length === 0 && viewable.length === 0) return result((await turn()).wroteText);
310
-
311
- const tools = files.tools(searchable, {
312
- ...(options.wholeDocumentAnalysis === false ? {} : {
313
- // Reading a whole file in parts is exploring too: the explorer model's work, when there is one.
314
- generate: createGeminiGenerateText({ url: explorerUrl ?? endpoint.url, headers, fetchImpl, ...(options.analysisConfig ? { generationConfig: options.analysisConfig } : {}) }),
315
- }),
316
- onProgress: (event) => options.onActivity?.(`${event.message}…`),
317
- ...(signal ? { signal } : {}),
318
- ...(viewable.length > 0 ? { viewPages: viewable } : {}),
105
+ const shared = { toolFilePlacement: options.toolFilePlacement, analysisConfig: options.analysisConfig, fetch: options.fetch };
106
+ const model = gemini(endpoint, { ...shared, generationConfig: options.generationConfig });
107
+ // The explorer is called with the same headers, in one piece, with its own settings when it has any.
108
+ const explorer = explorerUrl
109
+ ? gemini({ url: explorerUrl, headers: endpoint.headers }, { ...shared, generationConfig: options.explorerGenerationConfig ?? options.generationConfig })
110
+ : undefined;
111
+ return askWithFiles({
112
+ files: options.files,
113
+ model,
114
+ explorer,
115
+ documentIds: options.documentIds,
116
+ ...(options.documentPlacement ? { documentPlacement: options.documentPlacement } : {}),
117
+ messages: options.contents ? fromGeminiContents(options.contents) : options.messages ?? [],
118
+ ...(options.system !== undefined ? { system: options.system } : {}),
119
+ ...(options.owner !== undefined ? { owner: options.owner } : {}),
120
+ limits: {
121
+ ...(options.maxToolTurns !== undefined ? { toolTurns: options.maxToolTurns } : {}),
122
+ ...(options.maxToolCallsPerTurn !== undefined ? { callsPerTurn: options.maxToolCallsPerTurn } : {}),
123
+ ...options.limits,
124
+ },
125
+ ...(options.retry ? { retry: options.retry } : {}),
126
+ ...(options.budget ? { budget: options.budget } : {}),
127
+ ...(options.wholeDocumentAnalysis !== undefined ? { wholeDocumentAnalysis: options.wholeDocumentAnalysis } : {}),
128
+ ...(options.viewPages !== undefined ? { viewPages: options.viewPages } : {}),
129
+ ...(options.onText ? { onText: options.onText } : {}),
130
+ ...(options.onActivity ? { onActivity: options.onActivity } : {}),
131
+ ...(options.onStep ? { onStep: options.onStep } : {}),
132
+ ...(options.signal ? { signal: options.signal } : {}),
319
133
  });
320
- // The request that uses the tools is the chat's own, or one for the explorer model: the same
321
- // conversation (`contents` is one array, so it grows in both), that model's settings, and a
322
- // line that says what its part is.
323
- const explorerConfig = options.explorerGenerationConfig ?? options.generationConfig;
324
- const exploring: Body | undefined = explorerUrl ? {
325
- contents,
326
- systemInstruction: { parts: [{ text: `${system}\n\n${EXPLORER_INSTRUCTION}` }] },
327
- ...(explorerConfig ? { generationConfig: explorerConfig } : {}),
328
- } : undefined;
329
- const withTools = exploring ?? body;
330
- withTools.tools = [{ functionDeclarations: tools.declarations }];
331
- withTools.toolConfig = { functionCallingConfig: { mode: "AUTO" } };
332
- // How many turns the conversation had as it was asked. What follows them is the tool loop's.
333
- const asked = contents.length;
334
- if (searchable.length > 0) options.onActivity?.(`Too large to read at once: ${searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
335
-
336
- // Pages the model looks at stay in the request until the question is answered, so they are
337
- // counted twice: as bytes against the request limit, and as tokens against half of what the
338
- // budget keeps free for tool results and the answer.
339
- const { maxRequestBytes, reservedTokens } = files.budget;
340
- const bytesKeptFree = Math.max(REQUEST_BYTES_MARGIN, Math.floor(maxRequestBytes / 10));
341
- let pagesLeft = Math.floor(reservedTokens / 2 / PAGE_TOKENS);
342
-
343
- const maxTurns = Math.max(1, options.maxToolTurns ?? 12);
344
- let answered = false;
345
- // Tools run in at most maxTurns - 1 requests. The last request is the tool-free one below, so a
346
- // model that never stops calling tools does not cost a request whose calls are thrown away.
347
- for (let round = 1; round < maxTurns; round++) {
348
- const { parts, calls, wroteText } = await turn(exploring);
349
- if (calls.length === 0) {
350
- // Text from this turn is the answer. A remark made earlier, before a tool call, is not.
351
- // Neither is anything an explorer model writes: the answer is asked for below.
352
- answered = wroteText && !exploring;
353
- break;
354
- }
355
- body.contents.push({ role: "model", parts });
356
- const responses: Array<{ call: GeminiFunctionCall; result: ToolResult; files: ToolFile[] }> = [];
357
- // The size of the request as it stands, worked out when the first look at pages in this turn needs it.
358
- let requestBytes: number | undefined;
359
- for (const call of calls) {
360
- const label = tools.has(call.name) ? tools.describe(call.name, call.args) : call.name;
361
- options.onActivity?.(`${label}…`);
362
- let limits: ToolFileLimits | undefined;
363
- if (call.name === TOOL_NAMES.view) {
364
- requestBytes ??= Buffer.byteLength(JSON.stringify(withTools));
365
- // Base64 turns three bytes into four characters.
366
- limits = { maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4), maxPages: pagesLeft };
367
- }
368
- const output = await tools.executeWithFiles(call.name, call.args, limits);
369
- for (const file of output.files) requestBytes = (requestBytes ?? 0) + Math.ceil(file.bytes.length / 3) * 4 + 512;
370
- if (output.files.length > 0) pagesLeft -= pagesShown(output.result);
371
- const step = `${label}${toolResultSummary(label, output.result)}`;
372
- steps.push(step);
373
- options.onStep?.(step);
374
- responses.push({ call, result: { ...output.result, tool_turns_left: maxTurns - round - 1 }, files: output.files });
375
- }
376
- body.contents.push(...geminiFunctionResponseTurns(responses, { files: options.toolFilePlacement ?? "inside" }) as GeminiContent[]);
377
- }
378
-
379
- // Out of tool turns, or the last turn had no text (cut off, or a malformed tool call): ask once
380
- // more with no tools declared at all. (Gemini can ignore functionCallingConfig mode NONE and
381
- // keep calling tools.) A blocked prompt would only be blocked again.
382
- // With an explorer model this request is always made: it is the one the answering model gets.
383
- if (!answered && !blockReason) {
384
- options.onActivity?.("Writing the answer…");
385
- delete body.tools;
386
- delete body.toolConfig;
387
- let request = searchable.length > 0 ? FINAL_ANSWER_REQUEST : FINAL_ANSWER_AFTER_PAGES;
388
- if (exploring) {
389
- // The answering model gets the explorer's calls and what they returned, and nothing else of
390
- // it. This request ends with a user message, as it must: a Gemini 3 model refuses a
391
- // function call without its own thought signature in the turn it is still answering.
392
- body.contents = [...contents.slice(0, asked), ...contents.slice(asked).map(callsOnly)];
393
- if (steps.length === 0) request = FINAL_ANSWER_WITHOUT_TOOLS;
394
- }
395
- body.contents.push({ role: "user", parts: [{ text: request }] });
396
- answered = (await turn()).wroteText;
397
- }
398
- return result(answered);
399
- }
400
-
401
- /** How many pages a `view_pages` result showed: its `pages` is "12" or "12-14". */
402
- function pagesShown(result: ToolResult): number {
403
- const [first, last] = String(result.pages ?? "").split("-").map(Number);
404
- return Number.isFinite(first) ? (Number.isFinite(last) ? last! - first! + 1 : 1) : 0;
405
134
  }
@@ -0,0 +1,15 @@
1
+ import { ModelRequestError } from "../model.js";
2
+
3
+ /** Gemini answered with an HTTP error, or could not be reached (`status` 0). */
4
+ export class GeminiRequestError extends ModelRequestError {
5
+ constructor(message: string, status: number, options: { retryAfterMs?: number; cause?: unknown } = {}) {
6
+ super(message, status, options);
7
+ this.name = "GeminiRequestError";
8
+ }
9
+ }
10
+
11
+ /** What to say of a request that never got an answer: the reason, without the stack of the HTTP client. */
12
+ export function unreachable(error: unknown): GeminiRequestError {
13
+ const reason = error instanceof Error && error.message ? ` (${error.message})` : "";
14
+ return new GeminiRequestError(`Gemini could not be reached${reason}.`, 0, { cause: error });
15
+ }
@@ -1,13 +1,17 @@
1
1
  // Gemini (Generate Content REST) helpers. No SDK dependency: the caller supplies the URL and
2
2
  // auth headers, so this works with the Gemini API, Vertex AI, or an enterprise gateway.
3
- import type { GenerateText, ToolDeclaration, ToolFile, ToolResult } from "../types.js";
3
+ import type { ToolAnswer, ToolCall } from "../model.js";
4
+ import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
5
+ import { retryAfterMs } from "../retry.js";
6
+ import type { GenerateText, GenerateUsage, ToolDeclaration, ToolFile, ToolResult } from "../types.js";
7
+ import { GeminiRequestError, unreachable } from "./errors.js";
4
8
 
5
9
  /** Gemini accepts this package's JSON Schema subset as-is. */
6
10
  export function toGeminiTools(declarations: ToolDeclaration[]): { functionDeclarations: ToolDeclaration[] } {
7
11
  return { functionDeclarations: declarations };
8
12
  }
9
13
 
10
- export type GeminiFunctionCall = { name: string; args: Record<string, unknown>; id?: string };
14
+ export type GeminiFunctionCall = ToolCall;
11
15
 
12
16
  /**
13
17
  * Where a file that a tool returned goes in the request:
@@ -20,7 +24,18 @@ export type GeminiFunctionCall = { name: string; args: Record<string, unknown>;
20
24
  export type GeminiToolFilePlacement = "inside" | "beside";
21
25
 
22
26
  /** A function call of the model with what the tool returned for it. */
23
- export type GeminiToolAnswer = { call: GeminiFunctionCall; result: ToolResult; files?: ToolFile[] };
27
+ export type GeminiToolAnswer = ToolAnswer;
28
+
29
+ /** Gemini's `usageMetadata` in the terms every adapter reports: thoughts are output, cached tokens are input. */
30
+ export function usageOfGemini(usage: Record<string, unknown> | undefined): GenerateUsage {
31
+ const number = (key: string) => (typeof usage?.[key] === "number" ? usage[key] as number : 0);
32
+ return {
33
+ inputTokens: number("promptTokenCount") + number("toolUsePromptTokenCount"),
34
+ cachedInputTokens: number("cachedContentTokenCount"),
35
+ outputTokens: number("candidatesTokenCount") + number("thoughtsTokenCount"),
36
+ thoughtTokens: number("thoughtsTokenCount"),
37
+ };
38
+ }
24
39
 
25
40
  type UserTurn = { role: "user"; parts: unknown[] };
26
41
 
@@ -73,43 +88,70 @@ export function geminiFunctionResponseTurns(calls: GeminiToolAnswer[], options:
73
88
  return [{ role: "user", parts: responses }, ...(files.length > 0 ? [{ role: "user" as const, parts: files }] : [])];
74
89
  }
75
90
 
91
+ export { THINKING_OUTPUT_TOKENS } from "../output-limit.js";
92
+
76
93
  /**
77
94
  * A `GenerateText` backed by a non-streaming `:generateContent` endpoint.
78
95
  * `generationConfig` lets the caller apply model-specific rules (thinking level, output floors).
96
+ *
97
+ * When a reply stops at the output limit with most of that limit spent on thoughts, the request
98
+ * is sent once more with `THINKING_OUTPUT_TOKENS`, and later requests to the same URL start there.
79
99
  */
80
100
  export function createGeminiGenerateText(options: {
81
101
  url: string;
82
- headers: Record<string, string>;
102
+ /** Request headers, or a function returning them. A function is called for every request: a whole-file read can outlast an access token. */
103
+ headers: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
83
104
  fetchImpl?: typeof fetch;
84
105
  generationConfig?: (maxOutputTokens: number) => Record<string, unknown>;
85
106
  timeoutMs?: number;
86
107
  }): GenerateText {
87
108
  const fetchImpl = options.fetchImpl ?? fetch;
88
- return async ({ system, prompt, maxOutputTokens, signal, onTruncated }) => {
89
- const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
90
- const response = await fetchImpl(options.url, {
91
- method: "POST",
92
- headers: options.headers,
93
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
94
- body: JSON.stringify({
95
- contents: [{ role: "user", parts: [{ text: prompt }] }],
96
- systemInstruction: { role: "system", parts: [{ text: system }] },
97
- generationConfig: options.generationConfig?.(maxOutputTokens) ?? { maxOutputTokens, temperature: 0.2 },
98
- }),
99
- });
100
- const data = await response.json().catch(() => null) as {
101
- error?: { message?: string };
102
- candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
103
- } | null;
104
- if (!response.ok) throw new Error(data?.error?.message ?? `The model returned HTTP ${response.status}.`);
105
- const candidate = data?.candidates?.[0];
106
- const text = (candidate?.content?.parts ?? [])
107
- .filter((part) => part.thought !== true && typeof part.text === "string")
108
- .map((part) => part.text as string)
109
- .join("");
110
- if (!text.trim()) throw new Error(`The model returned no text${candidate?.finishReason ? ` (${candidate.finishReason})` : ""}.`);
111
- // The text stops mid-list when the output limit is reached. Say so instead of passing it off as complete.
112
- if (candidate?.finishReason === "MAX_TOKENS") onTruncated?.();
113
- return text;
109
+ const { url } = options;
110
+ return async ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
111
+ /** One request with an output limit: the text of the reply, why it ended, and what it thought. */
112
+ const send = async (limit: number): Promise<LimitedReply> => {
113
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
114
+ const headers = typeof options.headers === "function" ? await options.headers() : options.headers;
115
+ let response: Response;
116
+ try {
117
+ response = await fetchImpl(url, {
118
+ method: "POST",
119
+ headers,
120
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
121
+ body: JSON.stringify({
122
+ contents: [{ role: "user", parts: [{ text: prompt }] }],
123
+ systemInstruction: { role: "system", parts: [{ text: system }] },
124
+ generationConfig: options.generationConfig?.(limit) ?? { maxOutputTokens: limit, temperature: 0.2 },
125
+ }),
126
+ });
127
+ } catch (error) {
128
+ // Stopped by the caller, or out of time: reported as it is. Anything else is a connection that failed.
129
+ if (signal?.aborted || timeout.aborted) throw error;
130
+ throw unreachable(error);
131
+ }
132
+ const data = await response.json().catch(() => null) as {
133
+ error?: { message?: string };
134
+ candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
135
+ usageMetadata?: Record<string, unknown>;
136
+ } | null;
137
+ if (!response.ok) {
138
+ const wait = retryAfterMs(response.headers, data);
139
+ throw new GeminiRequestError(data?.error?.message ?? `The model returned HTTP ${response.status}.`, response.status, wait === undefined ? {} : { retryAfterMs: wait });
140
+ }
141
+ onUsage?.(usageOfGemini(data?.usageMetadata));
142
+ const candidate = data?.candidates?.[0];
143
+ const text = (candidate?.content?.parts ?? [])
144
+ .filter((part) => part.thought !== true && typeof part.text === "string")
145
+ .map((part) => part.text as string)
146
+ .join("");
147
+ const thoughts = data?.usageMetadata?.thoughtsTokenCount;
148
+ return {
149
+ text,
150
+ cutOff: candidate?.finishReason === "MAX_TOKENS",
151
+ ...(candidate?.finishReason ? { reason: candidate.finishReason } : {}),
152
+ thoughts: typeof thoughts === "number" ? thoughts : 0,
153
+ };
154
+ };
155
+ return completeWithinLimit(url, maxOutputTokens, send, { signal, onTruncated });
114
156
  };
115
157
  }
@@ -1,7 +1,9 @@
1
1
  export { askGemini, DocumentsNotFoundError, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, GeminiRequestError } from "./chat.js";
2
2
  export type { AskGeminiOptions, AskGeminiResult, ChatTurn, GeminiContent, GeminiPart } from "./chat.js";
3
+ export { fromGeminiContents, gemini, GEMINI_PAGE_TOKENS, geminiToolTurns } from "./adapter.js";
4
+ export type { GeminiModelOptions } from "./adapter.js";
3
5
  export { geminiApi, vertexAi, vertexHost } from "./endpoints.js";
4
6
  export type { GeminiEndpoint } from "./endpoints.js";
5
- export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, toGeminiTools } from "./generate.js";
7
+ export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, THINKING_OUTPUT_TOKENS, toGeminiTools, usageOfGemini } from "./generate.js";
6
8
  export type { GeminiFunctionCall, GeminiToolAnswer, GeminiToolFilePlacement } from "./generate.js";
7
9
  export { parseSseJson } from "./sse.js";
package/src/gemini/sse.ts CHANGED
@@ -1,34 +1 @@
1
- /** Parses a `text/event-stream` body into JSON objects, one per `data:` event. */
2
- export async function* parseSseJson<T>(stream: ReadableStream<Uint8Array>): AsyncGenerator<T> {
3
- const reader = stream.getReader();
4
- const decoder = new TextDecoder();
5
- let buffer = "";
6
- const parse = (block: string): T | undefined => {
7
- const data = block
8
- .split("\n")
9
- .filter((line) => line.startsWith("data:"))
10
- .map((line) => line.slice(5).trimStart())
11
- .join("\n");
12
- return data && data !== "[DONE]" ? JSON.parse(data) as T : undefined;
13
- };
14
- try {
15
- while (true) {
16
- const { done, value } = await reader.read();
17
- buffer += decoder.decode(value, { stream: !done });
18
- buffer = buffer.replace(/\r\n/g, "\n");
19
- let boundary = buffer.indexOf("\n\n");
20
- while (boundary >= 0) {
21
- const event = parse(buffer.slice(0, boundary));
22
- buffer = buffer.slice(boundary + 2);
23
- if (event !== undefined) yield event;
24
- boundary = buffer.indexOf("\n\n");
25
- }
26
- if (done) break;
27
- }
28
- const last = buffer.trim() ? parse(buffer.trim()) : undefined;
29
- if (last !== undefined) yield last;
30
- } finally {
31
- await reader.cancel().catch(() => undefined);
32
- reader.releaseLock();
33
- }
34
- }
1
+ export { parseSseJson } from "../sse.js";