llm-large-files 0.3.0 → 0.3.6
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.
- package/CHANGELOG.md +67 -0
- package/README.md +21 -1
- package/dist/extract.d.ts +1 -1
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +204 -22
- package/dist/extract.js.map +1 -1
- package/dist/gemini/chat.d.ts +32 -4
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +65 -15
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +17 -0
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +16 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +1 -1
- package/dist/gemini/index.js.map +1 -1
- package/dist/node/handlers.d.ts +9 -0
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +56 -13
- package/dist/node/handlers.js.map +1 -1
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +52 -9
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +6 -3
- package/dist/text.js.map +1 -1
- package/docs/api.md +29 -6
- package/docs/configuration.md +127 -1
- package/docs/getting-started.md +19 -1
- package/docs/how-it-works.md +21 -0
- package/docs/security.md +5 -0
- package/package.json +1 -1
- package/src/extract.ts +198 -19
- package/src/gemini/chat.ts +87 -19
- package/src/gemini/endpoints.ts +34 -2
- package/src/gemini/index.ts +1 -1
- package/src/node/handlers.ts +61 -9
- package/src/pdf-pictures.ts +60 -10
- package/src/text.ts +6 -3
package/src/extract.ts
CHANGED
|
@@ -82,24 +82,205 @@ function decodeXmlEntities(value: string): string {
|
|
|
82
82
|
});
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
/**
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
85
|
+
/** A tag name is read up to this many characters: the names that matter here are short. */
|
|
86
|
+
const MAX_TAG_NAME = 64;
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Collects the text of each paragraph of Office XML (`<w:p>` in Word, `<a:p>` in PowerPoint) in one
|
|
90
|
+
* pass, with no XML parser. The XML can come in pieces, as it is unpacked: a tag cut between two
|
|
91
|
+
* pieces is read whole. Every character is looked at once, so the time follows the length of the
|
|
92
|
+
* XML whatever its shape: a file of unclosed tags costs what a file of closed ones does.
|
|
93
|
+
*
|
|
94
|
+
* - A paragraph inside another one (the text box of a shape anchored in a paragraph) is a paragraph
|
|
95
|
+
* of its own, after the one it is anchored in, which keeps its text before and after the box.
|
|
96
|
+
* - `mc:Fallback` repeats `mc:Choice` for older programs, so it is skipped: a text box is read once.
|
|
97
|
+
* - Paragraph properties hold no text. Their tab stops are not tabs.
|
|
98
|
+
*/
|
|
99
|
+
class OfficeText {
|
|
100
|
+
private readonly paragraphTag: string;
|
|
101
|
+
private readonly paragraphEnd: string;
|
|
102
|
+
private readonly textTag: string;
|
|
103
|
+
private readonly textEnd: string;
|
|
104
|
+
private readonly propertiesTag: string;
|
|
105
|
+
private readonly propertiesEnd: string;
|
|
106
|
+
private readonly tabTag: string;
|
|
107
|
+
private readonly breakTags: ReadonlySet<string>;
|
|
108
|
+
/** The pieces of text of each paragraph, in the order the paragraphs start. */
|
|
109
|
+
private readonly paragraphs: string[][] = [];
|
|
110
|
+
/** The paragraphs that are open, the innermost last. */
|
|
111
|
+
private readonly open: string[][] = [];
|
|
112
|
+
private inText = false;
|
|
113
|
+
private inProperties = 0;
|
|
114
|
+
private inFallback = 0;
|
|
115
|
+
/** The tag being read, from its "<": its name so far, the quote of a value it is in, its last character. */
|
|
116
|
+
private tag: { name: string; named: boolean; quote: number; last: number } | undefined;
|
|
117
|
+
|
|
118
|
+
constructor(prefix: "w" | "a") {
|
|
119
|
+
this.paragraphTag = `${prefix}:p`;
|
|
120
|
+
this.paragraphEnd = `/${prefix}:p`;
|
|
121
|
+
this.textTag = `${prefix}:t`;
|
|
122
|
+
this.textEnd = `/${prefix}:t`;
|
|
123
|
+
this.propertiesTag = `${prefix}:pPr`;
|
|
124
|
+
this.propertiesEnd = `/${prefix}:pPr`;
|
|
125
|
+
this.tabTag = `${prefix}:tab`;
|
|
126
|
+
this.breakTags = new Set([`${prefix}:br`, `${prefix}:cr`]);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
write(xml: string): void {
|
|
130
|
+
const length = xml.length;
|
|
131
|
+
let at = 0;
|
|
132
|
+
while (at < length) {
|
|
133
|
+
const tag = this.tag;
|
|
134
|
+
if (!tag) {
|
|
135
|
+
const start = xml.indexOf("<", at);
|
|
136
|
+
const end = start === -1 ? length : start;
|
|
137
|
+
if (end > at && this.inText && this.inProperties === 0 && this.inFallback === 0) this.open.at(-1)?.push(xml.slice(at, end));
|
|
138
|
+
if (start === -1) return;
|
|
139
|
+
this.tag = { name: "", named: false, quote: 0, last: 0 };
|
|
140
|
+
at = start + 1;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
for (; at < length; at++) {
|
|
144
|
+
const code = xml.charCodeAt(at);
|
|
145
|
+
if (tag.quote !== 0) {
|
|
146
|
+
if (code === tag.quote) tag.quote = 0;
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (!tag.named) {
|
|
150
|
+
// A name ends at white space, at ">", or at the "/" of "<w:br/>". "</w:p>" starts with one.
|
|
151
|
+
if (code === 62 || code === 32 || code === 9 || code === 10 || code === 13 || (code === 47 && tag.name !== "")) tag.named = true;
|
|
152
|
+
else {
|
|
153
|
+
if (tag.name.length < MAX_TAG_NAME) tag.name += xml[at];
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (code === 62) break;
|
|
158
|
+
if (code === 34 || code === 39) tag.quote = code;
|
|
159
|
+
else if (code !== 32 && code !== 9 && code !== 10 && code !== 13) tag.last = code;
|
|
160
|
+
}
|
|
161
|
+
if (at === length) return; // The tag goes on in the next piece.
|
|
162
|
+
this.tag = undefined;
|
|
163
|
+
this.read(tag.name, tag.last === 47);
|
|
164
|
+
at++;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The text of each paragraph that has some, in the order the paragraphs start. */
|
|
169
|
+
texts(): string[] {
|
|
170
|
+
return this.paragraphs.map((pieces) => decodeXmlEntities(pieces.join(""))).filter((text) => text.trim());
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Acts on a tag that has been read. `empty` is a tag that closes itself, as `<w:br/>`. */
|
|
174
|
+
private read(name: string, empty: boolean): void {
|
|
175
|
+
if (name === "mc:Fallback") {
|
|
176
|
+
if (!empty) this.inFallback++;
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (name === "/mc:Fallback") {
|
|
180
|
+
if (this.inFallback > 0) this.inFallback--;
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (this.inFallback > 0) return;
|
|
184
|
+
if (name === this.paragraphTag) {
|
|
185
|
+
if (!empty) {
|
|
186
|
+
const pieces: string[] = [];
|
|
187
|
+
this.paragraphs.push(pieces);
|
|
188
|
+
this.open.push(pieces);
|
|
189
|
+
}
|
|
190
|
+
} else if (name === this.paragraphEnd) {
|
|
191
|
+
this.open.pop();
|
|
192
|
+
this.inText = false;
|
|
193
|
+
this.inProperties = 0;
|
|
194
|
+
} else if (name === this.textTag) {
|
|
195
|
+
this.inText = !empty;
|
|
196
|
+
} else if (name === this.textEnd) {
|
|
197
|
+
this.inText = false;
|
|
198
|
+
} else if (name === this.propertiesTag) {
|
|
199
|
+
if (!empty) this.inProperties++;
|
|
200
|
+
} else if (name === this.propertiesEnd) {
|
|
201
|
+
if (this.inProperties > 0) this.inProperties--;
|
|
202
|
+
} else if (this.inProperties === 0) {
|
|
203
|
+
if (name === this.tabTag) this.open.at(-1)?.push("\t");
|
|
204
|
+
else if (this.breakTags.has(name)) this.open.at(-1)?.push("\n");
|
|
95
205
|
}
|
|
96
|
-
|
|
97
|
-
}).filter((text) => text.trim());
|
|
206
|
+
}
|
|
98
207
|
}
|
|
99
208
|
|
|
100
|
-
|
|
209
|
+
/** Text of each paragraph of Office XML, in the order the paragraphs start. See `OfficeText`. */
|
|
210
|
+
export function officeXmlParagraphs(xml: string, prefix: "w" | "a"): string[] {
|
|
211
|
+
const text = new OfficeText(prefix);
|
|
212
|
+
text.write(xml);
|
|
213
|
+
return text.texts();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** The part of JSZip's stream of one file that is used here. */
|
|
217
|
+
type ZipStream = {
|
|
218
|
+
on(event: "data", listener: (chunk: string) => void): ZipStream;
|
|
219
|
+
on(event: "error", listener: (error: unknown) => void): ZipStream;
|
|
220
|
+
on(event: "end", listener: () => void): ZipStream;
|
|
221
|
+
resume(): ZipStream;
|
|
222
|
+
pause(): ZipStream;
|
|
223
|
+
};
|
|
224
|
+
/** `internalStream` hands out a file of the archive in pieces, as it is unpacked. */
|
|
225
|
+
type ZipFile = { internalStream(type: "string"): ZipStream };
|
|
101
226
|
type ZipArchive = { files: Record<string, unknown>; file(name: string): ZipFile | null };
|
|
102
227
|
|
|
228
|
+
/** The most XML read from one DOCX or PPTX, whatever its size: a document of thousands of pages. */
|
|
229
|
+
const MAX_OFFICE_XML = 128 * 1024 * 1024;
|
|
230
|
+
/**
|
|
231
|
+
* The parts read from an Office file unpack to less than its size: pictures, fonts and styles stay
|
|
232
|
+
* packed. A generated report that repeats one paragraph 50,000 times unpacks to 90 times its size.
|
|
233
|
+
* A file that unpacks to more than this many times its size, past the first 16 MB, is taken for a
|
|
234
|
+
* zip bomb, as Apache POI does.
|
|
235
|
+
*/
|
|
236
|
+
const MAX_OFFICE_EXPANSION = 100;
|
|
237
|
+
const OFFICE_ALLOWANCE = 16 * 1024 * 1024;
|
|
238
|
+
|
|
239
|
+
const megabytes = (size: number) => `${Math.round(size / 1024 / 1024)} MB`;
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Reads the paragraphs of the parts of one DOCX or PPTX, each a piece at a time as it is unpacked,
|
|
243
|
+
* counting what is unpacked: a file that grows far past its size is refused as it grows, before
|
|
244
|
+
* that much is in memory. Unpacking yields to other work between pieces.
|
|
245
|
+
*/
|
|
246
|
+
function officeReader(archive: ZipArchive, kind: "DOCX" | "PPTX", size: number) {
|
|
247
|
+
const limit = Math.min(MAX_OFFICE_XML, Math.max(OFFICE_ALLOWANCE, size * MAX_OFFICE_EXPANSION));
|
|
248
|
+
const refusal = limit === MAX_OFFICE_XML
|
|
249
|
+
? `This ${kind} unpacks to more than ${megabytes(limit)} of XML, more than is read from one file. Save it as text or PDF, and attach that.`
|
|
250
|
+
: `This ${kind} unpacks to more than ${megabytes(limit)}, over ${MAX_OFFICE_EXPANSION} times its size. A file that grows that much is not read: it may be a zip bomb. Save it as text or PDF, and attach that.`;
|
|
251
|
+
let unpacked = 0;
|
|
252
|
+
return (name: string, prefix: "w" | "a") => new Promise<string[]>((resolve, reject) => {
|
|
253
|
+
const file = archive.file(name);
|
|
254
|
+
if (!file) {
|
|
255
|
+
resolve([]);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
const text = new OfficeText(prefix);
|
|
259
|
+
let stopped = false;
|
|
260
|
+
const stream = file.internalStream("string");
|
|
261
|
+
stream
|
|
262
|
+
.on("data", (chunk) => {
|
|
263
|
+
if (stopped) return;
|
|
264
|
+
unpacked += chunk.length;
|
|
265
|
+
if (unpacked > limit) {
|
|
266
|
+
stopped = true;
|
|
267
|
+
stream.pause();
|
|
268
|
+
reject(new Error(refusal));
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
text.write(chunk);
|
|
272
|
+
})
|
|
273
|
+
.on("error", (error) => {
|
|
274
|
+
stopped = true;
|
|
275
|
+
reject(error);
|
|
276
|
+
})
|
|
277
|
+
.on("end", () => {
|
|
278
|
+
if (!stopped) resolve(text.texts());
|
|
279
|
+
})
|
|
280
|
+
.resume();
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
103
284
|
async function loadZip(bytes: Uint8Array): Promise<ZipArchive> {
|
|
104
285
|
let JSZip: { loadAsync(data: Uint8Array): Promise<ZipArchive> };
|
|
105
286
|
try {
|
|
@@ -116,11 +297,9 @@ const docx: Extractor = async (bytes) => {
|
|
|
116
297
|
.filter((name) => /^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/i.test(name))
|
|
117
298
|
.sort((left, right) => left === "word/document.xml" ? -1 : right === "word/document.xml" ? 1 : left.localeCompare(right));
|
|
118
299
|
if (!names.includes("word/document.xml")) throw new Error("This DOCX does not contain word/document.xml.");
|
|
300
|
+
const read = officeReader(archive, "DOCX", bytes.byteLength);
|
|
119
301
|
const sections: string[] = [];
|
|
120
|
-
for (const name of names)
|
|
121
|
-
const xml = await archive.file(name)?.async("string");
|
|
122
|
-
if (xml) sections.push(officeXmlParagraphs(xml, "w").join("\n"));
|
|
123
|
-
}
|
|
302
|
+
for (const name of names) sections.push((await read(name, "w")).join("\n"));
|
|
124
303
|
return { text: sections.filter(Boolean).join("\n\n") };
|
|
125
304
|
};
|
|
126
305
|
|
|
@@ -131,10 +310,10 @@ const pptx: Extractor = async (bytes) => {
|
|
|
131
310
|
.filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name))
|
|
132
311
|
.sort((left, right) => slideNumber(left) - slideNumber(right));
|
|
133
312
|
if (names.length === 0) throw new Error("This PPTX does not contain any slides.");
|
|
313
|
+
const read = officeReader(archive, "PPTX", bytes.byteLength);
|
|
134
314
|
const slides: string[] = [];
|
|
135
315
|
for (const name of names) {
|
|
136
|
-
const
|
|
137
|
-
const text = xml ? officeXmlParagraphs(xml, "a").join("\n") : "";
|
|
316
|
+
const text = (await read(name, "a")).join("\n");
|
|
138
317
|
slides.push(`## Slide ${slideNumber(name)}\n${text || "[No text on this slide]"}`);
|
|
139
318
|
}
|
|
140
319
|
return { text: slides.join("\n\n"), pages: names.length };
|
package/src/gemini/chat.ts
CHANGED
|
@@ -16,6 +16,13 @@ export type ChatTurn = { role: "user" | "model" | "assistant"; text: string };
|
|
|
16
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
17
|
/** The same, when the only tool was `view_pages`: the text of the files is in the prompt, not in tool results. */
|
|
18
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.";
|
|
19
26
|
|
|
20
27
|
/** What Gemini bills for one PDF page it is shown (measured: 520 to 532). */
|
|
21
28
|
const PAGE_TOKENS = 530;
|
|
@@ -38,6 +45,12 @@ export class GeminiRequestError extends Error {
|
|
|
38
45
|
|
|
39
46
|
export type AskGeminiOptions = {
|
|
40
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
|
+
*/
|
|
41
54
|
endpoint: GeminiEndpoint;
|
|
42
55
|
/** Documents this conversation may use. Where their text or cards go: see `documentPlacement`. */
|
|
43
56
|
documentIds: string[];
|
|
@@ -55,12 +68,19 @@ export type AskGeminiOptions = {
|
|
|
55
68
|
system?: string;
|
|
56
69
|
/** Sent with every chat request: temperature, maxOutputTokens, thinkingConfig, and so on. */
|
|
57
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>;
|
|
58
77
|
/** The user asking. Documents ingested with a different owner are treated as missing. */
|
|
59
78
|
owner?: string;
|
|
60
79
|
/**
|
|
61
80
|
* The most model requests for one question, counting the answer. Tools can run in all but the
|
|
62
81
|
* 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.
|
|
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.
|
|
64
84
|
*/
|
|
65
85
|
maxToolTurns?: number;
|
|
66
86
|
/** Offer `analyze_whole_document`, which reads a whole file in many model calls. Defaults to true. */
|
|
@@ -78,7 +98,10 @@ export type AskGeminiOptions = {
|
|
|
78
98
|
* function response.
|
|
79
99
|
*/
|
|
80
100
|
toolFilePlacement?: GeminiToolFilePlacement;
|
|
81
|
-
/**
|
|
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
|
+
*/
|
|
82
105
|
analysisConfig?: (maxOutputTokens: number) => Record<string, unknown>;
|
|
83
106
|
/** Answer text as it streams. Streaming is used when this is set and the endpoint has `streamUrl`. */
|
|
84
107
|
onText?: (delta: string) => void;
|
|
@@ -91,7 +114,10 @@ export type AskGeminiOptions = {
|
|
|
91
114
|
};
|
|
92
115
|
|
|
93
116
|
export type AskGeminiResult = {
|
|
94
|
-
/**
|
|
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
|
+
*/
|
|
95
121
|
text: string;
|
|
96
122
|
/**
|
|
97
123
|
* False when the model's last turn had no text: the prompt was blocked, the reply was cut off
|
|
@@ -105,7 +131,7 @@ export type AskGeminiResult = {
|
|
|
105
131
|
steps: string[];
|
|
106
132
|
/** Which documents went in whole and which were searched. */
|
|
107
133
|
plan: DocumentPlan;
|
|
108
|
-
/** 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). */
|
|
109
135
|
turns: number;
|
|
110
136
|
finishReason?: string;
|
|
111
137
|
/** Usage metadata of the last model response. */
|
|
@@ -154,14 +180,28 @@ function baseSize(contents: GeminiContent[], system: string | undefined): { toke
|
|
|
154
180
|
return { tokens, bytes };
|
|
155
181
|
}
|
|
156
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
|
+
|
|
157
193
|
/**
|
|
158
194
|
* Answers a chat turn about large documents with Gemini (Generate Content REST).
|
|
159
195
|
* Documents that fit go into the prompt whole; otherwise Gemini gets search/read tools and this
|
|
160
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.
|
|
161
199
|
*/
|
|
162
200
|
export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiResult> {
|
|
163
201
|
const fetchImpl = options.fetch ?? fetch;
|
|
164
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;
|
|
165
205
|
const contents = toContents(options);
|
|
166
206
|
const prepared = await files.prepare(options.documentIds, baseSize(contents, options.system), { owner: options.owner, viewPages: options.viewPages !== false });
|
|
167
207
|
if (prepared.missing.length) throw new DocumentsNotFoundError(prepared.missing);
|
|
@@ -196,13 +236,16 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
|
|
|
196
236
|
/**
|
|
197
237
|
* One model request. Text is emitted as it arrives; parts are kept as received.
|
|
198
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.
|
|
199
241
|
*/
|
|
200
|
-
const turn = async (): Promise<{ parts: GeminiPart[]; calls: GeminiFunctionCall[]; wroteText: boolean }> => {
|
|
242
|
+
const turn = async (exploring?: Body): Promise<{ parts: GeminiPart[]; calls: GeminiFunctionCall[]; wroteText: boolean }> => {
|
|
201
243
|
turns++;
|
|
202
|
-
const
|
|
244
|
+
const stream = streaming && !exploring;
|
|
245
|
+
const response = await fetchImpl(exploring ? explorerUrl! : stream ? endpoint.streamUrl! : endpoint.url, {
|
|
203
246
|
method: "POST",
|
|
204
247
|
headers,
|
|
205
|
-
body: JSON.stringify(body),
|
|
248
|
+
body: JSON.stringify(exploring ?? body),
|
|
206
249
|
signal,
|
|
207
250
|
});
|
|
208
251
|
if (!response.ok) {
|
|
@@ -221,11 +264,13 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
|
|
|
221
264
|
// Keep every part unchanged: Gemini 3 requires its thought signatures back.
|
|
222
265
|
parts.push(part);
|
|
223
266
|
if (typeof part.text === "string" && part.text && part.thought !== true) {
|
|
224
|
-
if (!
|
|
225
|
-
|
|
226
|
-
|
|
267
|
+
if (!exploring) {
|
|
268
|
+
if (!separated) {
|
|
269
|
+
emit("\n\n");
|
|
270
|
+
separated = true;
|
|
271
|
+
}
|
|
272
|
+
emit(part.text);
|
|
227
273
|
}
|
|
228
|
-
emit(part.text);
|
|
229
274
|
if (part.text.trim()) wroteText = true;
|
|
230
275
|
}
|
|
231
276
|
const call = part.functionCall as { name?: unknown; args?: unknown; id?: unknown } | undefined;
|
|
@@ -237,7 +282,7 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
|
|
|
237
282
|
finishReason = candidate?.finishReason ?? finishReason;
|
|
238
283
|
usage = chunk.usageMetadata ?? usage;
|
|
239
284
|
};
|
|
240
|
-
if (
|
|
285
|
+
if (stream) {
|
|
241
286
|
if (!response.body) throw new GeminiRequestError("Gemini returned an empty stream.", response.status);
|
|
242
287
|
for await (const chunk of parseSseJson<Chunk>(response.body)) take(chunk);
|
|
243
288
|
} else {
|
|
@@ -265,14 +310,27 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
|
|
|
265
310
|
|
|
266
311
|
const tools = files.tools(searchable, {
|
|
267
312
|
...(options.wholeDocumentAnalysis === false ? {} : {
|
|
268
|
-
|
|
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 } : {}) }),
|
|
269
315
|
}),
|
|
270
316
|
onProgress: (event) => options.onActivity?.(`${event.message}…`),
|
|
271
317
|
...(signal ? { signal } : {}),
|
|
272
318
|
...(viewable.length > 0 ? { viewPages: viewable } : {}),
|
|
273
319
|
});
|
|
274
|
-
|
|
275
|
-
|
|
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;
|
|
276
334
|
if (searchable.length > 0) options.onActivity?.(`Too large to read at once: ${searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
|
|
277
335
|
|
|
278
336
|
// Pages the model looks at stay in the request until the question is answered, so they are
|
|
@@ -287,10 +345,11 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
|
|
|
287
345
|
// Tools run in at most maxTurns - 1 requests. The last request is the tool-free one below, so a
|
|
288
346
|
// model that never stops calling tools does not cost a request whose calls are thrown away.
|
|
289
347
|
for (let round = 1; round < maxTurns; round++) {
|
|
290
|
-
const { parts, calls, wroteText } = await turn();
|
|
348
|
+
const { parts, calls, wroteText } = await turn(exploring);
|
|
291
349
|
if (calls.length === 0) {
|
|
292
350
|
// Text from this turn is the answer. A remark made earlier, before a tool call, is not.
|
|
293
|
-
|
|
351
|
+
// Neither is anything an explorer model writes: the answer is asked for below.
|
|
352
|
+
answered = wroteText && !exploring;
|
|
294
353
|
break;
|
|
295
354
|
}
|
|
296
355
|
body.contents.push({ role: "model", parts });
|
|
@@ -302,7 +361,7 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
|
|
|
302
361
|
options.onActivity?.(`${label}…`);
|
|
303
362
|
let limits: ToolFileLimits | undefined;
|
|
304
363
|
if (call.name === TOOL_NAMES.view) {
|
|
305
|
-
requestBytes ??= Buffer.byteLength(JSON.stringify(
|
|
364
|
+
requestBytes ??= Buffer.byteLength(JSON.stringify(withTools));
|
|
306
365
|
// Base64 turns three bytes into four characters.
|
|
307
366
|
limits = { maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4), maxPages: pagesLeft };
|
|
308
367
|
}
|
|
@@ -320,11 +379,20 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
|
|
|
320
379
|
// Out of tool turns, or the last turn had no text (cut off, or a malformed tool call): ask once
|
|
321
380
|
// more with no tools declared at all. (Gemini can ignore functionCallingConfig mode NONE and
|
|
322
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.
|
|
323
383
|
if (!answered && !blockReason) {
|
|
324
384
|
options.onActivity?.("Writing the answer…");
|
|
325
385
|
delete body.tools;
|
|
326
386
|
delete body.toolConfig;
|
|
327
|
-
|
|
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 }] });
|
|
328
396
|
answered = (await turn()).wroteText;
|
|
329
397
|
}
|
|
330
398
|
return result(answered);
|
package/src/gemini/endpoints.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
package/src/gemini/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { askGemini, DocumentsNotFoundError, FINAL_ANSWER_AFTER_PAGES, 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";
|