llm-large-files 0.5.0 → 0.8.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 +1719 -466
- package/README.md +190 -60
- package/dist/analyze.d.ts +8 -1
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +198 -54
- 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 +194 -40
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +63 -7
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1131 -214
- package/dist/ask.js.map +1 -1
- package/dist/decode.d.ts +19 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +97 -0
- package/dist/decode.js.map +1 -0
- 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 +59 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +80 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +339 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +163 -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 +9 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +26 -7
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +180 -314
- 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 +117 -66
- 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/endpoints.d.ts +5 -1
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +11 -2
- package/dist/gemini/endpoints.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 +33 -10
- 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/groups.d.ts +54 -0
- package/dist/groups.d.ts.map +1 -0
- package/dist/groups.js +136 -0
- package/dist/groups.js.map +1 -0
- package/dist/html.d.ts +11 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +1112 -0
- package/dist/html.js.map +1 -0
- 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 +13 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -5
- 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 +449 -93
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -1
- package/dist/limiter.d.ts.map +1 -1
- package/dist/limiter.js +3 -2
- package/dist/limiter.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 +190 -2
- 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 +184 -28
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +38 -0
- package/dist/node/ingest-child.d.ts.map +1 -0
- package/dist/node/ingest-child.js +42 -0
- package/dist/node/ingest-child.js.map +1 -0
- package/dist/node/isolated.d.ts +88 -0
- package/dist/node/isolated.d.ts.map +1 -0
- package/dist/node/isolated.js +381 -0
- package/dist/node/isolated.js.map +1 -0
- 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/office.d.ts +105 -0
- package/dist/office.d.ts.map +1 -0
- package/dist/office.js +1092 -0
- package/dist/office.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 +325 -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 +277 -20
- 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/peers.d.ts +8 -0
- package/dist/peers.d.ts.map +1 -0
- package/dist/peers.js +32 -0
- package/dist/peers.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/ranged.d.ts.map +1 -1
- package/dist/ranged.js +4 -2
- package/dist/ranged.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 +107 -24
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +803 -149
- 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 +9 -1
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +28 -9
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +87 -3
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +526 -24
- 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 +461 -46
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +103 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/word-styles.d.ts +102 -0
- package/dist/word-styles.d.ts.map +1 -0
- package/dist/word-styles.js +419 -0
- package/dist/word-styles.js.map +1 -0
- package/dist/xlsx.d.ts +23 -0
- package/dist/xlsx.d.ts.map +1 -0
- package/dist/xlsx.js +511 -0
- package/dist/xlsx.js.map +1 -0
- package/dist/xml-stream.d.ts +55 -0
- package/dist/xml-stream.d.ts.map +1 -0
- package/dist/xml-stream.js +235 -0
- package/dist/xml-stream.js.map +1 -0
- 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 +728 -0
- package/docs/guides/deployment.md +720 -0
- package/docs/guides/errors-and-reliability.md +748 -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 +1024 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1203 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1590 -0
- package/docs/how-it-works.md +1035 -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 +910 -0
- package/docs/reference/errors-and-retries.md +760 -0
- package/docs/reference/events.md +1001 -0
- package/docs/reference/gemini.md +827 -0
- package/docs/reference/library.md +1598 -0
- package/docs/reference/node.md +706 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +1031 -0
- package/docs/security.md +940 -101
- package/docs/troubleshooting.md +1410 -0
- package/package.json +7 -3
- package/src/analyze.ts +204 -49
- package/src/anthropic/adapter.ts +200 -40
- package/src/ask.ts +1151 -210
- package/src/decode.ts +89 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +125 -0
- package/src/events.ts +451 -0
- package/src/evidence.ts +11 -2
- package/src/extract.ts +191 -308
- package/src/gemini/adapter.ts +127 -70
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/endpoints.ts +12 -2
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +42 -13
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/groups.ts +162 -0
- package/src/html.ts +1071 -0
- package/src/http.ts +376 -1
- package/src/index.ts +29 -6
- package/src/library.ts +498 -93
- package/src/limiter.ts +6 -1
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +244 -4
- package/src/node/handlers.ts +196 -31
- package/src/node/index.ts +4 -0
- package/src/node/ingest-child.ts +61 -0
- package/src/node/isolated.ts +464 -0
- package/src/node/sse.ts +198 -0
- package/src/office.ts +1047 -0
- package/src/openai/adapter.ts +319 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +270 -20
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/peers.ts +29 -0
- package/src/plan.ts +70 -12
- package/src/ranged.ts +4 -2
- package/src/retry.ts +49 -5
- package/src/search.ts +800 -155
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +30 -9
- package/src/text.ts +524 -23
- package/src/tools.ts +445 -46
- package/src/types.ts +108 -5
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- package/src/xml-stream.ts +224 -0
- 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
|
|
|
@@ -66,10 +79,14 @@ function callsTurn(calls: ToolCall[]): GeminiContent {
|
|
|
66
79
|
return { role: "model", parts: calls.map((call) => ({ functionCall: { name: call.name, args: call.args, ...(call.id ? { id: call.id } : {}) } })) };
|
|
67
80
|
}
|
|
68
81
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
82
|
+
/**
|
|
83
|
+
* A turn of text, without its empty text parts: Vertex AI refuses an empty text parameter (a stored
|
|
84
|
+
* answer that came back empty is one). A native part stays, and a turn with no part left is none.
|
|
85
|
+
*/
|
|
86
|
+
const textTurn = (message: ModelTextMessage): GeminiContent[] => {
|
|
87
|
+
const parts = message.parts.flatMap((part): GeminiPart[] => (part.native !== undefined ? [part.native as GeminiPart] : part.text ? [{ text: part.text }] : []));
|
|
88
|
+
return parts.length > 0 ? [{ role: message.role === "user" ? "user" : "model", parts }] : [];
|
|
89
|
+
};
|
|
73
90
|
|
|
74
91
|
/**
|
|
75
92
|
* Gemini `contents` as messages of `askWithFiles`: text parts as text, every other part (an image,
|
|
@@ -92,8 +109,9 @@ export function fromGeminiContents(contents: GeminiContent[]): ChatMessage[] {
|
|
|
92
109
|
*/
|
|
93
110
|
export function geminiToolTurns(turns: ToolTurn[]): GeminiContent[] {
|
|
94
111
|
return turns.flatMap((turn) => {
|
|
95
|
-
|
|
96
|
-
|
|
112
|
+
// Sent again in later questions: without the tool turns this question had left.
|
|
113
|
+
const answers = turn.calls.map(({ result, ...call }) => ({ call, result: laterResult(result) }));
|
|
114
|
+
return [callsTurn(answers.map((answer) => answer.call)), ...geminiFunctionResponseTurns(answers)];
|
|
97
115
|
});
|
|
98
116
|
}
|
|
99
117
|
|
|
@@ -112,12 +130,12 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
|
|
|
112
130
|
if (!turns) {
|
|
113
131
|
// Its own turn goes back unchanged: Gemini 3 requires its thought signatures.
|
|
114
132
|
const asked = round.raw !== undefined ? round.raw as GeminiContent : callsTurn(round.calls);
|
|
115
|
-
turns = [asked, ...(round.answers.length > 0 ? geminiFunctionResponseTurns(round.answers, { files: placement })
|
|
133
|
+
turns = [asked, ...(round.answers.length > 0 ? geminiFunctionResponseTurns(round.answers, { files: placement }) : [])];
|
|
116
134
|
built.set(round, turns);
|
|
117
135
|
}
|
|
118
136
|
return turns;
|
|
119
137
|
};
|
|
120
|
-
const toContents = (messages: ModelMessage[]): GeminiContent[] => messages.flatMap((message) => (message.role === "tools" ? roundTurns(message) :
|
|
138
|
+
const toContents = (messages: ModelMessage[]): GeminiContent[] => messages.flatMap((message) => (message.role === "tools" ? roundTurns(message) : textTurn(message)));
|
|
121
139
|
const bodyOf = (request: ModelRequest): Body => ({
|
|
122
140
|
contents: toContents(request.messages),
|
|
123
141
|
...(request.system ? { systemInstruction: { parts: [{ text: request.system }] } } : {}),
|
|
@@ -150,69 +168,108 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
|
|
|
150
168
|
const stream = Boolean(hooks.onText && endpoint.streamUrl);
|
|
151
169
|
// Headers are asked for with each request: an access token may have been renewed since the last.
|
|
152
170
|
const headers = await resolveHeaders(endpoint);
|
|
153
|
-
|
|
171
|
+
const watch = idleWatch(hooks.signal, { firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs });
|
|
172
|
+
// A request the watch aborted got nothing back for the whole wait: that is no failed connection.
|
|
173
|
+
const lost = (error: unknown) => (watch.expired ? silent(watch.waitedMs) : unreachable(error));
|
|
154
174
|
try {
|
|
155
|
-
response
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
175
|
+
let response: Response;
|
|
176
|
+
try {
|
|
177
|
+
response = await fetchImpl(stream ? endpoint.streamUrl! : endpoint.url, {
|
|
178
|
+
method: "POST",
|
|
179
|
+
headers,
|
|
180
|
+
body: JSON.stringify(bodyOf(request)),
|
|
181
|
+
signal: watch.signal,
|
|
182
|
+
});
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (hooks.signal?.aborted) throw error;
|
|
185
|
+
throw lost(error);
|
|
186
|
+
}
|
|
187
|
+
// The headers are no piece of the reply: a server may send them at once and then think.
|
|
188
|
+
if (!response.ok) {
|
|
189
|
+
const data = await response.json().catch(() => null);
|
|
190
|
+
throw geminiFailure(response.status, data, retryAfterMs(response.headers, data), `Gemini returned HTTP ${response.status}.`);
|
|
191
|
+
}
|
|
192
|
+
return await readReply(response, stream, hooks, watch, lost);
|
|
193
|
+
} finally {
|
|
194
|
+
watch.stop();
|
|
164
195
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
196
|
+
},
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
/** The reply of a request that was answered: streamed, or in one piece. */
|
|
201
|
+
async function readReply(response: Response, stream: boolean, hooks: SendHooks, watch: IdleWatch, lost: (error: unknown) => GeminiRequestError): Promise<ModelReply> {
|
|
202
|
+
const parts: GeminiPart[] = [];
|
|
203
|
+
const calls: ToolCall[] = [];
|
|
204
|
+
let text = "";
|
|
205
|
+
let finishReason: string | undefined;
|
|
206
|
+
let blockReason: string | undefined;
|
|
207
|
+
let usage: Record<string, unknown> | undefined;
|
|
208
|
+
const take = (chunk: Chunk) => {
|
|
209
|
+
if (chunk.error?.message) {
|
|
210
|
+
throw geminiFailure(typeof chunk.error.code === "number" ? chunk.error.code : response.status, chunk, undefined, chunk.error.message);
|
|
169
211
|
}
|
|
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
|
-
}
|
|
212
|
+
if (chunk.promptFeedback?.blockReason) blockReason = chunk.promptFeedback.blockReason;
|
|
213
|
+
const candidate = chunk.candidates?.[0];
|
|
214
|
+
for (const part of candidate?.content?.parts ?? []) {
|
|
215
|
+
// Keep every part unchanged: Gemini 3 requires its thought signatures back.
|
|
216
|
+
parts.push(part);
|
|
217
|
+
if (typeof part.text === "string" && part.text && part.thought !== true) {
|
|
218
|
+
text += part.text;
|
|
219
|
+
hooks.onText?.(part.text);
|
|
220
|
+
}
|
|
221
|
+
const call = part.functionCall as { name?: unknown; args?: unknown; id?: unknown } | undefined;
|
|
222
|
+
if (call && typeof call.name === "string") {
|
|
223
|
+
const args = call.args && typeof call.args === "object" && !Array.isArray(call.args) ? call.args as Record<string, unknown> : {};
|
|
224
|
+
calls.push({ name: call.name, args, ...(typeof call.id === "string" ? { id: call.id } : {}) });
|
|
192
225
|
}
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
226
|
+
}
|
|
227
|
+
finishReason = candidate?.finishReason ?? finishReason;
|
|
228
|
+
usage = chunk.usageMetadata ?? usage;
|
|
229
|
+
};
|
|
230
|
+
const notTheReply = (error: unknown) => notJson(response, error);
|
|
231
|
+
if (stream) {
|
|
232
|
+
if (!response.body) throw new GeminiRequestError("Gemini returned an empty stream.", response.status);
|
|
233
|
+
let events: boolean;
|
|
234
|
+
let body: Response;
|
|
235
|
+
try {
|
|
236
|
+
({ events, response: body } = await streamedReply(response, watch));
|
|
237
|
+
} catch (error) {
|
|
238
|
+
if (hooks.signal?.aborted) throw error;
|
|
239
|
+
throw noteCutReply(lost(error));
|
|
240
|
+
}
|
|
241
|
+
if (events) {
|
|
198
242
|
try {
|
|
199
|
-
for await (const chunk of parseSseJson<Chunk>(
|
|
243
|
+
for await (const chunk of parseSseJson<Chunk>(body.body!, { onData: watch.pulse, signal: watch.signal })) take(chunk);
|
|
200
244
|
} catch (error) {
|
|
201
245
|
if (hooks.signal?.aborted || error instanceof GeminiRequestError) throw error;
|
|
202
|
-
//
|
|
203
|
-
throw
|
|
246
|
+
// An event too long to read would come again: it is not sent again, like a page in the reply's place.
|
|
247
|
+
if (error instanceof SseEventTooLongError) throw new GeminiRequestError(eventTooLongMessage("Gemini's", error), response.status, { kind: "invalid", cause: error });
|
|
248
|
+
// The connection went while the answer was on its way, or nothing came for the whole wait.
|
|
249
|
+
throw noteCutReply(lost(error));
|
|
204
250
|
}
|
|
251
|
+
// Every reply Gemini streams ends with a chunk that says why it ended. A stream that closed
|
|
252
|
+
// without one was cut off on its way (a proxy, a dropped connection): it is not a whole
|
|
253
|
+
// reply, and is sent again like a connection that failed, unless text of it was shown.
|
|
254
|
+
if (finishReason === undefined && blockReason === undefined) throw noteCutReply(new GeminiRequestError("Gemini's reply ended before it was complete.", 0));
|
|
205
255
|
} else {
|
|
206
|
-
|
|
256
|
+
// In one piece, though it was asked for as a stream: a gateway that does not stream (its
|
|
257
|
+
// chunks in a list, as Gemini sends them without `alt=sse`), or a page in the model's place.
|
|
258
|
+
const data = await readJson<Chunk | Chunk[]>(body, () => Boolean(hooks.signal?.aborted), lost, watch, notTheReply);
|
|
259
|
+
for (const chunk of Array.isArray(data) ? data : [data]) take(chunk);
|
|
207
260
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
|
|
261
|
+
} else {
|
|
262
|
+
take(await readJson<Chunk>(response, () => Boolean(hooks.signal?.aborted), lost, watch, notTheReply));
|
|
263
|
+
}
|
|
264
|
+
const finish = finishOfGemini(finishReason);
|
|
265
|
+
return {
|
|
266
|
+
text,
|
|
267
|
+
calls,
|
|
268
|
+
raw: { role: "model", parts } satisfies GeminiContent,
|
|
269
|
+
...(finishReason ? { finishReason } : {}),
|
|
270
|
+
...(finish ? { finish } : {}),
|
|
271
|
+
...(blockReason ? { blockReason } : {}),
|
|
272
|
+
...(usage ? { usage: usageOfGemini(usage), providerUsage: usage } : {}),
|
|
273
|
+
};
|
|
274
|
+
}
|
|
218
275
|
}
|
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/endpoints.ts
CHANGED
|
@@ -54,8 +54,18 @@ export function geminiApi(options: {
|
|
|
54
54
|
};
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
/**
|
|
57
|
+
/** A Vertex AI location: "global", "us", "eu", or a region such as "europe-west4". */
|
|
58
|
+
const LOCATION = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The host for a Vertex AI location: global, the us/eu multi-regions, or a single region. A location
|
|
62
|
+
* that is not one (with "/", "?", "#" or "@" it would name another host, which would get the access
|
|
63
|
+
* token) throws a TypeError.
|
|
64
|
+
*/
|
|
58
65
|
export function vertexHost(location: string): string {
|
|
66
|
+
if (typeof location !== "string" || !LOCATION.test(location)) {
|
|
67
|
+
throw new TypeError(`location must be a Vertex AI location such as "global", "us" or "europe-west4", and is ${JSON.stringify(location) ?? String(location)}.`);
|
|
68
|
+
}
|
|
59
69
|
if (location === "global") return "https://aiplatform.googleapis.com";
|
|
60
70
|
if (location === "us" || location === "eu") return `https://aiplatform.${location}.rep.googleapis.com`;
|
|
61
71
|
return `https://${location}-aiplatform.googleapis.com`;
|
|
@@ -76,7 +86,7 @@ export function vertexAi(options: {
|
|
|
76
86
|
apiVersion?: string;
|
|
77
87
|
}): GeminiEndpoint {
|
|
78
88
|
const location = options.location ?? "global";
|
|
79
|
-
const models = `${vertexHost(location)}/${options.apiVersion ?? "v1"}/projects/${encodeURIComponent(options.project)}/locations/${location}/publishers/google/models/`;
|
|
89
|
+
const models = `${vertexHost(location)}/${options.apiVersion ?? "v1"}/projects/${encodeURIComponent(options.project)}/locations/${encodeURIComponent(location)}/publishers/google/models/`;
|
|
80
90
|
const base = `${models}${encodeURIComponent(options.model)}`;
|
|
81
91
|
const explorer = explorerOf(options);
|
|
82
92
|
const token = options.accessToken;
|
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
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// Gemini (Generate Content REST) helpers. No SDK dependency: the caller supplies the URL and
|
|
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
|
-
import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
|
|
5
|
-
import {
|
|
4
|
+
import { completeWithinLimit, noTextReason, type LimitedReply } from "../output-limit.js";
|
|
5
|
+
import { readJson } from "../http.js";
|
|
6
|
+
import { noteNoRetry, 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,12 +109,15 @@ 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 {
|
|
108
116
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
109
117
|
const { url } = options;
|
|
110
118
|
return async ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
|
|
119
|
+
/** Set when Gemini blocked the prompt: sent again, it would be blocked again. */
|
|
120
|
+
let blocked = false;
|
|
111
121
|
/** One request with an output limit: the text of the reply, why it ended, and what it thought. */
|
|
112
122
|
const send = async (limit: number): Promise<LimitedReply> => {
|
|
113
123
|
const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
|
|
@@ -121,7 +131,8 @@ export function createGeminiGenerateText(options: {
|
|
|
121
131
|
body: JSON.stringify({
|
|
122
132
|
contents: [{ role: "user", parts: [{ text: prompt }] }],
|
|
123
133
|
systemInstruction: { role: "system", parts: [{ text: system }] },
|
|
124
|
-
|
|
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 },
|
|
125
136
|
}),
|
|
126
137
|
});
|
|
127
138
|
} catch (error) {
|
|
@@ -129,17 +140,27 @@ export function createGeminiGenerateText(options: {
|
|
|
129
140
|
if (signal?.aborted || timeout.aborted) throw error;
|
|
130
141
|
throw unreachable(error);
|
|
131
142
|
}
|
|
132
|
-
|
|
143
|
+
type Data = {
|
|
133
144
|
error?: { message?: string };
|
|
134
145
|
candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
|
|
135
146
|
usageMetadata?: Record<string, unknown>;
|
|
147
|
+
promptFeedback?: { blockReason?: unknown };
|
|
136
148
|
} | null;
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
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}.`);
|
|
141
155
|
onUsage?.(usageOfGemini(data?.usageMetadata));
|
|
142
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
|
+
}
|
|
143
164
|
const text = (candidate?.content?.parts ?? [])
|
|
144
165
|
.filter((part) => part.thought !== true && typeof part.text === "string")
|
|
145
166
|
.map((part) => part.text as string)
|
|
@@ -148,10 +169,18 @@ export function createGeminiGenerateText(options: {
|
|
|
148
169
|
return {
|
|
149
170
|
text,
|
|
150
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",
|
|
151
174
|
...(candidate?.finishReason ? { reason: candidate.finishReason } : {}),
|
|
152
175
|
thoughts: typeof thoughts === "number" ? thoughts : 0,
|
|
153
176
|
};
|
|
154
177
|
};
|
|
155
|
-
|
|
178
|
+
try {
|
|
179
|
+
return await completeWithinLimit(url, maxOutputTokens, send, { signal, onTruncated });
|
|
180
|
+
} catch (error) {
|
|
181
|
+
// A blocked prompt is not worth sending again: `withRetry` does not.
|
|
182
|
+
if (blocked && noTextReason(error) !== undefined) noteNoRetry(error as object);
|
|
183
|
+
throw error;
|
|
184
|
+
}
|
|
156
185
|
};
|
|
157
186
|
}
|
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";
|