llm-large-files 0.1.0 → 0.2.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 (69) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +1 -1
  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 +17 -1
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +73 -23
  9. package/dist/extract.js.map +1 -1
  10. package/dist/gemini/chat.d.ts +22 -2
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +41 -24
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts.map +1 -1
  15. package/dist/gemini/generate.js +4 -1
  16. package/dist/gemini/generate.js.map +1 -1
  17. package/dist/index.d.ts +2 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/library.d.ts +6 -0
  22. package/dist/library.d.ts.map +1 -1
  23. package/dist/library.js +15 -1
  24. package/dist/library.js.map +1 -1
  25. package/dist/map-reduce.d.ts +7 -0
  26. package/dist/map-reduce.d.ts.map +1 -1
  27. package/dist/map-reduce.js +58 -16
  28. package/dist/map-reduce.js.map +1 -1
  29. package/dist/pdf-layout.d.ts +32 -0
  30. package/dist/pdf-layout.d.ts.map +1 -0
  31. package/dist/pdf-layout.js +790 -0
  32. package/dist/pdf-layout.js.map +1 -0
  33. package/dist/plan.d.ts.map +1 -1
  34. package/dist/plan.js +6 -2
  35. package/dist/plan.js.map +1 -1
  36. package/dist/search.d.ts +8 -4
  37. package/dist/search.d.ts.map +1 -1
  38. package/dist/search.js +49 -24
  39. package/dist/search.js.map +1 -1
  40. package/dist/text.d.ts +18 -4
  41. package/dist/text.d.ts.map +1 -1
  42. package/dist/text.js +155 -15
  43. package/dist/text.js.map +1 -1
  44. package/dist/tools.d.ts.map +1 -1
  45. package/dist/tools.js +11 -3
  46. package/dist/tools.js.map +1 -1
  47. package/dist/types.d.ts +6 -0
  48. package/dist/types.d.ts.map +1 -1
  49. package/docs/api.md +20 -3
  50. package/docs/configuration.md +73 -5
  51. package/docs/getting-started.md +7 -4
  52. package/docs/how-it-works.md +26 -8
  53. package/docs/security.md +18 -5
  54. package/package.json +91 -91
  55. package/src/analyze.ts +3 -1
  56. package/src/extract.ts +77 -22
  57. package/src/gemini/chat.ts +60 -25
  58. package/src/gemini/generate.ts +3 -1
  59. package/src/index.ts +2 -1
  60. package/src/library.ts +241 -226
  61. package/src/map-reduce.ts +69 -16
  62. package/src/node/handlers.ts +122 -122
  63. package/src/pdf-layout.ts +771 -0
  64. package/src/plan.ts +100 -98
  65. package/src/search.ts +48 -25
  66. package/src/stores.ts +132 -132
  67. package/src/text.ts +131 -14
  68. package/src/tools.ts +274 -264
  69. package/src/types.ts +174 -168
package/src/extract.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { layoutPageText, plainPageText, type PdfTextItem } from "./pdf-layout.js";
1
2
  import type { DocumentFormat, ExtractedText, Extractor } from "./types.js";
2
3
 
3
4
  const EXTENSION_FORMATS: Record<string, DocumentFormat> = {
@@ -23,10 +24,22 @@ export function detectFormat(name: string, mimeType: string): DocumentFormat {
23
24
  return EXTENSION_FORMATS[extension] ?? MIME_FORMATS[mimeType.toLowerCase()] ?? "text";
24
25
  }
25
26
 
26
- /** Decodes text bytes, honoring UTF-8 and UTF-16 byte-order marks (common for Windows logs). */
27
+ const NOT_TEXT = "This file looks binary, not text. Attach a text, log, PDF, DOCX, or PPTX file.";
28
+
29
+ /**
30
+ * Decodes text bytes, honoring UTF-8 and UTF-16 byte-order marks (common for Windows logs).
31
+ * Throws a readable error for compressed and other binary files.
32
+ */
27
33
  export function decodeText(bytes: Uint8Array): string {
28
34
  if (bytes[0] === 0xff && bytes[1] === 0xfe) return new TextDecoder("utf-16le").decode(bytes.subarray(2));
29
35
  if (bytes[0] === 0xfe && bytes[1] === 0xff) return new TextDecoder("utf-16be").decode(bytes.subarray(2));
36
+ // Rotated logs often arrive as app.log.gz. Compressed bytes have few zeros, so name them here.
37
+ if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
38
+ throw new Error("This file is gzip-compressed. Decompress it, then attach the text file inside.");
39
+ }
40
+ if (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) {
41
+ throw new Error("This file is a ZIP archive. Extract it, then attach the text file you need.");
42
+ }
30
43
  const sample = bytes.subarray(0, 8_192);
31
44
  let zeros = 0;
32
45
  for (const byte of sample) if (byte === 0) zeros++;
@@ -41,9 +54,15 @@ export function decodeText(bytes: Uint8Array): string {
41
54
  const half = sample.length / 2;
42
55
  if (oddZeros / half > 0.6 && evenText / half > 0.6) return new TextDecoder("utf-16le").decode(bytes);
43
56
  }
44
- if (sample.length > 0 && zeros / sample.length > 0.01) {
45
- throw new Error("This file looks binary, not text. Attach a text, log, PDF, DOCX, or PPTX file.");
57
+ if (sample.length > 0 && zeros / sample.length > 0.01) throw new Error(NOT_TEXT);
58
+ // Compressed, encrypted, and media files spread control bytes evenly: about 1 byte in 10.
59
+ // Text has almost none, in UTF-8 or in a legacy single-byte encoding. Tab, line breaks, form
60
+ // feed, and ESC (colour codes) do not count.
61
+ let controls = 0;
62
+ for (const byte of sample) {
63
+ if (byte < 0x09 || (byte > 0x0d && byte < 0x20 && byte !== 0x1b) || byte === 0x7f) controls++;
46
64
  }
65
+ if (sample.length >= 64 && controls / sample.length > 0.03) throw new Error(NOT_TEXT);
47
66
  return new TextDecoder("utf-8").decode(bytes);
48
67
  }
49
68
 
@@ -120,33 +139,69 @@ const pptx: Extractor = async (bytes) => {
120
139
  return { text: slides.join("\n\n"), pages: names.length };
121
140
  };
122
141
 
123
- const pdf: Extractor = async (bytes) => {
124
- let unpdf: typeof import("unpdf");
125
- try {
126
- unpdf = await import("unpdf");
127
- } catch {
128
- throw new Error("Reading PDF files needs the optional dependency \"unpdf\".");
129
- }
130
- // pdf.js may detach the buffer it reads, so give it a copy.
131
- const document = await unpdf.getDocumentProxy(new Uint8Array(bytes));
132
- const { totalPages, text } = await unpdf.extractText(document, { mergePages: false });
133
- const pages = Array.isArray(text) ? text : [text];
134
- if (!pages.some((page) => page.trim())) {
135
- throw new Error("This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.");
136
- }
137
- return {
138
- text: pages.map((page, index) => `--- Page ${index + 1} ---\n${page.trim()}`).join("\n\n"),
139
- pages: totalPages,
140
- };
142
+ export type PdfExtractorOptions = {
143
+ /**
144
+ * Rebuild tables from the position of the text, and write each row as `| cell | cell | |`, so an
145
+ * empty cell stays an empty cell. Defaults to true. With false, the text is in pdf.js order, as
146
+ * in version 0.1.0.
147
+ */
148
+ tables?: boolean;
141
149
  };
142
150
 
151
+ /** Written in place of a page that has no text at all, so the model can say so instead of guessing. */
152
+ const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or a chart.]";
153
+
154
+ /**
155
+ * The built-in PDF extractor (needs `unpdf`). Use it to change an option:
156
+ * `createLargeFiles({ extractors: { pdf: createPdfExtractor({ tables: false }) } })`.
157
+ */
158
+ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor {
159
+ const tables = options.tables ?? true;
160
+ return async (bytes) => {
161
+ let unpdf: typeof import("unpdf");
162
+ try {
163
+ unpdf = await import("unpdf");
164
+ } catch {
165
+ throw new Error("Reading PDF files needs the optional dependency \"unpdf\".");
166
+ }
167
+ // pdf.js may detach the buffer it reads, so give it a copy.
168
+ const document = await unpdf.getDocumentProxy(new Uint8Array(bytes));
169
+ const pages: string[] = [];
170
+ let hasText = false;
171
+ for (let number = 1; number <= document.numPages; number++) {
172
+ const page = await document.getPage(number);
173
+ const content = await page.getTextContent();
174
+ const items = (content.items as unknown[]).filter((item): item is PdfTextItem => typeof (item as PdfTextItem).str === "string");
175
+ let text = "";
176
+ if (tables) {
177
+ try {
178
+ text = layoutPageText(items, page.getViewport({ scale: 1 }).transform);
179
+ } catch {
180
+ // Unusual geometry must never lose a page: fall back to the plain order.
181
+ text = plainPageText(items);
182
+ }
183
+ } else {
184
+ text = plainPageText(items);
185
+ }
186
+ text = text.trim();
187
+ if (text) hasText = true;
188
+ pages.push(`--- Page ${number} ---\n${text || PAGE_WITHOUT_TEXT}`);
189
+ page.cleanup();
190
+ }
191
+ if (!hasText) {
192
+ throw new Error("This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.");
193
+ }
194
+ return { text: pages.join("\n\n"), pages: document.numPages };
195
+ };
196
+ }
197
+
143
198
  export const defaultExtractors: Record<DocumentFormat, Extractor> = {
144
199
  text: plainText,
145
200
  markdown: plainText,
146
201
  log: plainText,
147
202
  json: plainText,
148
203
  csv: plainText,
149
- pdf,
204
+ pdf: createPdfExtractor(),
150
205
  docx,
151
206
  pptx,
152
207
  };
@@ -33,8 +33,15 @@ export class GeminiRequestError extends Error {
33
33
  export type AskGeminiOptions = {
34
34
  files: LargeFiles;
35
35
  endpoint: GeminiEndpoint;
36
- /** Documents this conversation may use. Their text or cards are added to the last user turn. */
36
+ /** Documents this conversation may use. Where their text or cards go: see `documentPlacement`. */
37
37
  documentIds: string[];
38
+ /**
39
+ * Where document text and cards are added. "first" (the default) puts them at the start of the
40
+ * first user turn, where they stay as the conversation grows, so Gemini's prompt cache can
41
+ * reuse them on every follow-up question. "last" appends them to the latest user turn, as 0.1.0
42
+ * did; the document then moves on every turn and is billed in full each time.
43
+ */
44
+ documentPlacement?: "first" | "last";
38
45
  /** Plain chat history; the last turn must be the user's question. Use this or `contents`. */
39
46
  messages?: ChatTurn[];
40
47
  /** Your own Gemini `contents` (with images, inline PDFs, etc.). The last turn must be the user's. */
@@ -44,7 +51,11 @@ export type AskGeminiOptions = {
44
51
  generationConfig?: Record<string, unknown>;
45
52
  /** The user asking. Documents ingested with a different owner are treated as missing. */
46
53
  owner?: string;
47
- /** Model turns that may call tools before a final, tool-free turn. Defaults to 12. */
54
+ /**
55
+ * The most model requests for one question, counting the answer. Tools can run in all but the
56
+ * 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.
58
+ */
48
59
  maxToolTurns?: number;
49
60
  /** Offer `analyze_whole_document`, which reads a whole file in many model calls. Defaults to true. */
50
61
  wholeDocumentAnalysis?: boolean;
@@ -61,7 +72,16 @@ export type AskGeminiOptions = {
61
72
  };
62
73
 
63
74
  export type AskGeminiResult = {
75
+ /** Everything the model wrote, including any remark it made before calling a tool. */
64
76
  text: string;
77
+ /**
78
+ * False when the model's last turn had no text: the prompt was blocked, the reply was cut off
79
+ * before any text, or the model produced a malformed tool call. `text` may then be empty or
80
+ * hold only an earlier remark, so show your own message instead of treating it as the answer.
81
+ */
82
+ answered: boolean;
83
+ /** Why Gemini refused the prompt (`promptFeedback.blockReason`), when it did. */
84
+ blockReason?: string;
65
85
  /** Every tool step taken, in order (also delivered through `onStep`). */
66
86
  steps: string[];
67
87
  /** Which documents went in whole and which were searched. */
@@ -84,6 +104,7 @@ type Body = {
84
104
  type Chunk = {
85
105
  candidates?: Array<{ finishReason?: string; content?: { parts?: GeminiPart[] } }>;
86
106
  usageMetadata?: Record<string, unknown>;
107
+ promptFeedback?: { blockReason?: string };
87
108
  error?: { message?: string };
88
109
  };
89
110
 
@@ -127,7 +148,12 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
127
148
  if (prepared.missing.length) throw new DocumentsNotFoundError(prepared.missing);
128
149
 
129
150
  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") });
151
+ if (blocks.length) {
152
+ const block = { text: blocks.join("\n\n") };
153
+ if (options.documentPlacement === "last") contents.at(-1)!.parts.push(block);
154
+ // The last turn is the user's, so there is always a first user turn.
155
+ else contents.find((content) => content.role === "user")!.parts.unshift(block);
156
+ }
131
157
  const system = [options.system?.trim(), prepared.instruction].filter(Boolean).join("\n\n");
132
158
  const body: Body = {
133
159
  contents,
@@ -140,6 +166,7 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
140
166
  let text = "";
141
167
  let turns = 0;
142
168
  let finishReason: string | undefined;
169
+ let blockReason: string | undefined;
143
170
  let usage: Record<string, unknown> | undefined;
144
171
  const steps: string[] = [];
145
172
  const emit = (delta: string) => {
@@ -147,8 +174,11 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
147
174
  options.onText?.(delta);
148
175
  };
149
176
 
150
- /** One model request. Text is emitted as it arrives; parts are kept as received. */
151
- const turn = async (): Promise<{ parts: GeminiPart[]; calls: GeminiFunctionCall[] }> => {
177
+ /**
178
+ * One model request. Text is emitted as it arrives; parts are kept as received.
179
+ * `wroteText` says whether this request produced any text of its own.
180
+ */
181
+ const turn = async (): Promise<{ parts: GeminiPart[]; calls: GeminiFunctionCall[]; wroteText: boolean }> => {
152
182
  turns++;
153
183
  const response = await fetchImpl(streaming ? endpoint.streamUrl! : endpoint.url, {
154
184
  method: "POST",
@@ -163,8 +193,10 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
163
193
  const parts: GeminiPart[] = [];
164
194
  const calls: GeminiFunctionCall[] = [];
165
195
  let separated = text.length === 0;
196
+ let wroteText = false;
166
197
  const take = (chunk: Chunk) => {
167
198
  if (chunk.error?.message) throw new GeminiRequestError(chunk.error.message, response.status);
199
+ if (chunk.promptFeedback?.blockReason) blockReason = chunk.promptFeedback.blockReason;
168
200
  const candidate = chunk.candidates?.[0];
169
201
  for (const part of candidate?.content?.parts ?? []) {
170
202
  // Keep every part unchanged: Gemini 3 requires its thought signatures back.
@@ -175,6 +207,7 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
175
207
  separated = true;
176
208
  }
177
209
  emit(part.text);
210
+ if (part.text.trim()) wroteText = true;
178
211
  }
179
212
  const call = part.functionCall as { name?: unknown; args?: unknown; id?: unknown } | undefined;
180
213
  if (call && typeof call.name === "string") {
@@ -191,11 +224,13 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
191
224
  } else {
192
225
  take(await response.json() as Chunk);
193
226
  }
194
- return { parts, calls };
227
+ return { parts, calls, wroteText };
195
228
  };
196
229
 
197
- const result = (): AskGeminiResult => ({
230
+ const result = (answered: boolean): AskGeminiResult => ({
198
231
  text,
232
+ answered,
233
+ ...(blockReason ? { blockReason } : {}),
199
234
  steps,
200
235
  plan: prepared.plan,
201
236
  turns,
@@ -203,10 +238,7 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
203
238
  ...(usage ? { usage } : {}),
204
239
  });
205
240
 
206
- if (prepared.plan.searchable.length === 0) {
207
- await turn();
208
- return result();
209
- }
241
+ if (prepared.plan.searchable.length === 0) return result((await turn()).wroteText);
210
242
 
211
243
  const tools = files.tools(prepared.plan.searchable, {
212
244
  ...(options.wholeDocumentAnalysis === false ? {} : {
@@ -220,16 +252,18 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
220
252
  options.onActivity?.(`Too large to read at once: ${prepared.plan.searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
221
253
 
222
254
  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;
255
+ let answered = false;
256
+ // Tools run in at most maxTurns - 1 requests. The last request is the tool-free one below, so a
257
+ // model that never stops calling tools does not cost a request whose calls are thrown away.
258
+ for (let round = 1; round < maxTurns; round++) {
259
+ const { parts, calls, wroteText } = await turn();
260
+ if (calls.length === 0) {
261
+ // Text from this turn is the answer. A remark made earlier, before a tool call, is not.
262
+ answered = wroteText;
229
263
  break;
230
264
  }
231
265
  body.contents.push({ role: "model", parts });
232
- const answered: Array<{ call: GeminiFunctionCall; result: ToolResult }> = [];
266
+ const responses: Array<{ call: GeminiFunctionCall; result: ToolResult }> = [];
233
267
  for (const call of calls) {
234
268
  const label = tools.has(call.name) ? tools.describe(call.name, call.args) : call.name;
235
269
  options.onActivity?.(`${label}…`);
@@ -237,19 +271,20 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
237
271
  const step = `${label}${toolResultSummary(label, output)}`;
238
272
  steps.push(step);
239
273
  options.onStep?.(step);
240
- answered.push({ call, result: { ...output, tool_turns_left: maxTurns - round - 1 } });
274
+ responses.push({ call, result: { ...output, tool_turns_left: maxTurns - round - 1 } });
241
275
  }
242
- body.contents.push(geminiFunctionResponses(answered) as GeminiContent);
276
+ body.contents.push(geminiFunctionResponses(responses) as GeminiContent);
243
277
  }
244
278
 
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) {
279
+ // Out of tool turns, or the last turn had no text (cut off, or a malformed tool call): ask once
280
+ // more with no tools declared at all. (Gemini can ignore functionCallingConfig mode NONE and
281
+ // keep calling tools.) A blocked prompt would only be blocked again.
282
+ if (!answered && !blockReason) {
248
283
  options.onActivity?.("Writing the answer…");
249
284
  delete body.tools;
250
285
  delete body.toolConfig;
251
286
  body.contents.push({ role: "user", parts: [{ text: FINAL_ANSWER_REQUEST }] });
252
- await turn();
287
+ answered = (await turn()).wroteText;
253
288
  }
254
- return result();
289
+ return result(answered);
255
290
  }
@@ -31,7 +31,7 @@ export function createGeminiGenerateText(options: {
31
31
  timeoutMs?: number;
32
32
  }): GenerateText {
33
33
  const fetchImpl = options.fetchImpl ?? fetch;
34
- return async ({ system, prompt, maxOutputTokens, signal }) => {
34
+ return async ({ system, prompt, maxOutputTokens, signal, onTruncated }) => {
35
35
  const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
36
36
  const response = await fetchImpl(options.url, {
37
37
  method: "POST",
@@ -54,6 +54,8 @@ export function createGeminiGenerateText(options: {
54
54
  .map((part) => part.text as string)
55
55
  .join("");
56
56
  if (!text.trim()) throw new Error(`The model returned no text${candidate?.finishReason ? ` (${candidate.finishReason})` : ""}.`);
57
+ // The text stops mid-list when the output limit is reached. Say so instead of passing it off as complete.
58
+ if (candidate?.finishReason === "MAX_TOKENS") onTruncated?.();
57
59
  return text;
58
60
  };
59
61
  }
package/src/index.ts CHANGED
@@ -3,7 +3,8 @@
3
3
  export { createLargeFiles, DEFAULT_BUDGET, isDocumentId, toDocumentSummary } from "./library.js";
4
4
  export type { AccessOptions, IngestInput, LargeFiles, LargeFilesOptions, 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
9
  export { TOOL_NAMES, toolResultSummary } from "./tools.js";
9
10
  export type * from "./types.js";