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/gemini/generate.ts
CHANGED
|
@@ -2,10 +2,37 @@
|
|
|
2
2
|
// auth headers, so this works with the Gemini API, Vertex AI, or an enterprise gateway.
|
|
3
3
|
import type { ToolAnswer, ToolCall } from "../model.js";
|
|
4
4
|
import { completeWithinLimit, noTextReason, type LimitedReply } from "../output-limit.js";
|
|
5
|
-
import { readJson } from "../http.js";
|
|
5
|
+
import { base64, partTimer, readJson, resolveHeaderSource, until, type HeaderSource } from "../http.js";
|
|
6
6
|
import { noteNoRetry, retryAfterMs } from "../retry.js";
|
|
7
7
|
import type { GenerateText, GenerateUsage, ToolDeclaration, ToolFile, ToolResult } from "../types.js";
|
|
8
|
-
import { finishOfGemini, geminiFailure, notJson, unreachable } from "./errors.js";
|
|
8
|
+
import { errorBodyOf, finishOfGemini, geminiFailure, notJson, statusOfError, tooSlow, unreachable } from "./errors.js";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* More fields for the body of a Gemini request (`gemini({ body, analysisBody })`): `safetySettings`,
|
|
12
|
+
* `labels` (Vertex AI), `serviceTier`, `cachedContent` for an explicit cache, or any other field the
|
|
13
|
+
* API takes. They are merged last, after the library's. The fields the library writes itself are
|
|
14
|
+
* typed `never`: set `generationConfig` and `analysisConfig` for those. Nothing is refused at run
|
|
15
|
+
* time. New in 0.10.0.
|
|
16
|
+
*/
|
|
17
|
+
export type GeminiRequestFields = {
|
|
18
|
+
/** Safety settings, as the API takes them: `{ category, threshold, method? }`. */
|
|
19
|
+
safetySettings?: Array<{ category: string; threshold: string; method?: string }>;
|
|
20
|
+
/**
|
|
21
|
+
* Vertex AI only: labels for the billing export, keys and values in lower case, each at most 63
|
|
22
|
+
* characters. They reach every reader of the billing data: never put a user ID or other personal
|
|
23
|
+
* data in them.
|
|
24
|
+
*/
|
|
25
|
+
labels?: Record<string, string>;
|
|
26
|
+
serviceTier?: string;
|
|
27
|
+
/** The name of an explicit context cache (`cachedContents/…`). */
|
|
28
|
+
cachedContent?: string;
|
|
29
|
+
contents?: never;
|
|
30
|
+
systemInstruction?: never;
|
|
31
|
+
tools?: never;
|
|
32
|
+
toolConfig?: never;
|
|
33
|
+
generationConfig?: never;
|
|
34
|
+
[key: string]: unknown;
|
|
35
|
+
};
|
|
9
36
|
|
|
10
37
|
/** Gemini accepts this package's JSON Schema subset as-is. */
|
|
11
38
|
export function toGeminiTools(declarations: ToolDeclaration[]): { functionDeclarations: ToolDeclaration[] } {
|
|
@@ -46,8 +73,6 @@ export type GeminiContent = { role: "user" | "model"; parts: GeminiPart[] };
|
|
|
46
73
|
/** A `user` turn: a `GeminiContent` that can go in `contents` as it is. */
|
|
47
74
|
type UserTurn = GeminiContent & { role: "user" };
|
|
48
75
|
|
|
49
|
-
const base64 = (bytes: Uint8Array) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
|
|
50
|
-
|
|
51
76
|
/** One function response, with `files` inside it. */
|
|
52
77
|
function functionResponse(call: GeminiFunctionCall, result: ToolResult, files: ToolFile[]): GeminiPart {
|
|
53
78
|
let response = result;
|
|
@@ -106,12 +131,30 @@ export { THINKING_OUTPUT_TOKENS } from "../output-limit.js";
|
|
|
106
131
|
*/
|
|
107
132
|
export function createGeminiGenerateText(options: {
|
|
108
133
|
url: string;
|
|
109
|
-
/**
|
|
110
|
-
|
|
134
|
+
/**
|
|
135
|
+
* Request headers, or a function returning them. A function is called for every request: a
|
|
136
|
+
* whole-file read can outlast an access token.
|
|
137
|
+
*/
|
|
138
|
+
headers: HeaderSource;
|
|
111
139
|
fetchImpl?: typeof fetch;
|
|
112
140
|
/** The `generationConfig` of each request, from its output limit. Defaults to `{ maxOutputTokens }`. */
|
|
113
141
|
generationConfig?: (maxOutputTokens: number) => Record<string, unknown>;
|
|
142
|
+
/**
|
|
143
|
+
* More fields for the body of each request, given its output limit, merged last
|
|
144
|
+
* (`gemini({ analysisBody })`). New in 0.10.0.
|
|
145
|
+
*/
|
|
146
|
+
body?: (maxOutputTokens: number) => GeminiRequestFields;
|
|
147
|
+
/**
|
|
148
|
+
* The longest time, in milliseconds, a request may take, its whole reply included. Defaults to
|
|
149
|
+
* 180,000; 0 sets none. A request past it is a `GeminiRequestError` of kind "timeout" and status
|
|
150
|
+
* 0 (since 0.10.0; before, the abort of the timer), which a whole-file read sends again once.
|
|
151
|
+
*/
|
|
114
152
|
timeoutMs?: number;
|
|
153
|
+
/**
|
|
154
|
+
* A request refused with HTTP 401 is sent once more, with the headers of `headers({ refresh: true })`
|
|
155
|
+
* (the endpoint's `refreshable`). New in 0.10.0.
|
|
156
|
+
*/
|
|
157
|
+
refreshable?: boolean | undefined;
|
|
115
158
|
}): GenerateText {
|
|
116
159
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
117
160
|
const { url } = options;
|
|
@@ -120,60 +163,98 @@ export function createGeminiGenerateText(options: {
|
|
|
120
163
|
let blocked = false;
|
|
121
164
|
/** One request with an output limit: the text of the reply, why it ended, and what it thought. */
|
|
122
165
|
const send = async (limit: number): Promise<LimitedReply> => {
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
166
|
+
const timer = partTimer(signal, options.timeoutMs);
|
|
167
|
+
// Stopped by the caller: reported as it is. Out of time: a timeout. Anything else is a connection that failed.
|
|
168
|
+
const lost = (error: unknown) => (timer.expired && !signal?.aborted ? tooSlow(timer.limitMs) : unreachable(error));
|
|
126
169
|
try {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
systemInstruction: { role: "system", parts: [{ text: system }] },
|
|
134
|
-
// No temperature: Gemini 3.6 and later ignore it, and Google says later models will refuse it.
|
|
135
|
-
generationConfig: options.generationConfig?.(limit) ?? { maxOutputTokens: limit },
|
|
136
|
-
}),
|
|
170
|
+
const body = JSON.stringify({
|
|
171
|
+
contents: [{ role: "user", parts: [{ text: prompt }] }],
|
|
172
|
+
systemInstruction: { role: "system", parts: [{ text: system }] },
|
|
173
|
+
// No temperature: Gemini 3.6 and later ignore it, and Google says later models will refuse it.
|
|
174
|
+
generationConfig: options.generationConfig?.(limit) ?? { maxOutputTokens: limit },
|
|
175
|
+
...options.body?.(limit),
|
|
137
176
|
});
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
177
|
+
const post = async (headers: Record<string, string>): Promise<Response> => {
|
|
178
|
+
try {
|
|
179
|
+
// The time limit ends the wait even for a fetch that does not stop when its signal aborts.
|
|
180
|
+
return await until(fetchImpl(url, { method: "POST", headers, ...(timer.signal ? { signal: timer.signal } : {}), body }), timer.signal);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
if (signal?.aborted) throw error;
|
|
183
|
+
throw lost(error);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
// An error may have no JSON body, and one that is a list is read by its first entry.
|
|
187
|
+
const failureOf = async (response: Response, cause?: unknown): Promise<Error> => {
|
|
188
|
+
const data = errorBodyOf(await response.json().catch(() => null));
|
|
189
|
+
return geminiFailure(response.status, data, retryAfterMs(response.headers, data), `The model returned HTTP ${response.status}.`, cause);
|
|
190
|
+
};
|
|
191
|
+
let response = await post(await resolveHeaderSource(options.headers));
|
|
192
|
+
// A token that was refused may be one a cache kept past its time: one more try, with a new one.
|
|
193
|
+
if (response.status === 401 && options.refreshable) {
|
|
194
|
+
let fresh: Record<string, string>;
|
|
195
|
+
try {
|
|
196
|
+
fresh = await resolveHeaderSource(options.headers, { refresh: true });
|
|
197
|
+
} catch (error) {
|
|
198
|
+
// No new token came: the refusal is the error, and why none came is its cause.
|
|
199
|
+
throw await failureOf(response, error);
|
|
200
|
+
}
|
|
201
|
+
discard(response);
|
|
202
|
+
response = await post(fresh);
|
|
203
|
+
}
|
|
204
|
+
type Chunk = {
|
|
205
|
+
error?: { message?: string; code?: unknown; status?: unknown };
|
|
206
|
+
candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
|
|
207
|
+
usageMetadata?: Record<string, unknown>;
|
|
208
|
+
promptFeedback?: { blockReason?: unknown };
|
|
209
|
+
};
|
|
210
|
+
if (!response.ok) throw await failureOf(response);
|
|
211
|
+
// A reply must have one: a body that could not be read is a connection that failed, and is
|
|
212
|
+
// sent again. It may be a list of chunks, as Gemini gives a reply without `alt=sse` (a
|
|
213
|
+
// gateway): every chunk is read, as a chat reply's are.
|
|
214
|
+
const data = await readJson<unknown>(response, () => Boolean(signal?.aborted), lost, timer.signal ? { pulse: () => undefined, signal: timer.signal } : undefined, (error) => notJson(response, error));
|
|
215
|
+
const chunks = (Array.isArray(data) ? data : [data]).filter((chunk): chunk is Chunk => chunk !== null && typeof chunk === "object" && !Array.isArray(chunk));
|
|
216
|
+
let text = "";
|
|
217
|
+
let answered = false;
|
|
218
|
+
let finishReason: string | undefined;
|
|
219
|
+
let usage: Record<string, unknown> | undefined;
|
|
220
|
+
let blockReason: unknown;
|
|
221
|
+
for (const chunk of chunks) {
|
|
222
|
+
// An error in a body of HTTP 200 (a gateway, or Vertex AI), alone or after part of the
|
|
223
|
+
// reply: thrown with its own status, so that a 503 is sent again rather than read as a
|
|
224
|
+
// reply with no text, or with part of its text.
|
|
225
|
+
if (chunk.error && typeof chunk.error === "object") throw geminiFailure(statusOfError(chunk.error), chunk, retryAfterMs(response.headers, chunk), "Gemini reported an error.");
|
|
226
|
+
usage = chunk.usageMetadata ?? usage;
|
|
227
|
+
blockReason = chunk.promptFeedback?.blockReason ?? blockReason;
|
|
228
|
+
const candidate = chunk.candidates?.[0];
|
|
229
|
+
if (!candidate) continue;
|
|
230
|
+
answered = true;
|
|
231
|
+
text += (candidate.content?.parts ?? [])
|
|
232
|
+
.filter((part) => part.thought !== true && typeof part.text === "string")
|
|
233
|
+
.map((part) => part.text as string)
|
|
234
|
+
.join("");
|
|
235
|
+
finishReason = candidate.finishReason ?? finishReason;
|
|
236
|
+
}
|
|
237
|
+
onUsage?.(usageOfGemini(usage));
|
|
238
|
+
// A prompt Gemini blocked comes with 200, a reason and no candidate: the reply has no text,
|
|
239
|
+
// and says why ("The model returned no text (PROHIBITED_CONTENT).").
|
|
240
|
+
if (!answered && typeof blockReason === "string" && blockReason) {
|
|
241
|
+
blocked = true;
|
|
242
|
+
return { text: "", cutOff: false, stopped: true, reason: blockReason, thoughts: 0 };
|
|
243
|
+
}
|
|
244
|
+
const thoughts = usage?.thoughtsTokenCount;
|
|
245
|
+
const finish = finishOfGemini(finishReason);
|
|
246
|
+
return {
|
|
247
|
+
text,
|
|
248
|
+
cutOff: finishReason === "MAX_TOKENS",
|
|
249
|
+
// Stopped before its end by a filter, or for another reason that is not the limit: what
|
|
250
|
+
// it wrote is not all there is.
|
|
251
|
+
stopped: finish === "filtered" || finish === "other",
|
|
252
|
+
...(finishReason ? { reason: finishReason } : {}),
|
|
253
|
+
thoughts: typeof thoughts === "number" ? thoughts : 0,
|
|
254
|
+
};
|
|
255
|
+
} finally {
|
|
256
|
+
timer.stop();
|
|
142
257
|
}
|
|
143
|
-
type Data = {
|
|
144
|
-
error?: { message?: string };
|
|
145
|
-
candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
|
|
146
|
-
usageMetadata?: Record<string, unknown>;
|
|
147
|
-
promptFeedback?: { blockReason?: unknown };
|
|
148
|
-
} | null;
|
|
149
|
-
// An error may have no JSON body. A reply must: one whose body could not be read is a
|
|
150
|
-
// connection that failed, and is sent again.
|
|
151
|
-
const data: Data = response.ok
|
|
152
|
-
? await readJson<Data>(response, () => Boolean(signal?.aborted) || timeout.aborted, unreachable, undefined, (error) => notJson(response, error))
|
|
153
|
-
: await response.json().catch(() => null) as Data;
|
|
154
|
-
if (!response.ok) throw geminiFailure(response.status, data, retryAfterMs(response.headers, data), `The model returned HTTP ${response.status}.`);
|
|
155
|
-
onUsage?.(usageOfGemini(data?.usageMetadata));
|
|
156
|
-
const candidate = data?.candidates?.[0];
|
|
157
|
-
// A prompt Gemini blocked comes with 200, a reason and no candidate: the reply has no text,
|
|
158
|
-
// and says why ("The model returned no text (PROHIBITED_CONTENT).").
|
|
159
|
-
const blockReason = data?.promptFeedback?.blockReason;
|
|
160
|
-
if (!candidate && typeof blockReason === "string" && blockReason) {
|
|
161
|
-
blocked = true;
|
|
162
|
-
return { text: "", cutOff: false, stopped: true, reason: blockReason, thoughts: 0 };
|
|
163
|
-
}
|
|
164
|
-
const text = (candidate?.content?.parts ?? [])
|
|
165
|
-
.filter((part) => part.thought !== true && typeof part.text === "string")
|
|
166
|
-
.map((part) => part.text as string)
|
|
167
|
-
.join("");
|
|
168
|
-
const thoughts = data?.usageMetadata?.thoughtsTokenCount;
|
|
169
|
-
return {
|
|
170
|
-
text,
|
|
171
|
-
cutOff: candidate?.finishReason === "MAX_TOKENS",
|
|
172
|
-
// Stopped by the safety filters before its end: what it wrote is not all there is.
|
|
173
|
-
stopped: finishOfGemini(candidate?.finishReason) === "filtered",
|
|
174
|
-
...(candidate?.finishReason ? { reason: candidate.finishReason } : {}),
|
|
175
|
-
thoughts: typeof thoughts === "number" ? thoughts : 0,
|
|
176
|
-
};
|
|
177
258
|
};
|
|
178
259
|
try {
|
|
179
260
|
return await completeWithinLimit(url, maxOutputTokens, send, { signal, onTruncated });
|
|
@@ -184,3 +265,12 @@ export function createGeminiGenerateText(options: {
|
|
|
184
265
|
}
|
|
185
266
|
};
|
|
186
267
|
}
|
|
268
|
+
|
|
269
|
+
/** A response that is not read: its body is let go, without waiting for it. */
|
|
270
|
+
export function discard(response: Response): void {
|
|
271
|
+
try {
|
|
272
|
+
void response.body?.cancel().catch(() => undefined);
|
|
273
|
+
} catch {
|
|
274
|
+
// A body that is locked, or a cancel that throws at once, holds nothing up.
|
|
275
|
+
}
|
|
276
|
+
}
|
package/src/gemini/index.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
export { askGemini, DocumentsNotFoundError, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, GeminiRequestError, partialResultOf } from "./chat.js";
|
|
2
|
-
export type { AskEvent, AskGeminiOptions, AskGeminiResult, ChatTurn, GeminiContent, GeminiPart } from "./chat.js";
|
|
2
|
+
export type { AskEvent, AskGeminiOptions, AskGeminiResult, ChatTurn, GeminiContent, GeminiOwnOptions, GeminiPart } from "./chat.js";
|
|
3
3
|
export { fromGeminiContents, gemini, GEMINI_PAGE_TOKENS, geminiToolTurns } from "./adapter.js";
|
|
4
|
-
export type { GeminiModelOptions } from "./adapter.js";
|
|
4
|
+
export type { FromGeminiContentsOptions, GeminiModelOptions } from "./adapter.js";
|
|
5
5
|
export { geminiApi, vertexAi, vertexHost } from "./endpoints.js";
|
|
6
|
-
export type { GeminiEndpoint } from "./endpoints.js";
|
|
6
|
+
export type { GeminiEndpoint, VertexAiOptions } from "./endpoints.js";
|
|
7
7
|
export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, THINKING_OUTPUT_TOKENS, toGeminiTools, usageOfGemini } from "./generate.js";
|
|
8
|
-
export type { GeminiFunctionCall, GeminiToolAnswer, GeminiToolFilePlacement } from "./generate.js";
|
|
8
|
+
export type { GeminiFunctionCall, GeminiRequestFields, GeminiToolAnswer, GeminiToolFilePlacement } from "./generate.js";
|
|
9
9
|
export { parseSseJson, SseEventTooLongError } from "./sse.js";
|
package/src/http.ts
CHANGED
|
@@ -1,11 +1,23 @@
|
|
|
1
1
|
// Small things every adapter needs for its HTTP requests.
|
|
2
2
|
import { sliceWhole } from "./text.js";
|
|
3
3
|
|
|
4
|
-
/**
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* What a function of headers is told: `refresh` is true when the headers are asked for again
|
|
6
|
+
* because the last ones were refused (HTTP 401), so a token kept in a cache is to be fetched anew.
|
|
7
|
+
* New in 0.10.0.
|
|
8
|
+
*/
|
|
9
|
+
export type HeaderContext = { refresh?: boolean };
|
|
6
10
|
|
|
7
|
-
|
|
8
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Request headers, or a function returning them: called for each request, so a token can be
|
|
13
|
+
* renewed. Since 0.10.0 the function may take a `HeaderContext`; one of no arguments still fits.
|
|
14
|
+
*/
|
|
15
|
+
export type HeaderSource = Record<string, string> | ((context?: HeaderContext) => Record<string, string> | Promise<Record<string, string>>);
|
|
16
|
+
|
|
17
|
+
/** The headers of a source. A function is called with `context` when one is given, and with nothing otherwise, as before 0.10.0. */
|
|
18
|
+
export async function resolveHeaderSource(source: HeaderSource | undefined, context?: HeaderContext): Promise<Record<string, string>> {
|
|
19
|
+
if (typeof source !== "function") return source ?? {};
|
|
20
|
+
return context ? source(context) : source();
|
|
9
21
|
}
|
|
10
22
|
|
|
11
23
|
/** A secret, or a function returning it: called for each request. */
|
|
@@ -48,6 +60,55 @@ export const DEFAULT_FIRST_BYTE_TIMEOUT_MS = 600_000;
|
|
|
48
60
|
/** The longest delay `setTimeout` takes: a longer one fires at once. About 24.8 days, which is no limit. */
|
|
49
61
|
const LONGEST_TIMER_MS = 2_147_483_647;
|
|
50
62
|
|
|
63
|
+
/**
|
|
64
|
+
* The longest time, by default, that one part read of a whole-file read may take, in milliseconds:
|
|
65
|
+
* from the request until its whole reply is in.
|
|
66
|
+
*/
|
|
67
|
+
export const DEFAULT_PART_TIMEOUT_MS = 180_000;
|
|
68
|
+
|
|
69
|
+
/** The time limit of one part read: see `partTimer`. */
|
|
70
|
+
export type PartTimer = {
|
|
71
|
+
/** The signal for `fetch`: it aborts when the caller's does, or when the time is up. */
|
|
72
|
+
readonly signal: AbortSignal | undefined;
|
|
73
|
+
/** True once the time ran out. The request was then aborted by the timer, not by the caller. */
|
|
74
|
+
readonly expired: boolean;
|
|
75
|
+
/** The time limit, in milliseconds, for the message. */
|
|
76
|
+
readonly limitMs: number;
|
|
77
|
+
/** The request is over: the timer is cleared. */
|
|
78
|
+
stop(): void;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* A time limit on one part read of a whole-file read: `timeoutMs` (by default
|
|
83
|
+
* `DEFAULT_PART_TIMEOUT_MS`) for the request and its whole reply. 0, or a value that is not a
|
|
84
|
+
* positive number, sets none. `expired` tells the timer's abort apart from the caller's, which the
|
|
85
|
+
* adapters report as a `ModelRequestError` of kind "timeout" and status 0: the rule of `withRetry`
|
|
86
|
+
* then sends it again once, as a chat request that got nothing back.
|
|
87
|
+
*/
|
|
88
|
+
export function partTimer(caller: AbortSignal | undefined, timeoutMs: number | undefined): PartTimer {
|
|
89
|
+
const limitMs = timeoutMs ?? DEFAULT_PART_TIMEOUT_MS;
|
|
90
|
+
if (!watching(limitMs)) return { signal: caller, expired: false, limitMs: 0, stop() {} };
|
|
91
|
+
const controller = new AbortController();
|
|
92
|
+
let expired = false;
|
|
93
|
+
const timer = setTimeout(() => {
|
|
94
|
+
expired = true;
|
|
95
|
+
controller.abort(new Error(`The part read took longer than ${waitText(limitMs)}.`));
|
|
96
|
+
}, Math.min(limitMs, LONGEST_TIMER_MS));
|
|
97
|
+
return {
|
|
98
|
+
signal: caller ? AbortSignal.any([caller, controller.signal]) : controller.signal,
|
|
99
|
+
get expired() {
|
|
100
|
+
return expired;
|
|
101
|
+
},
|
|
102
|
+
limitMs,
|
|
103
|
+
stop: () => clearTimeout(timer),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A wait in words: "180 s", or "50 ms" under a second. */
|
|
108
|
+
export function waitText(ms: number): string {
|
|
109
|
+
return ms >= 1_000 ? `${Math.round(ms / 1_000)} s` : `${Math.round(ms)} ms`;
|
|
110
|
+
}
|
|
111
|
+
|
|
51
112
|
/** Watches a request for silence: see `idleWatch`. */
|
|
52
113
|
export type IdleWatch = {
|
|
53
114
|
/** The signal for `fetch`: it aborts when the caller's does, or when nothing arrived for the whole wait. */
|
package/src/index.ts
CHANGED
|
@@ -2,12 +2,14 @@
|
|
|
2
2
|
// "llm-large-files/gemini", "llm-large-files/openai", "llm-large-files/anthropic", or your own.
|
|
3
3
|
// Node HTTP handlers are in "llm-large-files/node".
|
|
4
4
|
export { createLargeFiles, DEFAULT_CACHE_BYTES, DEFAULT_INGEST_TIMEOUT_MS, DEFAULT_MAX_PDF_PAGES, DEFAULT_MAX_TEXT_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, isDocumentId, NEVER_EXPIRES, toDocumentSummary } from "./library.js";
|
|
5
|
-
export type { AccessOptions, IngestInput, LargeFiles, LargeFilesOptions, PrepareOptions, ToolOptions } from "./library.js";
|
|
5
|
+
export type { AccessOptions, CreatedLargeFiles, IngestFromSource, IngestInput, IngestSource, LargeFiles, LargeFilesOptions, LargeFilesStats, OriginalReadContext, OriginalsReader, PrepareOptions, ToolOptions } from "./library.js";
|
|
6
6
|
export { DEFAULT_BUDGET, resolveBudget } from "./budget.js";
|
|
7
7
|
export type { ModelLimits } from "./budget.js";
|
|
8
|
-
export { askStream, askWithFiles, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, partialResultOf } from "./ask.js";
|
|
9
|
-
export type { AskLimits, AskOptions, AskResult } from "./ask.js";
|
|
10
|
-
export
|
|
8
|
+
export { askStream, askWithFiles, DEFAULT_INPUT_TOKENS, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, partialResultOf } from "./ask.js";
|
|
9
|
+
export type { AskLimits, AskOptions, AskResult, MissingDocumentsAction, MissingDocumentsContext, ToolResultContext, ToolResultVerdict } from "./ask.js";
|
|
10
|
+
export * from "./answer-info.js";
|
|
11
|
+
export * from "./citations.js";
|
|
12
|
+
export { classifyModelError, DocumentsNotFoundError, errorKindOf, ModelRequestError, TOOL_TURN_VERSION, UsageMeter } from "./model.js";
|
|
11
13
|
export type {
|
|
12
14
|
ChatMessage,
|
|
13
15
|
ModelErrorClass,
|
|
@@ -53,11 +55,14 @@ export { parseSseJson, SseEventTooLongError } from "./sse.js";
|
|
|
53
55
|
export type { SseHooks } from "./sse.js";
|
|
54
56
|
export { DEFAULT_FIRST_BYTE_TIMEOUT_MS, DEFAULT_IDLE_TIMEOUT_MS } from "./http.js";
|
|
55
57
|
export type { IdleWaits } from "./http.js";
|
|
56
|
-
export { DocumentStoreError, IngestError, ingestErrorCodeOf } from "./errors.js";
|
|
57
|
-
export type { IngestErrorCode } from "./errors.js";
|
|
58
|
-
export {
|
|
58
|
+
export { DocumentScopeError, DocumentStoreError, IngestError, ingestErrorCodeOf } from "./errors.js";
|
|
59
|
+
export type { DocumentScopeErrorCode, DocumentStoreOperation, IngestErrorCode } from "./errors.js";
|
|
60
|
+
export { errorInfoOf } from "./error-info.js";
|
|
61
|
+
export type { ErrorCategory, ErrorInfo } from "./error-info.js";
|
|
62
|
+
export { APP_DOCUMENT_ID_PATTERN, DOCUMENT_ID_PATTERN, DOCUMENT_META_VERSION, FileDocumentStore, hashedScopeSegment, isSafeScopeSegment, MemoryDocumentStore } from "./stores.js";
|
|
63
|
+
export type { FileDocumentScopes, FileDocumentStoreOptions } from "./stores.js";
|
|
59
64
|
export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";
|
|
60
65
|
export type { PdfExtractorOptions } from "./extract.js";
|
|
61
66
|
export { estimateTokens, utf8Bytes, jsonBytes } from "./text.js";
|
|
62
|
-
export { MAX_VIEW_PAGES, MAX_WHOLE_DOCUMENT_READS, REGEX_BUDGET_MS, TOOL_NAMES, toolResultSummary } from "./tools.js";
|
|
67
|
+
export { declarationsFor, MAX_VIEW_PAGES, MAX_WHOLE_DOCUMENT_READS, REGEX_BUDGET_MS, TOOL_NAMES, toolResultSummary } from "./tools.js";
|
|
63
68
|
export type * from "./types.js";
|