llm-large-files 0.2.0 → 0.3.5

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 (81) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +52 -6
  3. package/dist/extract.d.ts +13 -6
  4. package/dist/extract.d.ts.map +1 -1
  5. package/dist/extract.js +27 -6
  6. package/dist/extract.js.map +1 -1
  7. package/dist/gemini/chat.d.ts +48 -4
  8. package/dist/gemini/chat.d.ts.map +1 -1
  9. package/dist/gemini/chat.js +108 -24
  10. package/dist/gemini/chat.js.map +1 -1
  11. package/dist/gemini/endpoints.d.ts +17 -0
  12. package/dist/gemini/endpoints.d.ts.map +1 -1
  13. package/dist/gemini/endpoints.js +16 -2
  14. package/dist/gemini/endpoints.js.map +1 -1
  15. package/dist/gemini/generate.d.ts +34 -4
  16. package/dist/gemini/generate.d.ts.map +1 -1
  17. package/dist/gemini/generate.js +47 -7
  18. package/dist/gemini/generate.js.map +1 -1
  19. package/dist/gemini/index.d.ts +3 -3
  20. package/dist/gemini/index.d.ts.map +1 -1
  21. package/dist/gemini/index.js +2 -2
  22. package/dist/gemini/index.js.map +1 -1
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +1 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/library.d.ts +31 -1
  28. package/dist/library.d.ts.map +1 -1
  29. package/dist/library.js +44 -6
  30. package/dist/library.js.map +1 -1
  31. package/dist/pdf-layout.d.ts +7 -0
  32. package/dist/pdf-layout.d.ts.map +1 -1
  33. package/dist/pdf-layout.js +32 -2
  34. package/dist/pdf-layout.js.map +1 -1
  35. package/dist/pdf-pages.d.ts +45 -0
  36. package/dist/pdf-pages.d.ts.map +1 -0
  37. package/dist/pdf-pages.js +336 -0
  38. package/dist/pdf-pages.js.map +1 -0
  39. package/dist/pdf-pictures.d.ts +20 -0
  40. package/dist/pdf-pictures.d.ts.map +1 -0
  41. package/dist/pdf-pictures.js +336 -0
  42. package/dist/pdf-pictures.js.map +1 -0
  43. package/dist/plan.d.ts +13 -3
  44. package/dist/plan.d.ts.map +1 -1
  45. package/dist/plan.js +22 -17
  46. package/dist/plan.js.map +1 -1
  47. package/dist/search.d.ts +9 -0
  48. package/dist/search.d.ts.map +1 -1
  49. package/dist/search.js +41 -0
  50. package/dist/search.js.map +1 -1
  51. package/dist/stores.d.ts +7 -1
  52. package/dist/stores.d.ts.map +1 -1
  53. package/dist/stores.js +37 -5
  54. package/dist/stores.js.map +1 -1
  55. package/dist/tools.d.ts +11 -0
  56. package/dist/tools.d.ts.map +1 -1
  57. package/dist/tools.js +145 -13
  58. package/dist/tools.js.map +1 -1
  59. package/dist/types.d.ts +57 -3
  60. package/dist/types.d.ts.map +1 -1
  61. package/docs/api.md +59 -17
  62. package/docs/configuration.md +351 -5
  63. package/docs/getting-started.md +50 -3
  64. package/docs/how-it-works.md +73 -4
  65. package/docs/security.md +39 -4
  66. package/package.json +7 -2
  67. package/src/extract.ts +34 -8
  68. package/src/gemini/chat.ts +145 -30
  69. package/src/gemini/endpoints.ts +34 -2
  70. package/src/gemini/generate.ts +63 -9
  71. package/src/gemini/index.ts +3 -3
  72. package/src/index.ts +2 -2
  73. package/src/library.ts +74 -7
  74. package/src/pdf-layout.ts +37 -1
  75. package/src/pdf-pages.ts +315 -0
  76. package/src/pdf-pictures.ts +324 -0
  77. package/src/plan.ts +36 -16
  78. package/src/search.ts +37 -0
  79. package/src/stores.ts +39 -6
  80. package/src/tools.ts +147 -13
  81. package/src/types.ts +57 -3
@@ -1,9 +1,10 @@
1
1
  import type { LargeFiles } from "../library.js";
2
+ import { REQUEST_BYTES_MARGIN } from "../plan.js";
2
3
  import { estimateTokens, jsonBytes } from "../text.js";
3
- import { toolResultSummary } from "../tools.js";
4
- import type { DocumentPlan, ToolResult } from "../types.js";
4
+ import { TOOL_NAMES, toolResultSummary } from "../tools.js";
5
+ import type { DocumentPlan, ToolFile, ToolFileLimits, ToolResult } from "../types.js";
5
6
  import { resolveHeaders, type GeminiEndpoint } from "./endpoints.js";
6
- import { createGeminiGenerateText, geminiFunctionResponses, type GeminiFunctionCall } from "./generate.js";
7
+ import { createGeminiGenerateText, geminiFunctionResponseTurns, type GeminiFunctionCall, type GeminiToolFilePlacement } from "./generate.js";
7
8
  import { parseSseJson } from "./sse.js";
8
9
 
9
10
  export type GeminiPart = Record<string, unknown>;
@@ -13,6 +14,18 @@ export type ChatTurn = { role: "user" | "model" | "assistant"; text: string };
13
14
 
14
15
  /** Sent (invisibly to the user) when the model must stop using tools and answer. */
15
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;
16
29
 
17
30
  /** Some document IDs were never uploaded, have expired, or belong to another owner. */
18
31
  export class DocumentsNotFoundError extends Error {
@@ -32,6 +45,12 @@ export class GeminiRequestError extends Error {
32
45
 
33
46
  export type AskGeminiOptions = {
34
47
  files: LargeFiles;
48
+ /**
49
+ * Where the model is: the one that answers. When the endpoint also names an explorer model
50
+ * (`explorerModel` in `geminiApi()` and `vertexAi()`, or `explorerUrl`), that model makes the
51
+ * tool calls and reads a whole file in parts, and this one writes the answer from what the
52
+ * tools returned. Without an explorer, one model does both.
53
+ */
35
54
  endpoint: GeminiEndpoint;
36
55
  /** Documents this conversation may use. Where their text or cards go: see `documentPlacement`. */
37
56
  documentIds: string[];
@@ -49,17 +68,40 @@ export type AskGeminiOptions = {
49
68
  system?: string;
50
69
  /** Sent with every chat request: temperature, maxOutputTokens, thinkingConfig, and so on. */
51
70
  generationConfig?: Record<string, unknown>;
71
+ /**
72
+ * The same, for the requests of an explorer model. Defaults to `generationConfig`. Set it when
73
+ * the two models do not take the same settings: a thinking level that one of them refuses, for
74
+ * example. It is not used without an explorer model.
75
+ */
76
+ explorerGenerationConfig?: Record<string, unknown>;
52
77
  /** The user asking. Documents ingested with a different owner are treated as missing. */
53
78
  owner?: string;
54
79
  /**
55
80
  * The most model requests for one question, counting the answer. Tools can run in all but the
56
81
  * last: if the model is still calling tools then, the last request is sent with no tools so it
57
- * must answer. Defaults to 12.
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.
58
84
  */
59
85
  maxToolTurns?: number;
60
86
  /** Offer `analyze_whole_document`, which reads a whole file in many model calls. Defaults to true. */
61
87
  wholeDocumentAnalysis?: boolean;
62
- /** generationConfig for whole-document part reads. Defaults to `{ temperature: 0.2, maxOutputTokens }`. */
88
+ /**
89
+ * Offer `view_pages` for PDFs whose original file is kept (`keepOriginals`), so the model can
90
+ * look at pictures, charts and layout. Defaults to true. It changes nothing for a library that
91
+ * keeps no originals.
92
+ */
93
+ viewPages?: boolean;
94
+ /**
95
+ * Where the pages go in the request. "inside" (the default) puts the PDF in the function
96
+ * response itself, which Gemini 3 models read. "beside" sends it in a user turn of its own,
97
+ * after the function responses: use it for Gemini 2.5, which does not see a file inside a
98
+ * function response.
99
+ */
100
+ toolFilePlacement?: GeminiToolFilePlacement;
101
+ /**
102
+ * generationConfig for whole-document part reads. Defaults to `{ temperature: 0.2, maxOutputTokens }`.
103
+ * The parts are read by the explorer model when there is one, so write it for that model.
104
+ */
63
105
  analysisConfig?: (maxOutputTokens: number) => Record<string, unknown>;
64
106
  /** Answer text as it streams. Streaming is used when this is set and the endpoint has `streamUrl`. */
65
107
  onText?: (delta: string) => void;
@@ -72,7 +114,10 @@ export type AskGeminiOptions = {
72
114
  };
73
115
 
74
116
  export type AskGeminiResult = {
75
- /** Everything the model wrote, including any remark it made before calling a tool. */
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
+ */
76
121
  text: string;
77
122
  /**
78
123
  * False when the model's last turn had no text: the prompt was blocked, the reply was cut off
@@ -86,7 +131,7 @@ export type AskGeminiResult = {
86
131
  steps: string[];
87
132
  /** Which documents went in whole and which were searched. */
88
133
  plan: DocumentPlan;
89
- /** Model requests made for the chat itself (whole-document part reads not included). */
134
+ /** Model requests made for the chat itself, an explorer model's among them (whole-document part reads not included). */
90
135
  turns: number;
91
136
  finishReason?: string;
92
137
  /** Usage metadata of the last model response. */
@@ -135,16 +180,30 @@ function baseSize(contents: GeminiContent[], system: string | undefined): { toke
135
180
  return { tokens, bytes };
136
181
  }
137
182
 
183
+ /**
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
+
138
193
  /**
139
194
  * Answers a chat turn about large documents with Gemini (Generate Content REST).
140
195
  * Documents that fit go into the prompt whole; otherwise Gemini gets search/read tools and this
141
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.
142
199
  */
143
200
  export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiResult> {
144
201
  const fetchImpl = options.fetch ?? fetch;
145
202
  const { files, endpoint, signal } = options;
203
+ // A second model for the requests that use tools. The answering model's own URL is not one.
204
+ const explorerUrl = endpoint.explorerUrl && endpoint.explorerUrl !== endpoint.url ? endpoint.explorerUrl : undefined;
146
205
  const contents = toContents(options);
147
- const prepared = await files.prepare(options.documentIds, baseSize(contents, options.system), { owner: options.owner });
206
+ const prepared = await files.prepare(options.documentIds, baseSize(contents, options.system), { owner: options.owner, viewPages: options.viewPages !== false });
148
207
  if (prepared.missing.length) throw new DocumentsNotFoundError(prepared.missing);
149
208
 
150
209
  const blocks = [...new Set(options.documentIds)].map((id) => prepared.blocks.get(id)).filter((block): block is string => Boolean(block));
@@ -177,13 +236,16 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
177
236
  /**
178
237
  * One model request. Text is emitted as it arrives; parts are kept as received.
179
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.
180
241
  */
181
- const turn = async (): Promise<{ parts: GeminiPart[]; calls: GeminiFunctionCall[]; wroteText: boolean }> => {
242
+ const turn = async (exploring?: Body): Promise<{ parts: GeminiPart[]; calls: GeminiFunctionCall[]; wroteText: boolean }> => {
182
243
  turns++;
183
- const response = await fetchImpl(streaming ? endpoint.streamUrl! : endpoint.url, {
244
+ const stream = streaming && !exploring;
245
+ const response = await fetchImpl(exploring ? explorerUrl! : stream ? endpoint.streamUrl! : endpoint.url, {
184
246
  method: "POST",
185
247
  headers,
186
- body: JSON.stringify(body),
248
+ body: JSON.stringify(exploring ?? body),
187
249
  signal,
188
250
  });
189
251
  if (!response.ok) {
@@ -202,11 +264,13 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
202
264
  // Keep every part unchanged: Gemini 3 requires its thought signatures back.
203
265
  parts.push(part);
204
266
  if (typeof part.text === "string" && part.text && part.thought !== true) {
205
- if (!separated) {
206
- emit("\n\n");
207
- separated = true;
267
+ if (!exploring) {
268
+ if (!separated) {
269
+ emit("\n\n");
270
+ separated = true;
271
+ }
272
+ emit(part.text);
208
273
  }
209
- emit(part.text);
210
274
  if (part.text.trim()) wroteText = true;
211
275
  }
212
276
  const call = part.functionCall as { name?: unknown; args?: unknown; id?: unknown } | undefined;
@@ -218,7 +282,7 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
218
282
  finishReason = candidate?.finishReason ?? finishReason;
219
283
  usage = chunk.usageMetadata ?? usage;
220
284
  };
221
- if (streaming) {
285
+ if (stream) {
222
286
  if (!response.body) throw new GeminiRequestError("Gemini returned an empty stream.", response.status);
223
287
  for await (const chunk of parseSseJson<Chunk>(response.body)) take(chunk);
224
288
  } else {
@@ -238,53 +302,104 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
238
302
  ...(usage ? { usage } : {}),
239
303
  });
240
304
 
241
- if (prepared.plan.searchable.length === 0) return result((await turn()).wroteText);
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);
242
310
 
243
- const tools = files.tools(prepared.plan.searchable, {
311
+ const tools = files.tools(searchable, {
244
312
  ...(options.wholeDocumentAnalysis === false ? {} : {
245
- generate: createGeminiGenerateText({ url: endpoint.url, headers, fetchImpl, ...(options.analysisConfig ? { generationConfig: options.analysisConfig } : {}) }),
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 } : {}) }),
246
315
  }),
247
316
  onProgress: (event) => options.onActivity?.(`${event.message}…`),
248
317
  ...(signal ? { signal } : {}),
318
+ ...(viewable.length > 0 ? { viewPages: viewable } : {}),
249
319
  });
250
- body.tools = [{ functionDeclarations: tools.declarations }];
251
- body.toolConfig = { functionCallingConfig: { mode: "AUTO" } };
252
- options.onActivity?.(`Too large to read at once: ${prepared.plan.searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
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);
253
342
 
254
343
  const maxTurns = Math.max(1, options.maxToolTurns ?? 12);
255
344
  let answered = false;
256
345
  // Tools run in at most maxTurns - 1 requests. The last request is the tool-free one below, so a
257
346
  // model that never stops calling tools does not cost a request whose calls are thrown away.
258
347
  for (let round = 1; round < maxTurns; round++) {
259
- const { parts, calls, wroteText } = await turn();
348
+ const { parts, calls, wroteText } = await turn(exploring);
260
349
  if (calls.length === 0) {
261
350
  // Text from this turn is the answer. A remark made earlier, before a tool call, is not.
262
- answered = wroteText;
351
+ // Neither is anything an explorer model writes: the answer is asked for below.
352
+ answered = wroteText && !exploring;
263
353
  break;
264
354
  }
265
355
  body.contents.push({ role: "model", parts });
266
- const responses: Array<{ call: GeminiFunctionCall; result: ToolResult }> = [];
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;
267
359
  for (const call of calls) {
268
360
  const label = tools.has(call.name) ? tools.describe(call.name, call.args) : call.name;
269
361
  options.onActivity?.(`${label}…`);
270
- const output = await tools.execute(call.name, call.args);
271
- const step = `${label}${toolResultSummary(label, output)}`;
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)}`;
272
372
  steps.push(step);
273
373
  options.onStep?.(step);
274
- responses.push({ call, result: { ...output, tool_turns_left: maxTurns - round - 1 } });
374
+ responses.push({ call, result: { ...output.result, tool_turns_left: maxTurns - round - 1 }, files: output.files });
275
375
  }
276
- body.contents.push(geminiFunctionResponses(responses) as GeminiContent);
376
+ body.contents.push(...geminiFunctionResponseTurns(responses, { files: options.toolFilePlacement ?? "inside" }) as GeminiContent[]);
277
377
  }
278
378
 
279
379
  // Out of tool turns, or the last turn had no text (cut off, or a malformed tool call): ask once
280
380
  // more with no tools declared at all. (Gemini can ignore functionCallingConfig mode NONE and
281
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.
282
383
  if (!answered && !blockReason) {
283
384
  options.onActivity?.("Writing the answer…");
284
385
  delete body.tools;
285
386
  delete body.toolConfig;
286
- body.contents.push({ role: "user", parts: [{ text: FINAL_ANSWER_REQUEST }] });
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 }] });
287
396
  answered = (await turn()).wroteText;
288
397
  }
289
398
  return result(answered);
290
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
+ }
@@ -9,22 +9,48 @@ export type GeminiEndpoint = {
9
9
  streamUrl?: string;
10
10
  /** Request headers, or a function returning them (for short-lived access tokens). */
11
11
  headers: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
12
+ /**
13
+ * The non-streaming `...:generateContent` URL of a second model, the explorer. `askGemini` then
14
+ * sends it the requests that search, read and look at pages, and the model of `url` only writes
15
+ * the answer. It is called with the same headers. `geminiApi()` and `vertexAi()` set it from
16
+ * `explorerModel`. Unset, or the same as `url`, one model does both.
17
+ */
18
+ explorerUrl?: string | undefined;
12
19
  };
13
20
 
21
+ /**
22
+ * The model that explores the documents, when one is named and it is not the answering model
23
+ * itself. An empty name is no name, so a setting that was left empty can be passed as it is.
24
+ */
25
+ function explorerOf(options: { model: string; explorerModel?: string | undefined }): string | undefined {
26
+ const name = options.explorerModel?.trim();
27
+ return name && name !== options.model ? name : undefined;
28
+ }
29
+
14
30
  /** The Gemini Developer API with an API key. */
15
31
  export function geminiApi(options: {
16
32
  apiKey: string;
33
+ /** The model that answers. Without `explorerModel` it also searches and reads the documents. */
17
34
  model: string;
35
+ /**
36
+ * A second model that explores the documents: it makes the tool calls (search, read, look at
37
+ * pages) and reads a whole file in parts, and `model` then writes the answer from what it found.
38
+ * Leave it out or empty to have `model` do both.
39
+ */
40
+ explorerModel?: string | undefined;
18
41
  /** Defaults to "v1beta". */
19
42
  apiVersion?: string;
20
43
  /** Defaults to https://generativelanguage.googleapis.com. */
21
44
  baseUrl?: string;
22
45
  }): GeminiEndpoint {
23
- const base = `${(options.baseUrl ?? "https://generativelanguage.googleapis.com").replace(/\/+$/, "")}/${options.apiVersion ?? "v1beta"}/models/${encodeURIComponent(options.model)}`;
46
+ const models = `${(options.baseUrl ?? "https://generativelanguage.googleapis.com").replace(/\/+$/, "")}/${options.apiVersion ?? "v1beta"}/models/`;
47
+ const base = `${models}${encodeURIComponent(options.model)}`;
48
+ const explorer = explorerOf(options);
24
49
  return {
25
50
  url: `${base}:generateContent`,
26
51
  streamUrl: `${base}:streamGenerateContent?alt=sse`,
27
52
  headers: { "Content-Type": "application/json", "x-goog-api-key": options.apiKey },
53
+ ...(explorer ? { explorerUrl: `${models}${encodeURIComponent(explorer)}:generateContent` } : {}),
28
54
  };
29
55
  }
30
56
 
@@ -38,7 +64,10 @@ export function vertexHost(location: string): string {
38
64
  /** Vertex AI with an OAuth access token (for example from google-auth-library). */
39
65
  export function vertexAi(options: {
40
66
  project: string;
67
+ /** The model that answers. Without `explorerModel` it also searches and reads the documents. */
41
68
  model: string;
69
+ /** A second model that explores the documents, as in `geminiApi()`. Leave it out or empty for one model. */
70
+ explorerModel?: string | undefined;
42
71
  /** Defaults to "global". */
43
72
  location?: string;
44
73
  /** A token, or a function that returns a fresh one for each request. */
@@ -47,7 +76,9 @@ export function vertexAi(options: {
47
76
  apiVersion?: string;
48
77
  }): GeminiEndpoint {
49
78
  const location = options.location ?? "global";
50
- const base = `${vertexHost(location)}/${options.apiVersion ?? "v1"}/projects/${encodeURIComponent(options.project)}/locations/${location}/publishers/google/models/${encodeURIComponent(options.model)}`;
79
+ const models = `${vertexHost(location)}/${options.apiVersion ?? "v1"}/projects/${encodeURIComponent(options.project)}/locations/${location}/publishers/google/models/`;
80
+ const base = `${models}${encodeURIComponent(options.model)}`;
81
+ const explorer = explorerOf(options);
51
82
  const token = options.accessToken;
52
83
  return {
53
84
  url: `${base}:generateContent`,
@@ -56,6 +87,7 @@ export function vertexAi(options: {
56
87
  "Content-Type": "application/json",
57
88
  Authorization: `Bearer ${typeof token === "function" ? await token() : token}`,
58
89
  }),
90
+ ...(explorer ? { explorerUrl: `${models}${encodeURIComponent(explorer)}:generateContent` } : {}),
59
91
  };
60
92
  }
61
93
 
@@ -1,6 +1,6 @@
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, ToolResult } from "../types.js";
3
+ import type { GenerateText, ToolDeclaration, ToolFile, ToolResult } from "../types.js";
4
4
 
5
5
  /** Gemini accepts this package's JSON Schema subset as-is. */
6
6
  export function toGeminiTools(declarations: ToolDeclaration[]): { functionDeclarations: ToolDeclaration[] } {
@@ -9,14 +9,68 @@ export function toGeminiTools(declarations: ToolDeclaration[]): { functionDeclar
9
9
 
10
10
  export type GeminiFunctionCall = { name: string; args: Record<string, unknown>; id?: string };
11
11
 
12
- /** The `user` turn that answers a model turn's function calls, in call order. */
13
- export function geminiFunctionResponses(calls: Array<{ call: GeminiFunctionCall; result: ToolResult }>): { role: "user"; parts: unknown[] } {
14
- return {
15
- role: "user",
16
- parts: calls.map(({ call, result }) => ({
17
- functionResponse: { name: call.name, ...(call.id ? { id: call.id } : {}), response: result },
18
- })),
19
- };
12
+ /**
13
+ * Where a file that a tool returned goes in the request:
14
+ * - "inside": in the `parts` of its function response, which names it with `{ "$ref": name }`
15
+ * (Gemini 3 multimodal function responses). Gemini 2.5 accepts that form and does not see the
16
+ * file.
17
+ * - "beside": in a `user` turn of its own, after the turn of function responses, for a model that
18
+ * does not read a file inside a function response.
19
+ */
20
+ export type GeminiToolFilePlacement = "inside" | "beside";
21
+
22
+ /** A function call of the model with what the tool returned for it. */
23
+ export type GeminiToolAnswer = { call: GeminiFunctionCall; result: ToolResult; files?: ToolFile[] };
24
+
25
+ type UserTurn = { role: "user"; parts: unknown[] };
26
+
27
+ const base64 = (bytes: Uint8Array) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
28
+
29
+ /** One function response, with `files` inside it. */
30
+ function functionResponse(call: GeminiFunctionCall, result: ToolResult, files: ToolFile[]): unknown {
31
+ let response = result;
32
+ const parts: unknown[] = [];
33
+ if (files.length > 0) {
34
+ // The result names its file ("file": "pages-2-3.pdf"); that becomes the reference Gemini resolves.
35
+ response = { ...result };
36
+ const unnamed: Array<{ $ref: string }> = [];
37
+ for (const file of files) {
38
+ const named = Object.keys(response).find((key) => response[key] === file.name);
39
+ if (named) response[named] = { $ref: file.name };
40
+ else unnamed.push({ $ref: file.name });
41
+ parts.push({ inlineData: { mimeType: file.mimeType, displayName: file.name, data: base64(file.bytes) } });
42
+ }
43
+ if (unnamed.length > 0) response.files = unnamed;
44
+ }
45
+ return { functionResponse: { name: call.name, ...(call.id ? { id: call.id } : {}), response, ...(parts.length > 0 ? { parts } : {}) } };
46
+ }
47
+
48
+ /**
49
+ * The `user` turn that answers a model turn's function calls, in call order. A file that a tool
50
+ * returned (`executeWithFiles`) goes inside its function response, as base64 `inlineData`. To send
51
+ * files beside the function responses instead, use `geminiFunctionResponseTurns`.
52
+ */
53
+ export function geminiFunctionResponses(calls: GeminiToolAnswer[]): UserTurn {
54
+ return { role: "user", parts: calls.map(({ call, result, files = [] }) => functionResponse(call, result, files)) };
55
+ }
56
+
57
+ /**
58
+ * The turns that answer a model turn's function calls: add them all to `contents`, in order.
59
+ * With files "inside" (the default) that is the one turn of `geminiFunctionResponses`. With files
60
+ * "beside", the function responses carry no file and a second `user` turn holds the files, each
61
+ * after a line that names it and the tool it came from.
62
+ *
63
+ * The files get a turn of their own because Vertex AI refuses a turn in which anything follows a
64
+ * function response (HTTP 400 for Gemini 3 models, November 2026).
65
+ */
66
+ export function geminiFunctionResponseTurns(calls: GeminiToolAnswer[], options: { files?: GeminiToolFilePlacement } = {}): UserTurn[] {
67
+ if (options.files !== "beside") return [geminiFunctionResponses(calls)];
68
+ const responses = calls.map(({ call, result }) => functionResponse(call, result, []));
69
+ const files = calls.flatMap(({ call, files: returned = [] }) => returned.flatMap((file) => [
70
+ { text: `${file.name} (returned by ${call.name}):` },
71
+ { inlineData: { mimeType: file.mimeType, data: base64(file.bytes) } },
72
+ ]));
73
+ return [{ role: "user", parts: responses }, ...(files.length > 0 ? [{ role: "user" as const, parts: files }] : [])];
20
74
  }
21
75
 
22
76
  /**
@@ -1,7 +1,7 @@
1
- export { askGemini, DocumentsNotFoundError, FINAL_ANSWER_REQUEST, GeminiRequestError } from "./chat.js";
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
3
  export { geminiApi, vertexAi, vertexHost } from "./endpoints.js";
4
4
  export type { GeminiEndpoint } from "./endpoints.js";
5
- export { createGeminiGenerateText, geminiFunctionResponses, toGeminiTools } from "./generate.js";
6
- export type { GeminiFunctionCall } from "./generate.js";
5
+ export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, toGeminiTools } from "./generate.js";
6
+ export type { GeminiFunctionCall, GeminiToolAnswer, GeminiToolFilePlacement } from "./generate.js";
7
7
  export { parseSseJson } from "./sse.js";
package/src/index.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  // Core: provider-neutral. Gemini helpers live in "llm-large-files/gemini",
2
2
  // Node HTTP handlers in "llm-large-files/node".
3
3
  export { createLargeFiles, DEFAULT_BUDGET, isDocumentId, toDocumentSummary } from "./library.js";
4
- export type { AccessOptions, IngestInput, LargeFiles, LargeFilesOptions, ToolOptions } from "./library.js";
4
+ export type { AccessOptions, IngestInput, LargeFiles, LargeFilesOptions, PrepareOptions, ToolOptions } from "./library.js";
5
5
  export { FileDocumentStore, MemoryDocumentStore, DOCUMENT_ID_PATTERN } from "./stores.js";
6
6
  export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";
7
7
  export type { PdfExtractorOptions } from "./extract.js";
8
8
  export { estimateTokens, utf8Bytes, jsonBytes } from "./text.js";
9
- export { TOOL_NAMES, toolResultSummary } from "./tools.js";
9
+ export { MAX_VIEW_PAGES, TOOL_NAMES, toolResultSummary } from "./tools.js";
10
10
  export type * from "./types.js";