llm-large-files 0.1.0 → 0.3.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 (91) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +32 -6
  3. package/dist/analyze.d.ts.map +1 -1
  4. package/dist/analyze.js +5 -1
  5. package/dist/analyze.js.map +1 -1
  6. package/dist/extract.d.ts +30 -7
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +94 -23
  9. package/dist/extract.js.map +1 -1
  10. package/dist/gemini/chat.d.ts +38 -2
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +83 -32
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts +34 -4
  15. package/dist/gemini/generate.d.ts.map +1 -1
  16. package/dist/gemini/generate.js +51 -8
  17. package/dist/gemini/generate.js.map +1 -1
  18. package/dist/gemini/index.d.ts +3 -3
  19. package/dist/gemini/index.d.ts.map +1 -1
  20. package/dist/gemini/index.js +2 -2
  21. package/dist/gemini/index.js.map +1 -1
  22. package/dist/index.d.ts +4 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/library.d.ts +37 -1
  27. package/dist/library.d.ts.map +1 -1
  28. package/dist/library.js +59 -7
  29. package/dist/library.js.map +1 -1
  30. package/dist/map-reduce.d.ts +7 -0
  31. package/dist/map-reduce.d.ts.map +1 -1
  32. package/dist/map-reduce.js +58 -16
  33. package/dist/map-reduce.js.map +1 -1
  34. package/dist/pdf-layout.d.ts +39 -0
  35. package/dist/pdf-layout.d.ts.map +1 -0
  36. package/dist/pdf-layout.js +820 -0
  37. package/dist/pdf-layout.js.map +1 -0
  38. package/dist/pdf-pages.d.ts +45 -0
  39. package/dist/pdf-pages.d.ts.map +1 -0
  40. package/dist/pdf-pages.js +336 -0
  41. package/dist/pdf-pages.js.map +1 -0
  42. package/dist/pdf-pictures.d.ts +20 -0
  43. package/dist/pdf-pictures.d.ts.map +1 -0
  44. package/dist/pdf-pictures.js +336 -0
  45. package/dist/pdf-pictures.js.map +1 -0
  46. package/dist/plan.d.ts +13 -3
  47. package/dist/plan.d.ts.map +1 -1
  48. package/dist/plan.js +27 -18
  49. package/dist/plan.js.map +1 -1
  50. package/dist/search.d.ts +17 -4
  51. package/dist/search.d.ts.map +1 -1
  52. package/dist/search.js +90 -24
  53. package/dist/search.js.map +1 -1
  54. package/dist/stores.d.ts +7 -1
  55. package/dist/stores.d.ts.map +1 -1
  56. package/dist/stores.js +37 -5
  57. package/dist/stores.js.map +1 -1
  58. package/dist/text.d.ts +18 -4
  59. package/dist/text.d.ts.map +1 -1
  60. package/dist/text.js +155 -15
  61. package/dist/text.js.map +1 -1
  62. package/dist/tools.d.ts +11 -0
  63. package/dist/tools.d.ts.map +1 -1
  64. package/dist/tools.js +156 -16
  65. package/dist/tools.js.map +1 -1
  66. package/dist/types.d.ts +63 -3
  67. package/dist/types.d.ts.map +1 -1
  68. package/docs/api.md +56 -11
  69. package/docs/configuration.md +298 -6
  70. package/docs/getting-started.md +41 -7
  71. package/docs/how-it-works.md +77 -11
  72. package/docs/security.md +54 -6
  73. package/package.json +96 -91
  74. package/src/analyze.ts +3 -1
  75. package/src/extract.ts +105 -24
  76. package/src/gemini/chat.ts +116 -34
  77. package/src/gemini/generate.ts +66 -10
  78. package/src/gemini/index.ts +3 -3
  79. package/src/index.ts +4 -3
  80. package/src/library.ts +308 -226
  81. package/src/map-reduce.ts +69 -16
  82. package/src/node/handlers.ts +122 -122
  83. package/src/pdf-layout.ts +807 -0
  84. package/src/pdf-pages.ts +315 -0
  85. package/src/pdf-pictures.ts +324 -0
  86. package/src/plan.ts +120 -98
  87. package/src/search.ts +85 -25
  88. package/src/stores.ts +165 -132
  89. package/src/text.ts +131 -14
  90. package/src/tools.ts +408 -264
  91. package/src/types.ts +228 -168
@@ -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,11 @@ 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
+
20
+ /** What Gemini bills for one PDF page it is shown (measured: 520 to 532). */
21
+ const PAGE_TOKENS = 530;
16
22
 
17
23
  /** Some document IDs were never uploaded, have expired, or belong to another owner. */
18
24
  export class DocumentsNotFoundError extends Error {
@@ -33,8 +39,15 @@ export class GeminiRequestError extends Error {
33
39
  export type AskGeminiOptions = {
34
40
  files: LargeFiles;
35
41
  endpoint: GeminiEndpoint;
36
- /** Documents this conversation may use. Their text or cards are added to the last user turn. */
42
+ /** Documents this conversation may use. Where their text or cards go: see `documentPlacement`. */
37
43
  documentIds: string[];
44
+ /**
45
+ * Where document text and cards are added. "first" (the default) puts them at the start of the
46
+ * first user turn, where they stay as the conversation grows, so Gemini's prompt cache can
47
+ * reuse them on every follow-up question. "last" appends them to the latest user turn, as 0.1.0
48
+ * did; the document then moves on every turn and is billed in full each time.
49
+ */
50
+ documentPlacement?: "first" | "last";
38
51
  /** Plain chat history; the last turn must be the user's question. Use this or `contents`. */
39
52
  messages?: ChatTurn[];
40
53
  /** Your own Gemini `contents` (with images, inline PDFs, etc.). The last turn must be the user's. */
@@ -44,10 +57,27 @@ export type AskGeminiOptions = {
44
57
  generationConfig?: Record<string, unknown>;
45
58
  /** The user asking. Documents ingested with a different owner are treated as missing. */
46
59
  owner?: string;
47
- /** Model turns that may call tools before a final, tool-free turn. Defaults to 12. */
60
+ /**
61
+ * The most model requests for one question, counting the answer. Tools can run in all but the
62
+ * last: if the model is still calling tools then, the last request is sent with no tools so it
63
+ * must answer. Defaults to 12.
64
+ */
48
65
  maxToolTurns?: number;
49
66
  /** Offer `analyze_whole_document`, which reads a whole file in many model calls. Defaults to true. */
50
67
  wholeDocumentAnalysis?: boolean;
68
+ /**
69
+ * Offer `view_pages` for PDFs whose original file is kept (`keepOriginals`), so the model can
70
+ * look at pictures, charts and layout. Defaults to true. It changes nothing for a library that
71
+ * keeps no originals.
72
+ */
73
+ viewPages?: boolean;
74
+ /**
75
+ * Where the pages go in the request. "inside" (the default) puts the PDF in the function
76
+ * response itself, which Gemini 3 models read. "beside" sends it in a user turn of its own,
77
+ * after the function responses: use it for Gemini 2.5, which does not see a file inside a
78
+ * function response.
79
+ */
80
+ toolFilePlacement?: GeminiToolFilePlacement;
51
81
  /** generationConfig for whole-document part reads. Defaults to `{ temperature: 0.2, maxOutputTokens }`. */
52
82
  analysisConfig?: (maxOutputTokens: number) => Record<string, unknown>;
53
83
  /** Answer text as it streams. Streaming is used when this is set and the endpoint has `streamUrl`. */
@@ -61,7 +91,16 @@ export type AskGeminiOptions = {
61
91
  };
62
92
 
63
93
  export type AskGeminiResult = {
94
+ /** Everything the model wrote, including any remark it made before calling a tool. */
64
95
  text: string;
96
+ /**
97
+ * False when the model's last turn had no text: the prompt was blocked, the reply was cut off
98
+ * before any text, or the model produced a malformed tool call. `text` may then be empty or
99
+ * hold only an earlier remark, so show your own message instead of treating it as the answer.
100
+ */
101
+ answered: boolean;
102
+ /** Why Gemini refused the prompt (`promptFeedback.blockReason`), when it did. */
103
+ blockReason?: string;
65
104
  /** Every tool step taken, in order (also delivered through `onStep`). */
66
105
  steps: string[];
67
106
  /** Which documents went in whole and which were searched. */
@@ -84,6 +123,7 @@ type Body = {
84
123
  type Chunk = {
85
124
  candidates?: Array<{ finishReason?: string; content?: { parts?: GeminiPart[] } }>;
86
125
  usageMetadata?: Record<string, unknown>;
126
+ promptFeedback?: { blockReason?: string };
87
127
  error?: { message?: string };
88
128
  };
89
129
 
@@ -123,11 +163,16 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
123
163
  const fetchImpl = options.fetch ?? fetch;
124
164
  const { files, endpoint, signal } = options;
125
165
  const contents = toContents(options);
126
- const prepared = await files.prepare(options.documentIds, baseSize(contents, options.system), { owner: options.owner });
166
+ const prepared = await files.prepare(options.documentIds, baseSize(contents, options.system), { owner: options.owner, viewPages: options.viewPages !== false });
127
167
  if (prepared.missing.length) throw new DocumentsNotFoundError(prepared.missing);
128
168
 
129
169
  const blocks = [...new Set(options.documentIds)].map((id) => prepared.blocks.get(id)).filter((block): block is string => Boolean(block));
130
- if (blocks.length) contents.at(-1)!.parts.push({ text: blocks.join("\n\n") });
170
+ if (blocks.length) {
171
+ const block = { text: blocks.join("\n\n") };
172
+ if (options.documentPlacement === "last") contents.at(-1)!.parts.push(block);
173
+ // The last turn is the user's, so there is always a first user turn.
174
+ else contents.find((content) => content.role === "user")!.parts.unshift(block);
175
+ }
131
176
  const system = [options.system?.trim(), prepared.instruction].filter(Boolean).join("\n\n");
132
177
  const body: Body = {
133
178
  contents,
@@ -140,6 +185,7 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
140
185
  let text = "";
141
186
  let turns = 0;
142
187
  let finishReason: string | undefined;
188
+ let blockReason: string | undefined;
143
189
  let usage: Record<string, unknown> | undefined;
144
190
  const steps: string[] = [];
145
191
  const emit = (delta: string) => {
@@ -147,8 +193,11 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
147
193
  options.onText?.(delta);
148
194
  };
149
195
 
150
- /** One model request. Text is emitted as it arrives; parts are kept as received. */
151
- const turn = async (): Promise<{ parts: GeminiPart[]; calls: GeminiFunctionCall[] }> => {
196
+ /**
197
+ * One model request. Text is emitted as it arrives; parts are kept as received.
198
+ * `wroteText` says whether this request produced any text of its own.
199
+ */
200
+ const turn = async (): Promise<{ parts: GeminiPart[]; calls: GeminiFunctionCall[]; wroteText: boolean }> => {
152
201
  turns++;
153
202
  const response = await fetchImpl(streaming ? endpoint.streamUrl! : endpoint.url, {
154
203
  method: "POST",
@@ -163,8 +212,10 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
163
212
  const parts: GeminiPart[] = [];
164
213
  const calls: GeminiFunctionCall[] = [];
165
214
  let separated = text.length === 0;
215
+ let wroteText = false;
166
216
  const take = (chunk: Chunk) => {
167
217
  if (chunk.error?.message) throw new GeminiRequestError(chunk.error.message, response.status);
218
+ if (chunk.promptFeedback?.blockReason) blockReason = chunk.promptFeedback.blockReason;
168
219
  const candidate = chunk.candidates?.[0];
169
220
  for (const part of candidate?.content?.parts ?? []) {
170
221
  // Keep every part unchanged: Gemini 3 requires its thought signatures back.
@@ -175,6 +226,7 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
175
226
  separated = true;
176
227
  }
177
228
  emit(part.text);
229
+ if (part.text.trim()) wroteText = true;
178
230
  }
179
231
  const call = part.functionCall as { name?: unknown; args?: unknown; id?: unknown } | undefined;
180
232
  if (call && typeof call.name === "string") {
@@ -191,11 +243,13 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
191
243
  } else {
192
244
  take(await response.json() as Chunk);
193
245
  }
194
- return { parts, calls };
246
+ return { parts, calls, wroteText };
195
247
  };
196
248
 
197
- const result = (): AskGeminiResult => ({
249
+ const result = (answered: boolean): AskGeminiResult => ({
198
250
  text,
251
+ answered,
252
+ ...(blockReason ? { blockReason } : {}),
199
253
  steps,
200
254
  plan: prepared.plan,
201
255
  turns,
@@ -203,53 +257,81 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
203
257
  ...(usage ? { usage } : {}),
204
258
  });
205
259
 
206
- if (prepared.plan.searchable.length === 0) {
207
- await turn();
208
- return result();
209
- }
260
+ // Tools are needed for a file that is too large to send whole, and for a PDF whose pages can be
261
+ // looked at: that one may have its whole text in the prompt and still hide a chart from the model.
262
+ const { searchable } = prepared.plan;
263
+ const { viewable } = prepared;
264
+ if (searchable.length === 0 && viewable.length === 0) return result((await turn()).wroteText);
210
265
 
211
- const tools = files.tools(prepared.plan.searchable, {
266
+ const tools = files.tools(searchable, {
212
267
  ...(options.wholeDocumentAnalysis === false ? {} : {
213
268
  generate: createGeminiGenerateText({ url: endpoint.url, headers, fetchImpl, ...(options.analysisConfig ? { generationConfig: options.analysisConfig } : {}) }),
214
269
  }),
215
270
  onProgress: (event) => options.onActivity?.(`${event.message}…`),
216
271
  ...(signal ? { signal } : {}),
272
+ ...(viewable.length > 0 ? { viewPages: viewable } : {}),
217
273
  });
218
274
  body.tools = [{ functionDeclarations: tools.declarations }];
219
275
  body.toolConfig = { functionCallingConfig: { mode: "AUTO" } };
220
- options.onActivity?.(`Too large to read at once: ${prepared.plan.searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
276
+ if (searchable.length > 0) options.onActivity?.(`Too large to read at once: ${searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
277
+
278
+ // Pages the model looks at stay in the request until the question is answered, so they are
279
+ // counted twice: as bytes against the request limit, and as tokens against half of what the
280
+ // budget keeps free for tool results and the answer.
281
+ const { maxRequestBytes, reservedTokens } = files.budget;
282
+ const bytesKeptFree = Math.max(REQUEST_BYTES_MARGIN, Math.floor(maxRequestBytes / 10));
283
+ let pagesLeft = Math.floor(reservedTokens / 2 / PAGE_TOKENS);
221
284
 
222
285
  const maxTurns = Math.max(1, options.maxToolTurns ?? 12);
223
- let unanswered = false;
224
- for (let round = 1; round <= maxTurns; round++) {
225
- const { parts, calls } = await turn();
226
- if (calls.length === 0) break;
227
- if (round === maxTurns) {
228
- unanswered = true;
286
+ let answered = false;
287
+ // Tools run in at most maxTurns - 1 requests. The last request is the tool-free one below, so a
288
+ // model that never stops calling tools does not cost a request whose calls are thrown away.
289
+ for (let round = 1; round < maxTurns; round++) {
290
+ const { parts, calls, wroteText } = await turn();
291
+ if (calls.length === 0) {
292
+ // Text from this turn is the answer. A remark made earlier, before a tool call, is not.
293
+ answered = wroteText;
229
294
  break;
230
295
  }
231
296
  body.contents.push({ role: "model", parts });
232
- const answered: Array<{ call: GeminiFunctionCall; result: ToolResult }> = [];
297
+ const responses: Array<{ call: GeminiFunctionCall; result: ToolResult; files: ToolFile[] }> = [];
298
+ // The size of the request as it stands, worked out when the first look at pages in this turn needs it.
299
+ let requestBytes: number | undefined;
233
300
  for (const call of calls) {
234
301
  const label = tools.has(call.name) ? tools.describe(call.name, call.args) : call.name;
235
302
  options.onActivity?.(`${label}…`);
236
- const output = await tools.execute(call.name, call.args);
237
- const step = `${label}${toolResultSummary(label, output)}`;
303
+ let limits: ToolFileLimits | undefined;
304
+ if (call.name === TOOL_NAMES.view) {
305
+ requestBytes ??= Buffer.byteLength(JSON.stringify(body));
306
+ // Base64 turns three bytes into four characters.
307
+ limits = { maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4), maxPages: pagesLeft };
308
+ }
309
+ const output = await tools.executeWithFiles(call.name, call.args, limits);
310
+ for (const file of output.files) requestBytes = (requestBytes ?? 0) + Math.ceil(file.bytes.length / 3) * 4 + 512;
311
+ if (output.files.length > 0) pagesLeft -= pagesShown(output.result);
312
+ const step = `${label}${toolResultSummary(label, output.result)}`;
238
313
  steps.push(step);
239
314
  options.onStep?.(step);
240
- answered.push({ call, result: { ...output, tool_turns_left: maxTurns - round - 1 } });
315
+ responses.push({ call, result: { ...output.result, tool_turns_left: maxTurns - round - 1 }, files: output.files });
241
316
  }
242
- body.contents.push(geminiFunctionResponses(answered) as GeminiContent);
317
+ body.contents.push(...geminiFunctionResponseTurns(responses, { files: options.toolFilePlacement ?? "inside" }) as GeminiContent[]);
243
318
  }
244
319
 
245
- // Out of turns, or no answer yet: ask once more with no tools declared at all.
246
- // (Gemini can ignore functionCallingConfig mode NONE and keep calling tools.)
247
- if (unanswered || !text) {
320
+ // Out of tool turns, or the last turn had no text (cut off, or a malformed tool call): ask once
321
+ // more with no tools declared at all. (Gemini can ignore functionCallingConfig mode NONE and
322
+ // keep calling tools.) A blocked prompt would only be blocked again.
323
+ if (!answered && !blockReason) {
248
324
  options.onActivity?.("Writing the answer…");
249
325
  delete body.tools;
250
326
  delete body.toolConfig;
251
- body.contents.push({ role: "user", parts: [{ text: FINAL_ANSWER_REQUEST }] });
252
- await turn();
327
+ body.contents.push({ role: "user", parts: [{ text: searchable.length > 0 ? FINAL_ANSWER_REQUEST : FINAL_ANSWER_AFTER_PAGES }] });
328
+ answered = (await turn()).wroteText;
253
329
  }
254
- return result();
330
+ return result(answered);
331
+ }
332
+
333
+ /** How many pages a `view_pages` result showed: its `pages` is "12" or "12-14". */
334
+ function pagesShown(result: ToolResult): number {
335
+ const [first, last] = String(result.pages ?? "").split("-").map(Number);
336
+ return Number.isFinite(first) ? (Number.isFinite(last) ? last! - first! + 1 : 1) : 0;
255
337
  }
@@ -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
  /**
@@ -31,7 +85,7 @@ export function createGeminiGenerateText(options: {
31
85
  timeoutMs?: number;
32
86
  }): GenerateText {
33
87
  const fetchImpl = options.fetchImpl ?? fetch;
34
- return async ({ system, prompt, maxOutputTokens, signal }) => {
88
+ return async ({ system, prompt, maxOutputTokens, signal, onTruncated }) => {
35
89
  const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
36
90
  const response = await fetchImpl(options.url, {
37
91
  method: "POST",
@@ -54,6 +108,8 @@ export function createGeminiGenerateText(options: {
54
108
  .map((part) => part.text as string)
55
109
  .join("");
56
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?.();
57
113
  return text;
58
114
  };
59
115
  }
@@ -1,7 +1,7 @@
1
- export { askGemini, DocumentsNotFoundError, FINAL_ANSWER_REQUEST, GeminiRequestError } from "./chat.js";
1
+ export { askGemini, DocumentsNotFoundError, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, 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,9 +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
- export { defaultExtractors, detectFormat } from "./extract.js";
6
+ export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";
7
+ export type { PdfExtractorOptions } from "./extract.js";
7
8
  export { estimateTokens, utf8Bytes, jsonBytes } from "./text.js";
8
- export { TOOL_NAMES, toolResultSummary } from "./tools.js";
9
+ export { MAX_VIEW_PAGES, TOOL_NAMES, toolResultSummary } from "./tools.js";
9
10
  export type * from "./types.js";