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.
Files changed (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
@@ -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 { GenerateText, ToolDeclaration, ToolFile, ToolResult } from "../types.js";
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 = { name: string; args: Record<string, unknown>; id?: string };
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 = { call: GeminiFunctionCall; result: ToolResult; files?: ToolFile[] };
28
+ export type GeminiToolAnswer = ToolAnswer;
24
29
 
25
- type UserTurn = { role: "user"; parts: unknown[] };
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[]): unknown {
52
+ function functionResponse(call: GeminiFunctionCall, result: ToolResult, files: ToolFile[]): GeminiPart {
31
53
  let response = result;
32
- const parts: unknown[] = [];
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: Record<string, string>;
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<{ text: string; finishReason?: string; thoughts: number }> => {
120
+ const send = async (limit: number): Promise<LimitedReply> => {
119
121
  const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
120
- const response = await fetchImpl(url, {
121
- method: "POST",
122
- headers: options.headers,
123
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
124
- body: JSON.stringify({
125
- contents: [{ role: "user", parts: [{ text: prompt }] }],
126
- systemInstruction: { role: "system", parts: [{ text: system }] },
127
- generationConfig: options.generationConfig?.(limit) ?? { maxOutputTokens: limit, temperature: 0.2 },
128
- }),
129
- });
130
- const data = await response.json().catch(() => null) as {
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?: { thoughtsTokenCount?: unknown };
144
+ usageMetadata?: Record<string, unknown>;
134
145
  } | null;
135
- if (!response.ok) throw Object.assign(new Error(data?.error?.message ?? `The model returned HTTP ${response.status}.`), { status: response.status });
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
- ...(candidate?.finishReason ? { finishReason: candidate.finishReason } : {}),
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
  }
@@ -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
- /** Parses a `text/event-stream` body into JSON objects, one per `data:` event. */
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";