llm-large-files 0.9.0 → 0.10.1

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 +500 -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 +298 -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 +27 -8
  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 +7 -5
  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 +133 -36
  157. package/docs/guides/deployment.md +106 -13
  158. package/docs/guides/errors-and-reliability.md +158 -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 +264 -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 +189 -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 +273 -26
  179. package/docs/security.md +101 -12
  180. package/docs/troubleshooting.md +14 -12
  181. package/docs/upgrading-0.10.md +484 -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 +301 -0
  190. package/src/error-info.ts +36 -1
  191. package/src/errors.ts +3 -1
  192. package/src/events.ts +31 -7
  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 +7 -5
  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
@@ -1,5 +1,5 @@
1
- import { notJsonMessage } from "../http.js";
2
- import { ModelRequestError } from "../model.js";
1
+ import { notJsonMessage, unreachableReason, waitText } from "../http.js";
2
+ import { ModelRequestError, type ModelReply } from "../model.js";
3
3
 
4
4
  /** Gemini answered with an HTTP error, or could not be reached (`status` 0). */
5
5
  export class GeminiRequestError extends ModelRequestError {
@@ -11,8 +11,7 @@ export class GeminiRequestError extends ModelRequestError {
11
11
 
12
12
  /** What to say of a request that never got an answer: the reason, without the stack of the HTTP client. */
13
13
  export function unreachable(error: unknown): GeminiRequestError {
14
- const reason = error instanceof Error && error.message ? ` (${error.message})` : "";
15
- return new GeminiRequestError(`Gemini could not be reached${reason}.`, 0, { cause: error });
14
+ return new GeminiRequestError(`Gemini could not be reached${unreachableReason(error)}.`, 0, { cause: error });
16
15
  }
17
16
 
18
17
  /** A body that came with a status of success but is no JSON (a gateway's page): it is not sent again. */
@@ -25,24 +24,88 @@ export function silent(waitMs: number): GeminiRequestError {
25
24
  return new GeminiRequestError(`Gemini sent nothing for ${Math.round(waitMs / 1_000)} s.`, 0, { kind: "timeout" });
26
25
  }
27
26
 
28
- /** The error of a response that is not OK, from its JSON body: Gemini's `error.status` and `details` tell its kind. */
29
- export function geminiFailure(status: number, data: unknown, retryAfterMs: number | undefined, fallback: string): GeminiRequestError {
30
- const error = (data as { error?: { message?: unknown; status?: unknown; details?: unknown } } | null)?.error;
27
+ /** A part read whose whole reply did not come within its time limit (`timeoutMs`). New in 0.10.0. */
28
+ export function tooSlow(limitMs: number): GeminiRequestError {
29
+ return new GeminiRequestError(`Gemini took longer than ${waitText(limitMs)} to answer.`, 0, { kind: "timeout" });
30
+ }
31
+
32
+ /**
33
+ * The HTTP status of each code of `google.rpc.Code`, as Google maps them. An error that came
34
+ * inside a reply of HTTP 200 (an event of a stream, a body of a gateway) names its code this way
35
+ * when it has no number: `{ "status": "UNAVAILABLE" }` is 503.
36
+ */
37
+ export const GEMINI_STATUS: Readonly<Record<string, number>> = {
38
+ CANCELLED: 499,
39
+ UNKNOWN: 500,
40
+ INVALID_ARGUMENT: 400,
41
+ DEADLINE_EXCEEDED: 504,
42
+ NOT_FOUND: 404,
43
+ ALREADY_EXISTS: 409,
44
+ PERMISSION_DENIED: 403,
45
+ UNAUTHENTICATED: 401,
46
+ RESOURCE_EXHAUSTED: 429,
47
+ FAILED_PRECONDITION: 400,
48
+ ABORTED: 409,
49
+ OUT_OF_RANGE: 400,
50
+ UNIMPLEMENTED: 501,
51
+ INTERNAL: 500,
52
+ UNAVAILABLE: 503,
53
+ DATA_LOSS: 500,
54
+ };
55
+
56
+ /** Gemini's error object of a body: `{ error }`, or the first entry of a list, as a gateway may send it. */
57
+ export function errorBodyOf(data: unknown): { error?: { message?: unknown; code?: unknown; status?: unknown; details?: unknown } } | null {
58
+ const body = Array.isArray(data) ? data[0] : data;
59
+ return body !== null && typeof body === "object" ? body as { error?: { message?: unknown; code?: unknown; status?: unknown; details?: unknown } } : null;
60
+ }
61
+
62
+ /**
63
+ * The status of an error that came inside a reply of HTTP 200: its numeric `code`, else the status
64
+ * of its `google.rpc` code (`GEMINI_STATUS`), else 500, a failure on Gemini's side.
65
+ */
66
+ export function statusOfError(error: { code?: unknown; status?: unknown } | null | undefined): number {
67
+ const code = error?.code;
68
+ if (typeof code === "number" && Number.isInteger(code) && code >= 400 && code <= 599) return code;
69
+ const named = typeof error?.status === "string" && Object.hasOwn(GEMINI_STATUS, error.status) ? GEMINI_STATUS[error.status] : undefined;
70
+ return named ?? 500;
71
+ }
72
+
73
+ /**
74
+ * The error of a response that is not OK, or of an error in a reply of HTTP 200, from its JSON
75
+ * body: Gemini's `error.status` and `details` tell its kind. A body that is a list is read by its
76
+ * first entry. `cause`, when given, is the error's `cause`: why a token refused with HTTP 401 could
77
+ * not be renewed, for one.
78
+ */
79
+ export function geminiFailure(status: number, data: unknown, retryAfterMs: number | undefined, fallback: string, cause?: unknown): GeminiRequestError {
80
+ const error = errorBodyOf(data)?.error;
31
81
  return new GeminiRequestError(typeof error?.message === "string" && error.message ? error.message : fallback, status, {
82
+ ...(cause === undefined ? {} : { cause }),
32
83
  ...(retryAfterMs === undefined ? {} : { retryAfterMs }),
33
84
  ...(typeof error?.status === "string" ? { code: error.status } : {}),
34
85
  ...(error?.details !== undefined ? { details: error.details } : {}),
35
86
  });
36
87
  }
37
88
 
38
- const FILTERED = new Set(["SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "IMAGE_SAFETY"]);
39
- const MALFORMED = new Set(["MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL"]);
89
+ /** Reasons of a reply that a filter stopped: Gemini's safety filters, Model Armor on Vertex AI, and their image kinds. */
90
+ const FILTERED = new Set(["SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "IMAGE_SAFETY", "MODEL_ARMOR", "IMAGE_PROHIBITED_CONTENT", "IMAGE_RECITATION", "IMAGE_OTHER"]);
91
+ /** Reasons of a turn whose tool call could not be read. */
92
+ const MALFORMED = new Set(["MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL", "MALFORMED_RESPONSE"]);
93
+ /**
94
+ * Known reasons that are none of the others, and that asking again does not mend. LANGUAGE (a
95
+ * language the model does not take) is not a filter: `answerInfoOf` gives it reason "language".
96
+ */
97
+ const OTHER = new Set(["OTHER", "FINISH_REASON_UNSPECIFIED", "NO_IMAGE", "TOO_MANY_TOOL_CALLS", "MISSING_THOUGHT_SIGNATURE", "LANGUAGE"]);
40
98
 
41
- /** Gemini's `finishReason` in the terms of `ModelReply.finish`. Undefined for a reason it does not know. */
42
- export function finishOfGemini(reason: string | undefined): "complete" | "cut" | "filtered" | "malformed_call" | undefined {
99
+ /**
100
+ * Gemini's `finishReason` in the terms of `ModelReply.finish`. Undefined for a reason it does not
101
+ * know. Since 0.10.0, MODEL_ARMOR and the image reasons are "filtered", MALFORMED_RESPONSE is
102
+ * "malformed_call", and OTHER, LANGUAGE and four more are "other".
103
+ */
104
+ export function finishOfGemini(reason: string | undefined): ModelReply["finish"] {
43
105
  if (reason === "STOP") return "complete";
44
106
  if (reason === "MAX_TOKENS") return "cut";
45
107
  if (reason && FILTERED.has(reason)) return "filtered";
46
108
  if (reason && MALFORMED.has(reason)) return "malformed_call";
109
+ if (reason && OTHER.has(reason)) return "other";
47
110
  return undefined;
48
111
  }
@@ -2,10 +2,37 @@
2
2
  // auth headers, so this works with the Gemini API, Vertex AI, or an enterprise gateway.
3
3
  import type { ToolAnswer, ToolCall } from "../model.js";
4
4
  import { completeWithinLimit, noTextReason, type LimitedReply } from "../output-limit.js";
5
- import { readJson } from "../http.js";
5
+ import { base64, partTimer, readJson, resolveHeaderSource, until, type HeaderSource } from "../http.js";
6
6
  import { noteNoRetry, retryAfterMs } from "../retry.js";
7
7
  import type { GenerateText, GenerateUsage, ToolDeclaration, ToolFile, ToolResult } from "../types.js";
8
- import { finishOfGemini, geminiFailure, notJson, unreachable } from "./errors.js";
8
+ import { errorBodyOf, finishOfGemini, geminiFailure, notJson, statusOfError, tooSlow, unreachable } from "./errors.js";
9
+
10
+ /**
11
+ * More fields for the body of a Gemini request (`gemini({ body, analysisBody })`): `safetySettings`,
12
+ * `labels` (Vertex AI), `serviceTier`, `cachedContent` for an explicit cache, or any other field the
13
+ * API takes. They are merged last, after the library's. The fields the library writes itself are
14
+ * typed `never`: set `generationConfig` and `analysisConfig` for those. Nothing is refused at run
15
+ * time. New in 0.10.0.
16
+ */
17
+ export type GeminiRequestFields = {
18
+ /** Safety settings, as the API takes them: `{ category, threshold, method? }`. */
19
+ safetySettings?: Array<{ category: string; threshold: string; method?: string }>;
20
+ /**
21
+ * Vertex AI only: labels for the billing export, keys and values in lower case, each at most 63
22
+ * characters. They reach every reader of the billing data: never put a user ID or other personal
23
+ * data in them.
24
+ */
25
+ labels?: Record<string, string>;
26
+ serviceTier?: string;
27
+ /** The name of an explicit context cache (`cachedContents/…`). */
28
+ cachedContent?: string;
29
+ contents?: never;
30
+ systemInstruction?: never;
31
+ tools?: never;
32
+ toolConfig?: never;
33
+ generationConfig?: never;
34
+ [key: string]: unknown;
35
+ };
9
36
 
10
37
  /** Gemini accepts this package's JSON Schema subset as-is. */
11
38
  export function toGeminiTools(declarations: ToolDeclaration[]): { functionDeclarations: ToolDeclaration[] } {
@@ -46,8 +73,6 @@ export type GeminiContent = { role: "user" | "model"; parts: GeminiPart[] };
46
73
  /** A `user` turn: a `GeminiContent` that can go in `contents` as it is. */
47
74
  type UserTurn = GeminiContent & { role: "user" };
48
75
 
49
- const base64 = (bytes: Uint8Array) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
50
-
51
76
  /** One function response, with `files` inside it. */
52
77
  function functionResponse(call: GeminiFunctionCall, result: ToolResult, files: ToolFile[]): GeminiPart {
53
78
  let response = result;
@@ -106,12 +131,30 @@ export { THINKING_OUTPUT_TOKENS } from "../output-limit.js";
106
131
  */
107
132
  export function createGeminiGenerateText(options: {
108
133
  url: 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>>);
134
+ /**
135
+ * Request headers, or a function returning them. A function is called for every request: a
136
+ * whole-file read can outlast an access token.
137
+ */
138
+ headers: HeaderSource;
111
139
  fetchImpl?: typeof fetch;
112
140
  /** The `generationConfig` of each request, from its output limit. Defaults to `{ maxOutputTokens }`. */
113
141
  generationConfig?: (maxOutputTokens: number) => Record<string, unknown>;
142
+ /**
143
+ * More fields for the body of each request, given its output limit, merged last
144
+ * (`gemini({ analysisBody })`). New in 0.10.0.
145
+ */
146
+ body?: (maxOutputTokens: number) => GeminiRequestFields;
147
+ /**
148
+ * The longest time, in milliseconds, a request may take, its whole reply included. Defaults to
149
+ * 180,000; 0 sets none. A request past it is a `GeminiRequestError` of kind "timeout" and status
150
+ * 0 (since 0.10.0; before, the abort of the timer), which a whole-file read sends again once.
151
+ */
114
152
  timeoutMs?: number;
153
+ /**
154
+ * A request refused with HTTP 401 is sent once more, with the headers of `headers({ refresh: true })`
155
+ * (the endpoint's `refreshable`). New in 0.10.0.
156
+ */
157
+ refreshable?: boolean | undefined;
115
158
  }): GenerateText {
116
159
  const fetchImpl = options.fetchImpl ?? fetch;
117
160
  const { url } = options;
@@ -120,60 +163,98 @@ export function createGeminiGenerateText(options: {
120
163
  let blocked = false;
121
164
  /** One request with an output limit: the text of the reply, why it ended, and what it thought. */
122
165
  const send = async (limit: number): Promise<LimitedReply> => {
123
- const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
124
- const headers = typeof options.headers === "function" ? await options.headers() : options.headers;
125
- let response: Response;
166
+ const timer = partTimer(signal, options.timeoutMs);
167
+ // Stopped by the caller: reported as it is. Out of time: a timeout. Anything else is a connection that failed.
168
+ const lost = (error: unknown) => (timer.expired && !signal?.aborted ? tooSlow(timer.limitMs) : unreachable(error));
126
169
  try {
127
- response = await fetchImpl(url, {
128
- method: "POST",
129
- headers,
130
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
131
- body: JSON.stringify({
132
- contents: [{ role: "user", parts: [{ text: prompt }] }],
133
- systemInstruction: { role: "system", parts: [{ text: system }] },
134
- // No temperature: Gemini 3.6 and later ignore it, and Google says later models will refuse it.
135
- generationConfig: options.generationConfig?.(limit) ?? { maxOutputTokens: limit },
136
- }),
170
+ const body = JSON.stringify({
171
+ contents: [{ role: "user", parts: [{ text: prompt }] }],
172
+ systemInstruction: { role: "system", parts: [{ text: system }] },
173
+ // No temperature: Gemini 3.6 and later ignore it, and Google says later models will refuse it.
174
+ generationConfig: options.generationConfig?.(limit) ?? { maxOutputTokens: limit },
175
+ ...options.body?.(limit),
137
176
  });
138
- } catch (error) {
139
- // Stopped by the caller, or out of time: reported as it is. Anything else is a connection that failed.
140
- if (signal?.aborted || timeout.aborted) throw error;
141
- throw unreachable(error);
177
+ const post = async (headers: Record<string, string>): Promise<Response> => {
178
+ try {
179
+ // The time limit ends the wait even for a fetch that does not stop when its signal aborts.
180
+ return await until(fetchImpl(url, { method: "POST", headers, ...(timer.signal ? { signal: timer.signal } : {}), body }), timer.signal);
181
+ } catch (error) {
182
+ if (signal?.aborted) throw error;
183
+ throw lost(error);
184
+ }
185
+ };
186
+ // An error may have no JSON body, and one that is a list is read by its first entry.
187
+ const failureOf = async (response: Response, cause?: unknown): Promise<Error> => {
188
+ const data = errorBodyOf(await response.json().catch(() => null));
189
+ return geminiFailure(response.status, data, retryAfterMs(response.headers, data), `The model returned HTTP ${response.status}.`, cause);
190
+ };
191
+ let response = await post(await resolveHeaderSource(options.headers));
192
+ // A token that was refused may be one a cache kept past its time: one more try, with a new one.
193
+ if (response.status === 401 && options.refreshable) {
194
+ let fresh: Record<string, string>;
195
+ try {
196
+ fresh = await resolveHeaderSource(options.headers, { refresh: true });
197
+ } catch (error) {
198
+ // No new token came: the refusal is the error, and why none came is its cause.
199
+ throw await failureOf(response, error);
200
+ }
201
+ discard(response);
202
+ response = await post(fresh);
203
+ }
204
+ type Chunk = {
205
+ error?: { message?: string; code?: unknown; status?: unknown };
206
+ candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
207
+ usageMetadata?: Record<string, unknown>;
208
+ promptFeedback?: { blockReason?: unknown };
209
+ };
210
+ if (!response.ok) throw await failureOf(response);
211
+ // A reply must have one: a body that could not be read is a connection that failed, and is
212
+ // sent again. It may be a list of chunks, as Gemini gives a reply without `alt=sse` (a
213
+ // gateway): every chunk is read, as a chat reply's are.
214
+ const data = await readJson<unknown>(response, () => Boolean(signal?.aborted), lost, timer.signal ? { pulse: () => undefined, signal: timer.signal } : undefined, (error) => notJson(response, error));
215
+ const chunks = (Array.isArray(data) ? data : [data]).filter((chunk): chunk is Chunk => chunk !== null && typeof chunk === "object" && !Array.isArray(chunk));
216
+ let text = "";
217
+ let answered = false;
218
+ let finishReason: string | undefined;
219
+ let usage: Record<string, unknown> | undefined;
220
+ let blockReason: unknown;
221
+ for (const chunk of chunks) {
222
+ // An error in a body of HTTP 200 (a gateway, or Vertex AI), alone or after part of the
223
+ // reply: thrown with its own status, so that a 503 is sent again rather than read as a
224
+ // reply with no text, or with part of its text.
225
+ if (chunk.error && typeof chunk.error === "object") throw geminiFailure(statusOfError(chunk.error), chunk, retryAfterMs(response.headers, chunk), "Gemini reported an error.");
226
+ usage = chunk.usageMetadata ?? usage;
227
+ blockReason = chunk.promptFeedback?.blockReason ?? blockReason;
228
+ const candidate = chunk.candidates?.[0];
229
+ if (!candidate) continue;
230
+ answered = true;
231
+ text += (candidate.content?.parts ?? [])
232
+ .filter((part) => part.thought !== true && typeof part.text === "string")
233
+ .map((part) => part.text as string)
234
+ .join("");
235
+ finishReason = candidate.finishReason ?? finishReason;
236
+ }
237
+ onUsage?.(usageOfGemini(usage));
238
+ // A prompt Gemini blocked comes with 200, a reason and no candidate: the reply has no text,
239
+ // and says why ("The model returned no text (PROHIBITED_CONTENT).").
240
+ if (!answered && typeof blockReason === "string" && blockReason) {
241
+ blocked = true;
242
+ return { text: "", cutOff: false, stopped: true, reason: blockReason, thoughts: 0 };
243
+ }
244
+ const thoughts = usage?.thoughtsTokenCount;
245
+ const finish = finishOfGemini(finishReason);
246
+ return {
247
+ text,
248
+ cutOff: finishReason === "MAX_TOKENS",
249
+ // Stopped before its end by a filter, or for another reason that is not the limit: what
250
+ // it wrote is not all there is.
251
+ stopped: finish === "filtered" || finish === "other",
252
+ ...(finishReason ? { reason: finishReason } : {}),
253
+ thoughts: typeof thoughts === "number" ? thoughts : 0,
254
+ };
255
+ } finally {
256
+ timer.stop();
142
257
  }
143
- type Data = {
144
- error?: { message?: string };
145
- candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
146
- usageMetadata?: Record<string, unknown>;
147
- promptFeedback?: { blockReason?: unknown };
148
- } | null;
149
- // An error may have no JSON body. A reply must: one whose body could not be read is a
150
- // connection that failed, and is sent again.
151
- const data: Data = response.ok
152
- ? await readJson<Data>(response, () => Boolean(signal?.aborted) || timeout.aborted, unreachable, undefined, (error) => notJson(response, error))
153
- : await response.json().catch(() => null) as Data;
154
- if (!response.ok) throw geminiFailure(response.status, data, retryAfterMs(response.headers, data), `The model returned HTTP ${response.status}.`);
155
- onUsage?.(usageOfGemini(data?.usageMetadata));
156
- const candidate = data?.candidates?.[0];
157
- // A prompt Gemini blocked comes with 200, a reason and no candidate: the reply has no text,
158
- // and says why ("The model returned no text (PROHIBITED_CONTENT).").
159
- const blockReason = data?.promptFeedback?.blockReason;
160
- if (!candidate && typeof blockReason === "string" && blockReason) {
161
- blocked = true;
162
- return { text: "", cutOff: false, stopped: true, reason: blockReason, thoughts: 0 };
163
- }
164
- const text = (candidate?.content?.parts ?? [])
165
- .filter((part) => part.thought !== true && typeof part.text === "string")
166
- .map((part) => part.text as string)
167
- .join("");
168
- const thoughts = data?.usageMetadata?.thoughtsTokenCount;
169
- return {
170
- text,
171
- cutOff: candidate?.finishReason === "MAX_TOKENS",
172
- // Stopped by the safety filters before its end: what it wrote is not all there is.
173
- stopped: finishOfGemini(candidate?.finishReason) === "filtered",
174
- ...(candidate?.finishReason ? { reason: candidate.finishReason } : {}),
175
- thoughts: typeof thoughts === "number" ? thoughts : 0,
176
- };
177
258
  };
178
259
  try {
179
260
  return await completeWithinLimit(url, maxOutputTokens, send, { signal, onTruncated });
@@ -184,3 +265,12 @@ export function createGeminiGenerateText(options: {
184
265
  }
185
266
  };
186
267
  }
268
+
269
+ /** A response that is not read: its body is let go, without waiting for it. */
270
+ export function discard(response: Response): void {
271
+ try {
272
+ void response.body?.cancel().catch(() => undefined);
273
+ } catch {
274
+ // A body that is locked, or a cancel that throws at once, holds nothing up.
275
+ }
276
+ }
@@ -1,9 +1,9 @@
1
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";
2
+ export type { AskEvent, AskGeminiOptions, AskGeminiResult, ChatTurn, GeminiContent, GeminiOwnOptions, GeminiPart } from "./chat.js";
3
3
  export { fromGeminiContents, gemini, GEMINI_PAGE_TOKENS, geminiToolTurns } from "./adapter.js";
4
4
  export type { FromGeminiContentsOptions, GeminiModelOptions } from "./adapter.js";
5
5
  export { geminiApi, vertexAi, vertexHost } from "./endpoints.js";
6
- export type { GeminiEndpoint } from "./endpoints.js";
6
+ export type { GeminiEndpoint, VertexAiOptions } from "./endpoints.js";
7
7
  export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, THINKING_OUTPUT_TOKENS, toGeminiTools, usageOfGemini } from "./generate.js";
8
- export type { GeminiFunctionCall, GeminiToolAnswer, GeminiToolFilePlacement } from "./generate.js";
8
+ export type { GeminiFunctionCall, GeminiRequestFields, GeminiToolAnswer, GeminiToolFilePlacement } from "./generate.js";
9
9
  export { parseSseJson, SseEventTooLongError } from "./sse.js";
package/src/http.ts CHANGED
@@ -1,11 +1,23 @@
1
1
  // Small things every adapter needs for its HTTP requests.
2
2
  import { sliceWhole } from "./text.js";
3
3
 
4
- /** Request headers, or a function returning them: called for each request, so a token can be renewed. */
5
- export type HeaderSource = Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
4
+ /**
5
+ * What a function of headers is told: `refresh` is true when the headers are asked for again
6
+ * because the last ones were refused (HTTP 401), so a token kept in a cache is to be fetched anew.
7
+ * New in 0.10.0.
8
+ */
9
+ export type HeaderContext = { refresh?: boolean };
6
10
 
7
- export async function resolveHeaderSource(source: HeaderSource | undefined): Promise<Record<string, string>> {
8
- return typeof source === "function" ? source() : source ?? {};
11
+ /**
12
+ * Request headers, or a function returning them: called for each request, so a token can be
13
+ * renewed. Since 0.10.0 the function may take a `HeaderContext`; one of no arguments still fits.
14
+ */
15
+ export type HeaderSource = Record<string, string> | ((context?: HeaderContext) => Record<string, string> | Promise<Record<string, string>>);
16
+
17
+ /** The headers of a source. A function is called with `context` when one is given, and with nothing otherwise, as before 0.10.0. */
18
+ export async function resolveHeaderSource(source: HeaderSource | undefined, context?: HeaderContext): Promise<Record<string, string>> {
19
+ if (typeof source !== "function") return source ?? {};
20
+ return context ? source(context) : source();
9
21
  }
10
22
 
11
23
  /** A secret, or a function returning it: called for each request. */
@@ -48,6 +60,55 @@ export const DEFAULT_FIRST_BYTE_TIMEOUT_MS = 600_000;
48
60
  /** The longest delay `setTimeout` takes: a longer one fires at once. About 24.8 days, which is no limit. */
49
61
  const LONGEST_TIMER_MS = 2_147_483_647;
50
62
 
63
+ /**
64
+ * The longest time, by default, that one part read of a whole-file read may take, in milliseconds:
65
+ * from the request until its whole reply is in.
66
+ */
67
+ export const DEFAULT_PART_TIMEOUT_MS = 180_000;
68
+
69
+ /** The time limit of one part read: see `partTimer`. */
70
+ export type PartTimer = {
71
+ /** The signal for `fetch`: it aborts when the caller's does, or when the time is up. */
72
+ readonly signal: AbortSignal | undefined;
73
+ /** True once the time ran out. The request was then aborted by the timer, not by the caller. */
74
+ readonly expired: boolean;
75
+ /** The time limit, in milliseconds, for the message. */
76
+ readonly limitMs: number;
77
+ /** The request is over: the timer is cleared. */
78
+ stop(): void;
79
+ };
80
+
81
+ /**
82
+ * A time limit on one part read of a whole-file read: `timeoutMs` (by default
83
+ * `DEFAULT_PART_TIMEOUT_MS`) for the request and its whole reply. 0, or a value that is not a
84
+ * positive number, sets none. `expired` tells the timer's abort apart from the caller's, which the
85
+ * adapters report as a `ModelRequestError` of kind "timeout" and status 0: the rule of `withRetry`
86
+ * then sends it again once, as a chat request that got nothing back.
87
+ */
88
+ export function partTimer(caller: AbortSignal | undefined, timeoutMs: number | undefined): PartTimer {
89
+ const limitMs = timeoutMs ?? DEFAULT_PART_TIMEOUT_MS;
90
+ if (!watching(limitMs)) return { signal: caller, expired: false, limitMs: 0, stop() {} };
91
+ const controller = new AbortController();
92
+ let expired = false;
93
+ const timer = setTimeout(() => {
94
+ expired = true;
95
+ controller.abort(new Error(`The part read took longer than ${waitText(limitMs)}.`));
96
+ }, Math.min(limitMs, LONGEST_TIMER_MS));
97
+ return {
98
+ signal: caller ? AbortSignal.any([caller, controller.signal]) : controller.signal,
99
+ get expired() {
100
+ return expired;
101
+ },
102
+ limitMs,
103
+ stop: () => clearTimeout(timer),
104
+ };
105
+ }
106
+
107
+ /** A wait in words: "180 s", or "50 ms" under a second. */
108
+ export function waitText(ms: number): string {
109
+ return ms >= 1_000 ? `${Math.round(ms / 1_000)} s` : `${Math.round(ms)} ms`;
110
+ }
111
+
51
112
  /** Watches a request for silence: see `idleWatch`. */
52
113
  export type IdleWatch = {
53
114
  /** The signal for `fetch`: it aborts when the caller's does, or when nothing arrived for the whole wait. */
package/src/index.ts CHANGED
@@ -2,11 +2,13 @@
2
2
  // "llm-large-files/gemini", "llm-large-files/openai", "llm-large-files/anthropic", or your own.
3
3
  // Node HTTP handlers are in "llm-large-files/node".
4
4
  export { createLargeFiles, DEFAULT_CACHE_BYTES, DEFAULT_INGEST_TIMEOUT_MS, DEFAULT_MAX_PDF_PAGES, DEFAULT_MAX_TEXT_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, isDocumentId, NEVER_EXPIRES, toDocumentSummary } from "./library.js";
5
- export type { AccessOptions, IngestFromSource, IngestInput, IngestSource, LargeFiles, LargeFilesOptions, OriginalReadContext, OriginalsReader, PrepareOptions, ToolOptions } from "./library.js";
5
+ export type { AccessOptions, CreatedLargeFiles, IngestFromSource, IngestInput, IngestSource, LargeFiles, LargeFilesOptions, LargeFilesStats, OriginalReadContext, OriginalsReader, PrepareOptions, ToolOptions } from "./library.js";
6
6
  export { DEFAULT_BUDGET, resolveBudget } from "./budget.js";
7
7
  export type { ModelLimits } from "./budget.js";
8
- export { askStream, askWithFiles, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, partialResultOf } from "./ask.js";
9
- export type { AskLimits, AskOptions, AskResult, MissingDocumentsAction, MissingDocumentsContext } from "./ask.js";
8
+ export { askStream, askWithFiles, DEFAULT_INPUT_TOKENS, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, partialResultOf } from "./ask.js";
9
+ export type { AskLimits, AskOptions, AskResult, MissingDocumentsAction, MissingDocumentsContext, ToolResultContext, ToolResultVerdict } from "./ask.js";
10
+ export * from "./answer-info.js";
11
+ export * from "./citations.js";
10
12
  export { classifyModelError, DocumentsNotFoundError, errorKindOf, ModelRequestError, TOOL_TURN_VERSION, UsageMeter } from "./model.js";
11
13
  export type {
12
14
  ChatMessage,
@@ -52,7 +54,7 @@ export type { RetryNotice, RetryOptions } from "./retry.js";
52
54
  export { parseSseJson, SseEventTooLongError } from "./sse.js";
53
55
  export type { SseHooks } from "./sse.js";
54
56
  export { DEFAULT_FIRST_BYTE_TIMEOUT_MS, DEFAULT_IDLE_TIMEOUT_MS } from "./http.js";
55
- export type { IdleWaits } from "./http.js";
57
+ export type { HeaderContext, HeaderSource, IdleWaits } from "./http.js";
56
58
  export { DocumentScopeError, DocumentStoreError, IngestError, ingestErrorCodeOf } from "./errors.js";
57
59
  export type { DocumentScopeErrorCode, DocumentStoreOperation, IngestErrorCode } from "./errors.js";
58
60
  export { errorInfoOf } from "./error-info.js";
@@ -62,5 +64,5 @@ export type { FileDocumentScopes, FileDocumentStoreOptions } from "./stores.js";
62
64
  export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";
63
65
  export type { PdfExtractorOptions } from "./extract.js";
64
66
  export { estimateTokens, utf8Bytes, jsonBytes } from "./text.js";
65
- export { MAX_VIEW_PAGES, MAX_WHOLE_DOCUMENT_READS, REGEX_BUDGET_MS, TOOL_NAMES, toolResultSummary } from "./tools.js";
67
+ export { declarationsFor, MAX_VIEW_PAGES, MAX_WHOLE_DOCUMENT_READS, REGEX_BUDGET_MS, TOOL_NAMES, toolResultSummary } from "./tools.js";
66
68
  export type * from "./types.js";