llm-large-files 0.4.1 → 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 +1400 -338
- package/README.md +217 -49
- 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 +117 -0
- package/dist/anthropic/adapter.d.ts.map +1 -0
- package/dist/anthropic/adapter.js +542 -0
- package/dist/anthropic/adapter.js.map +1 -0
- package/dist/anthropic/index.d.ts +3 -0
- package/dist/anthropic/index.d.ts.map +1 -0
- package/dist/anthropic/index.js +2 -0
- package/dist/anthropic/index.js.map +1 -0
- package/dist/ask.d.ts +200 -0
- package/dist/ask.d.ts.map +1 -0
- package/dist/ask.js +1402 -0
- package/dist/ask.js.map +1 -0
- package/dist/budget.d.ts +23 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +64 -0
- package/dist/budget.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 +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 +42 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +138 -0
- package/dist/evidence.js.map +1 -0
- 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 +59 -0
- package/dist/gemini/adapter.d.ts.map +1 -0
- package/dist/gemini/adapter.js +226 -0
- package/dist/gemini/adapter.js.map +1 -0
- package/dist/gemini/chat.d.ts +53 -77
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +42 -300
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +16 -0
- package/dist/gemini/errors.d.ts.map +1 -0
- package/dist/gemini/errors.js +46 -0
- package/dist/gemini/errors.js.map +1 -0
- package/dist/gemini/generate.d.ts +18 -21
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +49 -92
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +6 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +4 -3
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -2
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -38
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +136 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +401 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +96 -8
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +414 -96
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +37 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +255 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +278 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +222 -0
- package/dist/model.js.map +1 -0
- 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 +109 -0
- package/dist/openai/adapter.d.ts.map +1 -0
- package/dist/openai/adapter.js +567 -0
- package/dist/openai/adapter.js.map +1 -0
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +2 -0
- package/dist/openai/index.js.map +1 -0
- package/dist/output-limit.d.ts +42 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +121 -0
- package/dist/output-limit.js.map +1 -0
- 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 +76 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +141 -0
- package/dist/retry.js.map +1 -0
- 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 +36 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +153 -0
- package/dist/sse.js.map +1 -0
- 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 +72 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +341 -60
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +128 -4
- 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 +58 -184
- package/docs/configuration.md +34 -490
- package/docs/getting-started.md +412 -177
- 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 +1022 -138
- 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 +902 -90
- package/docs/troubleshooting.md +1390 -0
- package/package.json +22 -4
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +611 -0
- package/src/anthropic/index.ts +2 -0
- package/src/ask.ts +1560 -0
- package/src/budget.ts +71 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +165 -0
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +271 -0
- package/src/gemini/chat.ts +87 -355
- package/src/gemini/errors.ts +48 -0
- package/src/gemini/generate.ts +67 -94
- package/src/gemini/index.ts +6 -4
- package/src/gemini/sse.ts +1 -34
- package/src/http.ts +434 -0
- package/src/index.ts +55 -4
- package/src/library.ts +497 -97
- package/src/map-reduce.ts +266 -59
- package/src/model.ts +433 -0
- 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 +613 -0
- package/src/openai/index.ts +2 -0
- package/src/output-limit.ts +135 -0
- 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 +176 -0
- package/src/search.ts +63 -10
- package/src/sse.ts +159 -0
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +338 -62
- package/src/types.ts +129 -5
- package/src/zip-directory.ts +136 -0
package/src/gemini/generate.ts
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
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
|
-
import type {
|
|
3
|
+
import type { ToolAnswer, ToolCall } from "../model.js";
|
|
4
|
+
import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
|
|
5
|
+
import { readJson } from "../http.js";
|
|
6
|
+
import { retryAfterMs } from "../retry.js";
|
|
7
|
+
import type { GenerateText, GenerateUsage, ToolDeclaration, ToolFile, ToolResult } from "../types.js";
|
|
8
|
+
import { finishOfGemini, geminiFailure, notJson, unreachable } from "./errors.js";
|
|
4
9
|
|
|
5
10
|
/** Gemini accepts this package's JSON Schema subset as-is. */
|
|
6
11
|
export function toGeminiTools(declarations: ToolDeclaration[]): { functionDeclarations: ToolDeclaration[] } {
|
|
7
12
|
return { functionDeclarations: declarations };
|
|
8
13
|
}
|
|
9
14
|
|
|
10
|
-
export type GeminiFunctionCall =
|
|
15
|
+
export type GeminiFunctionCall = ToolCall;
|
|
11
16
|
|
|
12
17
|
/**
|
|
13
18
|
* Where a file that a tool returned goes in the request:
|
|
@@ -20,16 +25,33 @@ export type GeminiFunctionCall = { name: string; args: Record<string, unknown>;
|
|
|
20
25
|
export type GeminiToolFilePlacement = "inside" | "beside";
|
|
21
26
|
|
|
22
27
|
/** A function call of the model with what the tool returned for it. */
|
|
23
|
-
export type GeminiToolAnswer =
|
|
28
|
+
export type GeminiToolAnswer = ToolAnswer;
|
|
24
29
|
|
|
25
|
-
|
|
30
|
+
/** Gemini's `usageMetadata` in the terms every adapter reports: thoughts are output, cached tokens are input. */
|
|
31
|
+
export function usageOfGemini(usage: Record<string, unknown> | undefined): GenerateUsage {
|
|
32
|
+
const number = (key: string) => (typeof usage?.[key] === "number" ? usage[key] as number : 0);
|
|
33
|
+
return {
|
|
34
|
+
inputTokens: number("promptTokenCount") + number("toolUsePromptTokenCount"),
|
|
35
|
+
cachedInputTokens: number("cachedContentTokenCount"),
|
|
36
|
+
outputTokens: number("candidatesTokenCount") + number("thoughtsTokenCount"),
|
|
37
|
+
thoughtTokens: number("thoughtsTokenCount"),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
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" };
|
|
26
48
|
|
|
27
49
|
const base64 = (bytes: Uint8Array) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
|
|
28
50
|
|
|
29
51
|
/** One function response, with `files` inside it. */
|
|
30
|
-
function functionResponse(call: GeminiFunctionCall, result: ToolResult, files: ToolFile[]):
|
|
52
|
+
function functionResponse(call: GeminiFunctionCall, result: ToolResult, files: ToolFile[]): GeminiPart {
|
|
31
53
|
let response = result;
|
|
32
|
-
const parts:
|
|
54
|
+
const parts: GeminiPart[] = [];
|
|
33
55
|
if (files.length > 0) {
|
|
34
56
|
// The result names its file ("file": "pages-2-3.pdf"); that becomes the reference Gemini resolves.
|
|
35
57
|
response = { ...result };
|
|
@@ -73,29 +95,7 @@ export function geminiFunctionResponseTurns(calls: GeminiToolAnswer[], options:
|
|
|
73
95
|
return [{ role: "user", parts: responses }, ...(files.length > 0 ? [{ role: "user" as const, parts: files }] : [])];
|
|
74
96
|
}
|
|
75
97
|
|
|
76
|
-
|
|
77
|
-
* A model that thinks counts its thoughts in `maxOutputTokens`. Asked for 4,096 tokens of notes on
|
|
78
|
-
* a part of a log, Gemini 3.8 Flash spent 3,931 of them thinking and wrote two lines, and Gemini 4
|
|
79
|
-
* wrote nothing at all (November 2026). A reply that was cut off that way is asked for again with
|
|
80
|
-
* this limit, the least Google recommends for a Gemini 4 model.
|
|
81
|
-
*/
|
|
82
|
-
export const THINKING_OUTPUT_TOKENS = 32_768;
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* What has been learned about the model behind a URL, so that a whole-file read does not pay for
|
|
86
|
-
* the wasted request with every part: the output limit it needs, or 0 when it refused that limit.
|
|
87
|
-
*/
|
|
88
|
-
const learnedLimits = new Map<string, number>();
|
|
89
|
-
/** The first request to a URL that is still on its way. Others wait for what it learns. */
|
|
90
|
-
const firstRequests = new Map<string, Promise<void>>();
|
|
91
|
-
/** URLs that have answered at least once. */
|
|
92
|
-
const answered = new Set<string>();
|
|
93
|
-
const MOST_REMEMBERED = 200;
|
|
94
|
-
|
|
95
|
-
function remember(url: string, limit: number): void {
|
|
96
|
-
if (learnedLimits.size >= MOST_REMEMBERED && !learnedLimits.has(url)) learnedLimits.clear();
|
|
97
|
-
learnedLimits.set(url, limit);
|
|
98
|
-
}
|
|
98
|
+
export { THINKING_OUTPUT_TOKENS } from "../output-limit.js";
|
|
99
99
|
|
|
100
100
|
/**
|
|
101
101
|
* A `GenerateText` backed by a non-streaming `:generateContent` endpoint.
|
|
@@ -106,33 +106,50 @@ function remember(url: string, limit: number): void {
|
|
|
106
106
|
*/
|
|
107
107
|
export function createGeminiGenerateText(options: {
|
|
108
108
|
url: string;
|
|
109
|
-
headers:
|
|
109
|
+
/** Request headers, or a function returning them. A function is called for every request: a whole-file read can outlast an access token. */
|
|
110
|
+
headers: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
|
|
110
111
|
fetchImpl?: typeof fetch;
|
|
112
|
+
/** The `generationConfig` of each request, from its output limit. Defaults to `{ maxOutputTokens }`. */
|
|
111
113
|
generationConfig?: (maxOutputTokens: number) => Record<string, unknown>;
|
|
112
114
|
timeoutMs?: number;
|
|
113
115
|
}): GenerateText {
|
|
114
116
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
115
117
|
const { url } = options;
|
|
116
|
-
return async ({ system, prompt, maxOutputTokens, signal, onTruncated }) => {
|
|
118
|
+
return async ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
|
|
117
119
|
/** One request with an output limit: the text of the reply, why it ended, and what it thought. */
|
|
118
|
-
const send = async (limit: number): Promise<
|
|
120
|
+
const send = async (limit: number): Promise<LimitedReply> => {
|
|
119
121
|
const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
122
|
+
const headers = typeof options.headers === "function" ? await options.headers() : options.headers;
|
|
123
|
+
let response: Response;
|
|
124
|
+
try {
|
|
125
|
+
response = await fetchImpl(url, {
|
|
126
|
+
method: "POST",
|
|
127
|
+
headers,
|
|
128
|
+
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
|
129
|
+
body: JSON.stringify({
|
|
130
|
+
contents: [{ role: "user", parts: [{ text: prompt }] }],
|
|
131
|
+
systemInstruction: { role: "system", parts: [{ text: system }] },
|
|
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 },
|
|
134
|
+
}),
|
|
135
|
+
});
|
|
136
|
+
} catch (error) {
|
|
137
|
+
// Stopped by the caller, or out of time: reported as it is. Anything else is a connection that failed.
|
|
138
|
+
if (signal?.aborted || timeout.aborted) throw error;
|
|
139
|
+
throw unreachable(error);
|
|
140
|
+
}
|
|
141
|
+
type Data = {
|
|
131
142
|
error?: { message?: string };
|
|
132
143
|
candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
|
|
133
|
-
usageMetadata?:
|
|
144
|
+
usageMetadata?: Record<string, unknown>;
|
|
134
145
|
} | null;
|
|
135
|
-
|
|
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}.`);
|
|
152
|
+
onUsage?.(usageOfGemini(data?.usageMetadata));
|
|
136
153
|
const candidate = data?.candidates?.[0];
|
|
137
154
|
const text = (candidate?.content?.parts ?? [])
|
|
138
155
|
.filter((part) => part.thought !== true && typeof part.text === "string")
|
|
@@ -141,57 +158,13 @@ export function createGeminiGenerateText(options: {
|
|
|
141
158
|
const thoughts = data?.usageMetadata?.thoughtsTokenCount;
|
|
142
159
|
return {
|
|
143
160
|
text,
|
|
144
|
-
|
|
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",
|
|
164
|
+
...(candidate?.finishReason ? { reason: candidate.finishReason } : {}),
|
|
145
165
|
thoughts: typeof thoughts === "number" ? thoughts : 0,
|
|
146
166
|
};
|
|
147
167
|
};
|
|
148
|
-
|
|
149
|
-
// The first request to a model finds out whether it thinks its limit away. The parts of a
|
|
150
|
-
// whole-file read are sent four at a time: the others wait for it, and one request is wasted
|
|
151
|
-
// on such a model, not four.
|
|
152
|
-
let learned = () => undefined as void;
|
|
153
|
-
if (!answered.has(url)) {
|
|
154
|
-
const first = firstRequests.get(url);
|
|
155
|
-
if (first) {
|
|
156
|
-
await first;
|
|
157
|
-
signal?.throwIfAborted();
|
|
158
|
-
} else {
|
|
159
|
-
firstRequests.set(url, new Promise<void>((resolve) => {
|
|
160
|
-
learned = () => {
|
|
161
|
-
if (answered.size >= MOST_REMEMBERED) answered.clear();
|
|
162
|
-
answered.add(url);
|
|
163
|
-
firstRequests.delete(url);
|
|
164
|
-
resolve();
|
|
165
|
-
};
|
|
166
|
-
}));
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
try {
|
|
170
|
-
const known = learnedLimits.get(url);
|
|
171
|
-
const limit = Math.max(maxOutputTokens, known ?? 0);
|
|
172
|
-
let reply = await send(limit);
|
|
173
|
-
// Cut off, with nothing written or with at least half of the limit gone on thoughts: the
|
|
174
|
-
// limit was too low for this model, not the notes too long.
|
|
175
|
-
const starved = reply.finishReason === "MAX_TOKENS" && (!reply.text.trim() || reply.thoughts >= limit / 2);
|
|
176
|
-
if (starved && known !== 0 && limit < THINKING_OUTPUT_TOKENS) {
|
|
177
|
-
remember(url, THINKING_OUTPUT_TOKENS);
|
|
178
|
-
try {
|
|
179
|
-
reply = await send(THINKING_OUTPUT_TOKENS);
|
|
180
|
-
} catch (error) {
|
|
181
|
-
if (signal?.aborted) throw error;
|
|
182
|
-
// A model or a gateway that refuses the larger limit (HTTP 400) is not asked for it again.
|
|
183
|
-
// Any other failure says nothing about the limit: the next request starts with it. What
|
|
184
|
-
// the first reply had is kept; with nothing in it, this error is the one to report.
|
|
185
|
-
if ((error as { status?: unknown } | null)?.status === 400) remember(url, 0);
|
|
186
|
-
if (!reply.text.trim()) throw error;
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
if (!reply.text.trim()) throw new Error(`The model returned no text${reply.finishReason ? ` (${reply.finishReason})` : ""}.`);
|
|
190
|
-
// The text stops mid-list when the output limit is reached. Say so instead of passing it off as complete.
|
|
191
|
-
if (reply.finishReason === "MAX_TOKENS") onTruncated?.();
|
|
192
|
-
return reply.text;
|
|
193
|
-
} finally {
|
|
194
|
-
learned();
|
|
195
|
-
}
|
|
168
|
+
return completeWithinLimit(url, maxOutputTokens, send, { signal, onTruncated });
|
|
196
169
|
};
|
|
197
170
|
}
|
package/src/gemini/index.ts
CHANGED
|
@@ -1,7 +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
|
+
export { fromGeminiContents, gemini, GEMINI_PAGE_TOKENS, geminiToolTurns } from "./adapter.js";
|
|
4
|
+
export type { GeminiModelOptions } from "./adapter.js";
|
|
3
5
|
export { geminiApi, vertexAi, vertexHost } from "./endpoints.js";
|
|
4
6
|
export type { GeminiEndpoint } from "./endpoints.js";
|
|
5
|
-
export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, THINKING_OUTPUT_TOKENS, toGeminiTools } from "./generate.js";
|
|
7
|
+
export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, THINKING_OUTPUT_TOKENS, toGeminiTools, usageOfGemini } from "./generate.js";
|
|
6
8
|
export type { GeminiFunctionCall, GeminiToolAnswer, GeminiToolFilePlacement } from "./generate.js";
|
|
7
|
-
export { parseSseJson } from "./sse.js";
|
|
9
|
+
export { parseSseJson, SseEventTooLongError } from "./sse.js";
|
package/src/gemini/sse.ts
CHANGED
|
@@ -1,34 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export async function* parseSseJson<T>(stream: ReadableStream<Uint8Array>): AsyncGenerator<T> {
|
|
3
|
-
const reader = stream.getReader();
|
|
4
|
-
const decoder = new TextDecoder();
|
|
5
|
-
let buffer = "";
|
|
6
|
-
const parse = (block: string): T | undefined => {
|
|
7
|
-
const data = block
|
|
8
|
-
.split("\n")
|
|
9
|
-
.filter((line) => line.startsWith("data:"))
|
|
10
|
-
.map((line) => line.slice(5).trimStart())
|
|
11
|
-
.join("\n");
|
|
12
|
-
return data && data !== "[DONE]" ? JSON.parse(data) as T : undefined;
|
|
13
|
-
};
|
|
14
|
-
try {
|
|
15
|
-
while (true) {
|
|
16
|
-
const { done, value } = await reader.read();
|
|
17
|
-
buffer += decoder.decode(value, { stream: !done });
|
|
18
|
-
buffer = buffer.replace(/\r\n/g, "\n");
|
|
19
|
-
let boundary = buffer.indexOf("\n\n");
|
|
20
|
-
while (boundary >= 0) {
|
|
21
|
-
const event = parse(buffer.slice(0, boundary));
|
|
22
|
-
buffer = buffer.slice(boundary + 2);
|
|
23
|
-
if (event !== undefined) yield event;
|
|
24
|
-
boundary = buffer.indexOf("\n\n");
|
|
25
|
-
}
|
|
26
|
-
if (done) break;
|
|
27
|
-
}
|
|
28
|
-
const last = buffer.trim() ? parse(buffer.trim()) : undefined;
|
|
29
|
-
if (last !== undefined) yield last;
|
|
30
|
-
} finally {
|
|
31
|
-
await reader.cancel().catch(() => undefined);
|
|
32
|
-
reader.releaseLock();
|
|
33
|
-
}
|
|
34
|
-
}
|
|
1
|
+
export { parseSseJson, SseEventTooLongError } from "../sse.js";
|