llm-large-files 0.4.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
@@ -0,0 +1,602 @@
1
+ # OpenAI-compatible endpoints
2
+
3
+ This guide shows how to run `askWithFiles` on a model behind the Chat Completions API, with
4
+ `openAiCompatible()` from `llm-large-files/openai`: OpenAI, Azure OpenAI, DeepSeek, OpenRouter,
5
+ vLLM, Ollama, LiteLLM, llama.cpp, or a gateway of your own. It is for you if one of these is your
6
+ only model, or the second model next to Gemini. Every option, with its type and default, is in the
7
+ [reference](../reference/openai.md).
8
+
9
+ ## The adapter in one sample
10
+
11
+ ```ts
12
+ import { readFile } from "node:fs/promises";
13
+ import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
14
+ import { openAiCompatible } from "llm-large-files/openai";
15
+
16
+ const files = createLargeFiles({ store: new MemoryDocumentStore() });
17
+
18
+ const model = openAiCompatible({
19
+ apiKey: process.env.OPENAI_API_KEY!, // sent as Authorization: Bearer …
20
+ model: "gpt-5.5", // baseUrl defaults to https://api.openai.com/v1
21
+ contextTokens: 400_000, // your model's window: the budget of a question stays inside it
22
+ });
23
+
24
+ const log = await files.ingest({ name: "app.log", bytes: await readFile("app.log") });
25
+
26
+ const result = await askWithFiles({
27
+ files,
28
+ model,
29
+ documentIds: [log.id],
30
+ messages: [{ role: "user", text: "Which errors came just before the outage?" }],
31
+ onText: (delta) => process.stdout.write(delta), // the answer streams as it is written
32
+ });
33
+ console.log(result.usage.byModel); // { "gpt-5.5": { requests, inputTokens, outputTokens, … } }
34
+ ```
35
+
36
+ `openAiCompatible()` returns a `ModelAdapter`. Give it to `askWithFiles` as `model`, which writes
37
+ the answer, or as `explorer`, which searches and reads ([below](#next-to-gemini)). It needs no SDK:
38
+ it posts JSON with the global `fetch` and reads the reply, streamed or in one piece. Make each
39
+ adapter once, when your server starts, and use it for every question: what it learns about the
40
+ server ([the name of the output limit](#the-name-of-the-output-limit)) lives in the adapter.
41
+
42
+ What it needs to reach the model:
43
+
44
+ | Option | Default | What it does |
45
+ |---|---|---|
46
+ | `model` | required | The model name the server knows, sent in every request: `"gpt-5.5"`, an Azure deployment name. It also names the model in usage totals, unless you set `id`. |
47
+ | `baseUrl` | `https://api.openai.com/v1` | The base of the API. `/chat/completions` is added to it; slashes at its end are dropped. |
48
+ | `url` | `baseUrl` + `/chat/completions` | The whole URL, when it is not built that way: an Azure deployment with `?api-version=`, a gateway. It wins over `baseUrl`. |
49
+ | `apiKey` | none | Sent as `Authorization: Bearer …`. A function is called before each request, so a token can be renewed. Without it, no `Authorization` header is sent. |
50
+ | `headers` | none | More headers, as an object or a function called before each request. They are added last, so a header spelled the same way (`Content-Type`, `Authorization`) replaces the adapter's own. |
51
+ | `contextTokens` | none | The model's context window in tokens. The budget of a question uses the smaller of it and the library's `budget.contextTokens` (1,000,000 unless you set it in `createLargeFiles`). A larger value raises nothing. |
52
+
53
+ The time it takes to get a key or a token is not counted against the waits of a chat request
54
+ (`firstByteTimeoutMs`, `idleTimeoutMs`). In a part read it counts toward `timeoutMs`
55
+ ([Waits](#waits)).
56
+
57
+ Set `contextTokens` for every model whose window is smaller than the library's budget. Without it,
58
+ the plan assumes a window of 1,000,000 tokens and puts up to 200,000 tokens of documents (the
59
+ default `inlineTokens`) into the prompt whole. A server with a smaller window refuses that request
60
+ as too large, and the loop has to plan again for a smaller window and send it again
61
+ ([how](../how-it-works.md)). That costs a refused request in every question, and works only when
62
+ the server says so with an error.
63
+
64
+ ## The options that matter for your server
65
+
66
+ | Option | Default | What it does |
67
+ |---|---|---|
68
+ | `body` | none | Fields added to every chat request: `temperature`, `reasoning_effort`, an output limit. |
69
+ | `analysisBody` | none | `(maxOutputTokens) => fields`, added to each part read of a whole-file read. |
70
+ | `maxTokensField` | by host | The name of the output limit in a part read: `"max_tokens"` or `"max_completion_tokens"` ([below](#the-name-of-the-output-limit)). |
71
+ | `systemRole` | `"system"` | `"developer"` for a server that wants the newer role name. Used in chat requests and part reads. |
72
+ | `answerWithoutTools` | `"tool_choice"` | How the request that must be answered in text says so. `"omit"` for a server that refuses `tool_choice`. |
73
+ | `stream` | `true` | `false` for a server that cannot stream. |
74
+ | `pdfInput` | `false` | `true` for a model that reads PDF input: `view_pages` is then offered ([Pages of PDFs](#pages-of-pdfs)). |
75
+
76
+ The waits are [below](#waits); `maxRequestBytes`, `tokenScale`, `pageTokens`, `id` and `fetch`
77
+ (a proxy, or a test double: [Testing](./testing.md)) are in the
78
+ [reference](../reference/openai.md).
79
+
80
+ ### What goes into a request
81
+
82
+ The fields of a chat request and of a part read, in their order, are in the reference:
83
+ [the body of a chat request](../reference/openai.md#openaicompatibleoptions).
84
+
85
+ - **`body` is spread last**, so a field there replaces the adapter's own. Leave `model`,
86
+ `messages`, `tools`, `tool_choice` and `stream_options` to the adapter, and use the `stream`
87
+ option instead of a `stream` field.
88
+ - **A chat request has no output limit** unless `body` gives one: the server's default applies. If
89
+ you set one there, name it as your server wants. `maxTokensField` is not used for chat requests.
90
+ - **`body` is not sent with part reads** of `analyze_whole_document`, which take `analysisBody`
91
+ instead: a setting the part reads need too goes in both.
92
+
93
+ The request that must be answered in text is the last one of a question when the tool turns or the
94
+ room run out, when a `limits` ceiling is reached, when the model's last turn had no text, and
95
+ always when there is an explorer; never after a blocked prompt. By default it keeps the tools
96
+ listed and sends `tool_choice: "none"`: a server may want the tools declared next to the tool calls
97
+ already in the conversation. With `answerWithoutTools: "omit"` the tools are left out of that request instead.
98
+
99
+ ## Recipes
100
+
101
+ Each recipe makes the adapter only. Use it as `model` or `explorer` in `askWithFiles`, as in the
102
+ first sample. The numbers given to `contextTokens` stand for your model's window: set the real one.
103
+
104
+ ### OpenAI
105
+
106
+ ```ts
107
+ import { openAiCompatible } from "llm-large-files/openai";
108
+
109
+ const openai = openAiCompatible({
110
+ apiKey: process.env.OPENAI_API_KEY!,
111
+ model: "gpt-5.5",
112
+ contextTokens: 400_000,
113
+ body: { reasoning_effort: "medium" }, // every chat request
114
+ analysisBody: () => ({ reasoning_effort: "low" }), // the part reads of a whole-file read
115
+ });
116
+ ```
117
+
118
+ - Part reads name their output limit `max_completion_tokens`, which OpenAI's newer models require.
119
+ - A reasoning model sends nothing while it thinks. `firstByteTimeoutMs` (600 s) is the wait for
120
+ its first piece. Its `completion_tokens_details.reasoning_tokens` are counted as
121
+ `usage.thoughtTokens`, and a part read that spent its limit on reasoning is asked again with a
122
+ larger one ([below](#the-name-of-the-output-limit)).
123
+ - `insufficient_quota` (no credit left) is of kind `"quota"`, and is not sent again, in an HTTP
124
+ error or inside a stream.
125
+ - OpenAI reports a failure inside a stream that began with HTTP 200 as
126
+ `{ type: "server_error", code: null }`. The adapter takes it for HTTP 500, which is sent again
127
+ when no text of the reply was shown.
128
+ - "Request too large for gpt-4o … on tokens per min (TPM): Limit 30000, Requested 45237" (HTTP
129
+ 429) is a single request larger than your tier lets through in a minute. No wait mends it, so it
130
+ is of kind `"context_overflow"`, with that limit as `limitTokens`: the loop makes the request
131
+ smaller, or plans the files again for 30,000 tokens, and a part read is read in halves. The step
132
+ says "The first request was larger than the 30,000 tokens a minute that the provider allows: the
133
+ files were planned again to fit it".
134
+ - `pdfInput: true` sends pages in the `file` part OpenAI documents for Chat Completions. It has not
135
+ been run against OpenAI.
136
+
137
+ ### Azure OpenAI
138
+
139
+ With a deployment URL and an API key:
140
+
141
+ ```ts
142
+ import { openAiCompatible } from "llm-large-files/openai";
143
+
144
+ const resource = process.env.AZURE_OPENAI_RESOURCE!; // the name in https://<resource>.openai.azure.com
145
+ const deployment = process.env.AZURE_OPENAI_DEPLOYMENT!;
146
+ const apiVersion = process.env.AZURE_OPENAI_API_VERSION!;
147
+
148
+ const azure = openAiCompatible({
149
+ url: `https://${resource}.openai.azure.com/openai/deployments/${deployment}/chat/completions?api-version=${apiVersion}`,
150
+ headers: { "api-key": process.env.AZURE_OPENAI_API_KEY! },
151
+ model: deployment, // sent in the body too, and names the model in usage totals
152
+ contextTokens: 400_000,
153
+ });
154
+ ```
155
+
156
+ With the `/openai/v1` path, `baseUrl` is enough, and `model` is the deployment name. Without a key,
157
+ pass a function as `apiKey` that returns a Microsoft Entra ID token: it is called before every
158
+ request and sent as `Authorization: Bearer …`.
159
+
160
+ ```ts
161
+ import { DefaultAzureCredential } from "@azure/identity";
162
+ import { openAiCompatible } from "llm-large-files/openai";
163
+
164
+ const credential = new DefaultAzureCredential();
165
+
166
+ const azure = openAiCompatible({
167
+ baseUrl: `https://${process.env.AZURE_OPENAI_RESOURCE}.openai.azure.com/openai/v1`,
168
+ apiKey: async () => (await credential.getToken("https://cognitiveservices.azure.com/.default")).token,
169
+ model: process.env.AZURE_OPENAI_DEPLOYMENT!,
170
+ contextTokens: 400_000,
171
+ });
172
+ ```
173
+
174
+ Azure OpenAI answers on three kinds of host. On Azure OpenAI's own paths, the adapter names the
175
+ output limit of a part read `max_completion_tokens`, because reasoning deployments refuse
176
+ `max_tokens`:
177
+
178
+ | Host | Paths | Output limit in a part read |
179
+ |---|---|---|
180
+ | `*.openai.azure.com` | all | `max_completion_tokens` |
181
+ | `*.cognitiveservices.azure.com`, `*.services.ai.azure.com` | paths with `/openai/` | `max_completion_tokens` |
182
+ | `*.cognitiveservices.azure.com`, `*.services.ai.azure.com` | other paths, such as `/models/…` | `max_tokens`: other models are served there |
183
+
184
+ Azure's "Could not finish the message because max_tokens or model output limit was reached" names
185
+ a field without refusing it: the adapter does not change the name for it, and the part read fails
186
+ with that message as its error.
187
+
188
+ ### DeepSeek
189
+
190
+ ```ts
191
+ import { openAiCompatible } from "llm-large-files/openai";
192
+
193
+ const deepseek = openAiCompatible({
194
+ baseUrl: "https://api.deepseek.com/v1",
195
+ apiKey: process.env.DEEPSEEK_API_KEY!,
196
+ model: "deepseek-v4-pro", // or "deepseek-reasoner"
197
+ contextTokens: 128_000,
198
+ });
199
+ ```
200
+
201
+ - **Two user turns in a row are sent as one**, joined by a blank line. The loop can send the
202
+ question and the request for an answer with no turn between them, and DeepSeek's reasoner
203
+ refuses two user turns in a row.
204
+ - **The model's own turn goes back with its `reasoning_content`**, streamed or not
205
+ ([the reply](../reference/openai.md#openaicompatibleoptions)).
206
+ - **`insufficient_system_resource`**: DeepSeek stops a reply when its servers run short. The
207
+ adapter takes that for the server's failure, HTTP 503, and the loop sends the request again. A
208
+ reply that is not streamed is checked before any of it is shown, so it can always be sent again;
209
+ a streamed one only when none of its text was shown yet.
210
+ - **Blank lines while a request waits** count as pieces of the reply, so a slow reply that is not
211
+ streamed does not run out the [waits](#waits).
212
+ - **Cached input**: `prompt_cache_hit_tokens` is counted as `usage.cachedInputTokens`.
213
+ - **No balance left**: "Insufficient Balance" comes as HTTP 402, of kind `"quota"`, and is not sent
214
+ again.
215
+ - Part reads name their output limit `max_tokens`.
216
+
217
+ ### OpenRouter
218
+
219
+ ```ts
220
+ import { openAiCompatible } from "llm-large-files/openai";
221
+
222
+ const openrouter = openAiCompatible({
223
+ baseUrl: "https://openrouter.ai/api/v1",
224
+ apiKey: process.env.OPENROUTER_API_KEY!,
225
+ model: process.env.OPENROUTER_MODEL!, // "vendor/model", as OpenRouter names it
226
+ contextTokens: 1_000_000,
227
+ });
228
+ ```
229
+
230
+ - **Reasoning is kept and sent back.** A streamed reply's `reasoning` and `reasoning_details` are
231
+ put together piece by piece (pieces of one detail share its `index`), kept in their order with
232
+ their other fields, and sent back with the turn unchanged. They hold the thought signature of a
233
+ Gemini 3 model behind OpenRouter, which that model needs in the next request.
234
+ - A request larger than the model takes is recognized from OpenRouter's error, with the window it
235
+ names, and the loop makes the request smaller.
236
+ - "Insufficient credits" comes as HTTP 402, of kind `"quota"`, and is not sent again.
237
+ - Part reads name their output limit `max_tokens`, unless the model behind refuses it
238
+ ([below](#the-name-of-the-output-limit)).
239
+
240
+ ### vLLM, Ollama and llama.cpp
241
+
242
+ A server of your own needs its URL, the model name it serves, and the window it runs the model
243
+ with. Give `apiKey` only if your server asks for one.
244
+
245
+ ```ts
246
+ import { openAiCompatible } from "llm-large-files/openai";
247
+
248
+ const vllm = openAiCompatible({
249
+ baseUrl: "http://localhost:8000/v1",
250
+ model: "my-model", // the name the server serves the model under
251
+ contextTokens: 32_768, // the server's max_model_len
252
+ });
253
+
254
+ const ollama = openAiCompatible({
255
+ baseUrl: "http://localhost:11434/v1",
256
+ model: "my-model",
257
+ contextTokens: 32_768, // the context length the model runs with on this server
258
+ });
259
+
260
+ const llamaCpp = openAiCompatible({
261
+ baseUrl: "http://localhost:8080/v1", // llama-server
262
+ model: "my-model",
263
+ contextTokens: 16_384, // the context size the server was started with
264
+ });
265
+ ```
266
+
267
+ What the adapter handles for these servers:
268
+
269
+ - **Tool calls.** The tools are sent as `tools` with `type: "function"`. The server must return
270
+ `tool_calls` for the model you serve; how to turn that on is the server's own setting.
271
+ - **Arguments that are not JSON.** A call whose arguments are not a JSON object is not run: the
272
+ model is told what was wrong and can send it again. The call goes back with `"{}"` as its
273
+ arguments, and so does a call whose arguments came empty: vLLM before 0.29 refuses the next
274
+ request of a conversation that holds such a call (HTTP 400).
275
+ - **Two user turns in a row are sent as one.** The chat templates of Mistral and Gemma models
276
+ refuse them.
277
+ - **A request larger than the window.** vLLM's error names the window (`max_model_len`) and the
278
+ tokens asked for ("your request has 40000 input tokens" in its newer wording), and the loop reads
279
+ both. The wordings of llama.cpp, LM Studio ("loaded with context length of only 4096 tokens"),
280
+ Text Generation Inference and Together ("`inputs` tokens + `max_new_tokens` must be <= 32769.
281
+ Given: 40000 …") and Amazon Bedrock ("Input is too long for requested model.") are recognized
282
+ too. The loop then makes the request smaller and sends it again, but each question pays for the
283
+ refused request: set `contextTokens`.
284
+ - **An error's message, wherever the server puts it.** Most servers put it in `error`. vLLM before
285
+ its OpenAI-shaped errors, SGLang and FastChat put a `message` at the top of the body, and servers
286
+ built on FastAPI a `detail` (a list of problems gives their `msg` joined with "; "). The adapter
287
+ reads all three; before 0.6.0, such a request too large became "The model returned HTTP 400.",
288
+ and the loop did not make it smaller.
289
+ - **The output limit** of a part read is named `max_tokens`.
290
+ - **`answerWithoutTools: "omit"`** for a server that refuses `tool_choice`, and
291
+ **`stream: false`** for one that cannot stream.
292
+
293
+ What it cannot see: a server that cuts a prompt to fit its window, without an error, answers from
294
+ what was left, and nothing tells the library so. `contextTokens` set to the window the server
295
+ really runs with is the only guard.
296
+
297
+ ### LiteLLM and other gateways
298
+
299
+ ```ts
300
+ import { openAiCompatible } from "llm-large-files/openai";
301
+
302
+ const gateway = openAiCompatible({
303
+ baseUrl: process.env.LITELLM_BASE_URL!, // the proxy's base URL; /chat/completions is added
304
+ apiKey: process.env.LITELLM_API_KEY!, // a key the proxy issued
305
+ model: "reasoning-model", // the model name in the proxy's configuration
306
+ maxTokensField: "max_completion_tokens", // the model behind it is an OpenAI reasoning model
307
+ contextTokens: 200_000,
308
+ id: "litellm/reasoning-model",
309
+ });
310
+ ```
311
+
312
+ - The host of a gateway is not OpenAI's, so part reads name their output limit `max_tokens`. When
313
+ the model behind it refuses that name, the adapter learns the other one, at the cost of one
314
+ refused request per adapter. `maxTokensField` saves that request.
315
+ - Set `maxRequestBytes` when the gateway limits the size of a request body. The budget's
316
+ `maxRequestBytes` (10 MB by default) is lowered to it, never raised.
317
+ - `id` names the adapter in `usage.byModel` (it defaults to `model`). Set it when two adapters
318
+ use the same model name.
319
+ - A gateway that gives up on a long request answers with an HTTP error (a 504, say), which is sent
320
+ again. Its own timeout should be longer than the model takes to start a reply: a reasoning model
321
+ sends nothing while it thinks. See [Deployment](./deployment.md) for proxies in front of your
322
+ own server.
323
+ - A gateway that streams under another content type than `text/event-stream`
324
+ (`application/octet-stream`, or none) is read by what its body starts with: events after
325
+ `data:` or a comment, JSON after `{` or `[`. One that answers HTTP 200 with a page of its own (a
326
+ sign-in page) fails with kind `"invalid"`, status 200, "The model's reply could not be read: it
327
+ was not JSON (text/html). A proxy or gateway may have answered in its place.", and is not sent
328
+ again. An empty body of HTTP 200 is sent again, as a reply cut off on its way.
329
+ - A gateway that sends `[DONE]` and then keeps the connection open is left one second later, with
330
+ the whole reply; so is one whose connection breaks after `[DONE]`. 0.5.0 waited for such a
331
+ connection to close, and took one that broke for a model that could not be reached, with the
332
+ answer already shown.
333
+
334
+ ## The name of the output limit
335
+
336
+ Only the part reads of a whole-file read send an output limit; chat requests do not, unless your
337
+ `body` does. Servers disagree on its name: OpenAI's newer models refuse `max_tokens` and want
338
+ `max_completion_tokens`, and many other servers know only `max_tokens`.
339
+
340
+ When you do not set `maxTokensField`, the name is chosen from the URL:
341
+
342
+ | URL | Name |
343
+ |---|---|
344
+ | `openai.com` and its subdomains (`api.openai.com`) | `max_completion_tokens` |
345
+ | Azure OpenAI ([the hosts above](#azure-openai)) | `max_completion_tokens` |
346
+ | Any other | `max_tokens` |
347
+
348
+ It is then learned. A part read that gets HTTP 400 refusing the name it was sent is sent again at
349
+ once with the other name, and the adapter keeps that name for every later part read. A refusal is
350
+ an error whose `param` is that name with the code `unsupported_parameter` or words that refuse it,
351
+ or, without a `param`, a message such as "Unsupported parameter: 'max_tokens' … Use
352
+ 'max_completion_tokens' instead", where the refused name comes first. Part reads refused at the
353
+ same time learn it once. An error that only mentions a name ("max_tokens or model output limit was
354
+ reached", "max_tokens is too large") changes nothing. When you set `maxTokensField`, that name is
355
+ always sent and nothing is learned.
356
+
357
+ The number itself: part notes start at 4,096 output tokens, and the answer of a whole-file read at
358
+ 8,192. A reasoning model counts its reasoning in that limit. When a part read is cut off with
359
+ nothing written, or with half its limit or more spent on reasoning (as the server reports it in
360
+ `completion_tokens_details.reasoning_tokens`), it is asked again with 32,768, and later part reads
361
+ of the same URL and model in this process start there. A server that refuses
362
+ 32,768 with HTTP 400 is not asked for it again, unless the 400 says the request was too large for
363
+ the model's window with that limit and the window is larger than 32,768: a later part may still
364
+ get it. A request refused as larger than the tokens a minute allows (OpenAI's or Groq's TPM) turns
365
+ the larger limit off when that allowance is no larger than 32,768. Both requests are counted in
366
+ `usage`.
367
+
368
+ ## Waits
369
+
370
+ | Wait | Option | Default | For |
371
+ |---|---|---|---|
372
+ | Before the first piece of a reply | `firstByteTimeoutMs` | 600,000 ms | Chat requests |
373
+ | Between two pieces of a reply | `idleTimeoutMs` | 300,000 ms | Chat requests |
374
+ | One request, in all | `timeoutMs` | 180,000 ms | Part reads |
375
+
376
+ - **Headers do not count** as a piece of a chat reply: a model that thinks sends nothing until it
377
+ has thought, and a reply that is not streamed comes whole at the end. Keep-alives count: an SSE
378
+ comment, or DeepSeek's blank lines in a reply that is not streamed. A reply that keeps arriving
379
+ has no limit in time. 0 waits without end.
380
+ - **When a wait runs out**, the request is aborted with an `OpenAiRequestError` of status 0 and kind
381
+ `"timeout"` ("The model sent nothing for 600 s."). `askWithFiles` sends it again once, unless
382
+ text of it was already shown.
383
+ - **A part read** has `timeoutMs` for the whole request, reply included. One that runs out is tried
384
+ once more at once, and then counts as a part that could not be read, which the tool result says.
385
+ Raise `timeoutMs` for a model that thinks long over a large part.
386
+
387
+ How failed requests are sent again, and what to tell your user, is in
388
+ [Errors and reliability](./errors-and-reliability.md).
389
+
390
+ ## Errors
391
+
392
+ A request that failed throws an `OpenAiRequestError`, a `ModelRequestError` of this adapter. Its
393
+ fields, and every message the adapter writes with its status and kind:
394
+ [`OpenAiRequestError`](../reference/openai.md#openairequesterror) and the errors table under
395
+ [`openAiCompatible()`](../reference/openai.md#openaicompatibleoptions).
396
+
397
+ `code` and `param` are new in 0.6.0. They come from an HTTP error response, and from an error
398
+ inside a stream too: `context_length_exceeded` there is HTTP 400, of kind `"context_overflow"`,
399
+ and `insufficient_quota` HTTP 429, of kind `"quota"`. In 0.5.0 an error inside a stream kept the
400
+ stream's HTTP 200, and was not sent again. `retryAfterMs` comes from an HTTP error response only.
401
+
402
+ A reply of HTTP 200 whose body is not JSON is an `OpenAiRequestError` of kind `"invalid"`, status
403
+ 200, with the `SyntaxError` as `cause`: "The model's reply could not be read: it was not JSON
404
+ (text/html). A proxy or gateway may have answered in its place." It was a `SyntaxError` before
405
+ 0.6.0. An empty body of HTTP 200 is "The model could not be reached (the reply was empty).", status
406
+ 0, and is sent again.
407
+
408
+ ```ts
409
+ import { askWithFiles, partialResultOf } from "llm-large-files";
410
+ import { OpenAiRequestError } from "llm-large-files/openai";
411
+
412
+ // files and model as in the first sample; documentIds and messages from your application.
413
+ try {
414
+ const result = await askWithFiles({ files, model, documentIds, messages });
415
+ console.log(result.text);
416
+ } catch (error) {
417
+ if (error instanceof OpenAiRequestError) {
418
+ // The provider's own words: log them, and show your user a message of your own.
419
+ console.error({ status: error.status, kind: error.kind, code: error.code, param: error.param, message: error.message });
420
+ }
421
+ const partial = partialResultOf(error); // what the question found and paid for before it failed
422
+ if (partial) console.error(partial.usage);
423
+ throw error;
424
+ }
425
+ ```
426
+
427
+ The kinds, the retries and a message for each case: [Errors and reliability](./errors-and-reliability.md).
428
+ The classes and helpers: [the errors reference](../reference/errors-and-retries.md).
429
+
430
+ ## What the adapter does with a reply
431
+
432
+ When it streams, what goes back to the model, how `finish_reason`, refusals and usage are read, and
433
+ the IDs it gives calls that came without one: "Streaming" and "The reply" under
434
+ [`openAiCompatible()`](../reference/openai.md#openaicompatibleoptions). A streamed tool call goes
435
+ back with every field the server sent in it, such as `extra_content`. A server that sends the name
436
+ of a tool call again with each piece of it is read right: the name is not doubled
437
+ (`search_documentsearch_document`, which the loop answered as an unknown tool before 0.6.0).
438
+
439
+ ## What it does not do
440
+
441
+ - It speaks Chat Completions only, at `/chat/completions` or your `url`. OpenAI's Responses API is
442
+ not supported.
443
+ - It sends no output limit in chat requests, and no prompt-cache settings. Cached tokens the server
444
+ reports are counted.
445
+ - It does not ask the server for the model's window. Without `contextTokens` the library's budget
446
+ holds.
447
+ - It counts no tokens with the model's tokenizer. The library estimates them, scaled by
448
+ `tokenScale`, and a question corrects the estimate by the counts the server reports.
449
+ - It cannot tell that a server cut a prompt down without an error.
450
+ - It sends no pages of PDFs unless `pdfInput` is on.
451
+
452
+ ## Pages of PDFs
453
+
454
+ By default the adapter says that its model cannot be sent a file, so `view_pages` is not offered.
455
+ That holds for the whole question: next to a Gemini model that could read the pages, an
456
+ OpenAI-compatible model without `pdfInput` turns them off for both.
457
+
458
+ ```ts
459
+ import { createLargeFiles, MemoryDocumentStore } from "llm-large-files";
460
+ import { openAiCompatible } from "llm-large-files/openai";
461
+
462
+ const files = createLargeFiles({ store: new MemoryDocumentStore(), keepOriginals: ["pdf"] });
463
+
464
+ const model = openAiCompatible({
465
+ apiKey: process.env.OPENAI_API_KEY!,
466
+ model: "gpt-5.5",
467
+ pdfInput: true, // view_pages is offered, and its pages go to the model as a file part
468
+ pageTokens: 1_000, // what the model bills for one page; 1,000 is the default
469
+ });
470
+ ```
471
+
472
+ With `pdfInput: true`, the pages of a `view_pages` call go in a user message after the tool
473
+ results: a line that names the file ("pages-2-3.pdf (returned by view_pages):"), then a `file` part
474
+ with `filename` and `file_data` as a base64 data URL. A tool message holds text only, so they
475
+ cannot go inside it. `pageTokens` is what one page costs in the budget of a question.
476
+
477
+ Turn it on only for a model that reads PDF input. It has not worked on any server yet: Gemini's
478
+ OpenAI layer refuses the `file` part (HTTP 400), and it has not been run against OpenAI or any
479
+ other server that reads PDF input. Keeping originals, the optional
480
+ dependencies and the costs of pages are in [PDFs](./pdfs.md).
481
+
482
+ ## Conversations kept as Chat Completions messages
483
+
484
+ If your application keeps its history as Chat Completions messages, two functions convert it:
485
+
486
+ ```ts
487
+ import { askWithFiles } from "llm-large-files";
488
+ import { fromOpenAiMessages, openAiToolTurns, type OpenAiMessage } from "llm-large-files/openai";
489
+
490
+ // loadHistory and saveHistory are your own storage; chatId and question come from the request;
491
+ // files, model and documentIds as before.
492
+ const history: OpenAiMessage[] = await loadHistory(chatId);
493
+ history.push({ role: "user", content: question });
494
+
495
+ const { system, messages } = fromOpenAiMessages(history);
496
+ const result = await askWithFiles({ files, model, documentIds, system, messages });
497
+
498
+ // What this question read goes between the question and its answer, in the same form.
499
+ history.push(...openAiToolTurns(result.toolTurns));
500
+ if (result.answered) history.push({ role: "assistant", content: result.text });
501
+ await saveHistory(chatId, history);
502
+ ```
503
+
504
+ `fromOpenAiMessages(history)`:
505
+
506
+ - joins the `system` and `developer` messages, with a blank line between them, into `system`;
507
+ - keeps text as text, and any other content part (`image_url`, a `file`) as a native part, sent to
508
+ the model as it is;
509
+ - makes an assistant turn of tool calls, and the `tool` messages that answer it, one stored round.
510
+ A tool message is read as a JSON object, or kept as `{ text }`. A call with no tool message gets
511
+ `{ error: "No result was kept for this call." }`, and a tool message whose call is not in the
512
+ history is dropped;
513
+ - does not keep the text of an assistant turn that also made tool calls.
514
+
515
+ `openAiToolTurns(result.toolTurns)` gives each round as an assistant message with its
516
+ `tool_calls` and one `tool` message per call, its content the JSON of the result. **Since 0.6.0, a
517
+ call that came without an ID gets a random one**, `call_` and 24 hexadecimal characters, and a new
518
+ one each time you convert. Before, they were numbered from 1 each time, so the stored rounds of two
519
+ questions had the same IDs. Convert a question's rounds once and store the messages; do not convert
520
+ them again and compare IDs.
521
+
522
+ Why to keep the rounds, how large they grow and how to keep a long conversation inside the window:
523
+ [Conversations](./conversations.md).
524
+
525
+ ## Next to Gemini
526
+
527
+ `askWithFiles` takes two adapters of any providers: `explorer` makes the tool calls and the part
528
+ reads, and `model` writes the answer from what they returned. A cheap OpenAI-compatible model can
529
+ explore while Gemini on Vertex AI answers:
530
+
531
+ ```ts
532
+ import { GoogleAuth } from "google-auth-library";
533
+ import { askWithFiles } from "llm-large-files";
534
+ import { gemini, vertexAi } from "llm-large-files/gemini";
535
+ import { openAiCompatible } from "llm-large-files/openai";
536
+
537
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
538
+
539
+ // Writes the answer, streamed.
540
+ const answering = gemini(vertexAi({
541
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
542
+ model: "gemini-3.8-flash",
543
+ accessToken: async () => (await auth.getAccessToken())!,
544
+ }), { contextTokens: 1_000_000 });
545
+
546
+ // Searches, reads, and reads whole files in parts.
547
+ const explorer = openAiCompatible({
548
+ baseUrl: "https://api.deepseek.com/v1",
549
+ apiKey: process.env.DEEPSEEK_API_KEY!,
550
+ model: "deepseek-v4-flash",
551
+ contextTokens: 128_000,
552
+ });
553
+
554
+ // files, documentIds and messages as before; send() writes to your stream to the browser.
555
+ const result = await askWithFiles({
556
+ files,
557
+ documentIds,
558
+ messages,
559
+ model: answering,
560
+ explorer,
561
+ onText: (delta) => send(delta),
562
+ });
563
+ console.log(result.usage.byModel); // one entry for "gemini-3.8-flash", one for "deepseek-v4-flash"
564
+ ```
565
+
566
+ The other way round works the same: `model: openAiCompatible(…)`, `explorer: gemini(…)`. What to
567
+ know about the pair:
568
+
569
+ - **Each model gets the conversation in its own form.** The explorer's own turns, with their
570
+ reasoning or signatures, go back only to the explorer. The answering model gets the calls and
571
+ what they returned, built in its form. A call that came without an ID goes to Gemini without
572
+ one. When the OpenAI-compatible model answers (the other way round), such a call is given one:
573
+ `call_1_1` for the first call of the first round.
574
+ - **The budget fits the smaller window** that the two adapters declare, and the larger
575
+ `tokenScale`. Give each its `contextTokens`.
576
+ - **`view_pages` needs both models to take files**: the OpenAI-compatible one only with `pdfInput`.
577
+ - **The explorer's requests are not streamed.** A thinking explorer sends nothing until its reply
578
+ is whole, and `firstByteTimeoutMs` is its wait.
579
+ - **The part reads are the explorer's**: its `analysisBody`, `maxTokensField` and `timeoutMs`
580
+ apply.
581
+ - **Native parts reach both models.** An `image_url` part in `messages` is sent to Gemini
582
+ unchanged, in OpenAI's form, which is not a Gemini part. With two providers, keep the turns to
583
+ text, or to parts both read.
584
+ - **`askGemini` cannot do this**: its explorer is a Gemini model. Use `askWithFiles` with
585
+ `gemini(vertexAi(…))`, as above.
586
+
587
+ Who does what, what changes for your application, and what it costs:
588
+ [An explorer model](./explorer-model.md). Setting up Gemini and Vertex AI:
589
+ [Gemini and Vertex AI](./vertex-and-gemini.md).
590
+
591
+ Gemini also has an OpenAI layer, at `https://generativelanguage.googleapis.com/v1beta/openai`, and
592
+ the adapter reads its errors, which come wrapped in a list. For Gemini, `gemini()` is the adapter to
593
+ use: it sends pages to the model, which the layer refuses as a `file` part.
594
+
595
+ ## What was run live
596
+
597
+ The live checks on record for this adapter ran on Gemini's OpenAI layer, in 0.5.0: a streamed
598
+ question about a 5.2 MB log, an explorer behind the layer with a thinking Gemini model answering,
599
+ and a part read. In each, the usage the library returned was what the provider reported. `pdfInput`
600
+ has not worked on any server yet: Gemini's OpenAI layer refuses its `file` part. The handling for the other servers in this guide is covered
601
+ by the tests in `test/openai.test.ts` and `test/loop-robustness.test.ts`, which replay the shapes
602
+ of their requests and replies. Dates and numbers are in [Measurements](../measurements.md).