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
@@ -0,0 +1,271 @@
1
+ // Gemini (Generate Content REST) as a model of `askWithFiles`.
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
+ import { retryAfterMs } from "../retry.js";
4
+ import { idleWatch, noteCutReply, readJson, streamedReply, type IdleWatch } from "../http.js";
5
+ import { eventTooLongMessage, parseSseJson, SseEventTooLongError } from "../sse.js";
6
+ import { resolveHeaders, type GeminiEndpoint } from "./endpoints.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";
9
+
10
+ export type { GeminiContent, GeminiPart };
11
+
12
+ /** What Gemini bills for one PDF page it is shown (measured: 520 to 532). */
13
+ export const GEMINI_PAGE_TOKENS = 530;
14
+
15
+ export type GeminiModelOptions = {
16
+ /** Sent with every chat request: temperature, maxOutputTokens, thinkingConfig, and so on. */
17
+ generationConfig?: Record<string, unknown> | undefined;
18
+ /**
19
+ * Where the pages of `view_pages` go in the request. "inside" (the default) puts the PDF in the
20
+ * function response itself, which Gemini 3 and 4 models read. "beside" sends it in a user turn
21
+ * of its own, after the function responses: use it for Gemini 2.5, which does not see a file
22
+ * inside a function response.
23
+ */
24
+ toolFilePlacement?: GeminiToolFilePlacement | undefined;
25
+ /** generationConfig for whole-document part reads. Defaults to `{ maxOutputTokens }`, with no temperature. */
26
+ analysisConfig?: ((maxOutputTokens: number) => Record<string, unknown>) | undefined;
27
+ /** The model's context window in tokens, when the budget of a question should follow it. */
28
+ contextTokens?: number | undefined;
29
+ /** The largest request body the model or your gateway takes, in bytes. */
30
+ maxRequestBytes?: number | undefined;
31
+ /** Tokens billed for one PDF page. Defaults to 530. */
32
+ pageTokens?: number | undefined;
33
+ /** Names the model in usage totals. Defaults to the model in the URL. */
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;
48
+ fetch?: typeof fetch | undefined;
49
+ };
50
+
51
+ type Body = {
52
+ contents: GeminiContent[];
53
+ systemInstruction?: { parts: Array<{ text: string }> };
54
+ generationConfig?: Record<string, unknown>;
55
+ tools?: unknown[];
56
+ toolConfig?: unknown;
57
+ };
58
+
59
+ type Chunk = {
60
+ candidates?: Array<{ finishReason?: string; content?: { parts?: GeminiPart[] } }>;
61
+ usageMetadata?: Record<string, unknown>;
62
+ promptFeedback?: { blockReason?: string };
63
+ error?: { message?: string; code?: unknown };
64
+ };
65
+
66
+ /** The model a Generate Content URL names: ".../models/gemini-3.8-flash:generateContent". */
67
+ function modelOf(url: string): string {
68
+ const name = /\/models\/([^/:?]+)/.exec(url)?.[1];
69
+ if (name) return decodeURIComponent(name);
70
+ try {
71
+ return new URL(url).host || "gemini";
72
+ } catch {
73
+ return "gemini";
74
+ }
75
+ }
76
+
77
+ /** A model turn that is known only by its tool calls. */
78
+ function callsTurn(calls: ToolCall[]): GeminiContent {
79
+ return { role: "model", parts: calls.map((call) => ({ functionCall: { name: call.name, args: call.args, ...(call.id ? { id: call.id } : {}) } })) };
80
+ }
81
+
82
+ const textTurn = (message: ModelTextMessage): GeminiContent => ({
83
+ role: message.role === "user" ? "user" : "model",
84
+ parts: message.parts.map((part) => (part.native !== undefined ? part.native as GeminiPart : { text: part.text ?? "" })),
85
+ });
86
+
87
+ /**
88
+ * Gemini `contents` as messages of `askWithFiles`: text parts as text, every other part (an image,
89
+ * an inline PDF, a function call of an earlier question) as it is.
90
+ */
91
+ export function fromGeminiContents(contents: GeminiContent[]): ChatMessage[] {
92
+ return contents.map((content): ModelTextMessage => ({
93
+ role: content.role === "user" ? "user" : "assistant",
94
+ parts: content.parts.map((part) => {
95
+ if (typeof part.text !== "string") return { native: part };
96
+ return Object.keys(part).length === 1 ? { text: part.text } : { native: part, text: part.text };
97
+ }),
98
+ }));
99
+ }
100
+
101
+ /**
102
+ * The tool rounds a question returned (`AskResult.toolTurns`) as Gemini `contents`: a model turn
103
+ * of function calls and a user turn of function responses for each. For an application that
104
+ * keeps its history as `contents`: put them between the question and its answer.
105
+ */
106
+ export function geminiToolTurns(turns: ToolTurn[]): GeminiContent[] {
107
+ return turns.flatMap((turn) => {
108
+ // Sent again in later questions: without the tool turns this question had left.
109
+ const answers = turn.calls.map(({ result, ...call }) => ({ call, result: laterResult(result) }));
110
+ return [callsTurn(answers.map((answer) => answer.call)), ...geminiFunctionResponseTurns(answers)];
111
+ });
112
+ }
113
+
114
+ /**
115
+ * A Gemini model for `askWithFiles`. `endpoint` says where it is: `geminiApi()`, `vertexAi()`, or
116
+ * your own URLs and headers for a gateway. Its `explorerUrl` is not used here: an explorer is a
117
+ * model of its own, `gemini(geminiApi({ apiKey, model: "the-explorer" }))`.
118
+ */
119
+ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "headers">, options: GeminiModelOptions = {}): ModelAdapter {
120
+ const fetchImpl = options.fetch ?? fetch;
121
+ const placement = options.toolFilePlacement ?? "inside";
122
+ // The turns of a tool round are built once: its pages are megabytes of base64.
123
+ const built = new WeakMap<ModelToolRound, GeminiContent[]>();
124
+ const roundTurns = (round: ModelToolRound): GeminiContent[] => {
125
+ let turns = built.get(round);
126
+ if (!turns) {
127
+ // Its own turn goes back unchanged: Gemini 3 requires its thought signatures.
128
+ const asked = round.raw !== undefined ? round.raw as GeminiContent : callsTurn(round.calls);
129
+ turns = [asked, ...(round.answers.length > 0 ? geminiFunctionResponseTurns(round.answers, { files: placement }) : [])];
130
+ built.set(round, turns);
131
+ }
132
+ return turns;
133
+ };
134
+ const toContents = (messages: ModelMessage[]): GeminiContent[] => messages.flatMap((message) => (message.role === "tools" ? roundTurns(message) : [textTurn(message)]));
135
+ const bodyOf = (request: ModelRequest): Body => ({
136
+ contents: toContents(request.messages),
137
+ ...(request.system ? { systemInstruction: { parts: [{ text: request.system }] } } : {}),
138
+ ...(options.generationConfig ? { generationConfig: options.generationConfig } : {}),
139
+ // A request that must be answered in text declares no tools at all: Gemini can ignore
140
+ // functionCallingConfig mode NONE and keep calling them.
141
+ ...(request.tools?.length && request.toolChoice !== "none" ? {
142
+ tools: [{ functionDeclarations: request.tools }],
143
+ toolConfig: { functionCallingConfig: { mode: "AUTO" } },
144
+ } : {}),
145
+ });
146
+
147
+ return {
148
+ id: options.id ?? modelOf(endpoint.url),
149
+ capabilities: {
150
+ ...(options.contextTokens ? { contextTokens: options.contextTokens } : {}),
151
+ ...(options.maxRequestBytes ? { maxRequestBytes: options.maxRequestBytes } : {}),
152
+ toolFiles: placement,
153
+ pageTokens: options.pageTokens ?? GEMINI_PAGE_TOKENS,
154
+ },
155
+ requestBytes: (request) => Buffer.byteLength(JSON.stringify(bodyOf(request))),
156
+ generateText: createGeminiGenerateText({
157
+ url: endpoint.url,
158
+ headers: endpoint.headers,
159
+ fetchImpl,
160
+ ...(options.analysisConfig ? { generationConfig: options.analysisConfig } : {}),
161
+ }),
162
+
163
+ async send(request: ModelRequest, hooks: SendHooks = {}): Promise<ModelReply> {
164
+ const stream = Boolean(hooks.onText && endpoint.streamUrl);
165
+ // Headers are asked for with each request: an access token may have been renewed since the last.
166
+ const headers = await resolveHeaders(endpoint);
167
+ const watch = idleWatch(hooks.signal, { firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs });
168
+ // A request the watch aborted got nothing back for the whole wait: that is no failed connection.
169
+ const lost = (error: unknown) => (watch.expired ? silent(watch.waitedMs) : unreachable(error));
170
+ try {
171
+ let response: Response;
172
+ try {
173
+ response = await fetchImpl(stream ? endpoint.streamUrl! : endpoint.url, {
174
+ method: "POST",
175
+ headers,
176
+ body: JSON.stringify(bodyOf(request)),
177
+ signal: watch.signal,
178
+ });
179
+ } catch (error) {
180
+ if (hooks.signal?.aborted) throw error;
181
+ throw lost(error);
182
+ }
183
+ // The headers are no piece of the reply: a server may send them at once and then think.
184
+ if (!response.ok) {
185
+ const data = await response.json().catch(() => null);
186
+ throw geminiFailure(response.status, data, retryAfterMs(response.headers, data), `Gemini returned HTTP ${response.status}.`);
187
+ }
188
+ return await readReply(response, stream, hooks, watch, lost);
189
+ } finally {
190
+ watch.stop();
191
+ }
192
+ },
193
+ };
194
+
195
+
196
+ /** The reply of a request that was answered: streamed, or in one piece. */
197
+ async function readReply(response: Response, stream: boolean, hooks: SendHooks, watch: IdleWatch, lost: (error: unknown) => GeminiRequestError): Promise<ModelReply> {
198
+ const parts: GeminiPart[] = [];
199
+ const calls: ToolCall[] = [];
200
+ let text = "";
201
+ let finishReason: string | undefined;
202
+ let blockReason: string | undefined;
203
+ let usage: Record<string, unknown> | undefined;
204
+ const take = (chunk: Chunk) => {
205
+ if (chunk.error?.message) {
206
+ throw geminiFailure(typeof chunk.error.code === "number" ? chunk.error.code : response.status, chunk, undefined, chunk.error.message);
207
+ }
208
+ if (chunk.promptFeedback?.blockReason) blockReason = chunk.promptFeedback.blockReason;
209
+ const candidate = chunk.candidates?.[0];
210
+ for (const part of candidate?.content?.parts ?? []) {
211
+ // Keep every part unchanged: Gemini 3 requires its thought signatures back.
212
+ parts.push(part);
213
+ if (typeof part.text === "string" && part.text && part.thought !== true) {
214
+ text += part.text;
215
+ hooks.onText?.(part.text);
216
+ }
217
+ const call = part.functionCall as { name?: unknown; args?: unknown; id?: unknown } | undefined;
218
+ if (call && typeof call.name === "string") {
219
+ const args = call.args && typeof call.args === "object" && !Array.isArray(call.args) ? call.args as Record<string, unknown> : {};
220
+ calls.push({ name: call.name, args, ...(typeof call.id === "string" ? { id: call.id } : {}) });
221
+ }
222
+ }
223
+ finishReason = candidate?.finishReason ?? finishReason;
224
+ usage = chunk.usageMetadata ?? usage;
225
+ };
226
+ const notTheReply = (error: unknown) => notJson(response, error);
227
+ if (stream) {
228
+ if (!response.body) throw new GeminiRequestError("Gemini returned an empty stream.", response.status);
229
+ let events: boolean;
230
+ let body: Response;
231
+ try {
232
+ ({ events, response: body } = await streamedReply(response, watch));
233
+ } catch (error) {
234
+ if (hooks.signal?.aborted) throw error;
235
+ throw noteCutReply(lost(error));
236
+ }
237
+ if (events) {
238
+ try {
239
+ for await (const chunk of parseSseJson<Chunk>(body.body!, { onData: watch.pulse, signal: watch.signal })) take(chunk);
240
+ } catch (error) {
241
+ if (hooks.signal?.aborted || error instanceof GeminiRequestError) throw error;
242
+ // An event too long to read would come again: it is not sent again, like a page in the reply's place.
243
+ if (error instanceof SseEventTooLongError) throw new GeminiRequestError(eventTooLongMessage("Gemini's", error), response.status, { kind: "invalid", cause: error });
244
+ // The connection went while the answer was on its way, or nothing came for the whole wait.
245
+ throw noteCutReply(lost(error));
246
+ }
247
+ // Every reply Gemini streams ends with a chunk that says why it ended. A stream that closed
248
+ // without one was cut off on its way (a proxy, a dropped connection): it is not a whole
249
+ // reply, and is sent again like a connection that failed, unless text of it was shown.
250
+ if (finishReason === undefined && blockReason === undefined) throw noteCutReply(new GeminiRequestError("Gemini's reply ended before it was complete.", 0));
251
+ } else {
252
+ // In one piece, though it was asked for as a stream: a gateway that does not stream (its
253
+ // chunks in a list, as Gemini sends them without `alt=sse`), or a page in the model's place.
254
+ const data = await readJson<Chunk | Chunk[]>(body, () => Boolean(hooks.signal?.aborted), lost, watch, notTheReply);
255
+ for (const chunk of Array.isArray(data) ? data : [data]) take(chunk);
256
+ }
257
+ } else {
258
+ take(await readJson<Chunk>(response, () => Boolean(hooks.signal?.aborted), lost, watch, notTheReply));
259
+ }
260
+ const finish = finishOfGemini(finishReason);
261
+ return {
262
+ text,
263
+ calls,
264
+ raw: { role: "model", parts } satisfies GeminiContent,
265
+ ...(finishReason ? { finishReason } : {}),
266
+ ...(finish ? { finish } : {}),
267
+ ...(blockReason ? { blockReason } : {}),
268
+ ...(usage ? { usage: usageOfGemini(usage), providerUsage: usage } : {}),
269
+ };
270
+ }
271
+ }