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.
- package/CHANGELOG.md +1400 -338
- package/README.md +217 -49
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +117 -0
- package/dist/anthropic/adapter.d.ts.map +1 -0
- package/dist/anthropic/adapter.js +542 -0
- package/dist/anthropic/adapter.js.map +1 -0
- package/dist/anthropic/index.d.ts +3 -0
- package/dist/anthropic/index.d.ts.map +1 -0
- package/dist/anthropic/index.js +2 -0
- package/dist/anthropic/index.js.map +1 -0
- package/dist/ask.d.ts +200 -0
- package/dist/ask.d.ts.map +1 -0
- package/dist/ask.js +1402 -0
- package/dist/ask.js.map +1 -0
- package/dist/budget.d.ts +23 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +64 -0
- package/dist/budget.js.map +1 -0
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +42 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +138 -0
- package/dist/evidence.js.map +1 -0
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +59 -0
- package/dist/gemini/adapter.d.ts.map +1 -0
- package/dist/gemini/adapter.js +226 -0
- package/dist/gemini/adapter.js.map +1 -0
- package/dist/gemini/chat.d.ts +53 -77
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +42 -300
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +16 -0
- package/dist/gemini/errors.d.ts.map +1 -0
- package/dist/gemini/errors.js +46 -0
- package/dist/gemini/errors.js.map +1 -0
- package/dist/gemini/generate.d.ts +18 -21
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +49 -92
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +6 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +4 -3
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -2
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -38
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +136 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +401 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +96 -8
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +414 -96
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +37 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +255 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +278 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +222 -0
- package/dist/model.js.map +1 -0
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/openai/adapter.d.ts +109 -0
- package/dist/openai/adapter.d.ts.map +1 -0
- package/dist/openai/adapter.js +567 -0
- package/dist/openai/adapter.js.map +1 -0
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +2 -0
- package/dist/openai/index.js.map +1 -0
- package/dist/output-limit.d.ts +42 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +121 -0
- package/dist/output-limit.js.map +1 -0
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +275 -14
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/retry.d.ts +76 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +141 -0
- package/dist/retry.js.map +1 -0
- package/dist/search.d.ts +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +36 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +153 -0
- package/dist/sse.js.map +1 -0
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +72 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +341 -60
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +128 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +58 -184
- package/docs/configuration.md +34 -490
- package/docs/getting-started.md +412 -177
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1022 -138
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +902 -90
- package/docs/troubleshooting.md +1390 -0
- package/package.json +22 -4
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +611 -0
- package/src/anthropic/index.ts +2 -0
- package/src/ask.ts +1560 -0
- package/src/budget.ts +71 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +165 -0
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +271 -0
- package/src/gemini/chat.ts +87 -355
- package/src/gemini/errors.ts +48 -0
- package/src/gemini/generate.ts +67 -94
- package/src/gemini/index.ts +6 -4
- package/src/gemini/sse.ts +1 -34
- package/src/http.ts +434 -0
- package/src/index.ts +55 -4
- package/src/library.ts +497 -97
- package/src/map-reduce.ts +266 -59
- package/src/model.ts +433 -0
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +613 -0
- package/src/openai/index.ts +2 -0
- package/src/output-limit.ts +135 -0
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +176 -0
- package/src/search.ts +63 -10
- package/src/sse.ts +159 -0
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +338 -62
- package/src/types.ts +129 -5
- package/src/zip-directory.ts +136 -0
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
# `llm-large-files/openai`
|
|
2
|
+
|
|
3
|
+
This page lists every export of `llm-large-files/openai` with its options, defaults, return values
|
|
4
|
+
and errors: the `openAiCompatible()` adapter, its error class, and the converters for a history
|
|
5
|
+
kept as Chat Completions messages. It is for you if a model of your question sits behind a Chat
|
|
6
|
+
Completions endpoint: OpenAI, Azure OpenAI, DeepSeek, OpenRouter, vLLM, Ollama, LiteLLM, llama.cpp,
|
|
7
|
+
or the OpenAI layer of the Gemini API. The recipe for each server is in the guide
|
|
8
|
+
[OpenAI-compatible endpoints](../guides/openai-compatible.md).
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { fromOpenAiMessages, openAiCompatible, openAiToolTurns, OpenAiRequestError } from "llm-large-files/openai";
|
|
12
|
+
import type { OpenAiCompatibleOptions, OpenAiMessage } from "llm-large-files/openai";
|
|
13
|
+
// What the signatures below use from the main entry:
|
|
14
|
+
import { ModelRequestError } from "llm-large-files";
|
|
15
|
+
import type { ChatMessage, ModelAdapter, ModelErrorKind, ToolTurn } from "llm-large-files";
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The entry point needs no OpenAI SDK: it posts JSON to the URL you give, with `fetch`.
|
|
19
|
+
|
|
20
|
+
## Contents
|
|
21
|
+
|
|
22
|
+
- [The model adapter](#the-model-adapter): [`openAiCompatible()`](#openaicompatibleoptions),
|
|
23
|
+
[`OpenAiCompatibleOptions`](#openaicompatibleoptions-1)
|
|
24
|
+
- [Errors](#errors): [`OpenAiRequestError`](#openairequesterror)
|
|
25
|
+
- [Chat Completions messages](#chat-completions-messages): [`OpenAiMessage`](#openaimessage),
|
|
26
|
+
[`fromOpenAiMessages()`](#fromopenaimessageshistory), [`openAiToolTurns()`](#openaitoolturnsturns)
|
|
27
|
+
|
|
28
|
+
## The model adapter
|
|
29
|
+
|
|
30
|
+
### openAiCompatible(options)
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
declare function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter;
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
A model behind a Chat Completions endpoint, as a [`ModelAdapter`](./ask.md#modeladapter) for
|
|
37
|
+
[`askWithFiles`](./ask.md#askwithfilesoptions): the model that answers, or the `explorer`. It makes
|
|
38
|
+
no request when it is created and throws nothing. The options are in
|
|
39
|
+
[`OpenAiCompatibleOptions`](#openaicompatibleoptions-1).
|
|
40
|
+
|
|
41
|
+
The adapter it returns:
|
|
42
|
+
|
|
43
|
+
| Member | Value |
|
|
44
|
+
|---|---|
|
|
45
|
+
| `id` | `options.id`, else `options.model`. It names the model in `usage.byModel` and in messages. |
|
|
46
|
+
| `capabilities` | `toolFiles` is `"beside"` with `pdfInput`, else `"none"`. `pageTokens` is `options.pageTokens`, else 1,000. `contextTokens`, `maxRequestBytes` and `tokenScale` are there only when you set them (0 counts as not set), so the loop counts a scale of 1 by default. No `outputTokens`, not `appendOnly`. See [`ModelCapabilities`](./ask.md#modelcapabilities). |
|
|
47
|
+
| `send(request, hooks?)` | One chat request, described below. |
|
|
48
|
+
| `requestBytes(request)` | The size in bytes of the JSON body of that request, without the two fields a stream adds. |
|
|
49
|
+
| `generateText` | The part reader of whole-file reads, described below. With it, `analyze_whole_document` can be offered when this adapter is the model that uses the tools (the explorer, when there is one), unless `wholeDocumentAnalysis` is `false`. |
|
|
50
|
+
|
|
51
|
+
**Where it posts.** Every request goes to `url`, or to `baseUrl` (default
|
|
52
|
+
`https://api.openai.com/v1`, trailing slashes removed) followed by `/chat/completions`. Its headers
|
|
53
|
+
are `Content-Type: application/json`; `Authorization: Bearer {apiKey}` when `apiKey` gives a
|
|
54
|
+
non-empty string; then `headers`, which can replace either. `apiKey` and `headers` are resolved
|
|
55
|
+
before every request, chat requests and part reads alike, so a function can return a renewed key.
|
|
56
|
+
|
|
57
|
+
**The body of a chat request**, in this order, a later field replacing an earlier one:
|
|
58
|
+
|
|
59
|
+
- `model`.
|
|
60
|
+
- `messages`: the system instruction first, as a message of role `systemRole` (`"system"`), when it
|
|
61
|
+
is not empty; then the conversation.
|
|
62
|
+
- `tools`, each as `{ type: "function", function: declaration }`, when the request offers tools. A
|
|
63
|
+
request that must be answered in text adds `tool_choice: "none"`. With
|
|
64
|
+
`answerWithoutTools: "omit"` it sends neither `tools` nor `tool_choice`.
|
|
65
|
+
- `stream: true` and `stream_options: { include_usage: true }`, when the request is streamed.
|
|
66
|
+
- Every field of `body`.
|
|
67
|
+
|
|
68
|
+
A chat request carries no output limit and no sampling field unless you put them in `body`.
|
|
69
|
+
|
|
70
|
+
**The conversation in the request.**
|
|
71
|
+
|
|
72
|
+
- A turn of text is a message whose `content` is a string: its text parts, joined by a blank line.
|
|
73
|
+
A turn with native parts has a list as `content`: `{ type: "text", text }` for each text part,
|
|
74
|
+
and each native part as it is.
|
|
75
|
+
- User turns that follow each other are made one, because some servers (DeepSeek's reasoner, the
|
|
76
|
+
chat templates of Mistral and Gemma models) refuse two user turns in a row.
|
|
77
|
+
- A model turn of this question goes back as it came (`ModelReply.raw`), with any
|
|
78
|
+
`reasoning_content`, `reasoning`, `reasoning_details` or `refusal` in it: a server may want them
|
|
79
|
+
again. A stored tool round (the `toolTurns` of an earlier question, or a round of another
|
|
80
|
+
adapter) becomes an assistant message with `content: null` and `tool_calls`, the arguments as a
|
|
81
|
+
JSON string. A call without an ID is given `call_{round}_{n}`.
|
|
82
|
+
- Each result is a message `{ role: "tool", tool_call_id, content }`, `content` being the result as
|
|
83
|
+
JSON. With `pdfInput`, the files the tools returned (the pages of `view_pages`) follow in one user
|
|
84
|
+
message: for each file, a text part `"{file name} (returned by view_pages):"` and a part
|
|
85
|
+
`{ type: "file", file: { filename, file_data: "data:application/pdf;base64,…" } }`.
|
|
86
|
+
|
|
87
|
+
**Streaming.** A chat request is streamed when `hooks.onText` is given and `stream` is not `false`.
|
|
88
|
+
Under `askWithFiles` that is the answering model's request when you pass `onText`; an explorer's
|
|
89
|
+
requests are never streamed. Each piece of text goes to `onText` as it arrives.
|
|
90
|
+
|
|
91
|
+
- A reply of type `text/event-stream` is read as events. A reply of another type, or of none, is
|
|
92
|
+
read by its first characters (since 0.6.0): as events when it starts like them (`data:`,
|
|
93
|
+
`event:`, `id:`, `retry:` or a comment), as one piece otherwise. A body that starts with more
|
|
94
|
+
than 65,536 characters of white space is read as one piece. A reply read whole gives `onText`
|
|
95
|
+
its text at once.
|
|
96
|
+
- `[DONE]` ends the reply. A server that then leaves the connection open is read for one more
|
|
97
|
+
second at most, and the body is cancelled, which closes the connection; a connection that breaks
|
|
98
|
+
after `[DONE]` keeps the reply too. 0.5.0 waited for such a connection to close, and failed a
|
|
99
|
+
request whose connection broke after `[DONE]` with status 0, with the whole answer already shown.
|
|
100
|
+
- A server that sends the name of a tool call again with each piece of the call does not make it
|
|
101
|
+
longer (since 0.6.0; it gave `search_documentsearch_document`). A name sent in pieces is joined.
|
|
102
|
+
|
|
103
|
+
**The reply** ([`ModelReply`](./ask.md#modelreply)):
|
|
104
|
+
|
|
105
|
+
- `text` is the message's content. When there is none and the model refused, it is the `refusal`,
|
|
106
|
+
which goes to `onText` too.
|
|
107
|
+
- `calls` are the `tool_calls` that have a name. Arguments that are not a JSON object give the call
|
|
108
|
+
a `problem`: the loop answers it with that message instead of running it, and the model can send
|
|
109
|
+
it again. In the turn that goes back, those arguments, and empty ones, become `"{}"`, and
|
|
110
|
+
arguments that came as an object become their JSON text. When
|
|
111
|
+
`finish_reason` is `"length"`, every call gets a `problem` that says it was cut off at the output
|
|
112
|
+
limit, and none is run.
|
|
113
|
+
- `raw` is the assistant message as it goes back: the content, `refusal`, `reasoning_content`
|
|
114
|
+
(DeepSeek), `reasoning` and `reasoning_details` (OpenRouter; the streamed pieces of one detail
|
|
115
|
+
are joined, its other fields kept), and `tool_calls`.
|
|
116
|
+
- `finishReason` is `finish_reason`. `finish` is `"complete"` for `stop`, `tool_calls` and
|
|
117
|
+
`function_call`, `"cut"` for `length`, and `"filtered"` for `content_filter`. A `content_filter`
|
|
118
|
+
reply with no text and no calls has `blockReason: "content_filter"`.
|
|
119
|
+
- `usage`: `inputTokens` is `prompt_tokens`; `cachedInputTokens` is
|
|
120
|
+
`prompt_tokens_details.cached_tokens`, or DeepSeek's `prompt_cache_hit_tokens`; `outputTokens` is
|
|
121
|
+
`completion_tokens`; `thoughtTokens` is `completion_tokens_details.reasoning_tokens`. A missing
|
|
122
|
+
number counts 0. `providerUsage` is the `usage` object as it came. A stream reports usage only
|
|
123
|
+
when the server sends it.
|
|
124
|
+
|
|
125
|
+
**Part reads** (`generateText`, for `analyze_whole_document`) go to the same URL with the same
|
|
126
|
+
headers and are never streamed. The body is `model`, a message of role `systemRole` and a user
|
|
127
|
+
message, the output limit under the name `maxTokensField`, then the fields of
|
|
128
|
+
`analysisBody(limit)`. `body` is not used. Each request may take `timeoutMs` (180 s). A reply cut
|
|
129
|
+
off with nothing written, or with half its limit or more spent thinking, while the limit was below
|
|
130
|
+
32,768, is asked again with 32,768 output tokens
|
|
131
|
+
([`THINKING_OUTPUT_TOKENS`](./gemini.md#thinking_output_tokens)), and later part reads to the same
|
|
132
|
+
URL and model start there. A server that refuses that limit with HTTP 400 is not asked for it
|
|
133
|
+
again. A refusal of the request as too large is not taken for that (since 0.6.0): one for the
|
|
134
|
+
model's window (HTTP 400), or for the tokens a minute the provider allows (OpenAI's 429, Groq's 413
|
|
135
|
+
or 429), turns the larger limit off only when the window or allowance it names is 32,768 tokens or
|
|
136
|
+
less; otherwise a later part may still get it. In 0.5.0 one 400 for the window turned it off for
|
|
137
|
+
every later question on that model, in that process.
|
|
138
|
+
|
|
139
|
+
**Errors.** `send` throws, and does not send anything again itself:
|
|
140
|
+
[`askWithFiles`](./ask.md#askwithfilesoptions) decides what is retried
|
|
141
|
+
([`RetryOptions`](./errors-and-retries.md#retryoptions)).
|
|
142
|
+
|
|
143
|
+
| Case | Error | `status` | `kind` |
|
|
144
|
+
|---|---|---|---|
|
|
145
|
+
| The server answered with an HTTP error | [`OpenAiRequestError`](#openairequesterror) with the body's `error.message` (or `error`, when it is a string; a body wrapped in a list, as the Gemini API's layer sends it, is read too); else, since 0.6.0, a `message` at the top of the body (vLLM before its OpenAI-shaped errors, SGLang, FastChat) or a FastAPI `detail` (a string, or the `msg` of each problem in a list, joined with "; "); else "The model returned HTTP {status}." (for example "The model returned HTTP 503."). With `param`, `code` and `retryAfterMs` when the server gave them, in `error` or at the top of the body. | The HTTP status | Told from the status, the message and `code` |
|
|
146
|
+
| An error object inside a stream that began with 200 | `OpenAiRequestError` with its `message`, else "The model reported an error.", with its `code` and `param` when they are strings (since 0.6.0). | Its `code` when that is a status from 400 to 599; else from its `type` or `code`: `server_error`, `api_error`, `internal_error`, `internal_server_error` 500; `service_unavailable` 503; `rate_limit_exceeded`, `rate_limit_error`, `tokens_exceeded`, `insufficient_quota` 429; `timeout` 408; `invalid_request_error`, `context_length_exceeded` 400; any other 500. In 0.5.0: its `code` when that was a number, else the response's 200, not sent again | Told from the status, the message and `code`: `context_length_exceeded` is `"context_overflow"`, and `insufficient_quota` `"quota"`, neither sent again |
|
|
147
|
+
| The connection failed, before or while the reply arrived, or an event of the stream was not JSON | `OpenAiRequestError`: "The model could not be reached (fetch failed).", the reason being the HTTP client's message | 0 | `"unreachable"` |
|
|
148
|
+
| A reply of HTTP 200 whose body is empty | `OpenAiRequestError`: "The model could not be reached (the reply was empty).", new in 0.6.0. When the reply's type is `text/event-stream`, "The model's reply ended before it was complete." Either is sent again as a reply cut off on its way. | 0 | `"unreachable"` |
|
|
149
|
+
| Nothing arrived for a whole wait (`firstByteTimeoutMs`, `idleTimeoutMs`) | `OpenAiRequestError`: "The model sent nothing for {seconds} s.", the wait that ran out (600 s or 300 s by default) | 0 | `"timeout"` |
|
|
150
|
+
| A stream that closed with no `finish_reason` and no `[DONE]` | `OpenAiRequestError`: "The model's reply ended before it was complete." | 0 | `"unreachable"` |
|
|
151
|
+
| `finish_reason` `"insufficient_system_resource"` (DeepSeek's servers ran short) | `OpenAiRequestError`: "The model's server stopped the reply: it ran short of resources." | 503 | `"server"` |
|
|
152
|
+
| A reply whose body is not JSON (a gateway's HTML page) | `OpenAiRequestError`: "The model's reply could not be read: it was not JSON (text/html). A proxy or gateway may have answered in its place.", the brackets holding the response's media type (left out when it has none), with the `SyntaxError` as `cause`. Not sent again. Until 0.6.0, the `SyntaxError` itself. | The response's, 200 | `"invalid"` |
|
|
153
|
+
| An event of the stream longer than 64,000,000 characters | `OpenAiRequestError`: "The model's reply could not be read: an event of its stream held more than 64,000,000 characters." Not sent again. New in 0.6.0. | The response's, 200 | `"invalid"` |
|
|
154
|
+
| `hooks.signal` aborted | The signal's reason, as it is | none | none |
|
|
155
|
+
|
|
156
|
+
A part read throws as `send` does for an HTTP error, a connection that failed, an empty body,
|
|
157
|
+
`insufficient_system_resource`, an abort and a body that is not JSON. It has no waits of
|
|
158
|
+
`firstByteTimeoutMs` and `idleTimeoutMs`; instead, a request that ran past `timeoutMs` throws the
|
|
159
|
+
error of its abort (a `TimeoutError`). A reply with no text throws
|
|
160
|
+
`Error("The model returned no text (length).")`, the reason in brackets being `finish_reason`.
|
|
161
|
+
These two have no `status`. In a whole-file read, the model is told why a part failed by the
|
|
162
|
+
error's kind and status, never by the server's message: "The model took too long to answer." for
|
|
163
|
+
the `TimeoutError`, "The model returned no text (length)." for a reply with no text, the reason
|
|
164
|
+
only when it is a plain word (see [`analyze_whole_document`](./tools.md#analyze_whole_document)).
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
import { askWithFiles } from "llm-large-files";
|
|
168
|
+
import { openAiCompatible } from "llm-large-files/openai";
|
|
169
|
+
|
|
170
|
+
// files, documentIds and messages come from your application.
|
|
171
|
+
const model = openAiCompatible({
|
|
172
|
+
model: "gpt-5.5",
|
|
173
|
+
apiKey: process.env.OPENAI_API_KEY!,
|
|
174
|
+
contextTokens: 400_000, // set this to your model's context window
|
|
175
|
+
body: { reasoning_effort: "low" }, // any field of the chat request
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
const result = await askWithFiles({
|
|
179
|
+
files,
|
|
180
|
+
model,
|
|
181
|
+
documentIds,
|
|
182
|
+
messages,
|
|
183
|
+
onText: (delta) => process.stdout.write(delta), // the answer streams
|
|
184
|
+
});
|
|
185
|
+
console.log(result.usage.byModel["gpt-5.5"]);
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Guide: [OpenAI-compatible endpoints](../guides/openai-compatible.md), with a recipe for each server
|
|
189
|
+
and the pairing with Gemini. A second model that explores while this one answers, or the other way
|
|
190
|
+
round: [explorer model](../guides/explorer-model.md).
|
|
191
|
+
|
|
192
|
+
### `OpenAiCompatibleOptions`
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
type OpenAiCompatibleOptions = {
|
|
196
|
+
model: string;
|
|
197
|
+
baseUrl?: string | undefined;
|
|
198
|
+
url?: string | undefined;
|
|
199
|
+
apiKey?: string | (() => string | Promise<string>) | undefined;
|
|
200
|
+
headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>) | undefined;
|
|
201
|
+
body?: Record<string, unknown> | undefined;
|
|
202
|
+
analysisBody?: ((maxOutputTokens: number) => Record<string, unknown>) | undefined;
|
|
203
|
+
maxTokensField?: "max_tokens" | "max_completion_tokens" | undefined;
|
|
204
|
+
systemRole?: "system" | "developer" | undefined;
|
|
205
|
+
answerWithoutTools?: "tool_choice" | "omit" | undefined;
|
|
206
|
+
pdfInput?: boolean | undefined;
|
|
207
|
+
stream?: boolean | undefined;
|
|
208
|
+
contextTokens?: number | undefined;
|
|
209
|
+
maxRequestBytes?: number | undefined;
|
|
210
|
+
pageTokens?: number | undefined;
|
|
211
|
+
tokenScale?: number | undefined;
|
|
212
|
+
timeoutMs?: number | undefined;
|
|
213
|
+
firstByteTimeoutMs?: number | undefined;
|
|
214
|
+
idleTimeoutMs?: number | undefined;
|
|
215
|
+
id?: string | undefined;
|
|
216
|
+
fetch?: typeof fetch | undefined;
|
|
217
|
+
};
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
The options of [`openAiCompatible()`](#openaicompatibleoptions).
|
|
221
|
+
|
|
222
|
+
| Option | Type | Default | What it does |
|
|
223
|
+
|---|---|---|---|
|
|
224
|
+
| `model` | `string` | required | The model name the endpoint knows, sent as `model` in every chat request and part read: `"gpt-5.5"`, `"deepseek-v4-pro"`, an Azure deployment name. |
|
|
225
|
+
| `baseUrl` | `string` | `"https://api.openai.com/v1"` | The base of the API. Trailing slashes are removed and `/chat/completions` is added. DeepSeek: `https://api.deepseek.com/v1`. The Gemini API's OpenAI layer: `https://generativelanguage.googleapis.com/v1beta/openai`. Not used when `url` is set. |
|
|
226
|
+
| `url` | `string` | `baseUrl` + `/chat/completions` | The whole Chat Completions URL, used as it is, query string included: Azure OpenAI, a gateway. Its host also sets the default of `maxTokensField`. |
|
|
227
|
+
| `apiKey` | `string \| (() => string \| Promise<string>)` | none | Sent as `Authorization: Bearer {key}`. A function is called before every request. Left out, or an empty string, no `Authorization` header is sent. |
|
|
228
|
+
| `headers` | `Record<string, string> \| (() => Record<string, string> \| Promise<Record<string, string>>)` | none | More headers, merged last: they can replace `Content-Type` and `Authorization`. Azure's `api-key` goes here. A function is called before every request. |
|
|
229
|
+
| `body` | `Record<string, unknown>` | none | More fields for the body of every chat request: `temperature`, `reasoning_effort`, `max_completion_tokens`. Spread last, so a field here replaces the adapter's own, `model`, `messages`, `tools` and `stream` included; a field set to `undefined` is left out of the JSON. Not sent with part reads. |
|
|
230
|
+
| `analysisBody` | `(maxOutputTokens: number) => Record<string, unknown>` | none | More fields for the body of each part read, given the output limit that request is sent with. Spread last. |
|
|
231
|
+
| `maxTokensField` | `"max_tokens" \| "max_completion_tokens"` | `"max_completion_tokens"` when the host is `openai.com` or ends in `.openai.com` or `.openai.azure.com`, or ends in `.cognitiveservices.azure.com` or `.services.ai.azure.com` with `/openai/` in the path; `"max_tokens"` anywhere else | The name of the output limit in a part read. Left out, a part read that the server refuses with HTTP 400 for that name (by `param` and `code`, or in its message) is sent again with the other name, and the adapter keeps the other name from then on. Set, it is always used. |
|
|
232
|
+
| `systemRole` | `"system" \| "developer"` | `"system"` | The role of the system message, in chat requests and in part reads. `"developer"` for an endpoint that wants the newer name. |
|
|
233
|
+
| `answerWithoutTools` | `"tool_choice" \| "omit"` | `"tool_choice"` | How the request that must be answered in text says so. `"tool_choice"` keeps the tools and sends `tool_choice: "none"`. `"omit"` leaves the tools out and sends no `tool_choice`, for a server that does not know `tool_choice`. |
|
|
234
|
+
| `pdfInput` | `boolean` | `false` | Send the pages of `view_pages` to the model, as `file` parts in a user message after the tool messages of the round. It makes `capabilities.toolFiles` `"beside"`. Off, `toolFiles` is `"none"`, and `view_pages` is not offered to any model of the question. Turn it on only for a model that reads PDF input: a tool message holds text only, and many servers behind this API take no PDF at all. |
|
|
235
|
+
| `stream` | `boolean` | `true` | Stream a chat request that has `onText`. `false` never streams, for a server without streaming. A request without `onText` is not streamed either way. |
|
|
236
|
+
| `contextTokens` | `number` | none | The model's context window in tokens. Set as `capabilities.contextTokens`, it keeps the budget of a question within it. Without it the library's budget holds: 1,000,000 tokens unless you set another. |
|
|
237
|
+
| `maxRequestBytes` | `number` | none | The largest request body the endpoint takes, in bytes. Set as `capabilities.maxRequestBytes`, it keeps the budget within it. Without it the library's budget holds: 10,000,000 bytes unless you set another. |
|
|
238
|
+
| `pageTokens` | `number` | `1_000` | Tokens one PDF page shown by `view_pages` costs. The loop sizes the pages a question may look at from it. It matters only with `pdfInput`. |
|
|
239
|
+
| `tokenScale` | `number` | none, counted as 1 | This model's tokens for one token of the library's estimate, which is fitted to Gemini. A model whose tokenizer counts a third more for the same text takes 1.33, and its documents are planned for a window that much smaller. |
|
|
240
|
+
| `timeoutMs` | `number` | `180_000` | The longest a part read's request may take, in milliseconds, each try counted apart, except that a request sent again with the other name of the output limit (see `maxTokensField`) shares the time of the first. A request that runs longer is aborted. Not used for chat requests. |
|
|
241
|
+
| `firstByteTimeoutMs` | `number` | `600_000` | The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count: a model that thinks sends nothing until it has thought, and a reply that is not streamed comes whole at the end. A request that gets nothing for that long is aborted with an `OpenAiRequestError` (`status` 0, `kind` `"timeout"`), which `askWithFiles` sends again once. 0, a negative or a non-finite number waits without end. The key and headers are resolved before the wait starts. Not used for part reads. |
|
|
242
|
+
| `idleTimeoutMs` | `number` | `300_000` | The longest wait, in milliseconds, between two pieces of a chat reply once it has started to arrive. Any bytes count, keep-alives included. The same error; `askWithFiles` sends the request again once, unless text of it was shown. 0 waits without end. Not used for part reads. |
|
|
243
|
+
| `id` | `string` | `model` | The name of the model in `usage.byModel` and in messages. |
|
|
244
|
+
| `fetch` | `typeof fetch` | the global `fetch` | Used for chat requests and part reads: a proxy, logging, tests. A `fetch` whose body is a Node stream (node-fetch) works too. |
|
|
245
|
+
|
|
246
|
+
The two waits default to [`DEFAULT_FIRST_BYTE_TIMEOUT_MS`](./errors-and-retries.md#default_first_byte_timeout_ms)
|
|
247
|
+
and [`DEFAULT_IDLE_TIMEOUT_MS`](./errors-and-retries.md#default_idle_timeout_ms). What to set
|
|
248
|
+
them to: [errors and reliability](../guides/errors-and-reliability.md). What a page costs and how
|
|
249
|
+
the budget follows the model: [costs and limits](../guides/costs-and-limits.md),
|
|
250
|
+
[PDFs](../guides/pdfs.md).
|
|
251
|
+
|
|
252
|
+
## Errors
|
|
253
|
+
|
|
254
|
+
### `OpenAiRequestError`
|
|
255
|
+
|
|
256
|
+
```ts
|
|
257
|
+
declare class OpenAiRequestError extends ModelRequestError {
|
|
258
|
+
readonly param?: string;
|
|
259
|
+
readonly code?: string;
|
|
260
|
+
constructor(message: string, status: number, options?: {
|
|
261
|
+
retryAfterMs?: number;
|
|
262
|
+
cause?: unknown;
|
|
263
|
+
kind?: ModelErrorKind;
|
|
264
|
+
code?: string | undefined;
|
|
265
|
+
details?: unknown;
|
|
266
|
+
param?: string;
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
A request to an OpenAI-compatible endpoint that failed: the server answered with an HTTP error, or
|
|
272
|
+
could not be reached (`status` 0). It is a
|
|
273
|
+
[`ModelRequestError`](./errors-and-retries.md#modelrequesterror), so code that handles every
|
|
274
|
+
provider through `ModelRequestError` and `kind` needs no case of its own for it. The table under
|
|
275
|
+
[`openAiCompatible()`](#openaicompatibleoptions) lists when the adapter throws one.
|
|
276
|
+
|
|
277
|
+
| Field | Type | What it holds |
|
|
278
|
+
|---|---|---|
|
|
279
|
+
| `name` | `string` | `"OpenAiRequestError"`. |
|
|
280
|
+
| `message` | `string` | The server's own message, or one of the adapter's (see the table above). It is the provider's text: log it, and do not show it to your users as it is. |
|
|
281
|
+
| `status` | `number` | The HTTP status, or the status of an error inside a stream; 0 when no answer came; 200 for a reply that came and could not be read. |
|
|
282
|
+
| `kind` | [`ModelErrorKind`](./errors-and-retries.md#modelerrorkind) | What went wrong, told from `status`, the message and `code`: `code` `"insufficient_quota"` makes it `"quota"`, and so does HTTP 402 (DeepSeek's "Insufficient Balance", OpenRouter's "Insufficient credits"); `"context_length_exceeded"` with a 4xx status makes it `"context_overflow"`, and so does a request larger than the tokens a minute allow (OpenAI's 429 "Request too large … on tokens per min (TPM)", Groq's 413 or 429). The adapter sets `"timeout"` itself for a wait that ran out, and `"invalid"` for a reply of HTTP 200 it could not read. New in 0.6.0. |
|
|
283
|
+
| `retryAfterMs` | `number \| undefined` | The wait the server asked for: its `retry-after-ms` or `Retry-After` header, or the `retryDelay` of a `google.rpc.RetryInfo` in the error body (the Gemini API's OpenAI layer). |
|
|
284
|
+
| `limitTokens`, `requestedTokens` | `number \| undefined` | For `kind` `"context_overflow"`: the model's limit and the tokens of the request, when the message gives them. New in 0.6.0. |
|
|
285
|
+
| `param` | `string \| undefined` | `error.param` of an HTTP error's body (or `param` at its top), or of an error inside a stream, when it is a string: the request field the error is about, such as `"max_tokens"`. New in 0.6.0. |
|
|
286
|
+
| `code` | `string \| undefined` | `error.code` of an HTTP error's body (or `code` at its top), or of an error inside a stream, when it is a string: the server's own word, such as `"unsupported_parameter"`, `"context_length_exceeded"` or `"insufficient_quota"`. New in 0.6.0. |
|
|
287
|
+
| `cause` | `unknown` | The HTTP client's error, for a request that could not be reached. |
|
|
288
|
+
|
|
289
|
+
The constructor takes the options of `ModelRequestError` and `param`. `code` sets the field and is
|
|
290
|
+
also used to tell the kind; `kind` given wins over what the status and message say. You build one
|
|
291
|
+
yourself only in a test or in a wrapper around the adapter.
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
import { askWithFiles, partialResultOf } from "llm-large-files";
|
|
295
|
+
import { OpenAiRequestError } from "llm-large-files/openai";
|
|
296
|
+
|
|
297
|
+
// files, model, documentIds and messages as above.
|
|
298
|
+
try {
|
|
299
|
+
await askWithFiles({ files, model, documentIds, messages });
|
|
300
|
+
} catch (error) {
|
|
301
|
+
if (error instanceof OpenAiRequestError) {
|
|
302
|
+
console.error(error.status, error.kind, error.code, error.param, error.message);
|
|
303
|
+
console.error(partialResultOf(error)?.usage); // what the question used before it failed
|
|
304
|
+
}
|
|
305
|
+
throw error;
|
|
306
|
+
}
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
Guide: [errors and reliability](../guides/errors-and-reliability.md), with what to show your users
|
|
310
|
+
for each `kind`.
|
|
311
|
+
|
|
312
|
+
## Chat Completions messages
|
|
313
|
+
|
|
314
|
+
### `OpenAiMessage`
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
type OpenAiMessage = { role: string; [key: string]: unknown };
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
A Chat Completions message as the API takes and returns it: `{ role: "user", content: "…" }`, an
|
|
321
|
+
assistant message with `tool_calls`, a `tool` message. Any field a server adds is allowed by the
|
|
322
|
+
type. [`fromOpenAiMessages`](#fromopenaimessageshistory) reads only `role`, `content`, `tool_calls`
|
|
323
|
+
and `tool_call_id`; other fields of a stored message, such as a user message's `name` or an
|
|
324
|
+
assistant message's `reasoning_content` or `refusal`, are dropped.
|
|
325
|
+
|
|
326
|
+
### fromOpenAiMessages(history)
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
declare function fromOpenAiMessages(history: OpenAiMessage[]): { system: string; messages: ChatMessage[] };
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
A conversation kept as Chat Completions messages, as `askWithFiles` takes it: `system` for its
|
|
333
|
+
`system` option, and `messages` ([`ChatMessage[]`](./ask.md#chatmessage)) for its `messages`. It
|
|
334
|
+
does not change `history`, and throws nothing.
|
|
335
|
+
|
|
336
|
+
| Message in `history` | What it becomes |
|
|
337
|
+
|---|---|
|
|
338
|
+
| `system` or `developer` | Its text (a string `content`, or the `text` parts of a list), added to `system`. Several are joined by a blank line; empty ones are left out. |
|
|
339
|
+
| `user`, or `assistant` with no `tool_calls` | A turn of that role. A string `content` is one text part. A list keeps its `text` parts as text and every other part (an `image_url`, a `file`) as a native part, in order. |
|
|
340
|
+
| `assistant` with `tool_calls` | A stored tool round ([`ToolTurn`](./ask.md#toolturn)): for each call its `id` (or `call_{n}_{m}` when it has none), its name, and its arguments parsed (`{}` when they are not a JSON object). Any `content` of that message is not kept. |
|
|
341
|
+
| `tool` | The result of the call with the same `tool_call_id` in an earlier round: the content parsed as a JSON object, else `{ text: content }`. A `tool` message that answers no known call is left out. |
|
|
342
|
+
| Any other role | Left out. |
|
|
343
|
+
|
|
344
|
+
A call that no `tool` message answers keeps the result
|
|
345
|
+
`{ error: "No result was kept for this call." }`.
|
|
346
|
+
|
|
347
|
+
Native parts reach every model of the question as they are. With a model of another provider (an
|
|
348
|
+
explorer on Gemini, say), both models must read parts in OpenAI's form.
|
|
349
|
+
|
|
350
|
+
### openAiToolTurns(turns)
|
|
351
|
+
|
|
352
|
+
```ts
|
|
353
|
+
declare function openAiToolTurns(turns: ToolTurn[]): OpenAiMessage[];
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
The tool rounds a question returned ([`AskResult.toolTurns`](./ask.md#askresult)) as Chat
|
|
357
|
+
Completions messages, for an application that keeps its history in that form. Put them between the
|
|
358
|
+
question and its answer. It throws nothing.
|
|
359
|
+
|
|
360
|
+
Each round becomes an assistant message `{ role: "assistant", content: null, tool_calls }`, the
|
|
361
|
+
arguments as a JSON string, followed by one `{ role: "tool", tool_call_id, content }` for each call,
|
|
362
|
+
`content` being the result as JSON, without `tool_turns_left`, which counted the turns of its own
|
|
363
|
+
question (since 0.6.0, as `askWithFiles` sends stored rounds). No files: `toolTurns` keep none. A call with an ID keeps it. A
|
|
364
|
+
call without one is given a new random ID, `call_` and 24 hex digits, a different one each time the
|
|
365
|
+
function runs, so that the rounds of two questions kept in one history never share an ID. (Before
|
|
366
|
+
0.6.0 such calls were numbered from 1.)
|
|
367
|
+
|
|
368
|
+
```ts
|
|
369
|
+
import { askWithFiles } from "llm-large-files";
|
|
370
|
+
import { fromOpenAiMessages, openAiToolTurns, type OpenAiMessage } from "llm-large-files/openai";
|
|
371
|
+
|
|
372
|
+
// files, model and documentIds as above. history is the chat so far, kept by your application
|
|
373
|
+
// as Chat Completions messages, ending with the user's question.
|
|
374
|
+
async function answer(history: OpenAiMessage[]): Promise<string> {
|
|
375
|
+
const { system, messages } = fromOpenAiMessages(history);
|
|
376
|
+
const result = await askWithFiles({ files, model, system, documentIds, messages });
|
|
377
|
+
// Keep what the tools returned between the question and the answer: a follow-up question
|
|
378
|
+
// then finds it without searching again.
|
|
379
|
+
history.push(...openAiToolTurns(result.toolTurns), { role: "assistant", content: result.text });
|
|
380
|
+
return result.text;
|
|
381
|
+
}
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
Guides: [conversations](../guides/conversations.md), which covers keeping `toolTurns` and the
|
|
385
|
+
history across requests, and [OpenAI-compatible endpoints](../guides/openai-compatible.md).
|