llm-large-files 0.9.0 → 0.10.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 (222) hide show
  1. package/CHANGELOG.md +446 -0
  2. package/README.md +13 -7
  3. package/dist/access.d.ts +45 -3
  4. package/dist/access.d.ts.map +1 -1
  5. package/dist/access.js +106 -3
  6. package/dist/access.js.map +1 -1
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +115 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +572 -103
  26. package/dist/ask.js.map +1 -1
  27. package/dist/citations.d.ts +36 -0
  28. package/dist/citations.d.ts.map +1 -0
  29. package/dist/citations.js +291 -0
  30. package/dist/citations.js.map +1 -0
  31. package/dist/error-info.d.ts +13 -0
  32. package/dist/error-info.d.ts.map +1 -1
  33. package/dist/error-info.js +37 -1
  34. package/dist/error-info.js.map +1 -1
  35. package/dist/errors.d.ts +3 -1
  36. package/dist/errors.d.ts.map +1 -1
  37. package/dist/errors.js +3 -1
  38. package/dist/errors.js.map +1 -1
  39. package/dist/events.d.ts +25 -7
  40. package/dist/events.d.ts.map +1 -1
  41. package/dist/events.js.map +1 -1
  42. package/dist/evidence.d.ts.map +1 -1
  43. package/dist/evidence.js +21 -2
  44. package/dist/evidence.js.map +1 -1
  45. package/dist/extract.d.ts.map +1 -1
  46. package/dist/extract.js +6 -1
  47. package/dist/extract.js.map +1 -1
  48. package/dist/gemini/adapter.d.ts +35 -4
  49. package/dist/gemini/adapter.d.ts.map +1 -1
  50. package/dist/gemini/adapter.js +68 -29
  51. package/dist/gemini/adapter.js.map +1 -1
  52. package/dist/gemini/chat.d.ts +28 -55
  53. package/dist/gemini/chat.d.ts.map +1 -1
  54. package/dist/gemini/chat.js +20 -27
  55. package/dist/gemini/chat.js.map +1 -1
  56. package/dist/gemini/endpoints.d.ts +59 -11
  57. package/dist/gemini/endpoints.d.ts.map +1 -1
  58. package/dist/gemini/endpoints.js +33 -7
  59. package/dist/gemini/endpoints.js.map +1 -1
  60. package/dist/gemini/errors.d.ts +39 -5
  61. package/dist/gemini/errors.d.ts.map +1 -1
  62. package/dist/gemini/errors.js +70 -9
  63. package/dist/gemini/errors.js.map +1 -1
  64. package/dist/gemini/generate.d.ts +53 -2
  65. package/dist/gemini/generate.d.ts.map +1 -1
  66. package/dist/gemini/generate.js +100 -50
  67. package/dist/gemini/generate.js.map +1 -1
  68. package/dist/gemini/index.d.ts +3 -3
  69. package/dist/gemini/index.d.ts.map +1 -1
  70. package/dist/http.d.ts +41 -3
  71. package/dist/http.d.ts.map +1 -1
  72. package/dist/http.js +40 -2
  73. package/dist/http.js.map +1 -1
  74. package/dist/index.d.ts +6 -4
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +4 -2
  77. package/dist/index.js.map +1 -1
  78. package/dist/ingest.d.ts +9 -1
  79. package/dist/ingest.d.ts.map +1 -1
  80. package/dist/ingest.js +50 -25
  81. package/dist/ingest.js.map +1 -1
  82. package/dist/library.d.ts +129 -2
  83. package/dist/library.d.ts.map +1 -1
  84. package/dist/library.js +224 -149
  85. package/dist/library.js.map +1 -1
  86. package/dist/map-reduce.d.ts +176 -10
  87. package/dist/map-reduce.d.ts.map +1 -1
  88. package/dist/map-reduce.js +804 -58
  89. package/dist/map-reduce.js.map +1 -1
  90. package/dist/model.d.ts +36 -4
  91. package/dist/model.d.ts.map +1 -1
  92. package/dist/model.js +17 -1
  93. package/dist/model.js.map +1 -1
  94. package/dist/node/handlers.d.ts +29 -8
  95. package/dist/node/handlers.d.ts.map +1 -1
  96. package/dist/node/handlers.js +148 -126
  97. package/dist/node/handlers.js.map +1 -1
  98. package/dist/node/index.d.ts +1 -1
  99. package/dist/node/index.d.ts.map +1 -1
  100. package/dist/node/index.js.map +1 -1
  101. package/dist/node/ingest-child.js +2 -2
  102. package/dist/node/ingest-child.js.map +1 -1
  103. package/dist/node/spool.d.ts +9 -5
  104. package/dist/node/spool.d.ts.map +1 -1
  105. package/dist/node/spool.js +28 -15
  106. package/dist/node/spool.js.map +1 -1
  107. package/dist/node/sse.d.ts +6 -5
  108. package/dist/node/sse.d.ts.map +1 -1
  109. package/dist/node/sse.js +8 -7
  110. package/dist/node/sse.js.map +1 -1
  111. package/dist/openai/adapter.d.ts +5 -1
  112. package/dist/openai/adapter.d.ts.map +1 -1
  113. package/dist/openai/adapter.js +53 -12
  114. package/dist/openai/adapter.js.map +1 -1
  115. package/dist/output-limit.d.ts +2 -1
  116. package/dist/output-limit.d.ts.map +1 -1
  117. package/dist/output-limit.js +5 -2
  118. package/dist/output-limit.js.map +1 -1
  119. package/dist/pdf-outline.d.ts +71 -0
  120. package/dist/pdf-outline.d.ts.map +1 -0
  121. package/dist/pdf-outline.js +414 -0
  122. package/dist/pdf-outline.js.map +1 -0
  123. package/dist/plan.d.ts +137 -7
  124. package/dist/plan.d.ts.map +1 -1
  125. package/dist/plan.js +248 -26
  126. package/dist/plan.js.map +1 -1
  127. package/dist/prepare.d.ts +50 -0
  128. package/dist/prepare.d.ts.map +1 -0
  129. package/dist/prepare.js +207 -0
  130. package/dist/prepare.js.map +1 -0
  131. package/dist/ranged.d.ts +2 -1
  132. package/dist/ranged.d.ts.map +1 -1
  133. package/dist/ranged.js +16 -3
  134. package/dist/ranged.js.map +1 -1
  135. package/dist/search.d.ts +7 -0
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +72 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/stores.d.ts +6 -0
  140. package/dist/stores.d.ts.map +1 -1
  141. package/dist/stores.js +82 -11
  142. package/dist/stores.js.map +1 -1
  143. package/dist/tools.d.ts +22 -2
  144. package/dist/tools.d.ts.map +1 -1
  145. package/dist/tools.js +323 -76
  146. package/dist/tools.js.map +1 -1
  147. package/dist/types.d.ts +49 -1
  148. package/dist/types.d.ts.map +1 -1
  149. package/dist/whole-cost.d.ts +37 -0
  150. package/dist/whole-cost.d.ts.map +1 -0
  151. package/dist/whole-cost.js +46 -0
  152. package/dist/whole-cost.js.map +1 -0
  153. package/docs/README.md +4 -0
  154. package/docs/guides/anthropic.md +5 -2
  155. package/docs/guides/conversations.md +1 -1
  156. package/docs/guides/costs-and-limits.md +132 -36
  157. package/docs/guides/deployment.md +106 -13
  158. package/docs/guides/errors-and-reliability.md +157 -45
  159. package/docs/guides/explorer-model.md +4 -1
  160. package/docs/guides/openai-compatible.md +47 -7
  161. package/docs/guides/own-adapter-and-loop.md +33 -6
  162. package/docs/guides/pdfs.md +96 -7
  163. package/docs/guides/storage.md +46 -3
  164. package/docs/guides/testing.md +71 -0
  165. package/docs/guides/vertex-and-gemini.md +159 -50
  166. package/docs/guides/web-app.md +10 -6
  167. package/docs/how-it-works.md +120 -22
  168. package/docs/measurements.md +172 -5
  169. package/docs/publishing.md +76 -4
  170. package/docs/reference/anthropic.md +12 -7
  171. package/docs/reference/ask.md +262 -35
  172. package/docs/reference/errors-and-retries.md +30 -2
  173. package/docs/reference/events.md +27 -10
  174. package/docs/reference/gemini.md +184 -68
  175. package/docs/reference/library.md +190 -23
  176. package/docs/reference/node.md +51 -17
  177. package/docs/reference/openai.md +21 -10
  178. package/docs/reference/tools.md +271 -26
  179. package/docs/security.md +101 -12
  180. package/docs/troubleshooting.md +14 -12
  181. package/docs/upgrading-0.10.md +472 -0
  182. package/package.json +5 -1
  183. package/src/access.ts +127 -4
  184. package/src/aggregate.ts +92 -14
  185. package/src/analyze.ts +2 -2
  186. package/src/answer-info.ts +45 -0
  187. package/src/anthropic/adapter.ts +40 -11
  188. package/src/ask.ts +646 -106
  189. package/src/citations.ts +294 -0
  190. package/src/error-info.ts +36 -1
  191. package/src/errors.ts +3 -1
  192. package/src/events.ts +29 -6
  193. package/src/evidence.ts +21 -2
  194. package/src/extract.ts +6 -1
  195. package/src/gemini/adapter.ts +99 -32
  196. package/src/gemini/chat.ts +53 -82
  197. package/src/gemini/endpoints.ts +89 -16
  198. package/src/gemini/errors.ts +74 -11
  199. package/src/gemini/generate.ts +147 -57
  200. package/src/gemini/index.ts +3 -3
  201. package/src/http.ts +65 -4
  202. package/src/index.ts +6 -4
  203. package/src/ingest.ts +58 -27
  204. package/src/library.ts +336 -142
  205. package/src/map-reduce.ts +855 -67
  206. package/src/model.ts +44 -4
  207. package/src/node/handlers.ts +159 -118
  208. package/src/node/index.ts +1 -0
  209. package/src/node/ingest-child.ts +2 -2
  210. package/src/node/spool.ts +28 -14
  211. package/src/node/sse.ts +8 -7
  212. package/src/openai/adapter.ts +56 -13
  213. package/src/output-limit.ts +5 -2
  214. package/src/pdf-outline.ts +400 -0
  215. package/src/plan.ts +287 -36
  216. package/src/prepare.ts +253 -0
  217. package/src/ranged.ts +16 -3
  218. package/src/search.ts +69 -13
  219. package/src/stores.ts +76 -11
  220. package/src/tools.ts +327 -75
  221. package/src/types.ts +45 -1
  222. package/src/whole-cost.ts +64 -0
@@ -6,10 +6,10 @@ import { retryAfterMs } from "../retry.js";
6
6
  import { idleWatch, noteCutReply, readJson, streamedReply, type IdleWatch } from "../http.js";
7
7
  import { eventTooLongMessage, parseSseJson, SseEventTooLongError } from "../sse.js";
8
8
  import { resolveHeaders, type GeminiEndpoint } from "./endpoints.js";
9
- import { finishOfGemini, geminiFailure, GeminiRequestError, notJson, silent, unreachable } from "./errors.js";
10
- import { createGeminiGenerateText, geminiFunctionResponseTurns, usageOfGemini, type GeminiContent, type GeminiPart, type GeminiToolFilePlacement } from "./generate.js";
9
+ import { errorBodyOf, finishOfGemini, geminiFailure, GeminiRequestError, notJson, silent, statusOfError, unreachable } from "./errors.js";
10
+ import { createGeminiGenerateText, discard, geminiFunctionResponseTurns, usageOfGemini, type GeminiContent, type GeminiPart, type GeminiRequestFields, type GeminiToolFilePlacement } from "./generate.js";
11
11
 
12
- export type { GeminiContent, GeminiPart };
12
+ export type { GeminiContent, GeminiPart, GeminiRequestFields };
13
13
 
14
14
  /** What Gemini bills for one PDF page it is shown (measured: 520 to 532). */
15
15
  export const GEMINI_PAGE_TOKENS = 530;
@@ -34,6 +34,36 @@ export type GeminiModelOptions = {
34
34
  pageTokens?: number | undefined;
35
35
  /** Names the model in usage totals. Defaults to the model in the URL. */
36
36
  id?: string | undefined;
37
+ /**
38
+ * More fields for the body of every chat request, the request for the answer included:
39
+ * `safetySettings`, `labels` (Vertex AI), `serviceTier`, `cachedContent`, and so on. Merged last,
40
+ * after the library's. New in 0.10.0.
41
+ */
42
+ body?: GeminiRequestFields | undefined;
43
+ /**
44
+ * More fields for the body of a whole-document part read, given the output limit it is sent with.
45
+ * Merged last. Its `generationConfig` is `analysisConfig`. New in 0.10.0.
46
+ */
47
+ analysisBody?: ((maxOutputTokens: number) => GeminiRequestFields) | undefined;
48
+ /**
49
+ * The mode of `functionCallingConfig` in a request that offers tools: "AUTO" (the default), or
50
+ * "VALIDATED", in which Gemini checks each call against the declaration of its tool. It is sent
51
+ * only with tools. New in 0.10.0.
52
+ */
53
+ functionCallingMode?: "AUTO" | "VALIDATED" | undefined;
54
+ /**
55
+ * The longest time, in milliseconds, that one part read of a whole-file read may take, its whole
56
+ * reply included. Defaults to 180,000; 0 sets none. A part past it is sent again once, and is
57
+ * then reported as "The model took too long to answer". New in 0.10.0.
58
+ */
59
+ timeoutMs?: number | undefined;
60
+ /**
61
+ * How the request that must be answered in text says so. "omit" (the default) declares no tools:
62
+ * Gemini can ignore mode NONE and keep calling them. "mode_none" keeps the tools and sends
63
+ * `functionCallingConfig` mode NONE, so that the request starts as the ones before it did; a tool
64
+ * call that still comes back is asked for again once. New in 0.10.0.
65
+ */
66
+ answerWithoutTools?: "omit" | "mode_none" | undefined;
37
67
  /**
38
68
  * The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count:
39
69
  * a model that thinks sends nothing until it has thought, and a reply that is not streamed comes
@@ -56,13 +86,16 @@ type Body = {
56
86
  generationConfig?: Record<string, unknown>;
57
87
  tools?: unknown[];
58
88
  toolConfig?: unknown;
89
+ [key: string]: unknown;
59
90
  };
60
91
 
61
92
  type Chunk = {
62
93
  candidates?: Array<{ finishReason?: string; content?: { parts?: GeminiPart[] } }>;
63
94
  usageMetadata?: Record<string, unknown>;
64
95
  promptFeedback?: { blockReason?: string };
65
- error?: { message?: string; code?: unknown };
96
+ error?: { message?: string; code?: unknown; status?: unknown; details?: unknown };
97
+ responseId?: unknown;
98
+ modelVersion?: unknown;
66
99
  };
67
100
 
68
101
  /** The model a Generate Content URL names: ".../models/gemini-3.8-flash:generateContent". */
@@ -204,11 +237,13 @@ export function geminiToolTurns(turns: ToolTurn[]): GeminiContent[] {
204
237
  /**
205
238
  * A Gemini model for `askWithFiles`. `endpoint` says where it is: `geminiApi()`, `vertexAi()`, or
206
239
  * your own URLs and headers for a gateway. Its `explorerUrl` is not used here: an explorer is a
207
- * model of its own, `gemini(geminiApi({ apiKey, model: "the-explorer" }))`.
240
+ * model of its own, `gemini(geminiApi({ apiKey, model: "the-explorer" }))`. A `refreshable`
241
+ * endpoint gets one more try, with headers asked for with `{ refresh: true }`, after a 401.
208
242
  */
209
- export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "headers">, options: GeminiModelOptions = {}): ModelAdapter {
243
+ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "headers" | "refreshable">, options: GeminiModelOptions = {}): ModelAdapter {
210
244
  const fetchImpl = options.fetch ?? fetch;
211
245
  const placement = options.toolFilePlacement ?? "inside";
246
+ const refreshable = endpoint.refreshable === true;
212
247
  // The turns of a tool round are built once: its pages are megabytes of base64.
213
248
  const built = new WeakMap<ModelToolRound, GeminiContent[]>();
214
249
  const roundTurns = (round: ModelToolRound): GeminiContent[] => {
@@ -222,17 +257,23 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
222
257
  return turns;
223
258
  };
224
259
  const toContents = (messages: ModelMessage[]): GeminiContent[] => messages.flatMap((message) => (message.role === "tools" ? roundTurns(message) : textTurn(message)));
225
- const bodyOf = (request: ModelRequest): Body => ({
226
- contents: toContents(request.messages),
227
- ...(request.system ? { systemInstruction: { parts: [{ text: request.system }] } } : {}),
228
- ...(options.generationConfig ? { generationConfig: options.generationConfig } : {}),
229
- // A request that must be answered in text declares no tools at all: Gemini can ignore
230
- // functionCallingConfig mode NONE and keep calling them.
231
- ...(request.tools?.length && request.toolChoice !== "none" ? {
232
- tools: [{ functionDeclarations: request.tools }],
233
- toolConfig: { functionCallingConfig: { mode: "AUTO" } },
234
- } : {}),
235
- });
260
+ const bodyOf = (request: ModelRequest): Body => {
261
+ const mustAnswer = request.toolChoice === "none";
262
+ // A request that must be answered in text declares no tools at all, by default: Gemini can
263
+ // ignore functionCallingConfig mode NONE and keep calling them. With "mode_none" it keeps
264
+ // them, so that it starts as the requests before it did.
265
+ const declare = Boolean(request.tools?.length) && (!mustAnswer || options.answerWithoutTools === "mode_none");
266
+ return {
267
+ contents: toContents(request.messages),
268
+ ...(request.system ? { systemInstruction: { parts: [{ text: request.system }] } } : {}),
269
+ ...(options.generationConfig ? { generationConfig: options.generationConfig } : {}),
270
+ ...(declare ? {
271
+ tools: [{ functionDeclarations: request.tools }],
272
+ toolConfig: { functionCallingConfig: { mode: mustAnswer ? "NONE" : options.functionCallingMode ?? "AUTO" } },
273
+ } : {}),
274
+ ...options.body,
275
+ };
276
+ };
236
277
 
237
278
  return {
238
279
  id: options.id ?? modelOf(endpoint.url),
@@ -248,33 +289,49 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
248
289
  headers: endpoint.headers,
249
290
  fetchImpl,
250
291
  ...(options.analysisConfig ? { generationConfig: options.analysisConfig } : {}),
292
+ ...(options.analysisBody ? { body: options.analysisBody } : {}),
293
+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
294
+ ...(refreshable ? { refreshable } : {}),
251
295
  }),
252
296
 
253
297
  async send(request: ModelRequest, hooks: SendHooks = {}): Promise<ModelReply> {
254
298
  const stream = Boolean(hooks.onText && endpoint.streamUrl);
255
299
  // Headers are asked for with each request: an access token may have been renewed since the last.
256
300
  const headers = await resolveHeaders(endpoint);
301
+ const body = JSON.stringify(bodyOf(request));
257
302
  const watch = idleWatch(hooks.signal, { firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs });
258
303
  // A request the watch aborted got nothing back for the whole wait: that is no failed connection.
259
304
  const lost = (error: unknown) => (watch.expired ? silent(watch.waitedMs) : unreachable(error));
260
- try {
261
- let response: Response;
305
+ const post = async (sent: Record<string, string>): Promise<Response> => {
262
306
  try {
263
- response = await fetchImpl(stream ? endpoint.streamUrl! : endpoint.url, {
264
- method: "POST",
265
- headers,
266
- body: JSON.stringify(bodyOf(request)),
267
- signal: watch.signal,
268
- });
307
+ return await fetchImpl(stream ? endpoint.streamUrl! : endpoint.url, { method: "POST", headers: sent, body, signal: watch.signal });
269
308
  } catch (error) {
270
309
  if (hooks.signal?.aborted) throw error;
271
310
  throw lost(error);
272
311
  }
273
- // The headers are no piece of the reply: a server may send them at once and then think.
274
- if (!response.ok) {
275
- const data = await response.json().catch(() => null);
276
- throw geminiFailure(response.status, data, retryAfterMs(response.headers, data), `Gemini returned HTTP ${response.status}.`);
312
+ };
313
+ /** The error of a response that is not OK, from its body. */
314
+ const failureOf = async (response: Response, cause?: unknown): Promise<GeminiRequestError> => {
315
+ const data = await response.json().catch(() => null);
316
+ return geminiFailure(response.status, data, retryAfterMs(response.headers, errorBodyOf(data)), `Gemini returned HTTP ${response.status}.`, cause);
317
+ };
318
+ try {
319
+ let response = await post(headers);
320
+ // A token that was refused may be one a cache kept past its time: one more try, with
321
+ // headers asked for anew. A second 401 is the error.
322
+ if (response.status === 401 && refreshable) {
323
+ let fresh: Record<string, string>;
324
+ try {
325
+ fresh = await resolveHeaders(endpoint, { refresh: true });
326
+ } catch (error) {
327
+ // No new token came: the refusal is the error, and why none came is its cause.
328
+ throw await failureOf(response, error);
329
+ }
330
+ discard(response);
331
+ response = await post(fresh);
277
332
  }
333
+ // The headers are no piece of the reply: a server may send them at once and then think.
334
+ if (!response.ok) throw await failureOf(response);
278
335
  return await readReply(response, stream, hooks, watch, lost);
279
336
  } finally {
280
337
  watch.stop();
@@ -291,10 +348,16 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
291
348
  let finishReason: string | undefined;
292
349
  let blockReason: string | undefined;
293
350
  let usage: Record<string, unknown> | undefined;
351
+ let responseId: string | undefined;
352
+ let responseModel: string | undefined;
294
353
  const take = (chunk: Chunk) => {
295
- if (chunk.error?.message) {
296
- throw geminiFailure(typeof chunk.error.code === "number" ? chunk.error.code : response.status, chunk, undefined, chunk.error.message);
354
+ // An error inside a reply of HTTP 200: its status is its own code, or that of its
355
+ // google.rpc name ("UNAVAILABLE" is 503), so that a busy server is tried again.
356
+ if (chunk.error && typeof chunk.error === "object") {
357
+ throw geminiFailure(statusOfError(chunk.error), chunk, retryAfterMs(undefined, chunk), typeof chunk.error.message === "string" && chunk.error.message ? chunk.error.message : "Gemini reported an error.");
297
358
  }
359
+ if (typeof chunk.responseId === "string" && chunk.responseId) responseId = chunk.responseId;
360
+ if (typeof chunk.modelVersion === "string" && chunk.modelVersion) responseModel = chunk.modelVersion;
298
361
  if (chunk.promptFeedback?.blockReason) blockReason = chunk.promptFeedback.blockReason;
299
362
  const candidate = chunk.candidates?.[0];
300
363
  for (const part of candidate?.content?.parts ?? []) {
@@ -345,7 +408,9 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
345
408
  for (const chunk of Array.isArray(data) ? data : [data]) take(chunk);
346
409
  }
347
410
  } else {
348
- take(await readJson<Chunk>(response, () => Boolean(hooks.signal?.aborted), lost, watch, notTheReply));
411
+ // A gateway may give the reply as a list of chunks, as Gemini does without `alt=sse`.
412
+ const data = await readJson<Chunk | Chunk[]>(response, () => Boolean(hooks.signal?.aborted), lost, watch, notTheReply);
413
+ for (const chunk of Array.isArray(data) ? data : [data]) take(chunk);
349
414
  }
350
415
  const finish = finishOfGemini(finishReason);
351
416
  return {
@@ -355,6 +420,8 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
355
420
  ...(finishReason ? { finishReason } : {}),
356
421
  ...(finish ? { finish } : {}),
357
422
  ...(blockReason ? { blockReason } : {}),
423
+ ...(responseId ? { responseId } : {}),
424
+ ...(responseModel ? { responseModel } : {}),
358
425
  ...(usage ? { usage: usageOfGemini(usage), providerUsage: usage } : {}),
359
426
  };
360
427
  }
@@ -1,12 +1,8 @@
1
- import { askWithFiles, type AskLimits, type AskOptions, type AskResult } from "../ask.js";
2
- import type { LargeFiles } from "../library.js";
3
- import type { AskEvent } from "../events.js";
1
+ import { askWithFiles, type AskOptions, type AskResult } from "../ask.js";
4
2
  import type { ChatMessage } from "../model.js";
5
- import type { RetryOptions } from "../retry.js";
6
- import type { Budget, DocumentScope } from "../types.js";
7
3
  import { fromGeminiContents, gemini, type GeminiContent } from "./adapter.js";
8
4
  import type { GeminiEndpoint } from "./endpoints.js";
9
- import type { GeminiToolFilePlacement } from "./generate.js";
5
+ import type { GeminiRequestFields, GeminiToolFilePlacement } from "./generate.js";
10
6
 
11
7
  export { DocumentsNotFoundError } from "../model.js";
12
8
  export { EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, partialResultOf } from "../ask.js";
@@ -15,8 +11,11 @@ export type { ChatTurn } from "../model.js";
15
11
  export type { GeminiContent, GeminiPart } from "./adapter.js";
16
12
  export { GeminiRequestError } from "./errors.js";
17
13
 
18
- export type AskGeminiOptions = {
19
- files: LargeFiles;
14
+ /**
15
+ * The options of `askGemini` that are its own. Every other option is `askWithFiles`'s
16
+ * (`AskOptions`), and goes to it as it is. New as a type of its own in 0.10.0.
17
+ */
18
+ export type GeminiOwnOptions = {
20
19
  /**
21
20
  * Where the model is: the one that answers. When the endpoint also names an explorer model
22
21
  * (`explorerModel` in `geminiApi()` and `vertexAi()`, or `explorerUrl`), that model makes the
@@ -24,15 +23,6 @@ export type AskGeminiOptions = {
24
23
  * tools returned. Without an explorer, one model does both.
25
24
  */
26
25
  endpoint: GeminiEndpoint;
27
- /** Documents this conversation may use. Where their text or cards go: see `documentPlacement`. */
28
- documentIds: string[];
29
- /**
30
- * Where document text and cards are added. "first" (the default) puts them at the start of the
31
- * first user turn, where they stay as the conversation grows, so Gemini's prompt cache can
32
- * reuse them on every follow-up question. "last" appends them to the latest user turn, as 0.1.0
33
- * did; the document then moves on every turn and is billed in full each time.
34
- */
35
- documentPlacement?: "first" | "last";
36
26
  /**
37
27
  * The chat history, as `askWithFiles` takes it; the last turn must be the user's question. It
38
28
  * may hold the tool rounds of earlier questions (`toolTurns` of their results), and turns with
@@ -42,7 +32,6 @@ export type AskGeminiOptions = {
42
32
  messages?: ChatMessage[];
43
33
  /** Your own Gemini `contents` (with images, inline PDFs, etc.). The last turn must be the user's. */
44
34
  contents?: GeminiContent[];
45
- system?: string;
46
35
  /** Sent with every chat request: temperature, maxOutputTokens, thinkingConfig, and so on. */
47
36
  generationConfig?: Record<string, unknown>;
48
37
  /**
@@ -51,36 +40,29 @@ export type AskGeminiOptions = {
51
40
  * example. It is not used without an explorer model.
52
41
  */
53
42
  explorerGenerationConfig?: Record<string, unknown>;
54
- /** The user asking. Documents ingested with a different owner are treated as missing. */
55
- owner?: string;
56
43
  /**
57
- * The scope of the question, such as [userId, chatId] (`AskOptions.scope`): documents ingested
58
- * with another scope are treated as missing. New in 0.9.0.
44
+ * More fields for the body of every chat request of the model that answers: `safetySettings`,
45
+ * `labels` (Vertex AI; never a user ID), `serviceTier`, `cachedContent`. Merged last
46
+ * (`GeminiModelOptions.body`). New in 0.10.0.
59
47
  */
60
- scope?: DocumentScope;
48
+ body?: GeminiRequestFields;
49
+ /** The same, for the requests of an explorer model. Defaults to `body`. New in 0.10.0. */
50
+ explorerBody?: GeminiRequestFields;
61
51
  /**
62
- * What to do when documents of `documentIds` are missing: "throw" (the default), "drop", or a
63
- * function that says (`AskOptions.onMissingDocuments`). New in 0.9.0.
52
+ * More fields for the body of a whole-document part read, given its output limit. The parts are
53
+ * read by the explorer model when there is one. New in 0.10.0.
64
54
  */
65
- onMissingDocuments?: AskOptions["onMissingDocuments"];
66
- /** The limits of the question: tool turns, calls in a turn, whole-file reads, tokens and requests. */
67
- limits?: AskLimits;
55
+ analysisBody?: (maxOutputTokens: number) => GeminiRequestFields;
56
+ /** `functionCallingConfig` mode of the requests that offer tools: "AUTO" (the default) or "VALIDATED". New in 0.10.0. */
57
+ functionCallingMode?: "AUTO" | "VALIDATED";
58
+ /** How the request for the answer in text says so: "omit" (the default) or "mode_none" (`GeminiModelOptions`). New in 0.10.0. */
59
+ answerWithoutTools?: "omit" | "mode_none";
60
+ /** The longest time, in milliseconds, of one part read of a whole-file read. Defaults to 180,000; 0 sets none. New in 0.10.0. */
61
+ timeoutMs?: number;
68
62
  /** `limits.toolTurns`, under the name it had before 0.5.0. Defaults to 12. */
69
63
  maxToolTurns?: number;
70
64
  /** `limits.callsPerTurn`, under the name it had before 0.5.0. Defaults to 8. */
71
65
  maxToolCallsPerTurn?: number;
72
- /** How a request that failed is sent again. Defaults to three more tries, with a wait that doubles. */
73
- retry?: RetryOptions;
74
- /** Budget fields for this question, in place of the library's. */
75
- budget?: Partial<Budget>;
76
- /** Offer `analyze_whole_document`, which reads a whole file in many model calls. Defaults to true. */
77
- wholeDocumentAnalysis?: boolean;
78
- /**
79
- * Offer `view_pages` for PDFs whose original file is kept (`keepOriginals`), so the model can
80
- * look at pictures, charts and layout. Defaults to true. It changes nothing for a library that
81
- * keeps no originals.
82
- */
83
- viewPages?: boolean;
84
66
  /**
85
67
  * Where the pages go in the request. "inside" (the default) puts the PDF in the function
86
68
  * response itself, which Gemini 3 models read. "beside" sends it in a user turn of its own,
@@ -103,24 +85,16 @@ export type AskGeminiOptions = {
103
85
  * arrive. Defaults to 300,000. 0 waits without end.
104
86
  */
105
87
  idleTimeoutMs?: number;
106
- /** Answer text as it streams. Streaming is used when this is set (or `streamText` is true) and the endpoint has `streamUrl`. */
107
- onText?: (delta: string) => void;
108
- /** Whether to ask for the answer as it is written (`AskOptions.streamText`). Defaults to true when `onText` is given. New in 0.7.0. */
109
- streamText?: boolean;
110
- /** Short-lived status, such as "Searching app.log for “timeout”…". */
111
- onActivity?: (text: string) => void;
112
- /** A finished step, such as "Search app.log (exact) for “timeout” — 12 matching lines". */
113
- onStep?: (text: string) => void;
114
- /** Everything the question does, as typed events in order (`AskOptions.onEvent`). New in 0.7.0. */
115
- onEvent?: (event: AskEvent) => void;
116
- /** The `runId` of the events. Defaults to one made for the question ("run_…"). */
117
- runId?: string;
118
- /** Put each tool result in its `tool.end` event (`AskOptions.eventResults`). Off by default. */
119
- eventResults?: boolean;
120
88
  fetch?: typeof fetch;
121
- signal?: AbortSignal;
122
89
  };
123
90
 
91
+ /**
92
+ * The options of `askGemini`: its own (`GeminiOwnOptions`), and every option of `askWithFiles` but
93
+ * the models, which it makes. Since 0.10.0 the options of `askWithFiles` are taken by their type, so
94
+ * an option new there reaches the loop through `askGemini` too; no option was removed.
95
+ */
96
+ export type AskGeminiOptions = Omit<AskOptions, "model" | "explorer" | "messages"> & GeminiOwnOptions;
97
+
124
98
  /** What `askWithFiles` returns. `usage` is summed over the whole question; Gemini's own `usageMetadata` of the last response is `lastUsage`. */
125
99
  export type AskGeminiResult = AskResult;
126
100
 
@@ -131,42 +105,39 @@ export type AskGeminiResult = AskResult;
131
105
  * and the tool loop runs, ending with a request without tools so there is always an answer.
132
106
  */
133
107
  export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiResult> {
134
- const { endpoint } = options;
108
+ const {
109
+ endpoint, messages, contents, generationConfig, explorerGenerationConfig, body, explorerBody, analysisBody, functionCallingMode,
110
+ answerWithoutTools, timeoutMs, maxToolTurns, maxToolCallsPerTurn, toolFilePlacement, analysisConfig, firstByteTimeoutMs, idleTimeoutMs,
111
+ fetch, limits, ...loop
112
+ } = options;
135
113
  // A second model for the requests that use tools. The answering model's own URL is not one.
136
114
  const explorerUrl = endpoint.explorerUrl && endpoint.explorerUrl !== endpoint.url ? endpoint.explorerUrl : undefined;
137
- const shared = { toolFilePlacement: options.toolFilePlacement, analysisConfig: options.analysisConfig, firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs, fetch: options.fetch };
138
- const model = gemini(endpoint, { ...shared, generationConfig: options.generationConfig });
115
+ const shared = {
116
+ toolFilePlacement, analysisConfig, firstByteTimeoutMs, idleTimeoutMs, fetch,
117
+ ...(analysisBody ? { analysisBody } : {}),
118
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
119
+ ...(functionCallingMode ? { functionCallingMode } : {}),
120
+ ...(answerWithoutTools ? { answerWithoutTools } : {}),
121
+ };
122
+ const model = gemini(endpoint, { ...shared, generationConfig, ...(body ? { body } : {}) });
139
123
  // The explorer is called with the same headers, in one piece, with its own settings when it has any.
124
+ const explorerBodyOf = explorerBody ?? body;
140
125
  const explorer = explorerUrl
141
- ? gemini({ url: explorerUrl, headers: endpoint.headers }, { ...shared, generationConfig: options.explorerGenerationConfig ?? options.generationConfig })
126
+ ? gemini({
127
+ url: explorerUrl,
128
+ headers: endpoint.headers,
129
+ ...(endpoint.refreshable ? { refreshable: endpoint.refreshable } : {}),
130
+ }, { ...shared, generationConfig: explorerGenerationConfig ?? generationConfig, ...(explorerBodyOf ? { body: explorerBodyOf } : {}) })
142
131
  : undefined;
143
132
  return askWithFiles({
144
- files: options.files,
133
+ ...loop,
145
134
  model,
146
135
  explorer,
147
- documentIds: options.documentIds,
148
- ...(options.documentPlacement ? { documentPlacement: options.documentPlacement } : {}),
149
- messages: options.contents ? fromGeminiContents(options.contents) : options.messages ?? [],
150
- ...(options.system !== undefined ? { system: options.system } : {}),
151
- ...(options.owner !== undefined ? { owner: options.owner } : {}),
152
- ...(options.scope !== undefined ? { scope: options.scope } : {}),
153
- ...(options.onMissingDocuments !== undefined ? { onMissingDocuments: options.onMissingDocuments } : {}),
136
+ messages: contents ? fromGeminiContents(contents) : messages ?? [],
154
137
  limits: {
155
- ...(options.maxToolTurns !== undefined ? { toolTurns: options.maxToolTurns } : {}),
156
- ...(options.maxToolCallsPerTurn !== undefined ? { callsPerTurn: options.maxToolCallsPerTurn } : {}),
157
- ...options.limits,
138
+ ...(maxToolTurns !== undefined ? { toolTurns: maxToolTurns } : {}),
139
+ ...(maxToolCallsPerTurn !== undefined ? { callsPerTurn: maxToolCallsPerTurn } : {}),
140
+ ...limits,
158
141
  },
159
- ...(options.retry ? { retry: options.retry } : {}),
160
- ...(options.budget ? { budget: options.budget } : {}),
161
- ...(options.wholeDocumentAnalysis !== undefined ? { wholeDocumentAnalysis: options.wholeDocumentAnalysis } : {}),
162
- ...(options.viewPages !== undefined ? { viewPages: options.viewPages } : {}),
163
- ...(options.onText ? { onText: options.onText } : {}),
164
- ...(options.streamText !== undefined ? { streamText: options.streamText } : {}),
165
- ...(options.onActivity ? { onActivity: options.onActivity } : {}),
166
- ...(options.onStep ? { onStep: options.onStep } : {}),
167
- ...(options.onEvent ? { onEvent: options.onEvent } : {}),
168
- ...(options.runId !== undefined ? { runId: options.runId } : {}),
169
- ...(options.eventResults !== undefined ? { eventResults: options.eventResults } : {}),
170
- ...(options.signal ? { signal: options.signal } : {}),
171
142
  });
172
143
  }
@@ -1,3 +1,5 @@
1
+ import { resolveHeaderSource, type HeaderContext, type HeaderSource } from "../http.js";
2
+
1
3
  /**
2
4
  * Where and how to call Gemini. Use `geminiApi()` or `vertexAi()`, or pass your own URLs and
3
5
  * headers for an enterprise gateway that proxies Generate Content.
@@ -7,8 +9,12 @@ export type GeminiEndpoint = {
7
9
  url: string;
8
10
  /** Streaming `...:streamGenerateContent?alt=sse` URL. Without it, answers arrive in one piece. */
9
11
  streamUrl?: string;
10
- /** Request headers, or a function returning them (for short-lived access tokens). */
11
- headers: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
12
+ /**
13
+ * Request headers, or a function returning them (for short-lived access tokens). Since 0.10.0 the
14
+ * function is called with `{ refresh: true }` when a request is sent again after a 401 (see
15
+ * `refreshable`); one of no arguments still fits.
16
+ */
17
+ headers: HeaderSource;
12
18
  /**
13
19
  * The non-streaming `...:generateContent` URL of a second model, the explorer. `askGemini` then
14
20
  * sends it the requests that search, read and look at pages, and the model of `url` only writes
@@ -16,6 +22,12 @@ export type GeminiEndpoint = {
16
22
  * `explorerModel`. Unset, or the same as `url`, one model does both.
17
23
  */
18
24
  explorerUrl?: string | undefined;
25
+ /**
26
+ * True when `headers` can give a token that is new, not the one it keeps in a cache: a request
27
+ * refused with HTTP 401 is then sent once more, with the headers of `headers({ refresh: true })`.
28
+ * A second 401 is the error. `vertexAi()` sets it when `accessToken` is a function. New in 0.10.0.
29
+ */
30
+ refreshable?: true | undefined;
19
31
  };
20
32
 
21
33
  /**
@@ -71,36 +83,97 @@ export function vertexHost(location: string): string {
71
83
  return `https://${location}-aiplatform.googleapis.com`;
72
84
  }
73
85
 
74
- /** Vertex AI with an OAuth access token (for example from google-auth-library). */
75
- export function vertexAi(options: {
76
- project: string;
86
+ /** An https origin: a host name of letters, digits, dots and dashes, with a port or none, and nothing after it. */
87
+ const ORIGIN = /^https:\/\/[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?(?::\d{1,5})?\/?$/;
88
+
89
+ /**
90
+ * The origin of `host`, which must be an https origin and nothing more. A path, a query, a
91
+ * fragment or an "@" would send the requests, and the token or key with them, somewhere else than
92
+ * the host it seems to name: it throws a TypeError, as a location that is not one does.
93
+ */
94
+ function originOf(host: string): string {
95
+ if (typeof host !== "string" || !ORIGIN.test(host)) {
96
+ throw new TypeError(`host must be an https origin such as "https://europe-west4-aiplatform.googleapis.com", with no path, query or "@", and is ${JSON.stringify(host) ?? String(host)}.`);
97
+ }
98
+ return new URL(host).origin;
99
+ }
100
+
101
+ /** What the two forms of `vertexAi()` take alike. */
102
+ type VertexAiCommon = {
77
103
  /** The model that answers. Without `explorerModel` it also searches and reads the documents. */
78
104
  model: string;
79
105
  /** A second model that explores the documents, as in `geminiApi()`. Leave it out or empty for one model. */
80
106
  explorerModel?: string | undefined;
81
- /** Defaults to "global". */
82
- location?: string;
83
- /** A token, or a function that returns a fresh one for each request. */
84
- accessToken: string | (() => string | Promise<string>);
107
+ /**
108
+ * More headers, merged after the library's (a name you give replaces the library's). A function
109
+ * is called for each request, with the same context as the endpoint's `headers`. New in 0.10.0.
110
+ */
111
+ headers?: HeaderSource | undefined;
112
+ /**
113
+ * The https origin to send the requests to, in place of the host of the location: a Private
114
+ * Service Connect endpoint, or a proxy that keeps Vertex AI's paths. An origin only
115
+ * ("https://host" or "https://host:port"); anything else throws a TypeError. New in 0.10.0.
116
+ */
117
+ host?: string | undefined;
85
118
  /** Defaults to "v1". */
86
119
  apiVersion?: string;
87
- }): GeminiEndpoint {
88
- const location = options.location ?? "global";
89
- const models = `${vertexHost(location)}/${options.apiVersion ?? "v1"}/projects/${encodeURIComponent(options.project)}/locations/${encodeURIComponent(location)}/publishers/google/models/`;
120
+ };
121
+
122
+ /**
123
+ * The options of `vertexAi()`: a project with an OAuth access token, or (since 0.10.0) an API key of
124
+ * Vertex AI express mode, which names no project or location.
125
+ */
126
+ export type VertexAiOptions =
127
+ | (VertexAiCommon & {
128
+ project: string;
129
+ /** Defaults to "global". */
130
+ location?: string;
131
+ /**
132
+ * A token, or a function that returns one for each request. The function is called with
133
+ * `{ refresh: true }` when the token it gave was refused (HTTP 401): return a new one then,
134
+ * not the one kept in a cache. A function of no arguments still fits.
135
+ */
136
+ accessToken: string | ((context: { refresh: boolean }) => string | Promise<string>);
137
+ apiKey?: never;
138
+ })
139
+ | (VertexAiCommon & {
140
+ /** The API key of Vertex AI express mode, sent as the `x-goog-api-key` header. */
141
+ apiKey: string;
142
+ project?: never;
143
+ location?: never;
144
+ accessToken?: never;
145
+ });
146
+
147
+ /**
148
+ * Vertex AI with an OAuth access token (for example from google-auth-library), or with an API key
149
+ * of express mode (since 0.10.0).
150
+ */
151
+ export function vertexAi(options: VertexAiOptions): GeminiEndpoint {
152
+ const express = typeof options.apiKey === "string";
153
+ const location = express ? undefined : options.location ?? "global";
154
+ const host = options.host !== undefined ? originOf(options.host) : vertexHost(location ?? "global");
155
+ const where = express ? "" : `projects/${encodeURIComponent(options.project!)}/locations/${encodeURIComponent(location!)}/`;
156
+ const models = `${host}/${options.apiVersion ?? "v1"}/${where}publishers/google/models/`;
90
157
  const base = `${models}${encodeURIComponent(options.model)}`;
91
158
  const explorer = explorerOf(options);
92
159
  const token = options.accessToken;
160
+ const own = options.headers;
93
161
  return {
94
162
  url: `${base}:generateContent`,
95
163
  streamUrl: `${base}:streamGenerateContent?alt=sse`,
96
- headers: async () => ({
164
+ headers: async (context?: HeaderContext) => ({
97
165
  "Content-Type": "application/json",
98
- Authorization: `Bearer ${typeof token === "function" ? await token() : token}`,
166
+ ...(express
167
+ ? { "x-goog-api-key": options.apiKey! }
168
+ : { Authorization: `Bearer ${typeof token === "function" ? await token({ refresh: context?.refresh === true }) : token}` }),
169
+ ...await resolveHeaderSource(own, context),
99
170
  }),
100
171
  ...(explorer ? { explorerUrl: `${models}${encodeURIComponent(explorer)}:generateContent` } : {}),
172
+ ...(typeof token === "function" ? { refreshable: true as const } : {}),
101
173
  };
102
174
  }
103
175
 
104
- export async function resolveHeaders(endpoint: GeminiEndpoint): Promise<Record<string, string>> {
105
- return typeof endpoint.headers === "function" ? endpoint.headers() : endpoint.headers;
176
+ /** The headers of an endpoint: `context` goes to a function of headers when it is given (a refresh after a 401). */
177
+ export async function resolveHeaders(endpoint: Pick<GeminiEndpoint, "headers">, context?: HeaderContext): Promise<Record<string, string>> {
178
+ return resolveHeaderSource(endpoint.headers, context);
106
179
  }