@vite-hub/gateways 0.1.0 → 0.3.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/README.md +109 -32
- package/dist/ai-sdk.d.ts +36 -0
- package/dist/ai-sdk.js +113 -0
- package/dist/definition-BVc8HZWs.js +317 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +258 -9
- package/dist/internal.d.ts +28 -10
- package/dist/internal.js +3 -2
- package/dist/presets-DbTUgWyL.d.ts +189 -0
- package/dist/{presets-B2Xutktt.js → presets-DltoYDBd.js} +132 -230
- package/dist/types-D0loH5yz.d.ts +305 -0
- package/package.json +44 -8
- package/dist/presets-CY0KQOx8.d.ts +0 -378
package/README.md
CHANGED
|
@@ -1,20 +1,67 @@
|
|
|
1
1
|
# @vite-hub/gateways
|
|
2
2
|
|
|
3
|
-
An AI gateway is one object that knows where AI requests go and how to sign them. A gateway has
|
|
3
|
+
An AI gateway is one object that knows where AI requests go and how to sign them. A gateway has three capabilities:
|
|
4
4
|
|
|
5
5
|
- **Driver routes.** It routes Codex and Claude Code model requests, for example through Vercel AI Gateway or CLIProxyAPI.
|
|
6
|
-
-
|
|
6
|
+
- **AI SDK models.** `languageModel(gateway, modelId)` from `@vite-hub/gateways/ai-sdk` returns an [AI SDK](https://ai-sdk.dev) model that sends its requests through the gateway.
|
|
7
|
+
- **`gateway.ask()`.** It answers typed [TypeSafe Jev](https://typesafe.ai) questions, such as "which category fits this transaction". Only gateways that can reach Jev have `ask()`.
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
`ask(prompt, { model, schema })` sends one model request and returns typed data that a schema checked. Without `schema`, it returns the answer text.
|
|
10
|
+
|
|
11
|
+
The package has no Agent, Vite, or Nitro code. It works in a plain Node script, a Worker, or another framework, and its only dependency is `nostics`. ViteHub applications import it as `vite-hub/gateways`. User docs: [AI Gateways](https://vitehub.dev/docs/gateways).
|
|
9
12
|
|
|
10
13
|
## Install
|
|
11
14
|
|
|
12
|
-
`ask()`
|
|
15
|
+
`languageModel()`, `ask()`, and `gateway.ask()` load optional peer dependencies only when you use them. `gateway.ask()` needs `advocaat`, the TypeSafe client. `languageModel()` needs the AI SDK provider package of its model API, usually `@ai-sdk/openai-compatible`, and `ask(prompt, { model, schema })` needs `ai`:
|
|
13
16
|
|
|
14
17
|
```sh
|
|
15
18
|
pnpm add @vite-hub/gateways advocaat
|
|
19
|
+
pnpm add @vite-hub/gateways ai @ai-sdk/openai-compatible
|
|
16
20
|
```
|
|
17
21
|
|
|
22
|
+
## Use a model with the AI SDK
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { generateText } from 'ai'
|
|
26
|
+
import { openrouter } from '@vite-hub/gateways'
|
|
27
|
+
import { languageModel } from '@vite-hub/gateways/ai-sdk'
|
|
28
|
+
|
|
29
|
+
// Reads OPENROUTER_API_KEY when it sends the request.
|
|
30
|
+
const model = languageModel(openrouter(), 'google/gemini-3-flash')
|
|
31
|
+
|
|
32
|
+
const { text } = await generateText({ model, prompt: 'What is a Server Primitive?' })
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Change the preset to change the provider. The model ID is the ID that the gateway uses. The `api` option selects the model API, and the type accepts only the APIs that the gateway serves:
|
|
36
|
+
|
|
37
|
+
| `api` | Request | URL | Package |
|
|
38
|
+
| --- | --- | --- | --- |
|
|
39
|
+
| `'chat'` | OpenAI Chat Completions | `openai-compatible` | `@ai-sdk/openai-compatible` |
|
|
40
|
+
| `'responses'` | OpenAI Responses | `openai-compatible`, else `codex` | `@ai-sdk/openai` |
|
|
41
|
+
| `'messages'` | Anthropic Messages | `claude-code` | `@ai-sdk/anthropic` |
|
|
42
|
+
|
|
43
|
+
The default is `'chat'` when the gateway has an `openai-compatible` URL, else `'messages'`, else `'responses'`. Use `api: 'responses'` for OpenAI reasoning models that call tools. The gateway resolves its URL, key, and headers for each request from the values that you passed or from `process.env`. Pass `fetch` to use a custom fetch implementation. `providerOptions` for `'chat'` go under the gateway name, such as `{ openrouter: { ... } }`; `'responses'` reads `openai` and `'messages'` reads `anthropic`.
|
|
44
|
+
|
|
45
|
+
## Get typed data from one call
|
|
46
|
+
|
|
47
|
+
`ask(prompt, { model, schema })` sends one request to an AI SDK model and returns the answer that the schema validated, as `[error, data]`. It needs the `ai` package. Use `languageModel(gateway, modelId)` to send it through any gateway:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { z } from 'zod'
|
|
51
|
+
import { ask, openrouter } from '@vite-hub/gateways'
|
|
52
|
+
import { languageModel } from '@vite-hub/gateways/ai-sdk'
|
|
53
|
+
|
|
54
|
+
const [error, receipt] = await ask('MERCADONA 23.10 -34.90 EUR', {
|
|
55
|
+
model: languageModel(openrouter(), 'google/gemini-3-flash'),
|
|
56
|
+
schema: z.object({ merchant: z.string(), amount: z.number() }),
|
|
57
|
+
})
|
|
58
|
+
if (error) throw error
|
|
59
|
+
|
|
60
|
+
receipt.merchant // string
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`schema` is a [Standard Schema](https://standardschema.dev) that converts to JSON Schema: Zod 4, ArkType, or Valibot wrapped with `toStandardJsonSchema()` from `@valibot/to-json-schema`. Leave out `schema` to get the answer as a string: `const [error, summary] = await ask(log, { model })`. Options: `instructions` (system instructions), `signal`, and `onUsage`. `error` is `GATEWAYS_ASK_MODEL_FAILED` when the request fails and `GATEWAYS_ASK_OUTPUT_INVALID` when the answer does not match the schema or has no text. Setup errors, such as a missing key or a schema without JSON Schema, throw. Use an Agent when the model must call tools or keep a conversation.
|
|
64
|
+
|
|
18
65
|
## Ask your first question
|
|
19
66
|
|
|
20
67
|
```ts
|
|
@@ -49,22 +96,37 @@ The answer types come from the questions:
|
|
|
49
96
|
|
|
50
97
|
`gateway.ask(state, questions, { signal, onUsage })` sends the questions in sequential bounded requests. The shared state plus each question must fit below 30,000 bytes. It retries up to two times when the provider answers 408, 429, 500, 502, 503, or 504, or when the network fails. `onUsage` receives the `model`, `provider`, and token `usage` of each request.
|
|
51
98
|
|
|
99
|
+
### Ask with any model
|
|
100
|
+
|
|
101
|
+
`askWithModel(model)` answers the same questions with any [AI SDK](https://ai-sdk.dev) model, in one structured output request. Use it where a gateway with `ask()` goes. It needs the `ai` package:
|
|
102
|
+
|
|
103
|
+
```ts [label.ts]
|
|
104
|
+
import { ask, askWithModel } from '@vite-hub/gateways'
|
|
105
|
+
import { openai } from '@ai-sdk/openai'
|
|
106
|
+
|
|
107
|
+
const answers = await askWithModel(openai('gpt-5.1-mini')).ask('MERCADONA 23.10 -34.90 EUR', {
|
|
108
|
+
category: ask.choice('Which category fits this bank transaction?', ['groceries', 'eatingOut']),
|
|
109
|
+
})
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
A chat model gives one answer and how sure it is. `probabilities` put that number on the answer and share the rest between the other options. Jev gives a real probability for every option, so prefer it when you compare or rank options.
|
|
113
|
+
|
|
52
114
|
## Presets
|
|
53
115
|
|
|
54
|
-
| Preset | Codex | Claude Code | `ask()` | Variables |
|
|
55
|
-
| --- | --- | --- | --- | --- |
|
|
56
|
-
| `
|
|
57
|
-
| `
|
|
58
|
-
| `
|
|
59
|
-
| `
|
|
60
|
-
| `
|
|
61
|
-
| `ollama()` | `<url>/v1` | `<url>` | | `OLLAMA_URL` (default `http://localhost:11434`), `OLLAMA_API_KEY` (default `ollama`) |
|
|
62
|
-
| `
|
|
63
|
-
| `
|
|
64
|
-
| `
|
|
65
|
-
| `
|
|
66
|
-
|
|
67
|
-
`typesafe()
|
|
116
|
+
| Preset | Codex | Claude Code | OpenAI-compatible | `ask()` | Variables |
|
|
117
|
+
| --- | --- | --- | --- | --- | --- |
|
|
118
|
+
| `vercel()` | `https://ai-gateway.vercel.sh/codex/v1` | `https://ai-gateway.vercel.sh/claude-code` | `https://ai-gateway.vercel.sh/v1` | `typesafe-ai/jev` at `https://ai-gateway.vercel.sh/v4/ai` | `AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN` |
|
|
119
|
+
| `cloudflare()` | | | `.../<account>/<gateway>/compat` | `jev-latest` through a [custom provider](#typesafe-through-cloudflare-ai-gateway) | `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_AI_GATEWAY_ID`, `CLOUDFLARE_AI_GATEWAY_TOKEN`, `CLOUDFLARE_AI_GATEWAY_API_KEY`, `TYPESAFE_API_KEY`, `CLOUDFLARE_AI_GATEWAY_SLUG` (see [Cloudflare AI Gateway](#cloudflare-ai-gateway)) |
|
|
120
|
+
| `openrouter()` | `https://openrouter.ai/api/v1` | `https://openrouter.ai/api` | `https://openrouter.ai/api/v1` | | `OPENROUTER_API_KEY` |
|
|
121
|
+
| `litellm()` | `<url>/v1` | `<url>` | `<url>/v1` | | `LITELLM_URL`, `LITELLM_API_KEY` |
|
|
122
|
+
| `cliproxy()` | `<url>/v1` | `<url>` | `<url>/v1` | | `CLIPROXY_URL`, `CLIPROXY_API_KEY` |
|
|
123
|
+
| `ollama()` | `<url>/v1` | `<url>` | `<url>/v1` | | `OLLAMA_URL` (default `http://localhost:11434`), `OLLAMA_API_KEY` (default `ollama`) |
|
|
124
|
+
| `openai()` | `https://api.openai.com/v1` | | `https://api.openai.com/v1` | | `OPENAI_API_KEY` |
|
|
125
|
+
| `chatgpt()` | `https://api.openai.com/v1` through a ChatGPT Connection | | | | None |
|
|
126
|
+
| `anthropic()` | | `https://api.anthropic.com` | | | `ANTHROPIC_API_KEY` |
|
|
127
|
+
| `typesafe()` | | | | `jev-latest` at `https://api.typesafe.ai` | `TYPESAFE_API_KEY`, `TYPESAFE_DEFAULT_MODEL` |
|
|
128
|
+
|
|
129
|
+
The type of a preset lists the model APIs that it serves: `AiGateway<{ routes: "codex" }>` accepts only gateways with a Codex URL, so a ViteHub Codex Driver with `anthropic()` and `languageModel(typesafe(), ...)` are type errors. `vercel()`, `typesafe()`, and `cloudflare()` return `AiGateway<{ ask: true }>`. `chatgpt()` returns a `ChatGPTGateway` descriptor for the Agent runtime. The other presets have no `ask()`, so `ask()` on them is a type error. CLIProxyAPI, LiteLLM, Ollama, OpenRouter, OpenAI, Anthropic, and the Cloudflare OpenAI-compatible endpoint forward model APIs only, not TypeSafe's `/v1/systemone`.
|
|
68
130
|
|
|
69
131
|
`cloudflareAccess()` returns the `CF-Access-Client-Id` and `CF-Access-Client-Secret` headers for a gateway behind Cloudflare Access, from `CF_ACCESS_CLIENT_ID` and `CF_ACCESS_CLIENT_SECRET`. Pass it as `headers`, for example `cliproxy({ headers: cloudflareAccess() })`.
|
|
70
132
|
|
|
@@ -72,27 +134,41 @@ The answer types come from the questions:
|
|
|
72
134
|
|
|
73
135
|
## Credentials
|
|
74
136
|
|
|
75
|
-
`chatgpt({ connection?: string })` is a credential-free descriptor for a ViteHub Codex Driver. It defaults to the `chatgpt` Connection. The Agent runtime applies the Connection's read policy and resolves a fresh plan token. This descriptor has no `apiKey` callback or `ask()` method. Configure `chatgpt({ appName })` from `@vite-hub/connections/chatgpt` on the Connection and sign in with `vitehub connections connect chatgpt`. See [ChatGPT plan usage](https://vitehub.dev/docs/connections/chatgpt).
|
|
137
|
+
`chatgpt({ connection?: string })` is a credential-free descriptor for a ViteHub Codex Driver or a model-backed Driver (`driver: { model, gateway: chatgpt() }`). It defaults to the `chatgpt` Connection. The Agent runtime applies the Connection's read policy and resolves a fresh plan token. This descriptor has no `apiKey` callback or `ask()` method. Configure `chatgpt({ appName })` from `@vite-hub/connections/chatgpt` on the Connection and sign in with `vitehub connections connect chatgpt`. See [ChatGPT plan usage](https://vitehub.dev/docs/connections/chatgpt).
|
|
76
138
|
|
|
77
|
-
A preset reads each value that you do not pass when it sends a request. Direct `gateway.ask()` calls, including imports from `vite-hub/gateways`, read `process.env`: `VITEHUB_<PRESET>_<FIELD>` first, such as `VITEHUB_TYPESAFE_API_KEY`, then the vendor variable in the table.
|
|
139
|
+
A preset reads each value that you do not pass when it sends a request. Direct `gateway.ask()` calls, including imports from `vite-hub/gateways`, read `process.env`: `VITEHUB_<PRESET>_<FIELD>` first, such as `VITEHUB_TYPESAFE_API_KEY`, then the vendor variable in the table. Provider Drivers and ask Drivers supply Server Env, with the Cloudflare bindings of the request. `languageModel()` reads `process.env`, also in an AI SDK model Driver. For a direct call with provider-backed Server Env or request bindings, load the values in your application and pass them to the preset.
|
|
78
140
|
|
|
79
141
|
Vercel keeps its credentials in separate Server Env fields: `vercel.apiKey` reads `AI_GATEWAY_API_KEY`, and `vercel.oidcToken` reads `VERCEL_OIDC_TOKEN`. The API key takes precedence; a token uses OIDC authentication even when an Env provider supplies it.
|
|
80
142
|
|
|
81
143
|
A value that you pass replaces its variable. Pass the values when the application stores the credentials, for example one key for each tenant:
|
|
82
144
|
|
|
83
|
-
```ts
|
|
145
|
+
```ts fragment
|
|
84
146
|
import { cloudflare, typesafe, vercel } from '@vite-hub/gateways'
|
|
85
147
|
|
|
86
148
|
typesafe({ apiKey: tenant.typesafeKey })
|
|
87
149
|
vercel({ apiKey: tenant.aiGatewayKey })
|
|
88
|
-
cloudflare({
|
|
150
|
+
cloudflare({ accountId, gatewayId, token: tenant.gatewayToken, typesafeApiKey: tenant.typesafeKey, slug })
|
|
89
151
|
```
|
|
90
152
|
|
|
91
|
-
An `apiKey` or header value can also be a function that returns the value for each request. `undefined` fails the request; it does not fall back to the variable. `typesafe()`, `vercel()`, and `cloudflare()` also take `model` and `fetch
|
|
153
|
+
An `apiKey` or header value can also be a function that returns the value for each request. `undefined` fails the request; it does not fall back to the variable. `cloudflare()` reads two keys, `typesafeApiKey` for `ask()` and an optional `providerApiKey` for models. `typesafe()`, `vercel()`, and `cloudflare()` also take `model` and `fetch` for `ask()`.
|
|
92
154
|
|
|
93
155
|
## Cloudflare AI Gateway
|
|
94
156
|
|
|
95
|
-
|
|
157
|
+
`cloudflare()` sends AI SDK model requests to the [OpenAI-compatible endpoint](https://developers.cloudflare.com/ai-gateway/usage/chat-completion/) of a Cloudflare AI Gateway: `https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/compat/chat/completions`. This endpoint supports only `api: 'chat'`; `api: 'responses'` is rejected. Model IDs are `{provider}/{model}`, such as `openai/gpt-5` or `workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast`.
|
|
158
|
+
|
|
159
|
+
Each request needs a gateway token, a provider key, or both:
|
|
160
|
+
|
|
161
|
+
| Setup | Variables | Headers |
|
|
162
|
+
| --- | --- | --- |
|
|
163
|
+
| The gateway stores the provider keys, or uses Unified Billing | `CLOUDFLARE_AI_GATEWAY_TOKEN` | `cf-aig-authorization` |
|
|
164
|
+
| Open gateway, provider key in the request | `CLOUDFLARE_AI_GATEWAY_API_KEY` (or `providerApiKey`) | `Authorization` |
|
|
165
|
+
| Authenticated gateway, provider key in the request | Both | Both |
|
|
166
|
+
|
|
167
|
+
`CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_AI_GATEWAY_ID` are always required. A request without a token and without a provider key fails with `GATEWAYS_R0002` before it is sent. The two keys never mix: `ask()` sends only the TypeSafe key, and model requests send only the provider key. `cloudflare({ apiKey })` throws and names both options. `cloudflare()` does not route Drivers: Codex and Claude Code need the vendor endpoints of the gateway, each with that vendor's key. To route a Driver through Cloudflare, define a gateway for it.
|
|
168
|
+
|
|
169
|
+
### TypeSafe through Cloudflare AI Gateway
|
|
170
|
+
|
|
171
|
+
Cloudflare AI Gateway has no TypeSafe provider. `cloudflare().ask()` reaches TypeSafe through a [custom provider](https://developers.cloudflare.com/ai-gateway/configuration/custom-providers/) that you create once per Cloudflare account. It reads `TYPESAFE_API_KEY`, or `typesafeApiKey` when you pass it. The gateway then logs each request, and its caching and rate limits apply.
|
|
96
172
|
|
|
97
173
|
1. In the Cloudflare dashboard, go to **Compute & AI** > **AI Gateway** and create a gateway. Its name is the gateway ID.
|
|
98
174
|
2. Go to **Custom Providers** and select **Add Custom Provider**. Set the slug to `typesafe` and the base URL to `https://api.typesafe.ai`. Or use the Cloudflare API:
|
|
@@ -119,11 +195,9 @@ Cloudflare AI Gateway has no TypeSafe provider. `cloudflare()` reaches TypeSafe
|
|
|
119
195
|
|
|
120
196
|
`cloudflare().ask()` sends `POST https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/custom-<slug>/v1/systemone` with the TypeSafe key as `Authorization` and the gateway token as `cf-aig-authorization`. TypeSafe still bills the requests.
|
|
121
197
|
|
|
122
|
-
`cloudflare()` does not route Drivers: Cloudflare's OpenAI and Anthropic endpoints each take that vendor's key. To route a Driver through Cloudflare, define a gateway for it.
|
|
123
|
-
|
|
124
198
|
## Custom gateways
|
|
125
199
|
|
|
126
|
-
Use `defineAiGateway()` for an endpoint without a preset. It routes
|
|
200
|
+
Use `defineAiGateway()` for an endpoint without a preset. It routes model requests and has no `ask()`. Its type lists the keys of `baseURL`:
|
|
127
201
|
|
|
128
202
|
```ts
|
|
129
203
|
import { defineAiGateway } from '@vite-hub/gateways'
|
|
@@ -142,7 +216,7 @@ export const codexThroughCloudflare = defineAiGateway({
|
|
|
142
216
|
| Option | Description |
|
|
143
217
|
| --- | --- |
|
|
144
218
|
| `name` | Shown in inspection and diagnostics. |
|
|
145
|
-
| `baseURL` | One URL for each
|
|
219
|
+
| `baseURL` | One URL for each model API: `codex` (OpenAI Responses at `<url>/responses`, for the Codex Driver), `claude-code` (Anthropic Messages at `<url>/v1/messages`, for the Claude Code Driver and `api: 'messages'`), and `openai-compatible` (OpenAI Chat Completions at `<url>/chat/completions` and Responses at `<url>/responses`, for AI SDK models). A function runs for each request. |
|
|
146
220
|
| `apiKey` | A string or a function. |
|
|
147
221
|
| `apiKeyEnv` | Host variables that supply the key, in order. |
|
|
148
222
|
| `auth` | `'bearer'` (default) sends `Authorization: Bearer <key>`. `'x-api-key'` sends `x-api-key: <key>`. |
|
|
@@ -150,9 +224,9 @@ export const codexThroughCloudflare = defineAiGateway({
|
|
|
150
224
|
|
|
151
225
|
## Use with ViteHub Agents
|
|
152
226
|
|
|
153
|
-
In a ViteHub application, set a gateway as `driver.gateway` to route an Agent's model requests, or pass a gateway with `ask()` to an ask Driver
|
|
227
|
+
In a ViteHub application, set a gateway as `driver.gateway` to route an Agent's model requests, pass `languageModel(gateway, modelId)` from `vite-hub/gateways/ai-sdk` as an AI SDK Driver `model`, or pass a gateway with `ask()` to an ask Driver. ViteHub declares the variables of each preset that a server file imports in Server Env. See [Use with Agents](https://vitehub.dev/docs/gateways/agents) in the ViteHub docs.
|
|
154
228
|
|
|
155
|
-
`@vite-hub/gateways/internal` is for ViteHub packages:
|
|
229
|
+
`@vite-hub/gateways/internal` is for ViteHub packages: model API route resolution and `ask()` with trace observers.
|
|
156
230
|
|
|
157
231
|
## Errors
|
|
158
232
|
|
|
@@ -163,9 +237,12 @@ Every error has a `code`, a `why`, and a `fix`. Errors from `ask()` keep the pro
|
|
|
163
237
|
| `GATEWAYS_R0001` | A gateway definition is not valid, such as an unknown option or a URL that is not http or https. It throws when you call the preset. |
|
|
164
238
|
| `GATEWAYS_R0002` | A key is missing or empty. The message names the variable to set, or `apiKey` when you passed it. |
|
|
165
239
|
| `GATEWAYS_R0003` | A header value is missing, empty, or has a line break. |
|
|
166
|
-
| `GATEWAYS_R0004` | A URL, a Cloudflare account ID, or an AI Gateway ID is missing or not valid. |
|
|
167
|
-
| `GATEWAYS_R0005` | `ask()` on a gateway that only routes
|
|
240
|
+
| `GATEWAYS_R0004` | A URL, a Cloudflare account ID, or an AI Gateway ID is missing or not valid, or the gateway does not serve the Driver or model API. |
|
|
241
|
+
| `GATEWAYS_R0005` | `ask()` on a gateway that only routes model requests. |
|
|
168
242
|
| `GATEWAYS_R0006` | `ask()` without the `advocaat` package. Install it with `pnpm add advocaat`. |
|
|
169
243
|
| `GATEWAYS_R0007` | A Jev question that the `ask` builders do not make, or a question that is too large. |
|
|
170
244
|
| `GATEWAYS_R0008` | The provider rejected the key with 401 or 403. `status` is 503, and the error has `providerStatus` and `requestId`. The `fix` names the variable to rotate. |
|
|
171
245
|
| `GATEWAYS_R0009` | The provider still failed after three attempts. `status` is 502, and the error has `providerStatus` and `requestId`. |
|
|
246
|
+
| `GATEWAYS_R0010` | `languageModel()` without the AI SDK provider package of its model API. The message names the package to install. |
|
|
247
|
+
| `GATEWAYS_R0011` | `askWithModel()` without the `ai` package. Install it with `pnpm add ai`. |
|
|
248
|
+
| `GATEWAYS_R0012` | The model of `askWithModel()` answered a question with a value that is not one of its options. |
|
package/dist/ai-sdk.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { c as AiGatewayRoute, i as AiGatewayCapabilities, t as AiGateway } from "./types-D0loH5yz.js";
|
|
2
|
+
import { LanguageModelV4 } from "@ai-sdk/provider";
|
|
3
|
+
//#region src/ai-sdk.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The model APIs that `languageModel()` can call, for the routes of a gateway:
|
|
6
|
+
* - `chat`: OpenAI Chat Completions at the `openai-compatible` URL, with `@ai-sdk/openai-compatible`.
|
|
7
|
+
* - `responses`: OpenAI Responses at the `openai-compatible` URL, else at the `codex` URL, with `@ai-sdk/openai`.
|
|
8
|
+
* - `messages`: Anthropic Messages at the `claude-code` URL, with `@ai-sdk/anthropic`.
|
|
9
|
+
*/
|
|
10
|
+
export type AiGatewayModelApi<TRoutes extends AiGatewayRoute = AiGatewayRoute> = ("openai-compatible" extends TRoutes ? "chat" | "responses" : never) | ("codex" extends TRoutes ? "responses" : never) | ("claude-code" extends TRoutes ? "messages" : never);
|
|
11
|
+
export interface AiGatewayLanguageModelOptions<TApi extends AiGatewayModelApi = AiGatewayModelApi> {
|
|
12
|
+
/** The model API to call. Default: `chat` when the gateway has an `openai-compatible` URL, else `messages`, else `responses`. */
|
|
13
|
+
api?: TApi;
|
|
14
|
+
/** Custom fetch implementation for model requests. Default: `globalThis.fetch`. */
|
|
15
|
+
fetch?: typeof globalThis.fetch;
|
|
16
|
+
}
|
|
17
|
+
/** Rejects a gateway that serves no model API, such as `typesafe()`, with a readable type error. */
|
|
18
|
+
type ServesModels<TRoutes extends AiGatewayRoute> = [AiGatewayModelApi<TRoutes>] extends [never] ? {
|
|
19
|
+
readonly "This gateway serves no model API. Use a gateway with an openai-compatible, claude-code, or codex baseURL.": never;
|
|
20
|
+
} : unknown;
|
|
21
|
+
/**
|
|
22
|
+
* An AI SDK language model that sends its requests through the gateway. The gateway resolves its URL, key, and headers
|
|
23
|
+
* for each request, from the values that you passed to the preset or from `process.env`.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* import { generateText } from 'ai'
|
|
27
|
+
* import { openrouter } from '@vite-hub/gateways'
|
|
28
|
+
* import { languageModel } from '@vite-hub/gateways/ai-sdk'
|
|
29
|
+
*
|
|
30
|
+
* await generateText({ model: languageModel(openrouter(), 'google/gemini-3-flash'), prompt: 'Hello' })
|
|
31
|
+
*/
|
|
32
|
+
export declare function languageModel<const TRoutes extends AiGatewayRoute, const TApis extends AiGatewayCapabilities["apis"] = AiGatewayCapabilities["apis"]>(gateway: AiGateway<{
|
|
33
|
+
apis: TApis;
|
|
34
|
+
routes: TRoutes;
|
|
35
|
+
}> & ServesModels<TRoutes>, modelId: string, options?: AiGatewayLanguageModelOptions<Extract<AiGatewayModelApi<TRoutes>, NoInfer<TApis>>>): LanguageModelV4;
|
|
36
|
+
//#endregion
|
package/dist/ai-sdk.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { i as aiGatewaySupports, s as resolveAiGatewayModelRoute, u as gatewayDiagnostics } from "./definition-BVc8HZWs.js";
|
|
2
|
+
//#region src/ai-sdk.ts
|
|
3
|
+
const packages = {
|
|
4
|
+
"chat": "@ai-sdk/openai-compatible",
|
|
5
|
+
"messages": "@ai-sdk/anthropic",
|
|
6
|
+
"responses": "@ai-sdk/openai"
|
|
7
|
+
};
|
|
8
|
+
function defaultApi(gateway) {
|
|
9
|
+
if (aiGatewaySupports(gateway, "openai-compatible")) return "chat";
|
|
10
|
+
if (aiGatewaySupports(gateway, "claude-code")) return "messages";
|
|
11
|
+
return "responses";
|
|
12
|
+
}
|
|
13
|
+
function routeOf(gateway, api) {
|
|
14
|
+
if (api === "messages") return "claude-code";
|
|
15
|
+
if (api === "responses" && !aiGatewaySupports(gateway, "openai-compatible")) return "codex";
|
|
16
|
+
return "openai-compatible";
|
|
17
|
+
}
|
|
18
|
+
async function load(api, importer) {
|
|
19
|
+
try {
|
|
20
|
+
return await importer();
|
|
21
|
+
} catch (error) {
|
|
22
|
+
throw gatewayDiagnostics.GATEWAYS_R0010({
|
|
23
|
+
message: `[vitehub] The "${api}" model API needs the ${packages[api]} package. Install it with: pnpm add ${packages[api]}`,
|
|
24
|
+
cause: error
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function headerRecord(route) {
|
|
29
|
+
return Object.fromEntries([...route.headers, ...route.auth === "x-api-key" && route.apiKey ? [["x-api-key", route.apiKey]] : []]);
|
|
30
|
+
}
|
|
31
|
+
async function createModel(name, modelId, api, route, fetch) {
|
|
32
|
+
const shared = {
|
|
33
|
+
headers: headerRecord(route),
|
|
34
|
+
name,
|
|
35
|
+
...fetch ? { fetch } : {}
|
|
36
|
+
};
|
|
37
|
+
if (api === "chat") {
|
|
38
|
+
const { createOpenAICompatible } = await load(api, async () => await import("@ai-sdk/openai-compatible"));
|
|
39
|
+
return createOpenAICompatible({
|
|
40
|
+
...shared,
|
|
41
|
+
baseURL: route.baseURL,
|
|
42
|
+
includeUsage: true,
|
|
43
|
+
...route.apiKey && route.auth === "bearer" ? { apiKey: route.apiKey } : {}
|
|
44
|
+
}).chatModel(modelId);
|
|
45
|
+
}
|
|
46
|
+
const apiKey = route.apiKey;
|
|
47
|
+
if (!apiKey) throw gatewayDiagnostics.GATEWAYS_R0002({ message: `[vitehub] Gateway "${name}" needs an API key for the "${api}" model API. Pass apiKey, or use api: "chat".` });
|
|
48
|
+
if (api === "responses") {
|
|
49
|
+
const { createOpenAI } = await load(api, async () => await import("@ai-sdk/openai"));
|
|
50
|
+
return createOpenAI({
|
|
51
|
+
...shared,
|
|
52
|
+
apiKey,
|
|
53
|
+
baseURL: route.baseURL,
|
|
54
|
+
fetch: route.auth === "x-api-key" ? async (input, init) => {
|
|
55
|
+
const headers = new Headers(init?.headers);
|
|
56
|
+
headers.delete("authorization");
|
|
57
|
+
headers.set("x-api-key", apiKey);
|
|
58
|
+
return await (fetch ?? globalThis.fetch)(input, {
|
|
59
|
+
...init,
|
|
60
|
+
headers
|
|
61
|
+
});
|
|
62
|
+
} : fetch
|
|
63
|
+
}).responses(modelId);
|
|
64
|
+
}
|
|
65
|
+
const { createAnthropic } = await load(api, async () => await import("@ai-sdk/anthropic"));
|
|
66
|
+
return createAnthropic({
|
|
67
|
+
...shared,
|
|
68
|
+
baseURL: `${route.baseURL}/v1`,
|
|
69
|
+
...route.auth === "x-api-key" ? { apiKey } : { authToken: apiKey }
|
|
70
|
+
}).languageModel(modelId);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* An AI SDK language model that sends its requests through the gateway. The gateway resolves its URL, key, and headers
|
|
74
|
+
* for each request, from the values that you passed to the preset or from `process.env`.
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* import { generateText } from 'ai'
|
|
78
|
+
* import { openrouter } from '@vite-hub/gateways'
|
|
79
|
+
* import { languageModel } from '@vite-hub/gateways/ai-sdk'
|
|
80
|
+
*
|
|
81
|
+
* await generateText({ model: languageModel(openrouter(), 'google/gemini-3-flash'), prompt: 'Hello' })
|
|
82
|
+
*/
|
|
83
|
+
function languageModel(gateway, modelId, options = {}) {
|
|
84
|
+
if (typeof gateway !== "object" || gateway === null || typeof gateway.baseURL !== "object" || gateway.baseURL === null) throw gatewayDiagnostics.GATEWAYS_R0001({ message: "[vitehub] languageModel(gateway, modelId) needs a gateway from a preset or defineAiGateway(). For chatgpt(), set driver: { model, gateway: chatgpt() } on an Agent." });
|
|
85
|
+
if (typeof modelId !== "string" || !modelId.trim()) throw gatewayDiagnostics.GATEWAYS_R0001({ message: "[vitehub] languageModel(gateway, modelId) needs a non-empty model ID." });
|
|
86
|
+
const api = options.api ?? defaultApi(gateway);
|
|
87
|
+
if (!packages[api]) throw gatewayDiagnostics.GATEWAYS_R0001({ message: `[vitehub] languageModel() api must be "chat", "responses", or "messages".` });
|
|
88
|
+
const route = routeOf(gateway, api);
|
|
89
|
+
if (gateway.modelApis && !gateway.modelApis.some((supported) => supported === api)) throw gatewayDiagnostics.GATEWAYS_R0004({ message: `[vitehub] Gateway "${gateway.name}" does not serve the "${api}" model API. Choose api: ${gateway.modelApis.map((supported) => `"${supported}"`).join(" or ")}.` });
|
|
90
|
+
if (!aiGatewaySupports(gateway, route)) throw gatewayDiagnostics.GATEWAYS_R0004({ message: `[vitehub] Gateway "${gateway.name}" does not serve the "${api}" model API. Set baseURL["${route}"] or choose another api.` });
|
|
91
|
+
const id = modelId.trim();
|
|
92
|
+
const model = async (abortSignal) => {
|
|
93
|
+
const resolved = await resolveAiGatewayModelRoute(gateway, route, abortSignal ? { abortSignal } : {});
|
|
94
|
+
return await createModel(gateway.name, id, api, resolved, options.fetch);
|
|
95
|
+
};
|
|
96
|
+
return {
|
|
97
|
+
specificationVersion: "v4",
|
|
98
|
+
provider: `${gateway.name}.${api}`,
|
|
99
|
+
modelId: id,
|
|
100
|
+
get supportedUrls() {
|
|
101
|
+
return createModel(gateway.name, id, api, {
|
|
102
|
+
apiKey: "unused",
|
|
103
|
+
auth: "bearer",
|
|
104
|
+
baseURL: "https://gateway.invalid",
|
|
105
|
+
headers: []
|
|
106
|
+
}).then((resolved) => resolved.supportedUrls);
|
|
107
|
+
},
|
|
108
|
+
doGenerate: async (callOptions) => await (await model(callOptions.abortSignal)).doGenerate(callOptions),
|
|
109
|
+
doStream: async (callOptions) => await (await model(callOptions.abortSignal)).doStream(callOptions)
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
//#endregion
|
|
113
|
+
export { languageModel };
|