llm-large-files 0.5.0 → 0.7.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 +1402 -467
- package/README.md +188 -60
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +190 -39
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +60 -4
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1068 -206
- package/dist/ask.js.map +1 -1
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +3 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +108 -61
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +13 -7
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +11 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +405 -85
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +182 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +311 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +275 -14
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +269 -42
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +102 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1012 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +897 -103
- package/docs/troubleshooting.md +1390 -0
- package/package.json +2 -2
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +196 -39
- package/src/ask.ts +1087 -202
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +5 -2
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +118 -65
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +23 -10
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/http.ts +376 -1
- package/src/index.ts +27 -5
- package/src/library.ts +459 -85
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +236 -3
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +306 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +49 -5
- package/src/search.ts +63 -10
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +261 -42
- package/src/types.ts +107 -4
- package/src/zip-directory.ts +136 -0
package/src/gemini/adapter.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
// Gemini (Generate Content REST) as a model of `askWithFiles`.
|
|
2
|
-
import type
|
|
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";
|
|
3
3
|
import { retryAfterMs } from "../retry.js";
|
|
4
|
-
import {
|
|
4
|
+
import { idleWatch, noteCutReply, readJson, streamedReply, type IdleWatch } from "../http.js";
|
|
5
|
+
import { eventTooLongMessage, parseSseJson, SseEventTooLongError } from "../sse.js";
|
|
5
6
|
import { resolveHeaders, type GeminiEndpoint } from "./endpoints.js";
|
|
6
|
-
import { GeminiRequestError, unreachable } from "./errors.js";
|
|
7
|
-
import { createGeminiGenerateText, geminiFunctionResponseTurns, usageOfGemini, type GeminiToolFilePlacement } from "./generate.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";
|
|
8
9
|
|
|
9
|
-
export type
|
|
10
|
-
export type GeminiContent = { role: "user" | "model"; parts: GeminiPart[] };
|
|
10
|
+
export type { GeminiContent, GeminiPart };
|
|
11
11
|
|
|
12
12
|
/** What Gemini bills for one PDF page it is shown (measured: 520 to 532). */
|
|
13
13
|
export const GEMINI_PAGE_TOKENS = 530;
|
|
@@ -22,7 +22,7 @@ export type GeminiModelOptions = {
|
|
|
22
22
|
* inside a function response.
|
|
23
23
|
*/
|
|
24
24
|
toolFilePlacement?: GeminiToolFilePlacement | undefined;
|
|
25
|
-
/** generationConfig for whole-document part reads. Defaults to `{
|
|
25
|
+
/** generationConfig for whole-document part reads. Defaults to `{ maxOutputTokens }`, with no temperature. */
|
|
26
26
|
analysisConfig?: ((maxOutputTokens: number) => Record<string, unknown>) | undefined;
|
|
27
27
|
/** The model's context window in tokens, when the budget of a question should follow it. */
|
|
28
28
|
contextTokens?: number | undefined;
|
|
@@ -32,6 +32,19 @@ export type GeminiModelOptions = {
|
|
|
32
32
|
pageTokens?: number | undefined;
|
|
33
33
|
/** Names the model in usage totals. Defaults to the model in the URL. */
|
|
34
34
|
id?: string | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count:
|
|
37
|
+
* a model that thinks sends nothing until it has thought, and a reply that is not streamed comes
|
|
38
|
+
* whole at the end. A request that gets nothing for that long is aborted and sent again, once.
|
|
39
|
+
* Defaults to 600,000. 0 waits without end.
|
|
40
|
+
*/
|
|
41
|
+
firstByteTimeoutMs?: number | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* The longest wait, in milliseconds, between two pieces of a chat reply once it has started to
|
|
44
|
+
* arrive (keep-alives count). A request that gets nothing for that long is aborted and sent
|
|
45
|
+
* again, once, unless text of it was shown. Defaults to 300,000. 0 waits without end.
|
|
46
|
+
*/
|
|
47
|
+
idleTimeoutMs?: number | undefined;
|
|
35
48
|
fetch?: typeof fetch | undefined;
|
|
36
49
|
};
|
|
37
50
|
|
|
@@ -92,8 +105,9 @@ export function fromGeminiContents(contents: GeminiContent[]): ChatMessage[] {
|
|
|
92
105
|
*/
|
|
93
106
|
export function geminiToolTurns(turns: ToolTurn[]): GeminiContent[] {
|
|
94
107
|
return turns.flatMap((turn) => {
|
|
95
|
-
|
|
96
|
-
|
|
108
|
+
// Sent again in later questions: without the tool turns this question had left.
|
|
109
|
+
const answers = turn.calls.map(({ result, ...call }) => ({ call, result: laterResult(result) }));
|
|
110
|
+
return [callsTurn(answers.map((answer) => answer.call)), ...geminiFunctionResponseTurns(answers)];
|
|
97
111
|
});
|
|
98
112
|
}
|
|
99
113
|
|
|
@@ -112,7 +126,7 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
|
|
|
112
126
|
if (!turns) {
|
|
113
127
|
// Its own turn goes back unchanged: Gemini 3 requires its thought signatures.
|
|
114
128
|
const asked = round.raw !== undefined ? round.raw as GeminiContent : callsTurn(round.calls);
|
|
115
|
-
turns = [asked, ...(round.answers.length > 0 ? geminiFunctionResponseTurns(round.answers, { files: placement })
|
|
129
|
+
turns = [asked, ...(round.answers.length > 0 ? geminiFunctionResponseTurns(round.answers, { files: placement }) : [])];
|
|
116
130
|
built.set(round, turns);
|
|
117
131
|
}
|
|
118
132
|
return turns;
|
|
@@ -150,69 +164,108 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
|
|
|
150
164
|
const stream = Boolean(hooks.onText && endpoint.streamUrl);
|
|
151
165
|
// Headers are asked for with each request: an access token may have been renewed since the last.
|
|
152
166
|
const headers = await resolveHeaders(endpoint);
|
|
153
|
-
|
|
167
|
+
const watch = idleWatch(hooks.signal, { firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs });
|
|
168
|
+
// A request the watch aborted got nothing back for the whole wait: that is no failed connection.
|
|
169
|
+
const lost = (error: unknown) => (watch.expired ? silent(watch.waitedMs) : unreachable(error));
|
|
154
170
|
try {
|
|
155
|
-
response
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
171
|
+
let response: Response;
|
|
172
|
+
try {
|
|
173
|
+
response = await fetchImpl(stream ? endpoint.streamUrl! : endpoint.url, {
|
|
174
|
+
method: "POST",
|
|
175
|
+
headers,
|
|
176
|
+
body: JSON.stringify(bodyOf(request)),
|
|
177
|
+
signal: watch.signal,
|
|
178
|
+
});
|
|
179
|
+
} catch (error) {
|
|
180
|
+
if (hooks.signal?.aborted) throw error;
|
|
181
|
+
throw lost(error);
|
|
182
|
+
}
|
|
183
|
+
// The headers are no piece of the reply: a server may send them at once and then think.
|
|
184
|
+
if (!response.ok) {
|
|
185
|
+
const data = await response.json().catch(() => null);
|
|
186
|
+
throw geminiFailure(response.status, data, retryAfterMs(response.headers, data), `Gemini returned HTTP ${response.status}.`);
|
|
187
|
+
}
|
|
188
|
+
return await readReply(response, stream, hooks, watch, lost);
|
|
189
|
+
} finally {
|
|
190
|
+
watch.stop();
|
|
164
191
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
192
|
+
},
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
/** The reply of a request that was answered: streamed, or in one piece. */
|
|
197
|
+
async function readReply(response: Response, stream: boolean, hooks: SendHooks, watch: IdleWatch, lost: (error: unknown) => GeminiRequestError): Promise<ModelReply> {
|
|
198
|
+
const parts: GeminiPart[] = [];
|
|
199
|
+
const calls: ToolCall[] = [];
|
|
200
|
+
let text = "";
|
|
201
|
+
let finishReason: string | undefined;
|
|
202
|
+
let blockReason: string | undefined;
|
|
203
|
+
let usage: Record<string, unknown> | undefined;
|
|
204
|
+
const take = (chunk: Chunk) => {
|
|
205
|
+
if (chunk.error?.message) {
|
|
206
|
+
throw geminiFailure(typeof chunk.error.code === "number" ? chunk.error.code : response.status, chunk, undefined, chunk.error.message);
|
|
169
207
|
}
|
|
170
|
-
|
|
171
|
-
const
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
if (typeof part.text === "string" && part.text && part.thought !== true) {
|
|
184
|
-
text += part.text;
|
|
185
|
-
hooks.onText?.(part.text);
|
|
186
|
-
}
|
|
187
|
-
const call = part.functionCall as { name?: unknown; args?: unknown; id?: unknown } | undefined;
|
|
188
|
-
if (call && typeof call.name === "string") {
|
|
189
|
-
const args = call.args && typeof call.args === "object" && !Array.isArray(call.args) ? call.args as Record<string, unknown> : {};
|
|
190
|
-
calls.push({ name: call.name, args, ...(typeof call.id === "string" ? { id: call.id } : {}) });
|
|
191
|
-
}
|
|
208
|
+
if (chunk.promptFeedback?.blockReason) blockReason = chunk.promptFeedback.blockReason;
|
|
209
|
+
const candidate = chunk.candidates?.[0];
|
|
210
|
+
for (const part of candidate?.content?.parts ?? []) {
|
|
211
|
+
// Keep every part unchanged: Gemini 3 requires its thought signatures back.
|
|
212
|
+
parts.push(part);
|
|
213
|
+
if (typeof part.text === "string" && part.text && part.thought !== true) {
|
|
214
|
+
text += part.text;
|
|
215
|
+
hooks.onText?.(part.text);
|
|
216
|
+
}
|
|
217
|
+
const call = part.functionCall as { name?: unknown; args?: unknown; id?: unknown } | undefined;
|
|
218
|
+
if (call && typeof call.name === "string") {
|
|
219
|
+
const args = call.args && typeof call.args === "object" && !Array.isArray(call.args) ? call.args as Record<string, unknown> : {};
|
|
220
|
+
calls.push({ name: call.name, args, ...(typeof call.id === "string" ? { id: call.id } : {}) });
|
|
192
221
|
}
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
222
|
+
}
|
|
223
|
+
finishReason = candidate?.finishReason ?? finishReason;
|
|
224
|
+
usage = chunk.usageMetadata ?? usage;
|
|
225
|
+
};
|
|
226
|
+
const notTheReply = (error: unknown) => notJson(response, error);
|
|
227
|
+
if (stream) {
|
|
228
|
+
if (!response.body) throw new GeminiRequestError("Gemini returned an empty stream.", response.status);
|
|
229
|
+
let events: boolean;
|
|
230
|
+
let body: Response;
|
|
231
|
+
try {
|
|
232
|
+
({ events, response: body } = await streamedReply(response, watch));
|
|
233
|
+
} catch (error) {
|
|
234
|
+
if (hooks.signal?.aborted) throw error;
|
|
235
|
+
throw noteCutReply(lost(error));
|
|
236
|
+
}
|
|
237
|
+
if (events) {
|
|
198
238
|
try {
|
|
199
|
-
for await (const chunk of parseSseJson<Chunk>(
|
|
239
|
+
for await (const chunk of parseSseJson<Chunk>(body.body!, { onData: watch.pulse, signal: watch.signal })) take(chunk);
|
|
200
240
|
} catch (error) {
|
|
201
241
|
if (hooks.signal?.aborted || error instanceof GeminiRequestError) throw error;
|
|
202
|
-
//
|
|
203
|
-
throw
|
|
242
|
+
// An event too long to read would come again: it is not sent again, like a page in the reply's place.
|
|
243
|
+
if (error instanceof SseEventTooLongError) throw new GeminiRequestError(eventTooLongMessage("Gemini's", error), response.status, { kind: "invalid", cause: error });
|
|
244
|
+
// The connection went while the answer was on its way, or nothing came for the whole wait.
|
|
245
|
+
throw noteCutReply(lost(error));
|
|
204
246
|
}
|
|
247
|
+
// Every reply Gemini streams ends with a chunk that says why it ended. A stream that closed
|
|
248
|
+
// without one was cut off on its way (a proxy, a dropped connection): it is not a whole
|
|
249
|
+
// reply, and is sent again like a connection that failed, unless text of it was shown.
|
|
250
|
+
if (finishReason === undefined && blockReason === undefined) throw noteCutReply(new GeminiRequestError("Gemini's reply ended before it was complete.", 0));
|
|
205
251
|
} else {
|
|
206
|
-
|
|
252
|
+
// In one piece, though it was asked for as a stream: a gateway that does not stream (its
|
|
253
|
+
// chunks in a list, as Gemini sends them without `alt=sse`), or a page in the model's place.
|
|
254
|
+
const data = await readJson<Chunk | Chunk[]>(body, () => Boolean(hooks.signal?.aborted), lost, watch, notTheReply);
|
|
255
|
+
for (const chunk of Array.isArray(data) ? data : [data]) take(chunk);
|
|
207
256
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
|
|
257
|
+
} else {
|
|
258
|
+
take(await readJson<Chunk>(response, () => Boolean(hooks.signal?.aborted), lost, watch, notTheReply));
|
|
259
|
+
}
|
|
260
|
+
const finish = finishOfGemini(finishReason);
|
|
261
|
+
return {
|
|
262
|
+
text,
|
|
263
|
+
calls,
|
|
264
|
+
raw: { role: "model", parts } satisfies GeminiContent,
|
|
265
|
+
...(finishReason ? { finishReason } : {}),
|
|
266
|
+
...(finish ? { finish } : {}),
|
|
267
|
+
...(blockReason ? { blockReason } : {}),
|
|
268
|
+
...(usage ? { usage: usageOfGemini(usage), providerUsage: usage } : {}),
|
|
269
|
+
};
|
|
270
|
+
}
|
|
218
271
|
}
|
package/src/gemini/chat.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { askWithFiles, type AskLimits, type AskResult } from "../ask.js";
|
|
2
2
|
import type { LargeFiles } from "../library.js";
|
|
3
|
+
import type { AskEvent } from "../events.js";
|
|
3
4
|
import type { ChatTurn, ToolTurn } from "../model.js";
|
|
4
5
|
import type { RetryOptions } from "../retry.js";
|
|
5
6
|
import type { Budget } from "../types.js";
|
|
@@ -8,7 +9,8 @@ import type { GeminiEndpoint } from "./endpoints.js";
|
|
|
8
9
|
import type { GeminiToolFilePlacement } from "./generate.js";
|
|
9
10
|
|
|
10
11
|
export { DocumentsNotFoundError } from "../model.js";
|
|
11
|
-
export { EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS } from "../ask.js";
|
|
12
|
+
export { EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, partialResultOf } from "../ask.js";
|
|
13
|
+
export type { AskEvent } from "../events.js";
|
|
12
14
|
export type { ChatTurn } from "../model.js";
|
|
13
15
|
export type { GeminiContent, GeminiPart } from "./adapter.js";
|
|
14
16
|
export { GeminiRequestError } from "./errors.js";
|
|
@@ -75,16 +77,34 @@ export type AskGeminiOptions = {
|
|
|
75
77
|
*/
|
|
76
78
|
toolFilePlacement?: GeminiToolFilePlacement;
|
|
77
79
|
/**
|
|
78
|
-
* generationConfig for whole-document part reads. Defaults to `{
|
|
80
|
+
* generationConfig for whole-document part reads. Defaults to `{ maxOutputTokens }`, with no temperature.
|
|
79
81
|
* The parts are read by the explorer model when there is one, so write it for that model.
|
|
80
82
|
*/
|
|
81
83
|
analysisConfig?: (maxOutputTokens: number) => Record<string, unknown>;
|
|
82
|
-
/**
|
|
84
|
+
/**
|
|
85
|
+
* The longest wait, in milliseconds, for the first piece of a chat reply (see
|
|
86
|
+
* `GeminiModelOptions`). Defaults to 600,000. 0 waits without end.
|
|
87
|
+
*/
|
|
88
|
+
firstByteTimeoutMs?: number;
|
|
89
|
+
/**
|
|
90
|
+
* The longest wait, in milliseconds, between two pieces of a chat reply once it has started to
|
|
91
|
+
* arrive. Defaults to 300,000. 0 waits without end.
|
|
92
|
+
*/
|
|
93
|
+
idleTimeoutMs?: number;
|
|
94
|
+
/** Answer text as it streams. Streaming is used when this is set (or `streamText` is true) and the endpoint has `streamUrl`. */
|
|
83
95
|
onText?: (delta: string) => void;
|
|
96
|
+
/** Whether to ask for the answer as it is written (`AskOptions.streamText`). Defaults to true when `onText` is given. New in 0.7.0. */
|
|
97
|
+
streamText?: boolean;
|
|
84
98
|
/** Short-lived status, such as "Searching app.log for “timeout”…". */
|
|
85
99
|
onActivity?: (text: string) => void;
|
|
86
100
|
/** A finished step, such as "Search app.log (exact) for “timeout” — 12 matching lines". */
|
|
87
101
|
onStep?: (text: string) => void;
|
|
102
|
+
/** Everything the question does, as typed events in order (`AskOptions.onEvent`). New in 0.7.0. */
|
|
103
|
+
onEvent?: (event: AskEvent) => void;
|
|
104
|
+
/** The `runId` of the events. Defaults to one made for the question ("run_…"). */
|
|
105
|
+
runId?: string;
|
|
106
|
+
/** Put each tool result in its `tool.end` event (`AskOptions.eventResults`). Off by default. */
|
|
107
|
+
eventResults?: boolean;
|
|
88
108
|
fetch?: typeof fetch;
|
|
89
109
|
signal?: AbortSignal;
|
|
90
110
|
};
|
|
@@ -102,7 +122,7 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
|
|
|
102
122
|
const { endpoint } = options;
|
|
103
123
|
// A second model for the requests that use tools. The answering model's own URL is not one.
|
|
104
124
|
const explorerUrl = endpoint.explorerUrl && endpoint.explorerUrl !== endpoint.url ? endpoint.explorerUrl : undefined;
|
|
105
|
-
const shared = { toolFilePlacement: options.toolFilePlacement, analysisConfig: options.analysisConfig, fetch: options.fetch };
|
|
125
|
+
const shared = { toolFilePlacement: options.toolFilePlacement, analysisConfig: options.analysisConfig, firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs, fetch: options.fetch };
|
|
106
126
|
const model = gemini(endpoint, { ...shared, generationConfig: options.generationConfig });
|
|
107
127
|
// The explorer is called with the same headers, in one piece, with its own settings when it has any.
|
|
108
128
|
const explorer = explorerUrl
|
|
@@ -127,8 +147,12 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
|
|
|
127
147
|
...(options.wholeDocumentAnalysis !== undefined ? { wholeDocumentAnalysis: options.wholeDocumentAnalysis } : {}),
|
|
128
148
|
...(options.viewPages !== undefined ? { viewPages: options.viewPages } : {}),
|
|
129
149
|
...(options.onText ? { onText: options.onText } : {}),
|
|
150
|
+
...(options.streamText !== undefined ? { streamText: options.streamText } : {}),
|
|
130
151
|
...(options.onActivity ? { onActivity: options.onActivity } : {}),
|
|
131
152
|
...(options.onStep ? { onStep: options.onStep } : {}),
|
|
153
|
+
...(options.onEvent ? { onEvent: options.onEvent } : {}),
|
|
154
|
+
...(options.runId !== undefined ? { runId: options.runId } : {}),
|
|
155
|
+
...(options.eventResults !== undefined ? { eventResults: options.eventResults } : {}),
|
|
132
156
|
...(options.signal ? { signal: options.signal } : {}),
|
|
133
157
|
});
|
|
134
158
|
}
|
package/src/gemini/errors.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { notJsonMessage } from "../http.js";
|
|
1
2
|
import { ModelRequestError } from "../model.js";
|
|
2
3
|
|
|
3
4
|
/** Gemini answered with an HTTP error, or could not be reached (`status` 0). */
|
|
4
5
|
export class GeminiRequestError extends ModelRequestError {
|
|
5
|
-
constructor(message: string, status: number, options:
|
|
6
|
+
constructor(message: string, status: number, options: ConstructorParameters<typeof ModelRequestError>[2] = {}) {
|
|
6
7
|
super(message, status, options);
|
|
7
8
|
this.name = "GeminiRequestError";
|
|
8
9
|
}
|
|
@@ -13,3 +14,35 @@ export function unreachable(error: unknown): GeminiRequestError {
|
|
|
13
14
|
const reason = error instanceof Error && error.message ? ` (${error.message})` : "";
|
|
14
15
|
return new GeminiRequestError(`Gemini could not be reached${reason}.`, 0, { cause: error });
|
|
15
16
|
}
|
|
17
|
+
|
|
18
|
+
/** A body that came with a status of success but is no JSON (a gateway's page): it is not sent again. */
|
|
19
|
+
export function notJson(response: Response, error: unknown): GeminiRequestError {
|
|
20
|
+
return new GeminiRequestError(notJsonMessage("Gemini's", response), response.status, { kind: "invalid", cause: error });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A request that got nothing back for the whole wait of its `IdleWatch`. */
|
|
24
|
+
export function silent(waitMs: number): GeminiRequestError {
|
|
25
|
+
return new GeminiRequestError(`Gemini sent nothing for ${Math.round(waitMs / 1_000)} s.`, 0, { kind: "timeout" });
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The error of a response that is not OK, from its JSON body: Gemini's `error.status` and `details` tell its kind. */
|
|
29
|
+
export function geminiFailure(status: number, data: unknown, retryAfterMs: number | undefined, fallback: string): GeminiRequestError {
|
|
30
|
+
const error = (data as { error?: { message?: unknown; status?: unknown; details?: unknown } } | null)?.error;
|
|
31
|
+
return new GeminiRequestError(typeof error?.message === "string" && error.message ? error.message : fallback, status, {
|
|
32
|
+
...(retryAfterMs === undefined ? {} : { retryAfterMs }),
|
|
33
|
+
...(typeof error?.status === "string" ? { code: error.status } : {}),
|
|
34
|
+
...(error?.details !== undefined ? { details: error.details } : {}),
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const FILTERED = new Set(["SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "IMAGE_SAFETY"]);
|
|
39
|
+
const MALFORMED = new Set(["MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL"]);
|
|
40
|
+
|
|
41
|
+
/** Gemini's `finishReason` in the terms of `ModelReply.finish`. Undefined for a reason it does not know. */
|
|
42
|
+
export function finishOfGemini(reason: string | undefined): "complete" | "cut" | "filtered" | "malformed_call" | undefined {
|
|
43
|
+
if (reason === "STOP") return "complete";
|
|
44
|
+
if (reason === "MAX_TOKENS") return "cut";
|
|
45
|
+
if (reason && FILTERED.has(reason)) return "filtered";
|
|
46
|
+
if (reason && MALFORMED.has(reason)) return "malformed_call";
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
package/src/gemini/generate.ts
CHANGED
|
@@ -2,9 +2,10 @@
|
|
|
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, type LimitedReply } from "../output-limit.js";
|
|
5
|
+
import { readJson } from "../http.js";
|
|
5
6
|
import { retryAfterMs } from "../retry.js";
|
|
6
7
|
import type { GenerateText, GenerateUsage, ToolDeclaration, ToolFile, ToolResult } from "../types.js";
|
|
7
|
-
import {
|
|
8
|
+
import { finishOfGemini, geminiFailure, notJson, unreachable } from "./errors.js";
|
|
8
9
|
|
|
9
10
|
/** Gemini accepts this package's JSON Schema subset as-is. */
|
|
10
11
|
export function toGeminiTools(declarations: ToolDeclaration[]): { functionDeclarations: ToolDeclaration[] } {
|
|
@@ -37,14 +38,20 @@ export function usageOfGemini(usage: Record<string, unknown> | undefined): Gener
|
|
|
37
38
|
};
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
|
|
41
|
+
/** One part of a Gemini turn, as the REST API takes it: `{ text }`, `{ functionCall }`, `{ inlineData }`… */
|
|
42
|
+
export type GeminiPart = Record<string, unknown>;
|
|
43
|
+
/** One turn of Gemini's `contents`. */
|
|
44
|
+
export type GeminiContent = { role: "user" | "model"; parts: GeminiPart[] };
|
|
45
|
+
|
|
46
|
+
/** A `user` turn: a `GeminiContent` that can go in `contents` as it is. */
|
|
47
|
+
type UserTurn = GeminiContent & { role: "user" };
|
|
41
48
|
|
|
42
49
|
const base64 = (bytes: Uint8Array) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
|
|
43
50
|
|
|
44
51
|
/** One function response, with `files` inside it. */
|
|
45
|
-
function functionResponse(call: GeminiFunctionCall, result: ToolResult, files: ToolFile[]):
|
|
52
|
+
function functionResponse(call: GeminiFunctionCall, result: ToolResult, files: ToolFile[]): GeminiPart {
|
|
46
53
|
let response = result;
|
|
47
|
-
const parts:
|
|
54
|
+
const parts: GeminiPart[] = [];
|
|
48
55
|
if (files.length > 0) {
|
|
49
56
|
// The result names its file ("file": "pages-2-3.pdf"); that becomes the reference Gemini resolves.
|
|
50
57
|
response = { ...result };
|
|
@@ -102,6 +109,7 @@ export function createGeminiGenerateText(options: {
|
|
|
102
109
|
/** Request headers, or a function returning them. A function is called for every request: a whole-file read can outlast an access token. */
|
|
103
110
|
headers: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
|
|
104
111
|
fetchImpl?: typeof fetch;
|
|
112
|
+
/** The `generationConfig` of each request, from its output limit. Defaults to `{ maxOutputTokens }`. */
|
|
105
113
|
generationConfig?: (maxOutputTokens: number) => Record<string, unknown>;
|
|
106
114
|
timeoutMs?: number;
|
|
107
115
|
}): GenerateText {
|
|
@@ -121,7 +129,8 @@ export function createGeminiGenerateText(options: {
|
|
|
121
129
|
body: JSON.stringify({
|
|
122
130
|
contents: [{ role: "user", parts: [{ text: prompt }] }],
|
|
123
131
|
systemInstruction: { role: "system", parts: [{ text: system }] },
|
|
124
|
-
|
|
132
|
+
// No temperature: Gemini 3.6 and later ignore it, and Google says later models will refuse it.
|
|
133
|
+
generationConfig: options.generationConfig?.(limit) ?? { maxOutputTokens: limit },
|
|
125
134
|
}),
|
|
126
135
|
});
|
|
127
136
|
} catch (error) {
|
|
@@ -129,15 +138,17 @@ export function createGeminiGenerateText(options: {
|
|
|
129
138
|
if (signal?.aborted || timeout.aborted) throw error;
|
|
130
139
|
throw unreachable(error);
|
|
131
140
|
}
|
|
132
|
-
|
|
141
|
+
type Data = {
|
|
133
142
|
error?: { message?: string };
|
|
134
143
|
candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
|
|
135
144
|
usageMetadata?: Record<string, unknown>;
|
|
136
145
|
} | null;
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
146
|
+
// An error may have no JSON body. A reply must: one whose body could not be read is a
|
|
147
|
+
// connection that failed, and is sent again.
|
|
148
|
+
const data: Data = response.ok
|
|
149
|
+
? await readJson<Data>(response, () => Boolean(signal?.aborted) || timeout.aborted, unreachable, undefined, (error) => notJson(response, error))
|
|
150
|
+
: await response.json().catch(() => null) as Data;
|
|
151
|
+
if (!response.ok) throw geminiFailure(response.status, data, retryAfterMs(response.headers, data), `The model returned HTTP ${response.status}.`);
|
|
141
152
|
onUsage?.(usageOfGemini(data?.usageMetadata));
|
|
142
153
|
const candidate = data?.candidates?.[0];
|
|
143
154
|
const text = (candidate?.content?.parts ?? [])
|
|
@@ -148,6 +159,8 @@ export function createGeminiGenerateText(options: {
|
|
|
148
159
|
return {
|
|
149
160
|
text,
|
|
150
161
|
cutOff: candidate?.finishReason === "MAX_TOKENS",
|
|
162
|
+
// Stopped by the safety filters before its end: what it wrote is not all there is.
|
|
163
|
+
stopped: finishOfGemini(candidate?.finishReason) === "filtered",
|
|
151
164
|
...(candidate?.finishReason ? { reason: candidate.finishReason } : {}),
|
|
152
165
|
thoughts: typeof thoughts === "number" ? thoughts : 0,
|
|
153
166
|
};
|
package/src/gemini/index.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
export { askGemini, DocumentsNotFoundError, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, GeminiRequestError } from "./chat.js";
|
|
2
|
-
export type { AskGeminiOptions, AskGeminiResult, ChatTurn, GeminiContent, GeminiPart } from "./chat.js";
|
|
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";
|
|
3
3
|
export { fromGeminiContents, gemini, GEMINI_PAGE_TOKENS, geminiToolTurns } from "./adapter.js";
|
|
4
4
|
export type { GeminiModelOptions } from "./adapter.js";
|
|
5
5
|
export { geminiApi, vertexAi, vertexHost } from "./endpoints.js";
|
|
6
6
|
export type { GeminiEndpoint } from "./endpoints.js";
|
|
7
7
|
export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, THINKING_OUTPUT_TOKENS, toGeminiTools, usageOfGemini } from "./generate.js";
|
|
8
8
|
export type { GeminiFunctionCall, GeminiToolAnswer, GeminiToolFilePlacement } from "./generate.js";
|
|
9
|
-
export { parseSseJson } from "./sse.js";
|
|
9
|
+
export { parseSseJson, SseEventTooLongError } from "./sse.js";
|
package/src/gemini/sse.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { parseSseJson } from "../sse.js";
|
|
1
|
+
export { parseSseJson, SseEventTooLongError } from "../sse.js";
|