llm-large-files 0.8.2 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +981 -0
- package/README.md +22 -17
- package/dist/access.d.ts +128 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +234 -0
- package/dist/access.js.map +1 -0
- 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 +159 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +743 -113
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.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/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +70 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +253 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +74 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +104 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +57 -13
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +35 -5
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +52 -36
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +54 -7
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +152 -41
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +38 -53
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -25
- 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 +4 -4
- 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 +13 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -5
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +78 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +893 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +295 -33
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +458 -650
- 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 +807 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +79 -6
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +80 -4
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +247 -14
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +491 -227
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +19 -4
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +106 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +378 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +6 -4
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +9 -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-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.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 +16 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +56 -12
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- 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/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +126 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +655 -141
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +47 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +440 -71
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +165 -14
- 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 +21 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +17 -10
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +147 -42
- package/docs/guides/deployment.md +380 -86
- package/docs/guides/errors-and-reliability.md +317 -67
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +60 -16
- package/docs/guides/pdfs.md +219 -36
- package/docs/guides/storage.md +676 -145
- package/docs/guides/testing.md +149 -129
- package/docs/guides/vertex-and-gemini.md +169 -57
- package/docs/guides/web-app.md +318 -80
- package/docs/how-it-works.md +155 -30
- package/docs/measurements.md +215 -13
- package/docs/publishing.md +185 -37
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +415 -47
- package/docs/reference/errors-and-retries.md +194 -14
- package/docs/reference/events.md +77 -27
- package/docs/reference/gemini.md +252 -87
- package/docs/reference/library.md +886 -178
- package/docs/reference/node.md +659 -111
- package/docs/reference/openai.md +21 -10
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +285 -30
- package/docs/security.md +404 -78
- package/docs/troubleshooting.md +151 -70
- package/docs/upgrading-0.10.md +472 -0
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +16 -3
- package/src/access.ts +267 -0
- 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 +866 -115
- package/src/cache.ts +20 -5
- package/src/citations.ts +294 -0
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +290 -0
- package/src/errors.ts +131 -15
- package/src/events.ts +112 -24
- package/src/evidence.ts +35 -5
- package/src/extract.ts +56 -34
- package/src/gemini/adapter.ts +196 -43
- package/src/gemini/chat.ts +63 -78
- 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 +4 -4
- package/src/http.ts +65 -4
- package/src/index.ts +13 -8
- package/src/ingest.ts +958 -0
- package/src/library.ts +711 -651
- package/src/map-reduce.ts +858 -70
- package/src/model.ts +113 -9
- package/src/node/handlers.ts +709 -221
- package/src/node/index.ts +14 -2
- package/src/node/ingest-child.ts +24 -6
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +379 -0
- package/src/node/sse.ts +9 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-layout.ts +69 -11
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +48 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/search.ts +69 -13
- package/src/source.ts +178 -0
- package/src/stores.ts +702 -142
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +461 -73
- package/src/types.ts +151 -14
- package/src/whole-cost.ts +64 -0
|
@@ -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,8 +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
|
|
155
|
-
| Turns with native parts in `messages` | Use `contents` | `{ role, parts: [{ text }, { native }] }` |
|
|
202
|
+
| A part reader of your own | No | Yes: an adapter whose `generateText` is yours |
|
|
156
203
|
|
|
157
204
|
Start with `askGemini`. Move to `askWithFiles` when you need a row of this table:
|
|
158
205
|
|
|
@@ -182,15 +229,24 @@ What the Gemini adapter does in either case:
|
|
|
182
229
|
answering model.
|
|
183
230
|
- **It never shows thoughts.** Parts that Gemini marks `"thought": true` are not in `text` and not
|
|
184
231
|
passed to `onText`.
|
|
185
|
-
- **The request that must be answered in text declares no tools
|
|
186
|
-
`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.
|
|
187
237
|
- **A stream that ends without a `finishReason` was cut off** on its way (a proxy, a dropped
|
|
188
238
|
connection). It is sent again when none of its text was shown, and is an error otherwise.
|
|
189
|
-
- **A turn with `MALFORMED_FUNCTION_CALL
|
|
190
|
-
request for the answer included: there the
|
|
191
|
-
the answer in text.
|
|
192
|
-
|
|
193
|
-
|
|
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`.
|
|
194
250
|
|
|
195
251
|
**Usage.** `usage.byModel` is keyed by the model name in the URL (`"gemini-3.8-flash"`). Input
|
|
196
252
|
tokens are `promptTokenCount` plus `toolUsePromptTokenCount`, cached tokens `cachedContentTokenCount`,
|
|
@@ -198,6 +254,54 @@ and output tokens `candidatesTokenCount` plus `thoughtsTokenCount` (the thoughts
|
|
|
198
254
|
`thoughtTokens`). `lastUsage` is Gemini's own `usageMetadata` of the last response. Turning that into
|
|
199
255
|
a cost: [Costs and limits](./costs-and-limits.md).
|
|
200
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
|
+
|
|
201
305
|
## Waits: a model that thinks sends nothing
|
|
202
306
|
|
|
203
307
|
A chat request has two waits. `firstByteTimeoutMs` (600,000 ms, ten minutes) is the longest wait for
|
|
@@ -238,7 +342,7 @@ What this means for your server:
|
|
|
238
342
|
- **Keep the waits below the request timeout of what stands in front of your server**, or raise
|
|
239
343
|
that timeout: a load balancer, a proxy, Cloud Run. Keep the stream to the browser alive while the
|
|
240
344
|
model is silent: [Web app](./web-app.md) and [Deployment](./deployment.md).
|
|
241
|
-
- **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).
|
|
242
346
|
|
|
243
347
|
## Thinking
|
|
244
348
|
|
|
@@ -364,30 +468,25 @@ await askWithFiles({
|
|
|
364
468
|
|
|
365
469
|
`analyze_whole_document` reads a file in parts, four at a time, and writes one answer from the
|
|
366
470
|
notes. `gemini()` reads the parts with `createGeminiGenerateText`: on the endpoint's `url` (not
|
|
367
|
-
streamed), with its headers (asked for before each request
|
|
368
|
-
`
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
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.
|
|
374
484
|
|
|
375
485
|
```ts
|
|
376
|
-
import
|
|
377
|
-
import { createGeminiGenerateText, gemini, vertexAi } from "llm-large-files/gemini";
|
|
486
|
+
import { askGemini } from "llm-large-files/gemini";
|
|
378
487
|
|
|
379
|
-
//
|
|
380
|
-
|
|
381
|
-
const reader: ModelAdapter = {
|
|
382
|
-
...gemini(readerEndpoint),
|
|
383
|
-
generateText: createGeminiGenerateText({
|
|
384
|
-
url: readerEndpoint.url,
|
|
385
|
-
headers: readerEndpoint.headers,
|
|
386
|
-
timeoutMs: 300_000, // five minutes for each part read
|
|
387
|
-
generationConfig: (maxOutputTokens) => ({ maxOutputTokens }), // the default: no temperature
|
|
388
|
-
}),
|
|
389
|
-
};
|
|
390
|
-
// 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
|
|
391
490
|
```
|
|
392
491
|
|
|
393
492
|
A part that Gemini refuses as larger than it takes is read as two halves, while `maxMapChunks` and
|
|
@@ -458,8 +557,10 @@ const endpoint: GeminiEndpoint = {
|
|
|
458
557
|
URL has none. With `askWithFiles`, name it with `gemini(endpoint, { id })`.
|
|
459
558
|
- **A body limit** of the gateway goes in `maxRequestBytes` ([above](#the-window-and-the-budget)).
|
|
460
559
|
|
|
461
|
-
|
|
462
|
-
|
|
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`:
|
|
463
564
|
|
|
464
565
|
```ts
|
|
465
566
|
import type { GeminiEndpoint } from "llm-large-files/gemini";
|
|
@@ -470,7 +571,8 @@ const path = `/v1/projects/${process.env.GOOGLE_CLOUD_PROJECT}/locations/europe-
|
|
|
470
571
|
const privateEndpoint: GeminiEndpoint = {
|
|
471
572
|
url: `${host}${path}:generateContent`,
|
|
472
573
|
streamUrl: `${host}${path}:streamGenerateContent?alt=sse`,
|
|
473
|
-
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,
|
|
474
576
|
};
|
|
475
577
|
```
|
|
476
578
|
|
|
@@ -553,14 +655,16 @@ not an overflow.
|
|
|
553
655
|
|
|
554
656
|
| What happened | `status` | `kind` | Sent again |
|
|
555
657
|
|---|---|---|---|
|
|
556
|
-
| 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 |
|
|
557
659
|
| An API key of the Gemini API that is not valid (`API_KEY_INVALID`) | 400 | `"auth"` | No |
|
|
558
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 |
|
|
559
661
|
| The provider or a gateway timed out | 408 | `"timeout"` | Yes |
|
|
560
662
|
| A conflict | 409 | `"invalid"` | Yes |
|
|
561
663
|
| A gateway refused the body as too large | 413 | `"context_overflow"` | Made smaller, as in [A request too large](#a-request-too-large) |
|
|
562
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 |
|
|
563
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) |
|
|
564
668
|
| The connection failed, or a stream ended before its `finishReason` | 0 | `"unreachable"` | Yes, unless text was shown |
|
|
565
669
|
| A reply of HTTP 200 whose body is empty | 0 | `"unreachable"` | Yes |
|
|
566
670
|
| A reply of HTTP 200 whose body is not JSON (a gateway's page) | 200 | `"invalid"` | No |
|
|
@@ -572,8 +676,9 @@ does.
|
|
|
572
676
|
|
|
573
677
|
## Gemini history stored as contents
|
|
574
678
|
|
|
575
|
-
`askGemini` takes
|
|
576
|
-
|
|
679
|
+
`askGemini` takes `messages` as `askWithFiles` does (`ChatMessage[]`: plain turns, stored tool
|
|
680
|
+
rounds, turns with native parts; since 0.9.0), or your own Gemini `contents` (with images and inline
|
|
681
|
+
PDFs) in `contents`; given both, `contents` is used. The last turn must be
|
|
577
682
|
the user's. Document text and cards are added at the start of the first user turn, and your array
|
|
578
683
|
is not changed. `fromGeminiContents(contents)` turns `contents` into `messages` for `askWithFiles`,
|
|
579
684
|
and `geminiToolTurns(result.toolTurns)` gives the tool rounds of a question as `contents`, to store
|
|
@@ -593,10 +698,13 @@ history.push(...geminiToolTurns(result.toolTurns), ...(result.answered ? [{ role
|
|
|
593
698
|
Store no model turn for a question that was not answered
|
|
594
699
|
([Conversations](./conversations.md#storing-a-conversation-and-asking-the-next-question)).
|
|
595
700
|
|
|
596
|
-
Rounds kept this way are sent as they are.
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
the
|
|
701
|
+
Rounds kept this way are sent as they are. Since 0.9.0 they are also rounds the loop knows, as
|
|
702
|
+
`toolTurns` in `messages` are: `fromGeminiContents` turns the rounds `geminiToolTurns` wrote back
|
|
703
|
+
into stored rounds, so a repeated call is answered with a pointer to its earlier result, old results
|
|
704
|
+
can be shortened when room runs short, and the rounds are sized as they are. Before, they were
|
|
705
|
+
plain parts, sized as media, and a repeated search ran again. Function turns of your own stay as
|
|
706
|
+
they are. What to store and how to keep a conversation inside the window:
|
|
707
|
+
[Conversations](./conversations.md#gemini-contents).
|
|
600
708
|
|
|
601
709
|
## A production setup
|
|
602
710
|
|
|
@@ -620,8 +728,11 @@ import { askGemini, vertexAi } from "llm-large-files/gemini";
|
|
|
620
728
|
|
|
621
729
|
const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
|
|
622
730
|
|
|
623
|
-
|
|
624
|
-
|
|
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();
|
|
625
736
|
if (!token) throw new Error("No access token from the application default credentials.");
|
|
626
737
|
return token;
|
|
627
738
|
}
|
|
@@ -663,6 +774,7 @@ export async function answer(question: {
|
|
|
663
774
|
system: "You are our support assistant. Cite the lines you used.",
|
|
664
775
|
generationConfig: { temperature: 0.3, thinkingConfig: { thinkingLevel: "high" } }, // the answering model
|
|
665
776
|
explorerGenerationConfig: { temperature: 0.2 }, // the explorer
|
|
777
|
+
body: { labels: { app: "support-assistant" } }, // billing labels: no user IDs
|
|
666
778
|
limits: { toolTurns: 12, inputTokens: 2_000_000, requests: 40 },
|
|
667
779
|
retry: { retries: 5, baseDelayMs: 2_000 },
|
|
668
780
|
signal,
|