llm-large-files 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +446 -0
- package/README.md +13 -7
- package/dist/access.d.ts +45 -3
- package/dist/access.d.ts.map +1 -1
- package/dist/access.js +106 -3
- package/dist/access.js.map +1 -1
- package/dist/aggregate.d.ts +6 -0
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +86 -13
- package/dist/aggregate.js.map +1 -1
- package/dist/analyze.d.ts +4 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +2 -2
- package/dist/analyze.js.map +1 -1
- package/dist/answer-info.d.ts +26 -0
- package/dist/answer-info.d.ts.map +1 -0
- package/dist/answer-info.js +32 -0
- package/dist/answer-info.js.map +1 -0
- package/dist/anthropic/adapter.d.ts +5 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +35 -10
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +115 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +572 -103
- package/dist/ask.js.map +1 -1
- package/dist/citations.d.ts +36 -0
- package/dist/citations.d.ts.map +1 -0
- package/dist/citations.js +291 -0
- package/dist/citations.js.map +1 -0
- package/dist/error-info.d.ts +13 -0
- package/dist/error-info.d.ts.map +1 -1
- package/dist/error-info.js +37 -1
- package/dist/error-info.js.map +1 -1
- package/dist/errors.d.ts +3 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +3 -1
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +25 -7
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +21 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +6 -1
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +35 -4
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +68 -29
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +28 -55
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -27
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +59 -11
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +33 -7
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +39 -5
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +70 -9
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +53 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +100 -50
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/http.d.ts +41 -3
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +40 -2
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +9 -1
- package/dist/ingest.d.ts.map +1 -1
- package/dist/ingest.js +50 -25
- package/dist/ingest.js.map +1 -1
- package/dist/library.d.ts +129 -2
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +224 -149
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +176 -10
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +804 -58
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +36 -4
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +17 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +29 -8
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +148 -126
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.js +2 -2
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/spool.d.ts +9 -5
- package/dist/node/spool.d.ts.map +1 -1
- package/dist/node/spool.js +28 -15
- package/dist/node/spool.js.map +1 -1
- package/dist/node/sse.d.ts +6 -5
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +8 -7
- package/dist/node/sse.js.map +1 -1
- package/dist/openai/adapter.d.ts +5 -1
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +53 -12
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +2 -1
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +5 -2
- package/dist/output-limit.js.map +1 -1
- package/dist/pdf-outline.d.ts +71 -0
- package/dist/pdf-outline.d.ts.map +1 -0
- package/dist/pdf-outline.js +414 -0
- package/dist/pdf-outline.js.map +1 -0
- package/dist/plan.d.ts +137 -7
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +248 -26
- package/dist/plan.js.map +1 -1
- package/dist/prepare.d.ts +50 -0
- package/dist/prepare.d.ts.map +1 -0
- package/dist/prepare.js +207 -0
- package/dist/prepare.js.map +1 -0
- package/dist/ranged.d.ts +2 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +16 -3
- package/dist/ranged.js.map +1 -1
- package/dist/search.d.ts +7 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +72 -10
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +6 -0
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +82 -11
- package/dist/stores.js.map +1 -1
- package/dist/tools.d.ts +22 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +323 -76
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +49 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/whole-cost.d.ts +37 -0
- package/dist/whole-cost.d.ts.map +1 -0
- package/dist/whole-cost.js +46 -0
- package/dist/whole-cost.js.map +1 -0
- package/docs/README.md +4 -0
- package/docs/guides/anthropic.md +5 -2
- package/docs/guides/conversations.md +1 -1
- package/docs/guides/costs-and-limits.md +132 -36
- package/docs/guides/deployment.md +106 -13
- package/docs/guides/errors-and-reliability.md +157 -45
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +33 -6
- package/docs/guides/pdfs.md +96 -7
- package/docs/guides/storage.md +46 -3
- package/docs/guides/testing.md +71 -0
- package/docs/guides/vertex-and-gemini.md +159 -50
- package/docs/guides/web-app.md +10 -6
- package/docs/how-it-works.md +120 -22
- package/docs/measurements.md +172 -5
- package/docs/publishing.md +76 -4
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +262 -35
- package/docs/reference/errors-and-retries.md +30 -2
- package/docs/reference/events.md +27 -10
- package/docs/reference/gemini.md +184 -68
- package/docs/reference/library.md +190 -23
- package/docs/reference/node.md +51 -17
- package/docs/reference/openai.md +21 -10
- package/docs/reference/tools.md +271 -26
- package/docs/security.md +101 -12
- package/docs/troubleshooting.md +14 -12
- package/docs/upgrading-0.10.md +472 -0
- package/package.json +5 -1
- package/src/access.ts +127 -4
- package/src/aggregate.ts +92 -14
- package/src/analyze.ts +2 -2
- package/src/answer-info.ts +45 -0
- package/src/anthropic/adapter.ts +40 -11
- package/src/ask.ts +646 -106
- package/src/citations.ts +294 -0
- package/src/error-info.ts +36 -1
- package/src/errors.ts +3 -1
- package/src/events.ts +29 -6
- package/src/evidence.ts +21 -2
- package/src/extract.ts +6 -1
- package/src/gemini/adapter.ts +99 -32
- package/src/gemini/chat.ts +53 -82
- package/src/gemini/endpoints.ts +89 -16
- package/src/gemini/errors.ts +74 -11
- package/src/gemini/generate.ts +147 -57
- package/src/gemini/index.ts +3 -3
- package/src/http.ts +65 -4
- package/src/index.ts +6 -4
- package/src/ingest.ts +58 -27
- package/src/library.ts +336 -142
- package/src/map-reduce.ts +855 -67
- package/src/model.ts +44 -4
- package/src/node/handlers.ts +159 -118
- package/src/node/index.ts +1 -0
- package/src/node/ingest-child.ts +2 -2
- package/src/node/spool.ts +28 -14
- package/src/node/sse.ts +8 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +16 -3
- package/src/search.ts +69 -13
- package/src/stores.ts +76 -11
- package/src/tools.ts +327 -75
- package/src/types.ts +45 -1
- package/src/whole-cost.ts +64 -0
package/docs/guides/storage.md
CHANGED
|
@@ -91,6 +91,9 @@ With `scopes` (new in 0.9.0), the files of each scope are in a folder of their o
|
|
|
91
91
|
- Every file is written under a temporary name and then renamed, so no reader, on this server or
|
|
92
92
|
another one, sees half a file. A rename or a removal that meets `EPERM`, `EACCES` or `EBUSY` (on
|
|
93
93
|
Windows, another process has the file open for a moment) is tried again for about 2.6 seconds.
|
|
94
|
+
- A text longer than 1,048,576 UTF-16 units is encoded and written a slice of that size at a
|
|
95
|
+
time, never cutting a character in two: the bytes are the same as written at once (new in
|
|
96
|
+
0.10.0). A 50 MB `put` held the event loop for 379 ms in 0.9; it now holds it for about 20 ms.
|
|
94
97
|
- `put` writes the text first and the metadata last. `delete` removes the metadata first, and
|
|
95
98
|
nothing else when that fails: it throws, and the document stays whole. Once the metadata is
|
|
96
99
|
gone, the document is gone: `delete` returns true, and a text, index or original it could not
|
|
@@ -121,12 +124,17 @@ With `scopes` (new in 0.9.0), the files of each scope are in a folder of their o
|
|
|
121
124
|
undefined. Since 0.9.0 it does so also when the removal fails: the next `sweep` tries again.
|
|
122
125
|
- `readTextRange` reads only the bytes asked for, so a tool call never loads a large file whole.
|
|
123
126
|
The whole text is read only when the plan sends it in the prompt.
|
|
127
|
+
- A volume that stops answering (a hung NFS mount) is given up on after `storeTimeoutMs`, 30 s by
|
|
128
|
+
default (new in 0.10.0): see [Time limits](#time-limits) and
|
|
129
|
+
[Deployment](./deployment.md#a-store-that-stops-answering) for the thread pool.
|
|
124
130
|
- `sweep` removes expired documents and returns how many: those whose metadata it removed itself,
|
|
125
|
-
so two sweeps at once count each document once
|
|
126
|
-
|
|
131
|
+
so two sweeps at once count each document once. Since 0.10.0 the metadata is first renamed to a
|
|
132
|
+
name of the sweep's own, then removed, so this holds on Windows too, where two removals of one
|
|
133
|
+
file at the same moment can both succeed. `delete` does the same. It also removes files that
|
|
127
134
|
belong to no document (an upload that failed, a server that stopped while writing) and temporary files, once
|
|
128
135
|
they are `orphanAgeMs` old, one hour by default: a younger one may be an upload in progress on
|
|
129
|
-
another server.
|
|
136
|
+
another server. A temporary name of a document's metadata is also young for `orphanAgeMs` after
|
|
137
|
+
it was renamed (its ctime): it may be a delete's, under way on another server. In a folder that may hold files of yours too (`directory` without `scopes`), it
|
|
130
138
|
removes such a file only when its name is an ID the library makes, or a temporary file:
|
|
131
139
|
`notes.txt` may be yours, not the text of a document `notes`. A document whose metadata could not
|
|
132
140
|
be read at all is left alone, whatever its age. One that cannot be removed is left for the next
|
|
@@ -912,6 +920,41 @@ What the library does with what you throw depends on the call:
|
|
|
912
920
|
- **`putIndex` on a later read**: an error is ignored. The index is used from memory, and built again
|
|
913
921
|
the next time.
|
|
914
922
|
|
|
923
|
+
### Time limits
|
|
924
|
+
|
|
925
|
+
Since 0.10.0 the library gives each call of your store a time limit, `storeTimeoutMs` of
|
|
926
|
+
[`LargeFilesOptions`](../reference/library.md#largefilesoptions), 30 seconds by default: `getMeta`,
|
|
927
|
+
`get`, `readTextRange`, `getIndex`, `putIndex` on a later read, `getOriginal` (the reading of the
|
|
928
|
+
bytes as well as the call), and `delete`. A call that does not settle within it is given up on: the
|
|
929
|
+
library throws a `DocumentStoreError` of code `"ETIMEDOUT"` (503, retryable), and a question in a
|
|
930
|
+
tool call ends with `run.error`. Before, a call that never settled held the question forever.
|
|
931
|
+
|
|
932
|
+
- **The call itself is not stopped.** The library cannot cancel your promise, and does not pass a
|
|
933
|
+
signal to your store. Give your client a time limit of its own (a driver's socket or operation
|
|
934
|
+
timeout, an `AbortSignal.timeout` on a `fetch`), shorter than `storeTimeoutMs`, so that a call
|
|
935
|
+
that is given up on also ends.
|
|
936
|
+
- **A call past the limit counts as stuck until it settles**, in the process
|
|
937
|
+
(`files.stats().stuckStoreCalls`). While `maxStuckStoreCalls` calls are stuck (half of
|
|
938
|
+
`UV_THREADPOOL_SIZE`, 2 by default), every new call of the library fails at once with code
|
|
939
|
+
`"STORE_STUCK"`, without calling your store. It matters most for stores on the file system, whose
|
|
940
|
+
calls hold threads of libuv's pool: see [Deployment](./deployment.md#a-store-that-stops-answering).
|
|
941
|
+
- **A caller's signal ends only its own wait** (`AccessOptions.signal`, `askWithFiles`' `signal`).
|
|
942
|
+
One opening of a document serves every caller of its scope, so a call that others wait on goes on
|
|
943
|
+
when one of them leaves.
|
|
944
|
+
- **A saved index that does not answer in time is not built again.** The opening of a document
|
|
945
|
+
read by range fails with `"ETIMEDOUT"`, as any call does; it does not read the whole text from the
|
|
946
|
+
same store to build the index, as it does for an index that is missing or broken.
|
|
947
|
+
- **`delete` runs one at a time** in a library: a delete waits for the one before it to settle. A
|
|
948
|
+
delete ends within `storeTimeoutMs` in all: its look-up, its turn and your store's `delete`
|
|
949
|
+
share it.
|
|
950
|
+
- **`ingest`** keeps its own limits: its writes, and its look-ups of an application's ID, end within
|
|
951
|
+
`ingestTimeoutMs` (2 minutes when it is 0), as before. Past them they count as stuck too, and
|
|
952
|
+
while too many calls are stuck an ingest fails at its first store call with `"STORE_STUCK"`.
|
|
953
|
+
**`sweep`** has `sweepTimeoutMs`, no limit by default, and never counts as stuck.
|
|
954
|
+
- Keep `storeTimeoutMs` above your slowest healthy call: a `get` of the largest text loaded whole
|
|
955
|
+
(`wholeDocumentBytes`, 2 MB by default), or a `getOriginal` of the largest original, at the store's
|
|
956
|
+
busiest. 0 sets no limit.
|
|
957
|
+
|
|
915
958
|
### Concurrency and several servers
|
|
916
959
|
|
|
917
960
|
- Every method may run many times at once, for the same document too. Many users ask at once, the
|
package/docs/guides/testing.md
CHANGED
|
@@ -1134,6 +1134,77 @@ The credentials are the application default credentials, as on your servers: see
|
|
|
1134
1134
|
[Gemini and Vertex AI](./vertex-and-gemini.md). For another provider, swap the adapter:
|
|
1135
1135
|
[OpenAI-compatible endpoints](./openai-compatible.md), [Claude](./anthropic.md).
|
|
1136
1136
|
|
|
1137
|
+
## The library's own evals
|
|
1138
|
+
|
|
1139
|
+
The repository has an eval suite in `evals/`: about 50 Hebrew and English questions over synthetic
|
|
1140
|
+
files (a Hebrew policy in Word, a budget workbook with two header rows, a windows-1255 CSV of 3,000
|
|
1141
|
+
rows, a deck, a 3 MB service log, a shift diary, Hebrew PDFs, a contract), each with the facts its
|
|
1142
|
+
answer must hold. It is how the library checks that a change to what it sends a model keeps the
|
|
1143
|
+
answers right. It is not part of the package. To run it, clone the repository and `npm install`:
|
|
1144
|
+
|
|
1145
|
+
```bash
|
|
1146
|
+
npm run eval:replay # every case from its recording: no network, no key
|
|
1147
|
+
npm run eval:recheck # the facts checked again on the recorded answers
|
|
1148
|
+
GEMINI_API_KEY=… npm run eval:record # each case once against the Gemini API, recorded
|
|
1149
|
+
GEMINI_API_KEY=… npm run eval:live -- --k 3
|
|
1150
|
+
```
|
|
1151
|
+
|
|
1152
|
+
- **Replay** answers each request from `evals/cassettes`, and checks the facts again on the
|
|
1153
|
+
recorded answers. CI runs it on every pull request. A request that changed fails with
|
|
1154
|
+
"prompt changed: re-record", with the case, the request and the first field that differs (the
|
|
1155
|
+
method, the URL, or a field of the body). A fact that held when recorded must hold again. A case
|
|
1156
|
+
that asks for a whole-file read must have made one when it was recorded, so its part, merge and
|
|
1157
|
+
final requests are in its cassette and a change to those prompts fails too.
|
|
1158
|
+
- **Recheck** is a replay that writes each case's facts, checked on its recorded answer, to the
|
|
1159
|
+
cassette. Run it after you change a fact and no request: a replay whose facts changed since the
|
|
1160
|
+
recording fails with "facts changed" until you do.
|
|
1161
|
+
- **Record** runs each case once on each model (Gemini 3.5 Flash-Lite and 3.8 Flash by default), and
|
|
1162
|
+
writes its cassette: each request as a hash with an outline of its fields, and the response. A
|
|
1163
|
+
cassette holds no request text and no project ID. Request headers are written from a short list
|
|
1164
|
+
(content-type, accept, anthropic-version, anthropic-beta); every other header value, and every
|
|
1165
|
+
URL parameter but `alt` and `api-version`, is written as `<redacted>`.
|
|
1166
|
+
- **Live** runs each case k times. A case passes only when every run passes (pass^k): a real model
|
|
1167
|
+
answers a little differently each time. A workflow of the repository runs it every week and on
|
|
1168
|
+
demand, once the repository has the `GEMINI_API_KEY` secret; until then it skips with a notice.
|
|
1169
|
+
|
|
1170
|
+
Record and live fail a case when a question ends with an error (a refused key, a quota), when a case
|
|
1171
|
+
not known to fail on 0.9.0 misses pass^k, or when a fact that held in every run of the baseline
|
|
1172
|
+
fails now. Each writes a report, `evals/results/<mode>.md`, with the runs as JSON beside it
|
|
1173
|
+
(`<mode>.json`, answers included). A replay or a recheck writes one only when given `--results`.
|
|
1174
|
+
The report gives, for each case and model, whether it passed, the requests (mean and median), the
|
|
1175
|
+
share of questions answered in one request, reads and whole reads per question, input tokens, the
|
|
1176
|
+
cached share, latency, whether the question's input-token ceiling was reached, and the line
|
|
1177
|
+
citations checked per answer. For each model it figures the release gates: counts right, Hebrew
|
|
1178
|
+
lookups right, Hebrew answered in Hebrew, citations inside what the tools showed, the requests of
|
|
1179
|
+
inline-table questions, and the facts lost against the baseline, which it lists. The baseline is
|
|
1180
|
+
the report of 0.9.0, `evals/baseline/0.9.0.md` (runs in `0.9.0.json`). Its answers are kept, so its
|
|
1181
|
+
facts are checked again as the cases say now.
|
|
1182
|
+
|
|
1183
|
+
| Option | What it does |
|
|
1184
|
+
| --- | --- |
|
|
1185
|
+
| `--k 3` | Runs of each case, live. |
|
|
1186
|
+
| `--models a,b` | The Gemini models. |
|
|
1187
|
+
| `--cases id,id` | Only these cases (their IDs are in `evals/cases.ts`). |
|
|
1188
|
+
| `--results file.json` | Adds the runs to this file, and writes its report beside it. |
|
|
1189
|
+
| `--title "…"` | The title of the report. |
|
|
1190
|
+
| `--notes notes.md` | Markdown put under the report's title. |
|
|
1191
|
+
| `--baseline file.json` | The results to compare facts with (`evals/baseline/0.9.0.json` by default; `none` for no comparison). |
|
|
1192
|
+
| `--max-input-tokens N` | No question starts once the run has used this many input tokens. |
|
|
1193
|
+
| `--question-input-tokens N` | A question that uses more is stopped (1,500,000 by default). |
|
|
1194
|
+
| `--concurrency N` | Cases run at once (4 against the API, 1 in a replay, by default: a replay runs the cases in the order they were recorded, as a model's part reads learn its output limit once in a process). |
|
|
1195
|
+
|
|
1196
|
+
`node evals/cli.mjs report --results file.json` writes the report of a results file again.
|
|
1197
|
+
|
|
1198
|
+
A fact is a number (to a tolerance, and next to its label when the value belongs to one row), a
|
|
1199
|
+
text the answer must say or must not say, a line the answer must cite, or the language: a Hebrew
|
|
1200
|
+
question is answered with at least 60% Hebrew letters, once citations, file names, numbers, code,
|
|
1201
|
+
identifiers, names and Latin glosses are left out. Facts read the answer without its markdown
|
|
1202
|
+
emphasis.
|
|
1203
|
+
|
|
1204
|
+
The record and replay under it is internal to `evals/` for now. It becomes public in
|
|
1205
|
+
`llm-large-files/testing` in 0.10.x, for recording the questions of your own app the same way;
|
|
1206
|
+
until then, [Recorded replies](#recorded-replies) shows a small version to copy.
|
|
1207
|
+
|
|
1137
1208
|
## Reference
|
|
1138
1209
|
|
|
1139
1210
|
- `fakeModel`, `says`, `calls`, `httpError`, `fakeFetch`, `sse`, `utf8`, `serviceLog` and
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
# Gemini API and Vertex AI
|
|
2
2
|
|
|
3
3
|
This guide sets up Gemini for production, on Vertex AI or on the Gemini API: endpoints and access
|
|
4
|
-
tokens, `askGemini` or `askWithFiles` with `gemini()`,
|
|
5
|
-
|
|
6
|
-
errors. It is for developers who call Gemini from a server. Every export and option of
|
|
4
|
+
tokens, `askGemini` or `askWithFiles` with `gemini()`, fields of your own in the request (safety
|
|
5
|
+
settings, labels), the waits on a model that thinks, thinking, the budget, an explorer model,
|
|
6
|
+
whole-file reads, pages of PDFs, an enterprise gateway, quotas and errors. It is for developers who call Gemini from a server. Every export and option of
|
|
7
7
|
`llm-large-files/gemini` is listed in the [reference](../reference/gemini.md).
|
|
8
8
|
|
|
9
9
|
## Vertex AI or the Gemini API
|
|
@@ -14,8 +14,8 @@ headers differ.
|
|
|
14
14
|
|
|
15
15
|
| | `vertexAi()` | `geminiApi()` |
|
|
16
16
|
|---|---|---|
|
|
17
|
-
| Sign-in | An OAuth access token, sent as `Authorization: Bearer
|
|
18
|
-
| Host | The host of the `location` you pick, `"global"` by default | `https://generativelanguage.googleapis.com` (`baseUrl`) |
|
|
17
|
+
| Sign-in | An OAuth access token, sent as `Authorization: Bearer …`; or an API key of express mode (`apiKey`, since 0.10.0) | An API key, sent as the `x-goog-api-key` header |
|
|
18
|
+
| Host | The host of the `location` you pick, `"global"` by default, or one of your own (`host`) | `https://generativelanguage.googleapis.com` (`baseUrl`) |
|
|
19
19
|
| API version | `"v1"` (`apiVersion`) | `"v1beta"` (`apiVersion`) |
|
|
20
20
|
| Streaming | `streamUrl` is set (`:streamGenerateContent?alt=sse`) | The same |
|
|
21
21
|
| A second model that explores | `explorerModel` | `explorerModel` |
|
|
@@ -27,7 +27,7 @@ for prototypes and for tests.
|
|
|
27
27
|
|
|
28
28
|
### Vertex AI
|
|
29
29
|
|
|
30
|
-
`vertexAi({ project, model, accessToken, location?, apiVersion?, explorerModel? })` builds the URL
|
|
30
|
+
`vertexAi({ project, model, accessToken, location?, apiVersion?, explorerModel?, headers?, host? })` builds the URL
|
|
31
31
|
`{host}/{apiVersion}/projects/{project}/locations/{location}/publishers/google/models/{model}:generateContent`,
|
|
32
32
|
and the same with `:streamGenerateContent?alt=sse` for streaming. `location` defaults to
|
|
33
33
|
`"global"`. The host follows the location: see [`vertexHost()`](../reference/gemini.md#vertexhostlocation).
|
|
@@ -38,6 +38,36 @@ the location does not have is refused, and the error has `kind` `"invalid"`. Set
|
|
|
38
38
|
when you need another version of the API than `"v1"`. The library was checked live on Vertex AI in
|
|
39
39
|
the `global` and `eu` locations: see [Measurements](../measurements.md).
|
|
40
40
|
|
|
41
|
+
Three options are new in 0.10.0:
|
|
42
|
+
|
|
43
|
+
- **`headers`**: more headers, merged after the library's, so a name you give replaces the
|
|
44
|
+
library's (`x-goog-user-project` for the project that is billed, `x-server-timeout`). A function
|
|
45
|
+
is called before every request, with the same context as the token function (below).
|
|
46
|
+
- **`host`**: the https origin to send the requests to, in place of the host of the location: a
|
|
47
|
+
Private Service Connect endpoint, or a proxy that keeps Vertex AI's paths. It must be an origin
|
|
48
|
+
and nothing more (`"https://vertex.psc.example.internal"`, a port allowed): a path, a query, a
|
|
49
|
+
fragment or an `@` throws a `TypeError`, since the token would go to another host.
|
|
50
|
+
- **`apiKey`**: Vertex AI express mode. The key goes in the `x-goog-api-key` header, and the URL
|
|
51
|
+
names no project or location: `https://aiplatform.googleapis.com/v1/publishers/google/models/{model}:generateContent`.
|
|
52
|
+
Give `apiKey`, or `project` and `accessToken`, not both.
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { vertexAi } from "llm-large-files/gemini";
|
|
56
|
+
|
|
57
|
+
// accessToken as in Access tokens for Vertex AI below.
|
|
58
|
+
const privateEndpoint = vertexAi({
|
|
59
|
+
project: process.env.GOOGLE_CLOUD_PROJECT!,
|
|
60
|
+
location: "europe-west4",
|
|
61
|
+
model: "gemini-3.8-flash",
|
|
62
|
+
accessToken,
|
|
63
|
+
host: process.env.VERTEX_HOST!, // "https://…": where your network reaches Vertex AI
|
|
64
|
+
headers: { "x-goog-user-project": process.env.BILLING_PROJECT! },
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// Express mode: an API key, no project.
|
|
68
|
+
const express = vertexAi({ apiKey: process.env.VERTEX_API_KEY!, model: "gemini-3.8-flash" });
|
|
69
|
+
```
|
|
70
|
+
|
|
41
71
|
### Access tokens for Vertex AI
|
|
42
72
|
|
|
43
73
|
`accessToken` is a string, or a function that returns one. Give a function: the adapter calls it
|
|
@@ -63,9 +93,12 @@ import { vertexAi } from "llm-large-files/gemini";
|
|
|
63
93
|
const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
|
|
64
94
|
|
|
65
95
|
// Called before every request. GoogleAuth keeps the token and fetches a new one when it is about
|
|
66
|
-
// to expire, so the call is cheap.
|
|
67
|
-
|
|
68
|
-
|
|
96
|
+
// to expire, so the call is cheap. After a 401 it is called with { refresh: true }: the token in the
|
|
97
|
+
// cache was refused, so it is marked expired and a new one is fetched.
|
|
98
|
+
async function accessToken({ refresh }: { refresh: boolean }): Promise<string> {
|
|
99
|
+
const client = await auth.getClient();
|
|
100
|
+
if (refresh) client.setCredentials({ ...client.credentials, expiry_date: 1 });
|
|
101
|
+
const { token } = await client.getAccessToken();
|
|
69
102
|
if (!token) throw new Error("No access token from the application default credentials.");
|
|
70
103
|
return token;
|
|
71
104
|
}
|
|
@@ -86,8 +119,18 @@ const endpoint = vertexAi({
|
|
|
86
119
|
- **An error thrown by your function** has no HTTP status and no `kind`. In a chat request it ends
|
|
87
120
|
the question with that error: the request is not sent again. In a part read it is tried once
|
|
88
121
|
more, and the part is then reported as one that could not be read.
|
|
89
|
-
- **A token that is refused
|
|
90
|
-
|
|
122
|
+
- **A token that is refused with HTTP 401** is asked for again, since 0.10.0, when `accessToken` is
|
|
123
|
+
a function: the function is called with `{ refresh: true }`, and the request is sent once more
|
|
124
|
+
with the token it returns. A token provider such as `google-auth-library` returns the token in
|
|
125
|
+
its cache until it nears its expiry, so calling it the same way again would send the token that
|
|
126
|
+
was refused: force a new one when `refresh` is true, as the sample does. That sample works for
|
|
127
|
+
the clients that keep their token in `credentials`: a service account, the metadata server
|
|
128
|
+
(Cloud Run, GKE, Compute Engine) and user credentials. A second 401 is the error: there is no
|
|
129
|
+
third try. If the function throws when it is asked to refresh, the first 401 is the error (a
|
|
130
|
+
`GeminiRequestError` of kind `"auth"`), with what the function threw as its `cause`. A token
|
|
131
|
+
given as a string, an API key and a gateway's headers get no second try.
|
|
132
|
+
- **A token that is refused for good** (HTTP 401 twice, or 403: a missing role, the Vertex AI API
|
|
133
|
+
not enabled in the project) is a `GeminiRequestError` with `kind` `"auth"`. It is not sent again.
|
|
91
134
|
|
|
92
135
|
### The Gemini API
|
|
93
136
|
|
|
@@ -138,12 +181,17 @@ On top of `askWithFiles`, `askGemini` adds:
|
|
|
138
181
|
- `contents`: the history as Gemini `contents`, with images or inline PDFs, in place of `messages`
|
|
139
182
|
([below](#gemini-history-stored-as-contents)).
|
|
140
183
|
- `generationConfig` for the model that answers and `explorerGenerationConfig` for the explorer.
|
|
141
|
-
-
|
|
142
|
-
|
|
184
|
+
- `body` for the model that answers and `explorerBody` for the explorer (new in 0.10.0;
|
|
185
|
+
[below](#fields-of-your-own-safety-settings-labels-and-more)).
|
|
186
|
+
- One value of `toolFilePlacement`, `analysisConfig`, `analysisBody`, `functionCallingMode`,
|
|
187
|
+
`answerWithoutTools`, `timeoutMs`, `firstByteTimeoutMs`, `idleTimeoutMs` and `fetch`, given to
|
|
188
|
+
both models.
|
|
143
189
|
- `maxToolTurns` and `maxToolCallsPerTurn`, the names that `limits.toolTurns` and
|
|
144
190
|
`limits.callsPerTurn` had before 0.5.0. `limits` wins when both are set.
|
|
145
191
|
|
|
146
|
-
Every other option goes to `askWithFiles` as it is.
|
|
192
|
+
Every other option goes to `askWithFiles` as it is. Since 0.10.0 the type of `askGemini`'s options
|
|
193
|
+
is that of `askWithFiles`'s, with the models taken out and the options above added: an option new
|
|
194
|
+
in `askWithFiles` reaches the loop through `askGemini` too. What `askGemini` cannot do:
|
|
147
195
|
|
|
148
196
|
| You need | `askGemini` | `askWithFiles` with `gemini()` |
|
|
149
197
|
|---|---|---|
|
|
@@ -151,7 +199,7 @@ Every other option goes to `askWithFiles` as it is. What `askGemini` cannot do:
|
|
|
151
199
|
| The cost of a page, the name in `usage.byModel` | No: 530 tokens, the model in the URL | `pageTokens`, `id` |
|
|
152
200
|
| An explorer with other headers, or of another provider | No: the same headers (with `vertexAi()` or `geminiApi()`, the same project, location and key too) | `explorer`: any adapter |
|
|
153
201
|
| Different waits, `fetch` or `toolFilePlacement` for each model | No: one value for both | Each adapter its own |
|
|
154
|
-
| A part reader of your own
|
|
202
|
+
| A part reader of your own | No | Yes: an adapter whose `generateText` is yours |
|
|
155
203
|
|
|
156
204
|
Start with `askGemini`. Move to `askWithFiles` when you need a row of this table:
|
|
157
205
|
|
|
@@ -181,15 +229,24 @@ What the Gemini adapter does in either case:
|
|
|
181
229
|
answering model.
|
|
182
230
|
- **It never shows thoughts.** Parts that Gemini marks `"thought": true` are not in `text` and not
|
|
183
231
|
passed to `onText`.
|
|
184
|
-
- **The request that must be answered in text declares no tools
|
|
185
|
-
`functionCallingConfig` mode `NONE` and go on calling them.
|
|
232
|
+
- **The request that must be answered in text declares no tools**, by default. Gemini can ignore
|
|
233
|
+
`functionCallingConfig` mode `NONE` and go on calling them. `answerWithoutTools: "mode_none"`
|
|
234
|
+
(new in 0.10.0) keeps the tools and sends mode `NONE`, so that the request starts as the ones
|
|
235
|
+
before it did, which may let Vertex AI's prompt cache serve more of it; a tool call that still
|
|
236
|
+
comes back is asked for again once. "omit" stays the default until a live measure says otherwise.
|
|
186
237
|
- **A stream that ends without a `finishReason` was cut off** on its way (a proxy, a dropped
|
|
187
238
|
connection). It is sent again when none of its text was shown, and is an error otherwise.
|
|
188
|
-
- **A turn with `MALFORMED_FUNCTION_CALL
|
|
189
|
-
request for the answer included: there the
|
|
190
|
-
the answer in text.
|
|
191
|
-
|
|
192
|
-
|
|
239
|
+
- **A turn with `MALFORMED_FUNCTION_CALL`, `UNEXPECTED_TOOL_CALL` or (since 0.10.0)
|
|
240
|
+
`MALFORMED_RESPONSE`** is asked for once more, the request for the answer included: there the
|
|
241
|
+
note says that no tool can be called, and asks for the answer in text.
|
|
242
|
+
- **Finish reasons.** `SAFETY`, `RECITATION`, `BLOCKLIST`, `PROHIBITED_CONTENT`, `SPII`,
|
|
243
|
+
`IMAGE_SAFETY` and, since 0.10.0, `MODEL_ARMOR` (Vertex AI's Model Armor), `IMAGE_PROHIBITED_CONTENT`,
|
|
244
|
+
`IMAGE_RECITATION` and `IMAGE_OTHER` mark a reply that a filter stopped: `finish` `"filtered"`.
|
|
245
|
+
`MAX_TOKENS` marks one cut off at the output limit: `"cut"`. Since 0.10.0 `OTHER`,
|
|
246
|
+
`FINISH_REASON_UNSPECIFIED`, `NO_IMAGE`, `TOO_MANY_TOOL_CALLS`, `MISSING_THOUGHT_SIGNATURE` and
|
|
247
|
+
`LANGUAGE` are `"other"`: a reason that asking again does not mend. `LANGUAGE` (a language the
|
|
248
|
+
model does not take) is no safety filter: tell a Hebrew user so, not that a filter stopped the
|
|
249
|
+
answer. The provider's own word is always in `finishReason`.
|
|
193
250
|
|
|
194
251
|
**Usage.** `usage.byModel` is keyed by the model name in the URL (`"gemini-3.8-flash"`). Input
|
|
195
252
|
tokens are `promptTokenCount` plus `toolUsePromptTokenCount`, cached tokens `cachedContentTokenCount`,
|
|
@@ -197,6 +254,54 @@ and output tokens `candidatesTokenCount` plus `thoughtsTokenCount` (the thoughts
|
|
|
197
254
|
`thoughtTokens`). `lastUsage` is Gemini's own `usageMetadata` of the last response. Turning that into
|
|
198
255
|
a cost: [Costs and limits](./costs-and-limits.md).
|
|
199
256
|
|
|
257
|
+
## Fields of your own: safety settings, labels and more
|
|
258
|
+
|
|
259
|
+
`body` adds fields to the body of every chat request, the request for the answer included, and
|
|
260
|
+
`analysisBody` to each part read of a whole-file read. They are merged last, after the library's,
|
|
261
|
+
and are counted in the size of the request. New in 0.10.0, in the shape of the `body` and
|
|
262
|
+
`analysisBody` of the [OpenAI-compatible](./openai-compatible.md) and [Claude](./anthropic.md)
|
|
263
|
+
adapters.
|
|
264
|
+
|
|
265
|
+
```ts
|
|
266
|
+
import { askGemini, type GeminiRequestFields } from "llm-large-files/gemini";
|
|
267
|
+
|
|
268
|
+
// files, endpoint, documentIds and messages as in the askGemini sample above.
|
|
269
|
+
const body: GeminiRequestFields = {
|
|
270
|
+
safetySettings: [{ category: "HARM_CATEGORY_HARASSMENT", threshold: "BLOCK_ONLY_HIGH" }],
|
|
271
|
+
labels: { app: "chatbot", team: "hr" }, // Vertex AI: billing labels. No user IDs.
|
|
272
|
+
};
|
|
273
|
+
await askGemini({
|
|
274
|
+
files, endpoint, documentIds, messages,
|
|
275
|
+
body, // the answering model, and the explorer
|
|
276
|
+
explorerBody: { labels: { app: "chatbot", role: "explorer" } }, // the explorer, when it needs other fields
|
|
277
|
+
analysisBody: () => ({ labels: { app: "chatbot", role: "parts" } }), // part reads
|
|
278
|
+
functionCallingMode: "VALIDATED",
|
|
279
|
+
});
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
- **`GeminiRequestFields`** types `safetySettings`, `labels`, `serviceTier` and `cachedContent`, and
|
|
283
|
+
takes any other field of the API. The fields the library writes (`contents`,
|
|
284
|
+
`systemInstruction`, `tools`, `toolConfig`, `generationConfig`) are typed `never`, so setting one
|
|
285
|
+
fails to compile: `generationConfig` and `analysisConfig` set those. Nothing is refused at run
|
|
286
|
+
time.
|
|
287
|
+
- **Labels reach the billing export** of the project, and everyone who reads it. Keys and values
|
|
288
|
+
are lower case, at most 63 characters. Never put a user ID, an email or other personal data in
|
|
289
|
+
them: label by app, team or feature. The Gemini API does not take labels.
|
|
290
|
+
- **A reply a safety setting stops** has `finish` `"filtered"`, as one stopped by Gemini's own
|
|
291
|
+
filters.
|
|
292
|
+
- **`cachedContent`** names an explicit context cache (`cachedContents/…`) that you made with the
|
|
293
|
+
API. The library makes none: Gemini 3 caches the start of a request by itself (implicit caching),
|
|
294
|
+
and the library keeps that start the same from one request to the next. A request that uses a
|
|
295
|
+
cache may not set `systemInstruction`, `tools` or `toolConfig`: they must be in the cache
|
|
296
|
+
([Vertex AI](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-use)).
|
|
297
|
+
The requests of `askGemini` and `askWithFiles` send the system text in every request (part reads
|
|
298
|
+
included), and tools in the requests that offer them, so `cachedContent` does not fit them. It
|
|
299
|
+
fits only a loop of your own with `gemini()` whose requests have no `system` and no tools.
|
|
300
|
+
- **`functionCallingMode: "VALIDATED"`** has Gemini check each call against the declaration of its
|
|
301
|
+
tool. It is sent only in a request that offers tools; `"AUTO"` is the default.
|
|
302
|
+
- **`body` changes the bytes of every request**, so the first request after you set it or change it
|
|
303
|
+
misses the prompt cache once.
|
|
304
|
+
|
|
200
305
|
## Waits: a model that thinks sends nothing
|
|
201
306
|
|
|
202
307
|
A chat request has two waits. `firstByteTimeoutMs` (600,000 ms, ten minutes) is the longest wait for
|
|
@@ -237,7 +342,7 @@ What this means for your server:
|
|
|
237
342
|
- **Keep the waits below the request timeout of what stands in front of your server**, or raise
|
|
238
343
|
that timeout: a load balancer, a proxy, Cloud Run. Keep the stream to the browser alive while the
|
|
239
344
|
model is silent: [Web app](./web-app.md) and [Deployment](./deployment.md).
|
|
240
|
-
- **Part reads have a limit of their own**, 180 s a request: [below](#whole-file-reads-in-parts).
|
|
345
|
+
- **Part reads have a limit of their own**, `timeoutMs` (180 s a request): [below](#whole-file-reads-in-parts).
|
|
241
346
|
|
|
242
347
|
## Thinking
|
|
243
348
|
|
|
@@ -363,30 +468,25 @@ await askWithFiles({
|
|
|
363
468
|
|
|
364
469
|
`analyze_whole_document` reads a file in parts, four at a time, and writes one answer from the
|
|
365
470
|
notes. `gemini()` reads the parts with `createGeminiGenerateText`: on the endpoint's `url` (not
|
|
366
|
-
streamed), with its headers (asked for before each request
|
|
367
|
-
`
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
471
|
+
streamed), with its headers (asked for before each request, and once more with `{ refresh: true }`
|
|
472
|
+
after a 401 on a `vertexAi()` endpoint with a token function), the adapter's `fetch`,
|
|
473
|
+
`analysisConfig` and `analysisBody`. The parts follow the question's `retry`, as chat requests do.
|
|
474
|
+
A part whose reply of HTTP 200 holds an error (a gateway, or Vertex AI) throws that error with its
|
|
475
|
+
status since 0.10.0, so a 503 is tried again; before, it was "The model returned no text".
|
|
476
|
+
|
|
477
|
+
Each part read may take `timeoutMs`: 180,000 ms by default, its whole reply included. That is a
|
|
478
|
+
limit of its own, not the waits above. A part past it is a `GeminiRequestError` of kind
|
|
479
|
+
`"timeout"` and status 0: it is tried once more, after the retry wait (`retry.baseDelayMs`: 250 to
|
|
480
|
+
500 ms by default) and with a `retry` event, and is then reported in the answer of the read
|
|
481
|
+
as "The model took too long to answer". Set `timeoutMs` on `gemini()` or `askGemini` (both
|
|
482
|
+
models get it); 0 sets none. New in 0.10.0: before, the limit could be changed only by replacing
|
|
483
|
+
the adapter's part reader, and a part past it came as the abort error of the timer.
|
|
373
484
|
|
|
374
485
|
```ts
|
|
375
|
-
import
|
|
376
|
-
import { createGeminiGenerateText, gemini, vertexAi } from "llm-large-files/gemini";
|
|
486
|
+
import { askGemini } from "llm-large-files/gemini";
|
|
377
487
|
|
|
378
|
-
//
|
|
379
|
-
|
|
380
|
-
const reader: ModelAdapter = {
|
|
381
|
-
...gemini(readerEndpoint),
|
|
382
|
-
generateText: createGeminiGenerateText({
|
|
383
|
-
url: readerEndpoint.url,
|
|
384
|
-
headers: readerEndpoint.headers,
|
|
385
|
-
timeoutMs: 300_000, // five minutes for each part read
|
|
386
|
-
generationConfig: (maxOutputTokens) => ({ maxOutputTokens }), // the default: no temperature
|
|
387
|
-
}),
|
|
388
|
-
};
|
|
389
|
-
// Give it as `explorer` (it reads the parts when there is one), or as `model` when it works alone.
|
|
488
|
+
// files, endpoint, documentIds and messages as in the askGemini sample above.
|
|
489
|
+
await askGemini({ files, endpoint, documentIds, messages, timeoutMs: 300_000 }); // five minutes a part
|
|
390
490
|
```
|
|
391
491
|
|
|
392
492
|
A part that Gemini refuses as larger than it takes is read as two halves, while `maxMapChunks` and
|
|
@@ -457,8 +557,10 @@ const endpoint: GeminiEndpoint = {
|
|
|
457
557
|
URL has none. With `askWithFiles`, name it with `gemini(endpoint, { id })`.
|
|
458
558
|
- **A body limit** of the gateway goes in `maxRequestBytes` ([above](#the-window-and-the-budget)).
|
|
459
559
|
|
|
460
|
-
|
|
461
|
-
|
|
560
|
+
A private endpoint of your network that keeps Vertex AI's paths needs no endpoint of your own
|
|
561
|
+
since 0.10.0: give its origin as `vertexAi({ host })` ([above](#vertex-ai)), and the token keeps its
|
|
562
|
+
second try after a 401. An endpoint of your own gets that try too when its `headers` function
|
|
563
|
+
takes `{ refresh }` and it says `refreshable: true`:
|
|
462
564
|
|
|
463
565
|
```ts
|
|
464
566
|
import type { GeminiEndpoint } from "llm-large-files/gemini";
|
|
@@ -469,7 +571,8 @@ const path = `/v1/projects/${process.env.GOOGLE_CLOUD_PROJECT}/locations/europe-
|
|
|
469
571
|
const privateEndpoint: GeminiEndpoint = {
|
|
470
572
|
url: `${host}${path}:generateContent`,
|
|
471
573
|
streamUrl: `${host}${path}:streamGenerateContent?alt=sse`,
|
|
472
|
-
headers: async () => ({ "Content-Type": "application/json", Authorization: `Bearer ${await accessToken()}` }),
|
|
574
|
+
headers: async (context) => ({ "Content-Type": "application/json", Authorization: `Bearer ${await accessToken({ refresh: context?.refresh === true })}` }),
|
|
575
|
+
refreshable: true,
|
|
473
576
|
};
|
|
474
577
|
```
|
|
475
578
|
|
|
@@ -552,14 +655,16 @@ not an overflow.
|
|
|
552
655
|
|
|
553
656
|
| What happened | `status` | `kind` | Sent again |
|
|
554
657
|
|---|---|---|---|
|
|
555
|
-
| The token was refused: expired, a missing role, the API not enabled | 401, 403 | `"auth"` |
|
|
658
|
+
| The token was refused: expired, a missing role, the API not enabled | 401, 403 | `"auth"` | A 401 once, with a new token, when `accessToken` is a function (since 0.10.0); otherwise no |
|
|
556
659
|
| An API key of the Gemini API that is not valid (`API_KEY_INVALID`) | 400 | `"auth"` | No |
|
|
557
660
|
| A setting the model does not take, a model the location does not have, another refusal | 400, 404, and any other 4xx not in this table | `"invalid"` | No |
|
|
558
661
|
| The provider or a gateway timed out | 408 | `"timeout"` | Yes |
|
|
559
662
|
| A conflict | 409 | `"invalid"` | Yes |
|
|
560
663
|
| A gateway refused the body as too large | 413 | `"context_overflow"` | Made smaller, as in [A request too large](#a-request-too-large) |
|
|
561
664
|
| Gemini failed on its side | 5xx | `"server"` | Yes |
|
|
665
|
+
| An error inside a stream, or in a body of HTTP 200, without a numeric code | The status of its `google.rpc` name: `"UNAVAILABLE"` 503, `"RESOURCE_EXHAUSTED"` 429, `"DEADLINE_EXCEEDED"` 504, `"INVALID_ARGUMENT"` 400 …; 500 for a name it does not know. Before 0.10.0, 200. | By the status | Yes for 429 and 5xx, unless text was shown; a daily quota is `"quota"`, and is not |
|
|
562
666
|
| Nothing came for `firstByteTimeoutMs` or `idleTimeoutMs` | 0 | `"timeout"` | Once |
|
|
667
|
+
| A part read took longer than `timeoutMs` | 0 | `"timeout"` | Once (since 0.10.0) |
|
|
563
668
|
| The connection failed, or a stream ended before its `finishReason` | 0 | `"unreachable"` | Yes, unless text was shown |
|
|
564
669
|
| A reply of HTTP 200 whose body is empty | 0 | `"unreachable"` | Yes |
|
|
565
670
|
| A reply of HTTP 200 whose body is not JSON (a gateway's page) | 200 | `"invalid"` | No |
|
|
@@ -623,8 +728,11 @@ import { askGemini, vertexAi } from "llm-large-files/gemini";
|
|
|
623
728
|
|
|
624
729
|
const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
|
|
625
730
|
|
|
626
|
-
|
|
627
|
-
|
|
731
|
+
// After a 401, { refresh: true }: the token in the cache was refused, and a new one is fetched.
|
|
732
|
+
async function accessToken({ refresh }: { refresh: boolean }): Promise<string> {
|
|
733
|
+
const client = await auth.getClient();
|
|
734
|
+
if (refresh) client.setCredentials({ ...client.credentials, expiry_date: 1 });
|
|
735
|
+
const { token } = await client.getAccessToken();
|
|
628
736
|
if (!token) throw new Error("No access token from the application default credentials.");
|
|
629
737
|
return token;
|
|
630
738
|
}
|
|
@@ -666,6 +774,7 @@ export async function answer(question: {
|
|
|
666
774
|
system: "You are our support assistant. Cite the lines you used.",
|
|
667
775
|
generationConfig: { temperature: 0.3, thinkingConfig: { thinkingLevel: "high" } }, // the answering model
|
|
668
776
|
explorerGenerationConfig: { temperature: 0.2 }, // the explorer
|
|
777
|
+
body: { labels: { app: "support-assistant" } }, // billing labels: no user IDs
|
|
669
778
|
limits: { toolTurns: 12, inputTokens: 2_000_000, requests: 40 },
|
|
670
779
|
retry: { retries: 5, baseDelayMs: 2_000 },
|
|
671
780
|
signal,
|
package/docs/guides/web-app.md
CHANGED
|
@@ -337,7 +337,8 @@ export const documents = createDocumentHandlers(files, {
|
|
|
337
337
|
- **It stays once the document is stored,** and `onUploaded` is told its `path`. **It is removed
|
|
338
338
|
when the upload fails**, whatever the reason: too large, a body that stops, a browser that leaves
|
|
339
339
|
before the ingest ends, a full disk (`503` with `Retry-After`), a disk that does not answer within
|
|
340
|
-
`uploadIdleTimeoutMs` (`
|
|
340
|
+
`uploadIdleTimeoutMs` (`503` "Upload failed (ETIMEDOUT)." with `Retry-After: 5`, a `500` before
|
|
341
|
+
0.10.0), a file that cannot be read, an ID
|
|
341
342
|
that is taken, or `onUploaded` throwing. A server that is killed in the middle of an upload
|
|
342
343
|
cannot remove it, and nothing else does: remove such files with a job of your own
|
|
343
344
|
([Deployment](./deployment.md#stopping-a-server)).
|
|
@@ -367,7 +368,8 @@ const documents = createDocumentHandlers(files, {
|
|
|
367
368
|
removed once the ingest ends, whatever the end. `onUploaded` runs after, without a path.
|
|
368
369
|
- **Room.** `maxSpooledUploadBytes` (ten times `maxUploadBytes`) bounds the spool's files at once:
|
|
369
370
|
past it, and on a full disk, the upload gets `503` with `Retry-After`. A disk that does not answer
|
|
370
|
-
within `uploadIdleTimeoutMs` gets `
|
|
371
|
+
within `uploadIdleTimeoutMs` gets `503` "Upload failed (ETIMEDOUT)." with `Retry-After: 5` (a
|
|
372
|
+
`500` before 0.10.0), and gives the room back.
|
|
371
373
|
`maxPendingUploadBytes` then counts only the bodies held in memory, so several uploads sent
|
|
372
374
|
without a `Content-Length` no longer fill it.
|
|
373
375
|
- **Where.** On a disk, not a memory-backed folder, which would take the memory back
|
|
@@ -422,8 +424,8 @@ a body another middleware already parsed, `401` "Sign in first." under `requireO
|
|
|
422
424
|
chat no longer exists." for a chat whose folder is gone, `413` over `maxUploadBytes`, `422` for a
|
|
423
425
|
file that cannot be read, `409` "A file is already saved for this upload." when a file is already at the
|
|
424
426
|
path of `prepareUpload`, `503` with `Retry-After` when the server holds as many uploads as it
|
|
425
|
-
takes at once, its readers are busy, its disk is full
|
|
426
|
-
after `Retry-After` seconds), `408` for a body that stopped arriving, an error's own status (400 to 599) from
|
|
427
|
+
takes at once, its readers are busy, its disk is full or does not answer, or the store failed
|
|
428
|
+
(send the file again after `Retry-After` seconds), `408` for a body that stopped arriving, an error's own status (400 to 599) from
|
|
427
429
|
`getOwner`, `getScope`, `prepareUpload`, `onUploaded` or an extractor, and `500` for a failure of the server, among
|
|
428
430
|
them `Upload failed (empty owner).`, `Upload failed (owner is not a string).`,
|
|
429
431
|
`Upload failed (invalid scope).` and `Upload failed.`. `get` answers `404` for a document this owner
|
|
@@ -912,8 +914,10 @@ What to know about the stream:
|
|
|
912
914
|
[when the text streams](#when-the-text-streams).
|
|
913
915
|
- **The callbacks still work.** Pass `onText`, `onActivity` and `onStep` too, and they get what they
|
|
914
916
|
always did. Each `notice` event says where its message went in the callbacks (`display`).
|
|
915
|
-
- **Evidence names its call.** Each entry of `result.evidence`
|
|
916
|
-
whose `tool.end` carries the same entry. A list of sources can
|
|
917
|
+
- **Evidence names its call.** Each entry of `result.evidence` that a tool call made has a
|
|
918
|
+
`callId` ("call_3"): the call whose `tool.end` carries the same entry. A list of sources can
|
|
919
|
+
point back to the list of tools. Since 0.10.0 the list starts with the files sent whole
|
|
920
|
+
(`tool: "inline"`), which have no `callId`: skip them when you look for the call.
|
|
917
921
|
- **A listener that throws ends the question** with that error, as a callback that throws always
|
|
918
922
|
did. `askStream` gives each event to the stream before your own `onEvent`, so the stream still
|
|
919
923
|
gets the last one. Changed in 0.7.0: a throw from `onActivity` or `onEvent` while a whole-file
|