llm-large-files 0.8.2 → 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 (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  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 +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
@@ -1,12 +1,8 @@
1
- import { askWithFiles, type AskLimits, type AskResult } from "../ask.js";
2
- import type { LargeFiles } from "../library.js";
3
- import type { AskEvent } from "../events.js";
4
- import type { ChatTurn, ToolTurn } from "../model.js";
5
- import type { RetryOptions } from "../retry.js";
6
- import type { Budget } from "../types.js";
1
+ import { askWithFiles, type AskOptions, type AskResult } from "../ask.js";
2
+ import type { ChatMessage } from "../model.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,23 +23,15 @@ 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
- * Plain chat history; the last turn must be the user's question. It may hold the tool rounds of
38
- * earlier questions (`toolTurns` of their results). Use this or `contents`.
27
+ * The chat history, as `askWithFiles` takes it; the last turn must be the user's question. It
28
+ * may hold the tool rounds of earlier questions (`toolTurns` of their results), and turns with
29
+ * parts, such as `fromGeminiContents(contents, { rounds: false })` gives. Use this or
30
+ * `contents`. Typed `ChatMessage[]` since 0.9.0; before, `Array<ChatTurn | ToolTurn>`.
39
31
  */
40
- messages?: Array<ChatTurn | ToolTurn>;
32
+ messages?: ChatMessage[];
41
33
  /** Your own Gemini `contents` (with images, inline PDFs, etc.). The last turn must be the user's. */
42
34
  contents?: GeminiContent[];
43
- system?: string;
44
35
  /** Sent with every chat request: temperature, maxOutputTokens, thinkingConfig, and so on. */
45
36
  generationConfig?: Record<string, unknown>;
46
37
  /**
@@ -49,26 +40,29 @@ export type AskGeminiOptions = {
49
40
  * example. It is not used without an explorer model.
50
41
  */
51
42
  explorerGenerationConfig?: Record<string, unknown>;
52
- /** The user asking. Documents ingested with a different owner are treated as missing. */
53
- owner?: string;
54
- /** The limits of the question: tool turns, calls in a turn, whole-file reads, tokens and requests. */
55
- limits?: AskLimits;
43
+ /**
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.
47
+ */
48
+ body?: GeminiRequestFields;
49
+ /** The same, for the requests of an explorer model. Defaults to `body`. New in 0.10.0. */
50
+ explorerBody?: GeminiRequestFields;
51
+ /**
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.
54
+ */
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;
56
62
  /** `limits.toolTurns`, under the name it had before 0.5.0. Defaults to 12. */
57
63
  maxToolTurns?: number;
58
64
  /** `limits.callsPerTurn`, under the name it had before 0.5.0. Defaults to 8. */
59
65
  maxToolCallsPerTurn?: number;
60
- /** How a request that failed is sent again. Defaults to three more tries, with a wait that doubles. */
61
- retry?: RetryOptions;
62
- /** Budget fields for this question, in place of the library's. */
63
- budget?: Partial<Budget>;
64
- /** Offer `analyze_whole_document`, which reads a whole file in many model calls. Defaults to true. */
65
- wholeDocumentAnalysis?: boolean;
66
- /**
67
- * Offer `view_pages` for PDFs whose original file is kept (`keepOriginals`), so the model can
68
- * look at pictures, charts and layout. Defaults to true. It changes nothing for a library that
69
- * keeps no originals.
70
- */
71
- viewPages?: boolean;
72
66
  /**
73
67
  * Where the pages go in the request. "inside" (the default) puts the PDF in the function
74
68
  * response itself, which Gemini 3 models read. "beside" sends it in a user turn of its own,
@@ -91,24 +85,16 @@ export type AskGeminiOptions = {
91
85
  * arrive. Defaults to 300,000. 0 waits without end.
92
86
  */
93
87
  idleTimeoutMs?: number;
94
- /** Answer text as it streams. Streaming is used when this is set (or `streamText` is true) and the endpoint has `streamUrl`. */
95
- onText?: (delta: string) => void;
96
- /** Whether to ask for the answer as it is written (`AskOptions.streamText`). Defaults to true when `onText` is given. New in 0.7.0. */
97
- streamText?: boolean;
98
- /** Short-lived status, such as "Searching app.log for “timeout”…". */
99
- onActivity?: (text: string) => void;
100
- /** A finished step, such as "Search app.log (exact) for “timeout” — 12 matching lines". */
101
- onStep?: (text: string) => void;
102
- /** Everything the question does, as typed events in order (`AskOptions.onEvent`). New in 0.7.0. */
103
- onEvent?: (event: AskEvent) => void;
104
- /** The `runId` of the events. Defaults to one made for the question ("run_…"). */
105
- runId?: string;
106
- /** Put each tool result in its `tool.end` event (`AskOptions.eventResults`). Off by default. */
107
- eventResults?: boolean;
108
88
  fetch?: typeof fetch;
109
- signal?: AbortSignal;
110
89
  };
111
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
+
112
98
  /** What `askWithFiles` returns. `usage` is summed over the whole question; Gemini's own `usageMetadata` of the last response is `lastUsage`. */
113
99
  export type AskGeminiResult = AskResult;
114
100
 
@@ -119,40 +105,39 @@ export type AskGeminiResult = AskResult;
119
105
  * and the tool loop runs, ending with a request without tools so there is always an answer.
120
106
  */
121
107
  export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiResult> {
122
- 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;
123
113
  // A second model for the requests that use tools. The answering model's own URL is not one.
124
114
  const explorerUrl = endpoint.explorerUrl && endpoint.explorerUrl !== endpoint.url ? endpoint.explorerUrl : undefined;
125
- const shared = { toolFilePlacement: options.toolFilePlacement, analysisConfig: options.analysisConfig, firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs, fetch: options.fetch };
126
- 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 } : {}) });
127
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;
128
125
  const explorer = explorerUrl
129
- ? 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 } : {}) })
130
131
  : undefined;
131
132
  return askWithFiles({
132
- files: options.files,
133
+ ...loop,
133
134
  model,
134
135
  explorer,
135
- documentIds: options.documentIds,
136
- ...(options.documentPlacement ? { documentPlacement: options.documentPlacement } : {}),
137
- messages: options.contents ? fromGeminiContents(options.contents) : options.messages ?? [],
138
- ...(options.system !== undefined ? { system: options.system } : {}),
139
- ...(options.owner !== undefined ? { owner: options.owner } : {}),
136
+ messages: contents ? fromGeminiContents(contents) : messages ?? [],
140
137
  limits: {
141
- ...(options.maxToolTurns !== undefined ? { toolTurns: options.maxToolTurns } : {}),
142
- ...(options.maxToolCallsPerTurn !== undefined ? { callsPerTurn: options.maxToolCallsPerTurn } : {}),
143
- ...options.limits,
138
+ ...(maxToolTurns !== undefined ? { toolTurns: maxToolTurns } : {}),
139
+ ...(maxToolCallsPerTurn !== undefined ? { callsPerTurn: maxToolCallsPerTurn } : {}),
140
+ ...limits,
144
141
  },
145
- ...(options.retry ? { retry: options.retry } : {}),
146
- ...(options.budget ? { budget: options.budget } : {}),
147
- ...(options.wholeDocumentAnalysis !== undefined ? { wholeDocumentAnalysis: options.wholeDocumentAnalysis } : {}),
148
- ...(options.viewPages !== undefined ? { viewPages: options.viewPages } : {}),
149
- ...(options.onText ? { onText: options.onText } : {}),
150
- ...(options.streamText !== undefined ? { streamText: options.streamText } : {}),
151
- ...(options.onActivity ? { onActivity: options.onActivity } : {}),
152
- ...(options.onStep ? { onStep: options.onStep } : {}),
153
- ...(options.onEvent ? { onEvent: options.onEvent } : {}),
154
- ...(options.runId !== undefined ? { runId: options.runId } : {}),
155
- ...(options.eventResults !== undefined ? { eventResults: options.eventResults } : {}),
156
- ...(options.signal ? { signal: options.signal } : {}),
157
142
  });
158
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
  }
@@ -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
  }