llm-large-files 0.8.2 → 0.10.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.
- package/CHANGELOG.md +981 -0
- package/README.md +22 -17
- package/dist/access.d.ts +128 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +234 -0
- package/dist/access.js.map +1 -0
- package/dist/aggregate.d.ts +6 -0
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +86 -13
- package/dist/aggregate.js.map +1 -1
- package/dist/analyze.d.ts +4 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +2 -2
- package/dist/analyze.js.map +1 -1
- package/dist/answer-info.d.ts +26 -0
- package/dist/answer-info.d.ts.map +1 -0
- package/dist/answer-info.js +32 -0
- package/dist/answer-info.js.map +1 -0
- package/dist/anthropic/adapter.d.ts +5 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +35 -10
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +159 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +743 -113
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/citations.d.ts +36 -0
- package/dist/citations.d.ts.map +1 -0
- package/dist/citations.js +291 -0
- package/dist/citations.js.map +1 -0
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +70 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +253 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +74 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +104 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +57 -13
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +35 -5
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +52 -36
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +54 -7
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +152 -41
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +38 -53
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -25
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +59 -11
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +33 -7
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +39 -5
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +70 -9
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +53 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +100 -50
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +4 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/http.d.ts +41 -3
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +40 -2
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +13 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -5
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +78 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +893 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +295 -33
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +458 -650
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +176 -10
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +807 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +79 -6
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +80 -4
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +247 -14
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +491 -227
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +19 -4
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +106 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +378 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +6 -4
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +9 -7
- package/dist/node/sse.js.map +1 -1
- package/dist/openai/adapter.d.ts +5 -1
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +53 -12
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +2 -1
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +5 -2
- package/dist/output-limit.js.map +1 -1
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.js.map +1 -1
- package/dist/pdf-outline.d.ts +71 -0
- package/dist/pdf-outline.d.ts.map +1 -0
- package/dist/pdf-outline.js +414 -0
- package/dist/pdf-outline.js.map +1 -0
- package/dist/plan.d.ts +137 -7
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +248 -26
- package/dist/plan.js.map +1 -1
- package/dist/prepare.d.ts +50 -0
- package/dist/prepare.d.ts.map +1 -0
- package/dist/prepare.js +207 -0
- package/dist/prepare.js.map +1 -0
- package/dist/ranged.d.ts +16 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +56 -12
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- package/dist/search.d.ts +7 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +72 -10
- package/dist/search.js.map +1 -1
- package/dist/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +126 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +655 -141
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +47 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +440 -71
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +165 -14
- package/dist/types.d.ts.map +1 -1
- package/dist/whole-cost.d.ts +37 -0
- package/dist/whole-cost.d.ts.map +1 -0
- package/dist/whole-cost.js +46 -0
- package/dist/whole-cost.js.map +1 -0
- package/docs/README.md +21 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +17 -10
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +147 -42
- package/docs/guides/deployment.md +380 -86
- package/docs/guides/errors-and-reliability.md +317 -67
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +60 -16
- package/docs/guides/pdfs.md +219 -36
- package/docs/guides/storage.md +676 -145
- package/docs/guides/testing.md +149 -129
- package/docs/guides/vertex-and-gemini.md +169 -57
- package/docs/guides/web-app.md +318 -80
- package/docs/how-it-works.md +155 -30
- package/docs/measurements.md +215 -13
- package/docs/publishing.md +185 -37
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +415 -47
- package/docs/reference/errors-and-retries.md +194 -14
- package/docs/reference/events.md +77 -27
- package/docs/reference/gemini.md +252 -87
- package/docs/reference/library.md +886 -178
- package/docs/reference/node.md +659 -111
- package/docs/reference/openai.md +21 -10
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +285 -30
- package/docs/security.md +404 -78
- package/docs/troubleshooting.md +151 -70
- package/docs/upgrading-0.10.md +472 -0
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +16 -3
- package/src/access.ts +267 -0
- package/src/aggregate.ts +92 -14
- package/src/analyze.ts +2 -2
- package/src/answer-info.ts +45 -0
- package/src/anthropic/adapter.ts +40 -11
- package/src/ask.ts +866 -115
- package/src/cache.ts +20 -5
- package/src/citations.ts +294 -0
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +290 -0
- package/src/errors.ts +131 -15
- package/src/events.ts +112 -24
- package/src/evidence.ts +35 -5
- package/src/extract.ts +56 -34
- package/src/gemini/adapter.ts +196 -43
- package/src/gemini/chat.ts +63 -78
- package/src/gemini/endpoints.ts +89 -16
- package/src/gemini/errors.ts +74 -11
- package/src/gemini/generate.ts +147 -57
- package/src/gemini/index.ts +4 -4
- package/src/http.ts +65 -4
- package/src/index.ts +13 -8
- package/src/ingest.ts +958 -0
- package/src/library.ts +711 -651
- package/src/map-reduce.ts +858 -70
- package/src/model.ts +113 -9
- package/src/node/handlers.ts +709 -221
- package/src/node/index.ts +14 -2
- package/src/node/ingest-child.ts +24 -6
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +379 -0
- package/src/node/sse.ts +9 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-layout.ts +69 -11
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +48 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/search.ts +69 -13
- package/src/source.ts +178 -0
- package/src/stores.ts +702 -142
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +461 -73
- package/src/types.ts +151 -14
- package/src/whole-cost.ts +64 -0
package/src/extract.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { decodeText, plainText } from "./decode.js";
|
|
|
2
2
|
import { html } from "./html.js";
|
|
3
3
|
import { TimeSlicer } from "./pause.js";
|
|
4
4
|
import { layoutPage, plainPageText, type LayoutBox, type PdfTextItem } from "./pdf-layout.js";
|
|
5
|
+
import { PdfHeadingFinder } from "./pdf-outline.js";
|
|
5
6
|
import { findPicturePages, parsePdf, type PageGeometry } from "./pdf-pictures.js";
|
|
6
7
|
import { checkPageWork, HeavyPage } from "./pdf-work.js";
|
|
7
8
|
import { formatBytes } from "./plan.js";
|
|
@@ -39,23 +40,34 @@ const MIME_FORMATS: Record<string, DocumentFormat> = {
|
|
|
39
40
|
};
|
|
40
41
|
|
|
41
42
|
/**
|
|
42
|
-
*
|
|
43
|
+
* The format a file's name, then its MIME type, say, and whether its bytes are to be looked at
|
|
44
|
+
* (`sniff`): a name and a type that say nothing more than text, without a ".txt" extension. Both
|
|
43
45
|
* come from the upload: only the tables' own keys count, not "constructor" or "__proto__", which
|
|
44
46
|
* every object has.
|
|
45
47
|
*/
|
|
46
|
-
export function
|
|
48
|
+
export function namedFormat(name: string, mimeType: string): { format: DocumentFormat; sniff: boolean } {
|
|
47
49
|
const extension = name.toLowerCase().split(".").at(-1) ?? "";
|
|
48
50
|
const mime = mimeType.toLowerCase();
|
|
49
|
-
const
|
|
51
|
+
const format = (Object.hasOwn(EXTENSION_FORMATS, extension) ? EXTENSION_FORMATS[extension] : undefined)
|
|
50
52
|
?? (Object.hasOwn(MIME_FORMATS, mime) ? MIME_FORMATS[mime] : undefined)
|
|
51
53
|
?? "text";
|
|
52
54
|
// A name that says text ("notes.txt") is taken at its word.
|
|
53
|
-
return
|
|
55
|
+
return { format, sniff: format === "text" && extension !== "txt" };
|
|
54
56
|
}
|
|
55
57
|
|
|
56
|
-
/**
|
|
57
|
-
|
|
58
|
-
const
|
|
58
|
+
/** Picks a format from the file name, then the MIME type, then the bytes, when they are given and the name and type say nothing. Unknown text-like files are "text". */
|
|
59
|
+
export function detectFormat(name: string, mimeType: string, bytes?: Uint8Array): DocumentFormat {
|
|
60
|
+
const { format, sniff } = namedFormat(name, mimeType);
|
|
61
|
+
return sniff && bytes ? sniffFormat(bytes) ?? format : format;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The bytes the format of a file is told by (`sniffFormat`): its first KB, and for a ZIP (an Office
|
|
66
|
+
* file) the names of its parts, in its first 64 KB and its directory, in its last MB.
|
|
67
|
+
*/
|
|
68
|
+
export const SNIFFED_FIRST = 1_024;
|
|
69
|
+
export const SNIFFED_HEAD = 64 * 1024;
|
|
70
|
+
export const SNIFFED_TAIL = 1024 * 1024;
|
|
59
71
|
|
|
60
72
|
/**
|
|
61
73
|
* The format of a file whose name and type say nothing (no extension, "application/octet-stream"),
|
|
@@ -64,11 +76,22 @@ const SNIFFED_TAIL = 1024 * 1024;
|
|
|
64
76
|
* extension was told "This file is a ZIP archive".
|
|
65
77
|
*/
|
|
66
78
|
export function sniffFormat(bytes: Uint8Array): DocumentFormat | undefined {
|
|
67
|
-
|
|
68
|
-
|
|
79
|
+
return sniffParts(bytes.subarray(0, SNIFFED_HEAD), bytes.subarray(Math.max(SNIFFED_HEAD, bytes.length - SNIFFED_TAIL)));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Whether the bytes start as a ZIP archive does: an Office file is one. */
|
|
83
|
+
export const isZip = (head: Uint8Array) => head[0] === 0x50 && head[1] === 0x4b && head[2] === 0x03 && head[3] === 0x04;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* `sniffFormat`, from the parts of a file it looks at, as they are read from a path without reading
|
|
87
|
+
* the rest: `head`, the file from its start (its first KB, or for a ZIP its first 64 KB), and
|
|
88
|
+
* `tail`, for a ZIP, the file from 64 KB (or its last MB, when it is larger) to its end.
|
|
89
|
+
*/
|
|
90
|
+
export function sniffParts(head: Uint8Array, tail: Uint8Array): DocumentFormat | undefined {
|
|
91
|
+
const start = latin1(head.subarray(0, SNIFFED_FIRST)).replace(/^\xef\xbb\xbf/, "").trimStart();
|
|
69
92
|
if (start.startsWith("%PDF-")) return "pdf";
|
|
70
|
-
if (
|
|
71
|
-
const names = latin1(
|
|
93
|
+
if (isZip(head)) {
|
|
94
|
+
const names = latin1(head.subarray(0, SNIFFED_HEAD)) + latin1(tail);
|
|
72
95
|
if (names.includes("word/document.xml")) return "docx";
|
|
73
96
|
if (names.includes("ppt/presentation.xml") || names.includes("ppt/slides/")) return "pptx";
|
|
74
97
|
if (names.includes("xl/workbook.xml")) return "xlsx";
|
|
@@ -176,30 +199,21 @@ function pageProgress(input: ExtractInput | undefined, stage: ExtractProgress["s
|
|
|
176
199
|
}
|
|
177
200
|
|
|
178
201
|
/**
|
|
179
|
-
* Loads pdf.js through `unpdf`, and refuses a version of unpdf that
|
|
180
|
-
* version of Node (`node`, as in `process.versions.node`), with a message that says what to install
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
* The
|
|
202
|
+
* Loads pdf.js through `unpdf`, and refuses a version of unpdf that would stop the process on this
|
|
203
|
+
* version of Node (`node`, as in `process.versions.node`), with a message that says what to install.
|
|
204
|
+
* pdf.js calls `Promise.try`, which Node 22 does not have (Node 24 does). unpdf adds it where it is
|
|
205
|
+
* missing, but 1.5.0 to 1.6.0 do not: there, the first PDF throws where nothing can catch it, and
|
|
206
|
+
* the whole process stops. An error of unpdf while it loads pdf.js is passed on as it is.
|
|
207
|
+
* The message gives the major version of Node only: an upload can be answered with it. Its start,
|
|
208
|
+
* "The unpdf installed would stop the whole server", is what `ingestErrorCodeOf` (errors.ts) reads
|
|
209
|
+
* as missing_dependency.
|
|
186
210
|
*/
|
|
187
211
|
export async function checkUnpdf(unpdf: { getResolvedPDFJS?: unknown }, node: string = process.versions.node): Promise<void> {
|
|
188
212
|
if (typeof unpdf.getResolvedPDFJS !== "function") return;
|
|
189
|
-
|
|
190
|
-
try {
|
|
191
|
-
await (unpdf.getResolvedPDFJS as () => Promise<unknown>)();
|
|
192
|
-
} catch (error) {
|
|
193
|
-
if (major >= 22) throw error;
|
|
194
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
195
|
-
throw new Error(`The unpdf installed cannot read PDF files on Node ${major} (${reason}). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.`);
|
|
196
|
-
}
|
|
213
|
+
await (unpdf.getResolvedPDFJS as () => Promise<unknown>)();
|
|
197
214
|
if (typeof (Promise as { try?: unknown }).try !== "function") {
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
: major < 24
|
|
201
|
-
? "Install unpdf 1.6.1 or later, or run Node 24 or later."
|
|
202
|
-
: "Install unpdf 1.6.1 or later.";
|
|
215
|
+
const major = Number.parseInt(node, 10);
|
|
216
|
+
const advice = major < 24 ? "Install unpdf 1.6.1 or later, or run Node 24 or later." : "Install unpdf 1.6.1 or later.";
|
|
203
217
|
throw new Error(`The unpdf installed would stop the whole server at the first PDF file on Node ${major}, so PDF files are not read. ${advice}`);
|
|
204
218
|
}
|
|
205
219
|
}
|
|
@@ -255,6 +269,8 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
|
|
|
255
269
|
const textLimit = Math.min(maxTextBytes, mostDrawn);
|
|
256
270
|
const texts: string[] = [];
|
|
257
271
|
const geometry: PageGeometry[] = [];
|
|
272
|
+
// The lines set larger than the body: the outline of a PDF whose text gives few headings (0.10.0).
|
|
273
|
+
const headingFinder = new PdfHeadingFinder();
|
|
258
274
|
/** The page objects read so far: a page tree that lists one page twice is refused. */
|
|
259
275
|
const seen = new Set<string>();
|
|
260
276
|
// pdf.js reads a page through promises that never let a timer or another request run: other
|
|
@@ -274,6 +290,7 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
|
|
|
274
290
|
const content = await page.getTextContent();
|
|
275
291
|
const items = (content.items as unknown[]).filter((item): item is PdfTextItem => typeof (item as PdfTextItem).str === "string");
|
|
276
292
|
const transform = page.getViewport({ scale: 1 }).transform as number[];
|
|
293
|
+
headingFinder.addPage(number, items);
|
|
277
294
|
let text = "";
|
|
278
295
|
let found: LayoutBox[] = [];
|
|
279
296
|
if (tables) {
|
|
@@ -312,7 +329,8 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
|
|
|
312
329
|
signal?.throwIfAborted();
|
|
313
330
|
looked.rethrow();
|
|
314
331
|
const pages = texts.map((text, index) => `--- Page ${index + 1} ---\n${pictured?.[index] ? `${PICTURE_ON_PAGE}\n` : ""}${text ? ownLines(text) : PAGE_WITHOUT_TEXT}`);
|
|
315
|
-
|
|
332
|
+
const headings = headingFinder.headings();
|
|
333
|
+
return { text: pages.join("\n\n"), pages: document.numPages, ...(headings.length > 0 ? { headings } : {}) };
|
|
316
334
|
};
|
|
317
335
|
}
|
|
318
336
|
|
|
@@ -329,11 +347,15 @@ export const defaultExtractors: Record<DocumentFormat, Extractor> = {
|
|
|
329
347
|
html,
|
|
330
348
|
};
|
|
331
349
|
|
|
350
|
+
/** The extractor of a format: the application's own (`LargeFilesOptions.extractors`), or the built-in one. */
|
|
351
|
+
export function extractorFor(format: DocumentFormat, extractors: Partial<Record<DocumentFormat, Extractor>> = {}): Extractor {
|
|
352
|
+
return extractors[format] ?? defaultExtractors[format];
|
|
353
|
+
}
|
|
354
|
+
|
|
332
355
|
export async function extractText(
|
|
333
356
|
bytes: Uint8Array,
|
|
334
357
|
input: ExtractInput,
|
|
335
358
|
extractors: Partial<Record<DocumentFormat, Extractor>> = {},
|
|
336
359
|
): Promise<ExtractedText> {
|
|
337
|
-
|
|
338
|
-
return extractor(bytes, input);
|
|
360
|
+
return extractorFor(input.format, extractors)(bytes, input);
|
|
339
361
|
}
|
package/src/gemini/adapter.ts
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
// Gemini (Generate Content REST) as a model of `askWithFiles`.
|
|
2
|
-
import { laterResult, type ChatMessage, type ModelAdapter, type ModelMessage, type ModelReply, type ModelRequest, type ModelTextMessage, type ModelToolRound, type SendHooks, type ToolCall, type ToolTurn } from "../model.js";
|
|
2
|
+
import { laterResult, TOOL_TURN_VERSION, type ChatMessage, type ModelAdapter, type ModelMessage, type ModelPart, type ModelReply, type ModelRequest, type ModelTextMessage, type ModelToolRound, type SendHooks, type ToolCall, type ToolTurn } from "../model.js";
|
|
3
|
+
import { TOOL_NAMES } from "../tools.js";
|
|
4
|
+
import type { ToolResult } from "../types.js";
|
|
3
5
|
import { retryAfterMs } from "../retry.js";
|
|
4
6
|
import { idleWatch, noteCutReply, readJson, streamedReply, type IdleWatch } from "../http.js";
|
|
5
7
|
import { eventTooLongMessage, parseSseJson, SseEventTooLongError } from "../sse.js";
|
|
6
8
|
import { resolveHeaders, type GeminiEndpoint } from "./endpoints.js";
|
|
7
|
-
import { finishOfGemini, geminiFailure, GeminiRequestError, notJson, silent, unreachable } from "./errors.js";
|
|
8
|
-
import { createGeminiGenerateText, geminiFunctionResponseTurns, usageOfGemini, type GeminiContent, type GeminiPart, type GeminiToolFilePlacement } from "./generate.js";
|
|
9
|
+
import { errorBodyOf, finishOfGemini, geminiFailure, GeminiRequestError, notJson, silent, statusOfError, unreachable } from "./errors.js";
|
|
10
|
+
import { createGeminiGenerateText, discard, geminiFunctionResponseTurns, usageOfGemini, type GeminiContent, type GeminiPart, type GeminiRequestFields, type GeminiToolFilePlacement } from "./generate.js";
|
|
9
11
|
|
|
10
|
-
export type { GeminiContent, GeminiPart };
|
|
12
|
+
export type { GeminiContent, GeminiPart, GeminiRequestFields };
|
|
11
13
|
|
|
12
14
|
/** What Gemini bills for one PDF page it is shown (measured: 520 to 532). */
|
|
13
15
|
export const GEMINI_PAGE_TOKENS = 530;
|
|
@@ -32,6 +34,36 @@ export type GeminiModelOptions = {
|
|
|
32
34
|
pageTokens?: number | undefined;
|
|
33
35
|
/** Names the model in usage totals. Defaults to the model in the URL. */
|
|
34
36
|
id?: string | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* More fields for the body of every chat request, the request for the answer included:
|
|
39
|
+
* `safetySettings`, `labels` (Vertex AI), `serviceTier`, `cachedContent`, and so on. Merged last,
|
|
40
|
+
* after the library's. New in 0.10.0.
|
|
41
|
+
*/
|
|
42
|
+
body?: GeminiRequestFields | undefined;
|
|
43
|
+
/**
|
|
44
|
+
* More fields for the body of a whole-document part read, given the output limit it is sent with.
|
|
45
|
+
* Merged last. Its `generationConfig` is `analysisConfig`. New in 0.10.0.
|
|
46
|
+
*/
|
|
47
|
+
analysisBody?: ((maxOutputTokens: number) => GeminiRequestFields) | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* The mode of `functionCallingConfig` in a request that offers tools: "AUTO" (the default), or
|
|
50
|
+
* "VALIDATED", in which Gemini checks each call against the declaration of its tool. It is sent
|
|
51
|
+
* only with tools. New in 0.10.0.
|
|
52
|
+
*/
|
|
53
|
+
functionCallingMode?: "AUTO" | "VALIDATED" | undefined;
|
|
54
|
+
/**
|
|
55
|
+
* The longest time, in milliseconds, that one part read of a whole-file read may take, its whole
|
|
56
|
+
* reply included. Defaults to 180,000; 0 sets none. A part past it is sent again once, and is
|
|
57
|
+
* then reported as "The model took too long to answer". New in 0.10.0.
|
|
58
|
+
*/
|
|
59
|
+
timeoutMs?: number | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* How the request that must be answered in text says so. "omit" (the default) declares no tools:
|
|
62
|
+
* Gemini can ignore mode NONE and keep calling them. "mode_none" keeps the tools and sends
|
|
63
|
+
* `functionCallingConfig` mode NONE, so that the request starts as the ones before it did; a tool
|
|
64
|
+
* call that still comes back is asked for again once. New in 0.10.0.
|
|
65
|
+
*/
|
|
66
|
+
answerWithoutTools?: "omit" | "mode_none" | undefined;
|
|
35
67
|
/**
|
|
36
68
|
* The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count:
|
|
37
69
|
* a model that thinks sends nothing until it has thought, and a reply that is not streamed comes
|
|
@@ -54,13 +86,16 @@ type Body = {
|
|
|
54
86
|
generationConfig?: Record<string, unknown>;
|
|
55
87
|
tools?: unknown[];
|
|
56
88
|
toolConfig?: unknown;
|
|
89
|
+
[key: string]: unknown;
|
|
57
90
|
};
|
|
58
91
|
|
|
59
92
|
type Chunk = {
|
|
60
93
|
candidates?: Array<{ finishReason?: string; content?: { parts?: GeminiPart[] } }>;
|
|
61
94
|
usageMetadata?: Record<string, unknown>;
|
|
62
95
|
promptFeedback?: { blockReason?: string };
|
|
63
|
-
error?: { message?: string; code?: unknown };
|
|
96
|
+
error?: { message?: string; code?: unknown; status?: unknown; details?: unknown };
|
|
97
|
+
responseId?: unknown;
|
|
98
|
+
modelVersion?: unknown;
|
|
64
99
|
};
|
|
65
100
|
|
|
66
101
|
/** The model a Generate Content URL names: ".../models/gemini-3.8-flash:generateContent". */
|
|
@@ -88,18 +123,102 @@ const textTurn = (message: ModelTextMessage): GeminiContent[] => {
|
|
|
88
123
|
return parts.length > 0 ? [{ role: message.role === "user" ? "user" : "model", parts }] : [];
|
|
89
124
|
};
|
|
90
125
|
|
|
126
|
+
export type FromGeminiContentsOptions = {
|
|
127
|
+
/**
|
|
128
|
+
* Turn the tool rounds of earlier questions back into stored rounds (`ToolTurn`), as
|
|
129
|
+
* `geminiToolTurns` wrote them: a `model` turn made only of `functionCall` parts that call this
|
|
130
|
+
* library's tools (`TOOL_NAMES`), followed by the `user` turn of their `functionResponse` parts,
|
|
131
|
+
* one for each call, in the same order, with the same names and ids. The loop can then point a
|
|
132
|
+
* repeated call to them, shorten them to make room, and size them as it sizes `toolTurns`. The
|
|
133
|
+
* request is the same for the rounds `geminiToolTurns` wrote. A turn with anything else in it (a
|
|
134
|
+
* function of your own, a thought signature, a file in a response) stays as it is, and so does a
|
|
135
|
+
* round that ends `contents`: its responses are the turn the model answers. Defaults to true;
|
|
136
|
+
* false gives the turns of 0.8. New in 0.9.0.
|
|
137
|
+
*/
|
|
138
|
+
rounds?: boolean;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/** The names of the library's tools. */
|
|
142
|
+
const LIBRARY_TOOLS: ReadonlySet<string> = new Set(Object.values(TOOL_NAMES));
|
|
143
|
+
|
|
144
|
+
const isPlainObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
145
|
+
/** Whether `value` has no keys but those `allowed`. */
|
|
146
|
+
const onlyKeys = (value: Record<string, unknown>, allowed: readonly string[]) => Object.keys(value).every((key) => allowed.includes(key));
|
|
147
|
+
/** The field `name` of a part that has that field and no other, when it is an object. */
|
|
148
|
+
const soleField = (part: GeminiPart | undefined, name: string): Record<string, unknown> | undefined => {
|
|
149
|
+
if (!isPlainObject(part)) return undefined;
|
|
150
|
+
const keys = Object.keys(part);
|
|
151
|
+
return keys.length === 1 && keys[0] === name && isPlainObject(part[name]) ? part[name] : undefined;
|
|
152
|
+
};
|
|
153
|
+
|
|
91
154
|
/**
|
|
92
|
-
*
|
|
93
|
-
*
|
|
155
|
+
* A stored tool round of the library, in the form `geminiToolTurns` gives it: `asked` is a model
|
|
156
|
+
* turn of calls of the library's tools and nothing else, and `answered` the turn of their
|
|
157
|
+
* responses, in the same order. Undefined for anything else.
|
|
94
158
|
*/
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
159
|
+
function liftedRound(asked: GeminiContent, answered: GeminiContent | undefined): ToolTurn | undefined {
|
|
160
|
+
if (asked.role !== "model" || answered?.role !== "user" || !Array.isArray(asked.parts) || !Array.isArray(answered.parts)) return undefined;
|
|
161
|
+
if (asked.parts.length === 0 || answered.parts.length !== asked.parts.length) return undefined;
|
|
162
|
+
const calls: ToolTurn["calls"] = [];
|
|
163
|
+
for (const [index, part] of asked.parts.entries()) {
|
|
164
|
+
const call = soleField(part, "functionCall");
|
|
165
|
+
const response = soleField(answered.parts[index], "functionResponse");
|
|
166
|
+
if (!call || !response || !onlyKeys(call, ["name", "args", "id"]) || !onlyKeys(response, ["name", "id", "response"])) return undefined;
|
|
167
|
+
const { name, args = {}, id } = call;
|
|
168
|
+
if (typeof name !== "string" || !LIBRARY_TOOLS.has(name) || !isPlainObject(args) || (id !== undefined && typeof id !== "string")) return undefined;
|
|
169
|
+
if (response.name !== name || response.id !== id || !isPlainObject(response.response)) return undefined;
|
|
170
|
+
calls.push({ ...(id ? { id } : {}), name, args, result: response.response as ToolResult });
|
|
171
|
+
}
|
|
172
|
+
return { role: "tools", version: TOOL_TURN_VERSION, calls };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* The text a function part is sized by: the JSON of its call or response. Undefined for any other
|
|
177
|
+
* part, and for a response with files in it, which is sized as media.
|
|
178
|
+
*/
|
|
179
|
+
function sizingText(part: GeminiPart): string | undefined {
|
|
180
|
+
for (const name of ["functionCall", "functionResponse"]) {
|
|
181
|
+
const field = part[name];
|
|
182
|
+
if (!isPlainObject(field)) continue;
|
|
183
|
+
if (Array.isArray(field.parts) && field.parts.length > 0) return undefined;
|
|
184
|
+
return JSON.stringify(field);
|
|
185
|
+
}
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** A part of a turn that is not part of a stored round. */
|
|
190
|
+
function partOf(part: GeminiPart): ModelPart {
|
|
191
|
+
if (typeof part.text !== "string") {
|
|
192
|
+
const text = sizingText(part);
|
|
193
|
+
return text === undefined ? { native: part } : { native: part, text };
|
|
194
|
+
}
|
|
195
|
+
return Object.keys(part).length === 1 ? { text: part.text } : { native: part, text: part.text };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Gemini `contents` as messages of `askWithFiles`: text parts as text, the tool rounds of earlier
|
|
200
|
+
* questions that `geminiToolTurns` gave as stored rounds (see `options.rounds`, since 0.9.0), and
|
|
201
|
+
* every other part (an image, an inline PDF, a function call of your own) as it is. A function
|
|
202
|
+
* part kept as it is is sized by the JSON of its call or response (since 0.9.0; before, as media).
|
|
203
|
+
*/
|
|
204
|
+
export function fromGeminiContents(contents: GeminiContent[], options: FromGeminiContentsOptions = {}): ChatMessage[] {
|
|
205
|
+
const lift = options.rounds !== false;
|
|
206
|
+
const messages: ChatMessage[] = [];
|
|
207
|
+
for (let at = 0; at < contents.length; at++) {
|
|
208
|
+
const content = contents[at]!;
|
|
209
|
+
// A round is lifted only when a turn follows it. Responses that end `contents` are the turn the
|
|
210
|
+
// model answers (an application that ran the tools in a loop of its own hands them over), and
|
|
211
|
+
// stay as they are, as in 0.8.
|
|
212
|
+
const round = lift && at + 2 < contents.length ? liftedRound(content, contents[at + 1]) : undefined;
|
|
213
|
+
if (round) {
|
|
214
|
+
messages.push(round);
|
|
215
|
+
at++;
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
const turn: ModelTextMessage = { role: content.role === "user" ? "user" : "assistant", parts: content.parts.map(partOf) };
|
|
219
|
+
messages.push(turn);
|
|
220
|
+
}
|
|
221
|
+
return messages;
|
|
103
222
|
}
|
|
104
223
|
|
|
105
224
|
/**
|
|
@@ -118,11 +237,13 @@ export function geminiToolTurns(turns: ToolTurn[]): GeminiContent[] {
|
|
|
118
237
|
/**
|
|
119
238
|
* A Gemini model for `askWithFiles`. `endpoint` says where it is: `geminiApi()`, `vertexAi()`, or
|
|
120
239
|
* your own URLs and headers for a gateway. Its `explorerUrl` is not used here: an explorer is a
|
|
121
|
-
* model of its own, `gemini(geminiApi({ apiKey, model: "the-explorer" }))`.
|
|
240
|
+
* model of its own, `gemini(geminiApi({ apiKey, model: "the-explorer" }))`. A `refreshable`
|
|
241
|
+
* endpoint gets one more try, with headers asked for with `{ refresh: true }`, after a 401.
|
|
122
242
|
*/
|
|
123
|
-
export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "headers">, options: GeminiModelOptions = {}): ModelAdapter {
|
|
243
|
+
export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "headers" | "refreshable">, options: GeminiModelOptions = {}): ModelAdapter {
|
|
124
244
|
const fetchImpl = options.fetch ?? fetch;
|
|
125
245
|
const placement = options.toolFilePlacement ?? "inside";
|
|
246
|
+
const refreshable = endpoint.refreshable === true;
|
|
126
247
|
// The turns of a tool round are built once: its pages are megabytes of base64.
|
|
127
248
|
const built = new WeakMap<ModelToolRound, GeminiContent[]>();
|
|
128
249
|
const roundTurns = (round: ModelToolRound): GeminiContent[] => {
|
|
@@ -136,17 +257,23 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
|
|
|
136
257
|
return turns;
|
|
137
258
|
};
|
|
138
259
|
const toContents = (messages: ModelMessage[]): GeminiContent[] => messages.flatMap((message) => (message.role === "tools" ? roundTurns(message) : textTurn(message)));
|
|
139
|
-
const bodyOf = (request: ModelRequest): Body =>
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
//
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
260
|
+
const bodyOf = (request: ModelRequest): Body => {
|
|
261
|
+
const mustAnswer = request.toolChoice === "none";
|
|
262
|
+
// A request that must be answered in text declares no tools at all, by default: Gemini can
|
|
263
|
+
// ignore functionCallingConfig mode NONE and keep calling them. With "mode_none" it keeps
|
|
264
|
+
// them, so that it starts as the requests before it did.
|
|
265
|
+
const declare = Boolean(request.tools?.length) && (!mustAnswer || options.answerWithoutTools === "mode_none");
|
|
266
|
+
return {
|
|
267
|
+
contents: toContents(request.messages),
|
|
268
|
+
...(request.system ? { systemInstruction: { parts: [{ text: request.system }] } } : {}),
|
|
269
|
+
...(options.generationConfig ? { generationConfig: options.generationConfig } : {}),
|
|
270
|
+
...(declare ? {
|
|
271
|
+
tools: [{ functionDeclarations: request.tools }],
|
|
272
|
+
toolConfig: { functionCallingConfig: { mode: mustAnswer ? "NONE" : options.functionCallingMode ?? "AUTO" } },
|
|
273
|
+
} : {}),
|
|
274
|
+
...options.body,
|
|
275
|
+
};
|
|
276
|
+
};
|
|
150
277
|
|
|
151
278
|
return {
|
|
152
279
|
id: options.id ?? modelOf(endpoint.url),
|
|
@@ -162,33 +289,49 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
|
|
|
162
289
|
headers: endpoint.headers,
|
|
163
290
|
fetchImpl,
|
|
164
291
|
...(options.analysisConfig ? { generationConfig: options.analysisConfig } : {}),
|
|
292
|
+
...(options.analysisBody ? { body: options.analysisBody } : {}),
|
|
293
|
+
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
|
294
|
+
...(refreshable ? { refreshable } : {}),
|
|
165
295
|
}),
|
|
166
296
|
|
|
167
297
|
async send(request: ModelRequest, hooks: SendHooks = {}): Promise<ModelReply> {
|
|
168
298
|
const stream = Boolean(hooks.onText && endpoint.streamUrl);
|
|
169
299
|
// Headers are asked for with each request: an access token may have been renewed since the last.
|
|
170
300
|
const headers = await resolveHeaders(endpoint);
|
|
301
|
+
const body = JSON.stringify(bodyOf(request));
|
|
171
302
|
const watch = idleWatch(hooks.signal, { firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs });
|
|
172
303
|
// A request the watch aborted got nothing back for the whole wait: that is no failed connection.
|
|
173
304
|
const lost = (error: unknown) => (watch.expired ? silent(watch.waitedMs) : unreachable(error));
|
|
174
|
-
|
|
175
|
-
let response: Response;
|
|
305
|
+
const post = async (sent: Record<string, string>): Promise<Response> => {
|
|
176
306
|
try {
|
|
177
|
-
|
|
178
|
-
method: "POST",
|
|
179
|
-
headers,
|
|
180
|
-
body: JSON.stringify(bodyOf(request)),
|
|
181
|
-
signal: watch.signal,
|
|
182
|
-
});
|
|
307
|
+
return await fetchImpl(stream ? endpoint.streamUrl! : endpoint.url, { method: "POST", headers: sent, body, signal: watch.signal });
|
|
183
308
|
} catch (error) {
|
|
184
309
|
if (hooks.signal?.aborted) throw error;
|
|
185
310
|
throw lost(error);
|
|
186
311
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
312
|
+
};
|
|
313
|
+
/** The error of a response that is not OK, from its body. */
|
|
314
|
+
const failureOf = async (response: Response, cause?: unknown): Promise<GeminiRequestError> => {
|
|
315
|
+
const data = await response.json().catch(() => null);
|
|
316
|
+
return geminiFailure(response.status, data, retryAfterMs(response.headers, errorBodyOf(data)), `Gemini returned HTTP ${response.status}.`, cause);
|
|
317
|
+
};
|
|
318
|
+
try {
|
|
319
|
+
let response = await post(headers);
|
|
320
|
+
// A token that was refused may be one a cache kept past its time: one more try, with
|
|
321
|
+
// headers asked for anew. A second 401 is the error.
|
|
322
|
+
if (response.status === 401 && refreshable) {
|
|
323
|
+
let fresh: Record<string, string>;
|
|
324
|
+
try {
|
|
325
|
+
fresh = await resolveHeaders(endpoint, { refresh: true });
|
|
326
|
+
} catch (error) {
|
|
327
|
+
// No new token came: the refusal is the error, and why none came is its cause.
|
|
328
|
+
throw await failureOf(response, error);
|
|
329
|
+
}
|
|
330
|
+
discard(response);
|
|
331
|
+
response = await post(fresh);
|
|
191
332
|
}
|
|
333
|
+
// The headers are no piece of the reply: a server may send them at once and then think.
|
|
334
|
+
if (!response.ok) throw await failureOf(response);
|
|
192
335
|
return await readReply(response, stream, hooks, watch, lost);
|
|
193
336
|
} finally {
|
|
194
337
|
watch.stop();
|
|
@@ -205,10 +348,16 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
|
|
|
205
348
|
let finishReason: string | undefined;
|
|
206
349
|
let blockReason: string | undefined;
|
|
207
350
|
let usage: Record<string, unknown> | undefined;
|
|
351
|
+
let responseId: string | undefined;
|
|
352
|
+
let responseModel: string | undefined;
|
|
208
353
|
const take = (chunk: Chunk) => {
|
|
209
|
-
|
|
210
|
-
|
|
354
|
+
// An error inside a reply of HTTP 200: its status is its own code, or that of its
|
|
355
|
+
// google.rpc name ("UNAVAILABLE" is 503), so that a busy server is tried again.
|
|
356
|
+
if (chunk.error && typeof chunk.error === "object") {
|
|
357
|
+
throw geminiFailure(statusOfError(chunk.error), chunk, retryAfterMs(undefined, chunk), typeof chunk.error.message === "string" && chunk.error.message ? chunk.error.message : "Gemini reported an error.");
|
|
211
358
|
}
|
|
359
|
+
if (typeof chunk.responseId === "string" && chunk.responseId) responseId = chunk.responseId;
|
|
360
|
+
if (typeof chunk.modelVersion === "string" && chunk.modelVersion) responseModel = chunk.modelVersion;
|
|
212
361
|
if (chunk.promptFeedback?.blockReason) blockReason = chunk.promptFeedback.blockReason;
|
|
213
362
|
const candidate = chunk.candidates?.[0];
|
|
214
363
|
for (const part of candidate?.content?.parts ?? []) {
|
|
@@ -259,7 +408,9 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
|
|
|
259
408
|
for (const chunk of Array.isArray(data) ? data : [data]) take(chunk);
|
|
260
409
|
}
|
|
261
410
|
} else {
|
|
262
|
-
|
|
411
|
+
// A gateway may give the reply as a list of chunks, as Gemini does without `alt=sse`.
|
|
412
|
+
const data = await readJson<Chunk | Chunk[]>(response, () => Boolean(hooks.signal?.aborted), lost, watch, notTheReply);
|
|
413
|
+
for (const chunk of Array.isArray(data) ? data : [data]) take(chunk);
|
|
263
414
|
}
|
|
264
415
|
const finish = finishOfGemini(finishReason);
|
|
265
416
|
return {
|
|
@@ -269,6 +420,8 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
|
|
|
269
420
|
...(finishReason ? { finishReason } : {}),
|
|
270
421
|
...(finish ? { finish } : {}),
|
|
271
422
|
...(blockReason ? { blockReason } : {}),
|
|
423
|
+
...(responseId ? { responseId } : {}),
|
|
424
|
+
...(responseModel ? { responseModel } : {}),
|
|
272
425
|
...(usage ? { usage: usageOfGemini(usage), providerUsage: usage } : {}),
|
|
273
426
|
};
|
|
274
427
|
}
|