@vite-hub/gateways 0.4.1 → 0.5.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 +69 -15
- package/dist/ai-sdk.d.ts +3 -3
- package/dist/ai-sdk.js +67 -23
- package/dist/{definition-BVc8HZWs.js → definition-BQbaNIoi.js} +17 -127
- package/dist/diagnostics-KWRXsfZ3.js +123 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -11
- package/dist/internal.d.ts +14 -3
- package/dist/internal.js +4 -3
- package/dist/jev-BI0dIeB8.js +421 -0
- package/dist/presets-C7I0uIZc.js +507 -0
- package/dist/{presets-QQzoSUSu.d.ts → presets-xSYbZBJS.d.ts} +21 -9
- package/dist/testing.d.ts +47 -0
- package/dist/testing.js +153 -0
- package/dist/{types-CF5dF7X1.d.ts → types-CYigOOA5.d.ts} +0 -2
- package/package.json +9 -2
- package/dist/presets-CRYxSoMw.js +0 -900
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ The package has no Agent, Vite, or Nitro code. It works in a plain Node script,
|
|
|
12
12
|
|
|
13
13
|
## Install
|
|
14
14
|
|
|
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
|
|
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` (`@ai-sdk/openai` with `openai()`), and `ask(prompt, { model, schema })` needs `ai`:
|
|
16
16
|
|
|
17
17
|
```sh
|
|
18
18
|
pnpm add @vite-hub/gateways advocaat
|
|
@@ -36,11 +36,13 @@ Change the preset to change the provider. The model ID is the ID that the gatewa
|
|
|
36
36
|
|
|
37
37
|
| `api` | Request | URL | Package |
|
|
38
38
|
| --- | --- | --- | --- |
|
|
39
|
-
| `'chat'` | OpenAI Chat Completions | `openai-compatible` | `@ai-sdk/openai-compatible` |
|
|
39
|
+
| `'chat'` | OpenAI Chat Completions | `openai-compatible` | `@ai-sdk/openai-compatible`, or `@ai-sdk/openai` with `openai()` |
|
|
40
40
|
| `'responses'` | OpenAI Responses | `openai-compatible`, else `codex` | `@ai-sdk/openai` |
|
|
41
41
|
| `'messages'` | Anthropic Messages | `claude-code` | `@ai-sdk/anthropic` |
|
|
42
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.
|
|
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.
|
|
44
|
+
|
|
45
|
+
Put `providerOptions` under the gateway name for compatible Chat (such as `{ openrouter: { ... } }`), `openai` for `openai()` Chat and Responses, and `anthropic` for Messages. Compatible Chat passes request fields to the gateway. `openai()` Chat reads native SDK options and still sends raw Chat Completions fields such as `parallel_tool_calls`. A raw field takes precedence over its SDK option. `openai()` Chat keeps JSON mode for schema output, so `ask()` validates the result locally and accepts schemas with optional fields.
|
|
44
46
|
|
|
45
47
|
## Get typed data from one call
|
|
46
48
|
|
|
@@ -64,6 +66,19 @@ receipt.merchant // string
|
|
|
64
66
|
|
|
65
67
|
## Ask your first question
|
|
66
68
|
|
|
69
|
+
Pick the builder by the answer that you want. The answer types come from the questions.
|
|
70
|
+
|
|
71
|
+
| You want | Write | You get |
|
|
72
|
+
| --- | --- | --- |
|
|
73
|
+
| Yes or no | `ask.if(instructions, { threshold? })` | `boolean`. `true` when the probability of yes is above `threshold`. The default is `0.5`. |
|
|
74
|
+
| The probability of yes | `ask.chance(instructions, { true?, false? })` | `{ chance }`, from `0` to `1`. |
|
|
75
|
+
| One label | `ask.switch(instructions, criteria)` | The label, such as `'groceries'`. |
|
|
76
|
+
| One label, with how sure the model is | `ask.choice(instructions, criteria)` | `{ choice, confidence, probabilities }`. |
|
|
77
|
+
| A rating on an ordered scale | `ask.score(instructions, levels)` | `{ score, ratio, confidence, legend, probabilities }`, for 2 to 10 levels. |
|
|
78
|
+
| The same question for each item of a list | `ask.each(items, { key, question })` | One question for each item, under the key that `key(item)` returns. Pass the map to `gateway.ask()`, or spread it into your questions. |
|
|
79
|
+
|
|
80
|
+
For `ask.switch()` and `ask.choice()`, `criteria` maps labels to descriptions, or is a list of 2 to 255 labels.
|
|
81
|
+
|
|
67
82
|
```ts
|
|
68
83
|
import { ask, typesafe } from '@vite-hub/gateways'
|
|
69
84
|
|
|
@@ -84,17 +99,6 @@ answers.category.confidence // 0 to 1
|
|
|
84
99
|
answers.recurring // boolean
|
|
85
100
|
```
|
|
86
101
|
|
|
87
|
-
The answer types come from the questions:
|
|
88
|
-
|
|
89
|
-
| Builder | Answer |
|
|
90
|
-
| --- | --- |
|
|
91
|
-
| `ask.choice(instructions, criteria)` | `{ choice, confidence, probabilities }`. `criteria` maps labels to descriptions, or is a list of 2 to 255 labels. |
|
|
92
|
-
| `ask.switch(instructions, criteria)` | The selected label only. |
|
|
93
|
-
| `ask.score(instructions, levels)` | `{ score, ratio, confidence, legend, probabilities }` for 2 to 10 ordered levels. |
|
|
94
|
-
| `ask.chance(instructions, criteria?)` | `{ chance }`, the probability of yes. |
|
|
95
|
-
| `ask.if(instructions, { threshold? })` | `true` when the probability of yes is above `threshold`, between `0` and `1`. The default is `0.5`. |
|
|
96
|
-
| `ask.each(items, { key, question })` | One question for each item, under the key that `key(item)` returns. |
|
|
97
|
-
|
|
98
102
|
`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. It returns `[error, answers]`: a rejected key returns `GATEWAYS_R0008` and a provider that still fails returns `GATEWAYS_R0009`. A missing key or a question that the `ask` builders did not make throws.
|
|
99
103
|
|
|
100
104
|
### Ask with any model
|
|
@@ -113,6 +117,23 @@ if (error) throw error // GATEWAYS_ASK_MODEL_FAILED when the model request fails
|
|
|
113
117
|
|
|
114
118
|
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.
|
|
115
119
|
|
|
120
|
+
### Test without a key
|
|
121
|
+
|
|
122
|
+
`scriptedAsk(script)` from `@vite-hub/gateways/testing` returns a `gateway` whose `ask()` answers each question with `script(key, question, state)`, and the `calls` that it received. `answers.choice()`, `answers.score()`, `answers.chance()`, and `answers.first()` build answers that pass the same checks as a Jev answer:
|
|
123
|
+
|
|
124
|
+
```ts [label.test.ts]
|
|
125
|
+
import { ask } from '@vite-hub/gateways'
|
|
126
|
+
import { answers, scriptedAsk } from '@vite-hub/gateways/testing'
|
|
127
|
+
|
|
128
|
+
const { gateway, calls } = scriptedAsk((key, question) => key === 'category' ? answers.choice(question, 'groceries', 0.9) : answers.first(question))
|
|
129
|
+
const [, result] = await gateway.ask('MERCADONA 23.10 -34.90 EUR', {
|
|
130
|
+
category: ask.choice('Which category fits this bank transaction?', ['groceries', 'eatingOut']),
|
|
131
|
+
})
|
|
132
|
+
result?.category.choice // 'groceries'
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
`ask()` calls `onUsage` with `provider: 'scripted'` and the `usage` option. `{ error: 'GATEWAYS_R0008' }` or `{ error: 'GATEWAYS_R0009' }` returns a rejected key or a failing provider instead.
|
|
136
|
+
|
|
116
137
|
## Presets
|
|
117
138
|
|
|
118
139
|
| Preset | Codex | Claude Code | OpenAI-compatible | `ask()` | Variables |
|
|
@@ -123,12 +144,13 @@ A chat model gives one answer and how sure it is. `probabilities` put that numbe
|
|
|
123
144
|
| `litellm()` | `<url>/v1` | `<url>` | `<url>/v1` | | `LITELLM_URL`, `LITELLM_API_KEY` |
|
|
124
145
|
| `cliproxy()` | `<url>/v1` | `<url>` | `<url>/v1` | | `CLIPROXY_URL`, `CLIPROXY_API_KEY` |
|
|
125
146
|
| `ollama()` | `<url>/v1` | `<url>` | `<url>/v1` | | `OLLAMA_URL` (default `http://localhost:11434`), `OLLAMA_API_KEY` (default `ollama`) |
|
|
147
|
+
| `emulate()` | | `<url>` (AI SDK `messages` only) | `<url>/v1` | | `VITEHUB_EMULATE_URL` (default `http://localhost:4014`). No key. |
|
|
126
148
|
| `openai()` | `https://api.openai.com/v1` | | `https://api.openai.com/v1` | | `OPENAI_API_KEY` |
|
|
127
149
|
| `chatgpt()` | `https://api.openai.com/v1` through a ChatGPT Connection | | | | None |
|
|
128
150
|
| `anthropic()` | | `https://api.anthropic.com` | | | `ANTHROPIC_API_KEY` |
|
|
129
151
|
| `typesafe()` | | | | `jev-latest` at `https://api.typesafe.ai` | `TYPESAFE_API_KEY`, `TYPESAFE_DEFAULT_MODEL` |
|
|
130
152
|
|
|
131
|
-
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`.
|
|
153
|
+
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, the AI emulator, OpenRouter, OpenAI, Anthropic, and the Cloudflare OpenAI-compatible endpoint forward model APIs only, not TypeSafe's `/v1/systemone`.
|
|
132
154
|
|
|
133
155
|
`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() })`.
|
|
134
156
|
|
|
@@ -154,6 +176,38 @@ cloudflare({ accountId, gatewayId, token: tenant.gatewayToken, typesafeApiKey: t
|
|
|
154
176
|
|
|
155
177
|
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()`.
|
|
156
178
|
|
|
179
|
+
## AI emulator
|
|
180
|
+
|
|
181
|
+
`emulate()` sends model requests to the [AI emulator](https://emulate.dev/docs/ai) (`@emulators/ai`). The emulator answers from rules that you write, not from a model, so the same request gets the same answer each time. Use it in dev and tests. It needs no AI key.
|
|
182
|
+
|
|
183
|
+
Start the emulator:
|
|
184
|
+
|
|
185
|
+
```sh
|
|
186
|
+
npx emulate@0.14.0 start --service ai --port 4014
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
Then use it like any other gateway:
|
|
190
|
+
|
|
191
|
+
```ts [answer.ts]
|
|
192
|
+
import { generateText } from 'ai'
|
|
193
|
+
import { emulate } from '@vite-hub/gateways'
|
|
194
|
+
import { languageModel } from '@vite-hub/gateways/ai-sdk'
|
|
195
|
+
|
|
196
|
+
// Reads VITEHUB_EMULATE_URL, else uses http://localhost:4014.
|
|
197
|
+
const model = languageModel(emulate(), 'gpt-5.1', { api: 'responses' })
|
|
198
|
+
|
|
199
|
+
const { text } = await generateText({ model, prompt: 'Hello' })
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
- `emulate()` serves AI SDK models with `api: 'chat'`, `'responses'`, and `'messages'`. The emulator accepts any model ID.
|
|
203
|
+
- Without a matching rule, the emulator returns a default reply. For `Output.object()` and `generateObject()`, that reply follows your schema on all three APIs.
|
|
204
|
+
- It reads no credentials. It sends the key `emulate`, because the AI SDK providers need a key.
|
|
205
|
+
- `emulate({ url })` replaces `VITEHUB_EMULATE_URL`.
|
|
206
|
+
- In a test, start the emulator in the test process with `createEmulator({ service: 'ai', port: 0, seed: { ai: { strict: true, rules } } })` from the `emulate` package, and pass its `url`. With `strict: true`, a request that no rule matches fails with a 400 that shows the missing rule.
|
|
207
|
+
- `GET <url>/_ai/calls` lists each request and the rule that answered it.
|
|
208
|
+
- The emulator rejects hosted tools, such as web search.
|
|
209
|
+
- It does not serve the CLI Drivers. It has no Codex URL, so `codexDriver({ gateway: emulate() })` is a type error, because the emulator rejects the `custom` tools that the Codex CLI sends. To run a Codex Agent without tools on the emulator, set `VITEHUB_MODELS=emulate`, and ViteHub sets up Codex for it. Read [Run on the AI emulator](https://vitehub.dev/docs/agents/agent-drivers#run-on-the-ai-emulator). Claude Code cannot use it either, because the emulator rejects its `system` turns. Its URL is there only for AI SDK `messages` models.
|
|
210
|
+
|
|
157
211
|
## Cloudflare AI Gateway
|
|
158
212
|
|
|
159
213
|
`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`.
|
package/dist/ai-sdk.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { o as AiGatewayCapabilities, t as AiGateway, u as AiGatewayRoute } from "./types-
|
|
1
|
+
import { o as AiGatewayCapabilities, t as AiGateway, u as AiGatewayRoute } from "./types-CYigOOA5.js";
|
|
2
2
|
import { LanguageModelV4 } from "@ai-sdk/provider";
|
|
3
3
|
//#region src/ai-sdk.d.ts
|
|
4
4
|
/**
|
|
5
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`.
|
|
6
|
+
* - `chat`: OpenAI Chat Completions at the `openai-compatible` URL, with `@ai-sdk/openai-compatible`. The `openai()`
|
|
7
|
+
* preset uses `@ai-sdk/openai`.
|
|
7
8
|
* - `responses`: OpenAI Responses at the `openai-compatible` URL, else at the `codex` URL, with `@ai-sdk/openai`.
|
|
8
9
|
* - `messages`: Anthropic Messages at the `claude-code` URL, with `@ai-sdk/anthropic`.
|
|
9
10
|
*/
|
|
@@ -14,7 +15,6 @@ export interface AiGatewayLanguageModelOptions<TApi extends AiGatewayModelApi =
|
|
|
14
15
|
/** Custom fetch implementation for model requests. Default: `globalThis.fetch`. */
|
|
15
16
|
fetch?: typeof globalThis.fetch;
|
|
16
17
|
}
|
|
17
|
-
/** Rejects a gateway that serves no model API, such as `typesafe()`, with a readable type error. */
|
|
18
18
|
type ServesModels<TRoutes extends AiGatewayRoute> = [AiGatewayModelApi<TRoutes>] extends [never] ? {
|
|
19
19
|
readonly "This gateway serves no model API. Use a gateway with an openai-compatible, claude-code, or codex baseURL.": never;
|
|
20
20
|
} : unknown;
|
package/dist/ai-sdk.js
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as gatewayDiagnostics } from "./diagnostics-KWRXsfZ3.js";
|
|
2
|
+
import { c as isRecord, i as aiGatewayOpenAIChat, n as aiGatewayLanguageModel, o as aiGatewayStructuredOutputs, s as aiGatewaySupports, u as resolveAiGatewayModelRoute } from "./definition-BQbaNIoi.js";
|
|
2
3
|
//#region src/ai-sdk.ts
|
|
3
4
|
const packages = {
|
|
4
5
|
"chat": "@ai-sdk/openai-compatible",
|
|
5
6
|
"messages": "@ai-sdk/anthropic",
|
|
6
7
|
"responses": "@ai-sdk/openai"
|
|
7
8
|
};
|
|
9
|
+
/** The AI SDK provider package of one model API on one gateway. */
|
|
10
|
+
function packageOf(gateway, api) {
|
|
11
|
+
return api === "chat" && Reflect.get(gateway, aiGatewayOpenAIChat) === true ? "@ai-sdk/openai" : packages[api];
|
|
12
|
+
}
|
|
8
13
|
function defaultApi(gateway) {
|
|
9
14
|
if (aiGatewaySupports(gateway, "openai-compatible")) return "chat";
|
|
10
15
|
if (aiGatewaySupports(gateway, "claude-code")) return "messages";
|
|
@@ -15,39 +20,60 @@ function routeOf(gateway, api) {
|
|
|
15
20
|
if (api === "responses" && !aiGatewaySupports(gateway, "openai-compatible")) return "codex";
|
|
16
21
|
return "openai-compatible";
|
|
17
22
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
return await importer();
|
|
21
|
-
} catch (error) {
|
|
23
|
+
function missingProvider(api, name) {
|
|
24
|
+
return (error) => {
|
|
22
25
|
throw gatewayDiagnostics.GATEWAYS_R0010({
|
|
23
|
-
message: `[vitehub] The "${api}" model API needs the ${
|
|
26
|
+
message: `[vitehub] The "${api}" model API needs the ${name} package. Install it with: pnpm add ${name}`,
|
|
24
27
|
cause: error
|
|
25
28
|
});
|
|
26
|
-
}
|
|
29
|
+
};
|
|
27
30
|
}
|
|
28
31
|
function headerRecord(route) {
|
|
29
32
|
return Object.fromEntries([...route.headers, ...route.auth === "x-api-key" && route.apiKey ? [["x-api-key", route.apiKey]] : []]);
|
|
30
33
|
}
|
|
31
|
-
|
|
34
|
+
const sdkChatFields = /* @__PURE__ */ new Set([
|
|
35
|
+
"messages",
|
|
36
|
+
"tools",
|
|
37
|
+
"tool_choice",
|
|
38
|
+
"stream",
|
|
39
|
+
"stream_options"
|
|
40
|
+
]);
|
|
41
|
+
/** Keeps raw Chat Completions parameters that the compatible SDK used to send. */
|
|
42
|
+
function openAIChatFetch(providerOptions, fetch = globalThis.fetch) {
|
|
43
|
+
const overrides = Object.entries(providerOptions?.openai ?? {}).filter(([key, value]) => /^[a-z][a-z0-9_]*$/.test(key) && !sdkChatFields.has(key) && !(key === "logprobs" && typeof value === "number"));
|
|
44
|
+
if (!overrides.length) return fetch;
|
|
45
|
+
return async (input, init) => {
|
|
46
|
+
const body = typeof init?.body === "string" ? JSON.parse(init.body) : void 0;
|
|
47
|
+
return await fetch(input, isRecord(body) ? {
|
|
48
|
+
...init,
|
|
49
|
+
body: JSON.stringify({
|
|
50
|
+
...body,
|
|
51
|
+
...Object.fromEntries(overrides)
|
|
52
|
+
})
|
|
53
|
+
} : init);
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
async function createModel(name, modelId, api, provider, route, fetch, structuredOutputs = false) {
|
|
32
57
|
const shared = {
|
|
33
58
|
headers: headerRecord(route),
|
|
34
59
|
name,
|
|
35
60
|
...fetch ? { fetch } : {}
|
|
36
61
|
};
|
|
37
|
-
if (api === "chat") {
|
|
38
|
-
const { createOpenAICompatible } = await
|
|
62
|
+
if (api === "chat" && provider === "@ai-sdk/openai-compatible") {
|
|
63
|
+
const { createOpenAICompatible } = await import("@ai-sdk/openai-compatible").catch(missingProvider(api, provider));
|
|
39
64
|
return createOpenAICompatible({
|
|
40
65
|
...shared,
|
|
41
66
|
baseURL: route.baseURL,
|
|
42
67
|
includeUsage: true,
|
|
68
|
+
...structuredOutputs ? { supportsStructuredOutputs: true } : {},
|
|
43
69
|
...route.apiKey && route.auth === "bearer" ? { apiKey: route.apiKey } : {}
|
|
44
70
|
}).chatModel(modelId);
|
|
45
71
|
}
|
|
46
72
|
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
|
|
48
|
-
if (api === "responses") {
|
|
49
|
-
const { createOpenAI } = await
|
|
50
|
-
|
|
73
|
+
if (!apiKey) throw gatewayDiagnostics.GATEWAYS_R0002({ message: `[vitehub] Gateway "${name}" needs an API key for the "${api}" model API. Pass apiKey${api === "chat" ? "" : `, or use api: "chat"`}.` });
|
|
74
|
+
if (api === "chat" || api === "responses") {
|
|
75
|
+
const { createOpenAI } = await import("@ai-sdk/openai").catch(missingProvider(api, "@ai-sdk/openai"));
|
|
76
|
+
const openai = createOpenAI({
|
|
51
77
|
...shared,
|
|
52
78
|
apiKey,
|
|
53
79
|
baseURL: route.baseURL,
|
|
@@ -60,9 +86,10 @@ async function createModel(name, modelId, api, route, fetch) {
|
|
|
60
86
|
headers
|
|
61
87
|
});
|
|
62
88
|
} : fetch
|
|
63
|
-
})
|
|
89
|
+
});
|
|
90
|
+
return api === "chat" ? openai.chat(modelId) : openai.responses(modelId);
|
|
64
91
|
}
|
|
65
|
-
const { createAnthropic } = await
|
|
92
|
+
const { createAnthropic } = await import("@ai-sdk/anthropic").catch(missingProvider(api, "@ai-sdk/anthropic"));
|
|
66
93
|
return createAnthropic({
|
|
67
94
|
...shared,
|
|
68
95
|
baseURL: `${route.baseURL}/v1`,
|
|
@@ -89,25 +116,42 @@ function languageModel(gateway, modelId, options = {}) {
|
|
|
89
116
|
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
117
|
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
118
|
const id = modelId.trim();
|
|
92
|
-
const
|
|
119
|
+
const provider = packageOf(gateway, api);
|
|
120
|
+
const structuredOutputs = Reflect.get(gateway, aiGatewayStructuredOutputs) === true;
|
|
121
|
+
const nativeChat = api === "chat" && provider === "@ai-sdk/openai";
|
|
122
|
+
const model = async ({ abortSignal, providerOptions }) => {
|
|
93
123
|
const resolved = await resolveAiGatewayModelRoute(gateway, route, abortSignal ? { abortSignal } : {});
|
|
94
|
-
|
|
124
|
+
const fetch = nativeChat ? openAIChatFetch(providerOptions, options.fetch) : options.fetch;
|
|
125
|
+
return await createModel(gateway.name, id, api, provider, resolved, fetch, structuredOutputs);
|
|
95
126
|
};
|
|
96
|
-
|
|
127
|
+
/** Keeps JSON mode on Chat; the caller still has its schema for local validation. */
|
|
128
|
+
function request(callOptions) {
|
|
129
|
+
return nativeChat && callOptions.responseFormat?.type === "json" ? {
|
|
130
|
+
...callOptions,
|
|
131
|
+
responseFormat: { type: "json" }
|
|
132
|
+
} : callOptions;
|
|
133
|
+
}
|
|
134
|
+
const languageModel = {
|
|
97
135
|
specificationVersion: "v4",
|
|
98
136
|
provider: `${gateway.name}.${api}`,
|
|
99
137
|
modelId: id,
|
|
100
138
|
get supportedUrls() {
|
|
101
|
-
return createModel(gateway.name, id, api, {
|
|
139
|
+
return createModel(gateway.name, id, api, provider, {
|
|
102
140
|
apiKey: "unused",
|
|
103
141
|
auth: "bearer",
|
|
104
142
|
baseURL: "https://gateway.invalid",
|
|
105
143
|
headers: []
|
|
106
|
-
}).then((resolved) => resolved.supportedUrls);
|
|
144
|
+
}, void 0, structuredOutputs).then((resolved) => resolved.supportedUrls);
|
|
107
145
|
},
|
|
108
|
-
doGenerate: async (callOptions) => await (await model(callOptions
|
|
109
|
-
doStream: async (callOptions) => await (await model(callOptions
|
|
146
|
+
doGenerate: async (callOptions) => await (await model(callOptions)).doGenerate(request(callOptions)),
|
|
147
|
+
doStream: async (callOptions) => await (await model(callOptions)).doStream(request(callOptions))
|
|
110
148
|
};
|
|
149
|
+
const modelRoute = Object.freeze({
|
|
150
|
+
api,
|
|
151
|
+
gateway: gateway.name,
|
|
152
|
+
modelId: id
|
|
153
|
+
});
|
|
154
|
+
return Object.defineProperty(languageModel, aiGatewayLanguageModel, { value: modelRoute });
|
|
111
155
|
}
|
|
112
156
|
//#endregion
|
|
113
157
|
export { languageModel };
|
|
@@ -1,129 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
//#region src/public-diagnostics.ts
|
|
3
|
-
const publicCodes = /* @__PURE__ */ new Set([
|
|
4
|
-
"GATEWAYS_R0002",
|
|
5
|
-
"GATEWAYS_R0006",
|
|
6
|
-
"GATEWAYS_R0008",
|
|
7
|
-
"GATEWAYS_R0009",
|
|
8
|
-
"GATEWAYS_R0011"
|
|
9
|
-
]);
|
|
10
|
-
const publicDiagnostics = /* @__PURE__ */ new WeakMap();
|
|
11
|
-
function recordPublicAiGatewayDiagnostic(diagnostic) {
|
|
12
|
-
if (publicCodes.has(diagnostic.code)) publicDiagnostics.set(diagnostic, {
|
|
13
|
-
message: diagnostic.message,
|
|
14
|
-
fix: diagnostic.fix
|
|
15
|
-
});
|
|
16
|
-
}
|
|
17
|
-
/** Client-safe text captured when this package creates a known gateway diagnostic. */
|
|
18
|
-
function getPublicAiGatewayDiagnostic(cause) {
|
|
19
|
-
return cause instanceof Error ? publicDiagnostics.get(cause) : void 0;
|
|
20
|
-
}
|
|
21
|
-
//#endregion
|
|
22
|
-
//#region src/diagnostics.ts
|
|
23
|
-
const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
24
|
-
const gatewayDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
25
|
-
docsBase: "https://vitehub.dev/docs/gateways/diagnostics",
|
|
26
|
-
reporters: [recordPublicAiGatewayDiagnostic],
|
|
27
|
-
codes: {
|
|
28
|
-
/** An AI gateway definition is invalid. */
|
|
29
|
-
GATEWAYS_R0001: {
|
|
30
|
-
...dynamicError,
|
|
31
|
-
fix: "Change the gateway option that the message names in the preset call, such as `vercel()` or `chatgpt()`, in `defineAiGateway()`, or in `languageModel()`, as the message says."
|
|
32
|
-
},
|
|
33
|
-
/** A gateway API key is missing or resolves to an empty value. */
|
|
34
|
-
GATEWAYS_R0002: {
|
|
35
|
-
...dynamicError,
|
|
36
|
-
fix: "Set the API key env variable that the message names in the Server Env, or pass the key option that the message names to the gateway."
|
|
37
|
-
},
|
|
38
|
-
/** A gateway header value is missing, empty, or has a line break. */
|
|
39
|
-
GATEWAYS_R0003: {
|
|
40
|
-
...dynamicError,
|
|
41
|
-
fix: "Set the header value that the message names, in the env variable or the gateway option that the message names, as one line without line breaks."
|
|
42
|
-
},
|
|
43
|
-
/** A gateway URL, Cloudflare account ID, or AI Gateway ID is missing or invalid, or the gateway does not serve a model API. */
|
|
44
|
-
GATEWAYS_R0004: {
|
|
45
|
-
...dynamicError,
|
|
46
|
-
fix: "Set the gateway URL, account ID, or gateway ID that the message names by env variable or option, or pass an `api` that the gateway serves to `languageModel(gateway, modelId, { api })`."
|
|
47
|
-
},
|
|
48
|
-
/** `ask()` was called on a gateway that only routes model requests. */
|
|
49
|
-
GATEWAYS_R0005: {
|
|
50
|
-
...dynamicError,
|
|
51
|
-
fix: "Call `ask()` on a gateway from `typesafe()`, `vercel()`, or `cloudflare()`."
|
|
52
|
-
},
|
|
53
|
-
/** `ask()` needs the optional `advocaat` package. */
|
|
54
|
-
GATEWAYS_R0006: {
|
|
55
|
-
...dynamicError,
|
|
56
|
-
fix: "Install the `advocaat` package with `pnpm add advocaat`."
|
|
57
|
-
},
|
|
58
|
-
/** A Jev question is not a question that the `ask` builders make, or it is too large. */
|
|
59
|
-
GATEWAYS_R0007: {
|
|
60
|
-
...dynamicError,
|
|
61
|
-
fix: "Build each question with `ask.choice()`, `ask.score()`, `ask.chance()`, `ask.if()`, or `ask.switch()`, within the limits that the message names."
|
|
62
|
-
},
|
|
63
|
-
/** The provider rejected the key with 401 or 403. */
|
|
64
|
-
GATEWAYS_R0008: {
|
|
65
|
-
why: ({ provider, status }) => `[vitehub] The ${provider} Jev provider rejected the API key with HTTP ${status}. The key is missing, expired, or not allowed to call Jev.`,
|
|
66
|
-
fix: ({ env, option = "apiKey" }) => env ? `Set or rotate ${env}.` : `Pass a valid ${option} to the gateway, or rotate the key.`
|
|
67
|
-
},
|
|
68
|
-
/** The provider still failed after three attempts. */
|
|
69
|
-
GATEWAYS_R0009: {
|
|
70
|
-
why: ({ provider, status, attempts }) => `[vitehub] The ${provider} Jev provider failed${status === void 0 ? " to respond" : ` with HTTP ${status}`} after ${attempts} attempts.`,
|
|
71
|
-
fix: "This is usually temporary. Retry later. The cause has the provider response."
|
|
72
|
-
},
|
|
73
|
-
/** `languageModel()` needs the optional AI SDK provider package of its model API. */
|
|
74
|
-
GATEWAYS_R0010: {
|
|
75
|
-
...dynamicError,
|
|
76
|
-
fix: "Install the AI SDK provider package that the message names with `pnpm add <package>`."
|
|
77
|
-
},
|
|
78
|
-
/** `ask()` with a schema and `askWithModel()` need the optional `ai` package. */
|
|
79
|
-
GATEWAYS_R0011: {
|
|
80
|
-
...dynamicError,
|
|
81
|
-
fix: "Install the `ai` package with `pnpm add ai`."
|
|
82
|
-
},
|
|
83
|
-
/** The model answered a question with a value that is not one of its options. */
|
|
84
|
-
GATEWAYS_R0012: {
|
|
85
|
-
...dynamicError,
|
|
86
|
-
fix: "Ask the question again, or make its prompt and options clearer so that the model picks one of the options. A retry often helps."
|
|
87
|
-
},
|
|
88
|
-
GATEWAYS_ASK_EACH_KEY_DUPLICATE: {
|
|
89
|
-
why: ({ key }) => `ask.each produced duplicate key ${key}`,
|
|
90
|
-
fix: "Return a different key for each item from the `key` function of `ask.each(items, { key, question })`, such as the item id."
|
|
91
|
-
},
|
|
92
|
-
GATEWAYS_ASK_EACH_KEY_INVALID: {
|
|
93
|
-
why: "ask.each keys must be non-empty strings",
|
|
94
|
-
fix: "Return a non-empty string from the `key` function of `ask.each(items, { key, question })` for every item."
|
|
95
|
-
},
|
|
96
|
-
GATEWAYS_ASK_MODEL_FAILED: {
|
|
97
|
-
why: ({ status }) => `[vitehub] The ask() model request failed${status === void 0 ? "" : ` with HTTP ${status}`}.`,
|
|
98
|
-
fix: "Check the model ID and the gateway key. For HTTP 429 or 5xx, retry later. The cause has the provider response."
|
|
99
|
-
},
|
|
100
|
-
GATEWAYS_ASK_OUTPUT_INVALID: {
|
|
101
|
-
why: ({ finishReason, issue }) => finishReason !== void 0 ? `[vitehub] The model answer to ask() has no text. The model stopped with finish reason "${finishReason}".` : `[vitehub] The model answer to ask() is not JSON that the schema accepts${issue === void 0 ? "." : `: ${issue}`}`,
|
|
102
|
-
fix: "Ask again, because a retry often helps. If it repeats, describe each field in the schema or the prompt, or make the schema less strict. For finish reason \"content-filter\", change the prompt. For \"length\", shorten the prompt or use a model with a larger output limit."
|
|
103
|
-
},
|
|
104
|
-
GATEWAYS_ASK_PROMPT_INVALID: {
|
|
105
|
-
why: "ask() needs a non-empty prompt string",
|
|
106
|
-
fix: "Pass the question as the first argument: `ask('Summarize this run', { model, schema })`."
|
|
107
|
-
},
|
|
108
|
-
GATEWAYS_ASK_SCHEMA_INVALID: {
|
|
109
|
-
why: ({ problem, vendor }) => problem === "standard" ? "ask() needs a Standard Schema in `schema`" : `ask() needs a schema that converts to JSON Schema, and this ${vendor} schema does not`,
|
|
110
|
-
fix: "Pass a Zod 4 or ArkType schema, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema`."
|
|
111
|
-
},
|
|
112
|
-
GATEWAYS_ASK_THRESHOLD_INVALID: {
|
|
113
|
-
why: ({ problem }) => problem === "finite" ? "ask.if threshold must be a finite number" : "ask.if threshold must be between 0 and 1",
|
|
114
|
-
fix: "Pass `ask.if(instructions, { threshold })` a number from 0 to 1, or omit `threshold` to use 0.5."
|
|
115
|
-
},
|
|
116
|
-
GATEWAYS_JEV_INPUT_TOO_LARGE: {
|
|
117
|
-
why: ({ question }) => question === void 0 ? "[vitehub] Jev shared state exceeds the safe per-question input budget." : `[vitehub] Jev question "${question}" exceeds the safe per-question input budget.`,
|
|
118
|
-
fix: "Pass less shared state to the ask, or split a long question into shorter ones, so each question with the shared state stays under 30,000 bytes of JSON."
|
|
119
|
-
},
|
|
120
|
-
GATEWAYS_JEV_RESPONSE_INVALID: {
|
|
121
|
-
why: ({ name, problem }) => problem === "missing" ? `[vitehub] Jev response is missing answer "${name}".` : `[vitehub] Jev choice answer "${name}" is missing a valid probability distribution.`,
|
|
122
|
-
fix: "Retry the ask, because the Jev service sent an incomplete answer. If it repeats, update the `advocaat` package and check the Jev service status."
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
});
|
|
126
|
-
//#endregion
|
|
1
|
+
import { t as gatewayDiagnostics } from "./diagnostics-KWRXsfZ3.js";
|
|
127
2
|
//#region src/definition.ts
|
|
128
3
|
const gatewayKeys = /* @__PURE__ */ new Set([
|
|
129
4
|
"apiKey",
|
|
@@ -145,6 +20,21 @@ const aiGatewayAsks = Symbol.for("vitehub.aiGateway.ask");
|
|
|
145
20
|
* that stores provider keys. A symbol key, so key checks and copies skip it. Driver routes still need every value.
|
|
146
21
|
*/
|
|
147
22
|
const aiGatewayOptionalCredentials = Symbol.for("vitehub.aiGateway.optionalCredentials");
|
|
23
|
+
/**
|
|
24
|
+
* Marks a gateway whose `openai-compatible` URL is the OpenAI API itself, such as `openai()`. Its `chat` model API then
|
|
25
|
+
* uses `@ai-sdk/openai`, the package that serves OpenAI, so the app needs no `@ai-sdk/openai-compatible`.
|
|
26
|
+
*/
|
|
27
|
+
const aiGatewayOpenAIChat = Symbol.for("vitehub.aiGateway.openaiChat");
|
|
28
|
+
/**
|
|
29
|
+
* Marks a gateway whose Chat Completions endpoint accepts a JSON schema in `response_format`. A symbol key, so key
|
|
30
|
+
* checks and copies skip it. `languageModel()` then sends the output schema on `api: "chat"`, not plain `json_object`.
|
|
31
|
+
*/
|
|
32
|
+
const aiGatewayStructuredOutputs = Symbol.for("vitehub.aiGateway.structuredOutputs");
|
|
33
|
+
/**
|
|
34
|
+
* The route of a model that `languageModel()` returns: its gateway name, model API, and model ID. A symbol key, so key
|
|
35
|
+
* checks and copies skip it. ViteHub Agents read it to send the same model to the AI emulator.
|
|
36
|
+
*/
|
|
37
|
+
const aiGatewayLanguageModel = Symbol.for("vitehub.aiGateway.languageModel");
|
|
148
38
|
/** Resolves model credentials together with headers that depend on their source. */
|
|
149
39
|
const aiGatewayModelCredentials = Symbol.for("vitehub.aiGateway.modelCredentials");
|
|
150
40
|
const routes = [
|
|
@@ -314,4 +204,4 @@ async function resolveAiGatewayModelRoute(gateway, route, context) {
|
|
|
314
204
|
};
|
|
315
205
|
}
|
|
316
206
|
//#endregion
|
|
317
|
-
export {
|
|
207
|
+
export { aiGatewayOptionalCredentials as a, isRecord as c, resolveAiGatewayRoute as d, resolveAiGatewaySecret as f, aiGatewayOpenAIChat as i, normalizeAiGateway as l, aiGatewayLanguageModel as n, aiGatewayStructuredOutputs as o, aiGatewayModelCredentials as r, aiGatewaySupports as s, aiGatewayAsks as t, resolveAiGatewayModelRoute as u };
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { defineDiagnostics } from "nostics";
|
|
2
|
+
//#region src/public-diagnostics.ts
|
|
3
|
+
const publicCodes = /* @__PURE__ */ new Set([
|
|
4
|
+
"GATEWAYS_R0002",
|
|
5
|
+
"GATEWAYS_R0006",
|
|
6
|
+
"GATEWAYS_R0008",
|
|
7
|
+
"GATEWAYS_R0009",
|
|
8
|
+
"GATEWAYS_R0011"
|
|
9
|
+
]);
|
|
10
|
+
const publicDiagnostics = /* @__PURE__ */ new WeakMap();
|
|
11
|
+
function recordPublicAiGatewayDiagnostic(diagnostic) {
|
|
12
|
+
if (publicCodes.has(diagnostic.code)) publicDiagnostics.set(diagnostic, {
|
|
13
|
+
message: diagnostic.message,
|
|
14
|
+
fix: diagnostic.fix
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
/** Client-safe text captured when this package creates a known gateway diagnostic. */
|
|
18
|
+
function getPublicAiGatewayDiagnostic(cause) {
|
|
19
|
+
return cause instanceof Error ? publicDiagnostics.get(cause) : void 0;
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/diagnostics.ts
|
|
23
|
+
const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
24
|
+
const gatewayDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
25
|
+
docsBase: "https://vitehub.dev/docs/gateways/diagnostics",
|
|
26
|
+
reporters: [recordPublicAiGatewayDiagnostic],
|
|
27
|
+
codes: {
|
|
28
|
+
GATEWAYS_R0001: {
|
|
29
|
+
...dynamicError,
|
|
30
|
+
fix: "Change the gateway option that the message names in the preset call, such as `vercel()` or `chatgpt()`, in `defineAiGateway()`, or in `languageModel()`, as the message says."
|
|
31
|
+
},
|
|
32
|
+
GATEWAYS_R0002: {
|
|
33
|
+
...dynamicError,
|
|
34
|
+
fix: "Set the API key env variable that the message names in the Server Env, or pass the key option that the message names to the gateway."
|
|
35
|
+
},
|
|
36
|
+
GATEWAYS_R0003: {
|
|
37
|
+
...dynamicError,
|
|
38
|
+
fix: "Set the header value that the message names, in the env variable or the gateway option that the message names, as one line without line breaks."
|
|
39
|
+
},
|
|
40
|
+
GATEWAYS_R0004: {
|
|
41
|
+
...dynamicError,
|
|
42
|
+
fix: "Set the gateway URL, account ID, or gateway ID that the message names by env variable or option, or pass an `api` that the gateway serves to `languageModel(gateway, modelId, { api })`."
|
|
43
|
+
},
|
|
44
|
+
GATEWAYS_R0005: {
|
|
45
|
+
...dynamicError,
|
|
46
|
+
fix: "Call `ask()` on a gateway from `typesafe()`, `vercel()`, or `cloudflare()`."
|
|
47
|
+
},
|
|
48
|
+
GATEWAYS_R0006: {
|
|
49
|
+
...dynamicError,
|
|
50
|
+
fix: "Install the `advocaat` package with `pnpm add advocaat`."
|
|
51
|
+
},
|
|
52
|
+
GATEWAYS_R0007: {
|
|
53
|
+
...dynamicError,
|
|
54
|
+
fix: "Build each question with `ask.choice()`, `ask.score()`, `ask.chance()`, `ask.if()`, or `ask.switch()`, within the limits that the message names."
|
|
55
|
+
},
|
|
56
|
+
GATEWAYS_R0008: {
|
|
57
|
+
why: ({ provider, status }) => `[vitehub] The ${provider} Jev provider rejected the API key with HTTP ${status}. The key is missing, expired, or not allowed to call Jev.`,
|
|
58
|
+
fix: ({ env, option = "apiKey" }) => env ? `Set or rotate ${env}.` : `Pass a valid ${option} to the gateway, or rotate the key.`
|
|
59
|
+
},
|
|
60
|
+
GATEWAYS_R0009: {
|
|
61
|
+
why: ({ provider, status, attempts }) => `[vitehub] The ${provider} Jev provider failed${status === void 0 ? " to respond" : ` with HTTP ${status}`} after ${attempts} attempts.`,
|
|
62
|
+
fix: "This is usually temporary. Retry later. The cause has the provider response."
|
|
63
|
+
},
|
|
64
|
+
GATEWAYS_R0010: {
|
|
65
|
+
...dynamicError,
|
|
66
|
+
fix: "Install the AI SDK provider package that the message names with `pnpm add <package>`."
|
|
67
|
+
},
|
|
68
|
+
GATEWAYS_R0011: {
|
|
69
|
+
...dynamicError,
|
|
70
|
+
fix: "Install the `ai` package with `pnpm add ai`."
|
|
71
|
+
},
|
|
72
|
+
GATEWAYS_R0012: {
|
|
73
|
+
...dynamicError,
|
|
74
|
+
fix: "Ask the question again, or make its prompt and options clearer so that the model picks one of the options. A retry often helps."
|
|
75
|
+
},
|
|
76
|
+
GATEWAYS_ASK_EACH_KEY_DUPLICATE: {
|
|
77
|
+
why: ({ key }) => `ask.each produced duplicate key ${key}`,
|
|
78
|
+
fix: "Return a different key for each item from the `key` function of `ask.each(items, { key, question })`, such as the item id."
|
|
79
|
+
},
|
|
80
|
+
GATEWAYS_ASK_EACH_KEY_INVALID: {
|
|
81
|
+
why: "ask.each keys must be non-empty strings",
|
|
82
|
+
fix: "Return a non-empty string from the `key` function of `ask.each(items, { key, question })` for every item."
|
|
83
|
+
},
|
|
84
|
+
GATEWAYS_ASK_MODEL_FAILED: {
|
|
85
|
+
why: ({ status }) => `[vitehub] The ask() model request failed${status === void 0 ? "" : ` with HTTP ${status}`}.`,
|
|
86
|
+
fix: "Check the model ID and the gateway key. For HTTP 429 or 5xx, retry later. The cause has the provider response."
|
|
87
|
+
},
|
|
88
|
+
GATEWAYS_ASK_OUTPUT_INVALID: {
|
|
89
|
+
why: ({ finishReason, issue }) => finishReason !== void 0 ? `[vitehub] The model answer to ask() has no text. The model stopped with finish reason "${finishReason}".` : `[vitehub] The model answer to ask() is not JSON that the schema accepts${issue === void 0 ? "." : `: ${issue}`}`,
|
|
90
|
+
fix: "Ask again, because a retry often helps. If it repeats, describe each field in the schema or the prompt, or make the schema less strict. For finish reason \"content-filter\", change the prompt. For \"length\", shorten the prompt or use a model with a larger output limit."
|
|
91
|
+
},
|
|
92
|
+
GATEWAYS_ASK_PROMPT_INVALID: {
|
|
93
|
+
why: "ask() needs a non-empty prompt string",
|
|
94
|
+
fix: "Pass the question as the first argument: `ask('Summarize this run', { model, schema })`."
|
|
95
|
+
},
|
|
96
|
+
GATEWAYS_ASK_SCHEMA_INVALID: {
|
|
97
|
+
why: ({ problem, vendor }) => problem === "standard" ? "ask() needs a Standard Schema in `schema`" : `ask() needs a schema that converts to JSON Schema, and this ${vendor} schema does not`,
|
|
98
|
+
fix: "Pass a Zod 4 or ArkType schema, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema`."
|
|
99
|
+
},
|
|
100
|
+
GATEWAYS_ASK_THRESHOLD_INVALID: {
|
|
101
|
+
why: ({ problem }) => problem === "finite" ? "ask.if threshold must be a finite number" : "ask.if threshold must be between 0 and 1",
|
|
102
|
+
fix: "Pass `ask.if(instructions, { threshold })` a number from 0 to 1, or omit `threshold` to use 0.5."
|
|
103
|
+
},
|
|
104
|
+
GATEWAYS_JEV_INPUT_TOO_LARGE: {
|
|
105
|
+
why: ({ question }) => question === void 0 ? "[vitehub] Jev shared state exceeds the safe per-question input budget." : `[vitehub] Jev question "${question}" exceeds the safe per-question input budget.`,
|
|
106
|
+
fix: "Pass less shared state to the ask, or split a long question into shorter ones, so each question with the shared state stays under 30,000 bytes of JSON."
|
|
107
|
+
},
|
|
108
|
+
GATEWAYS_JEV_RESPONSE_INVALID: {
|
|
109
|
+
why: ({ name, problem }) => problem === "missing" ? `[vitehub] Jev response is missing answer "${name}".` : `[vitehub] Jev choice answer "${name}" is missing a valid probability distribution.`,
|
|
110
|
+
fix: "Retry the ask, because the Jev service sent an incomplete answer. If it repeats, update the `advocaat` package and check the Jev service status."
|
|
111
|
+
},
|
|
112
|
+
GATEWAYS_TESTING_ANSWER_INVALID: {
|
|
113
|
+
why: ({ problem }) => `[vitehub] ${problem}`,
|
|
114
|
+
fix: "Return an answer for the question's type. With `answers.choice()`, give the chosen label a highest probability. With `answers.score()`, use a level from 0 to the last index."
|
|
115
|
+
},
|
|
116
|
+
GATEWAYS_TRACE_OBSERVER_FAILED: {
|
|
117
|
+
why: ({ event }) => `[vitehub] The \`observe\` callback threw on the "${event}" trace event. The Jev request went on without this event.`,
|
|
118
|
+
fix: "Fix the error in the `observe` callback that the cause names. A trace observer must not throw."
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
//#endregion
|
|
123
|
+
export { getPublicAiGatewayDiagnostic as n, gatewayDiagnostics as t };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { A as AskScoreAnswer, B as askWithModel, C as AskChoiceLabels, D as AskJson, E as AskIfQuestion, F as AskError, I as AskModel, L as AskOptions, M as AskScoreQuestion, N as AskSwitchQuestion, O as AskQuestion, P as ask, R as AskResult, S as AskChoiceCriteria, T as AskEntry, _ as AskAnswers, a as AiGatewayAskResult, b as AskChanceQuestion, c as AiGatewayDefinition, d as AiGatewaySealedSecret, f as AiGatewaySecret, g as AskAnswerType, h as AskAnswer, i as AiGatewayAskOptions, j as AskScoreCriteria, k as AskQuestions, l as AiGatewayDriver, m as AiGatewayValue, n as AiGatewayAsk, o as AiGatewayCapabilities, p as AiGatewayUsage, r as AiGatewayAskError, s as AiGatewayContext, t as AiGateway, u as AiGatewayRoute, v as AskChanceAnswer, w as AskChoiceQuestion, x as AskChoiceAnswer, y as AskChanceCriteria, z as AskSchema } from "./types-
|
|
2
|
-
import {
|
|
3
|
-
export { type AiAskGatewayOptions, type AiGateway, type AiGatewayAsk, type AiGatewayAskError, type AiGatewayAskOptions, type AiGatewayAskResult, type AiGatewayCapabilities, type AiGatewayContext, type AiGatewayDefinition, type AiGatewayDriver, type AiGatewayEnvField, type AiGatewayPresetOptions, type AiGatewayRoute, type AiGatewaySealedSecret, type AiGatewaySecret, type AiGatewayUsage, type AiGatewayValue, type AiHostedGatewayOptions, type AiModelGateway, type AskAnswer, type AskAnswerType, type AskAnswers, type AskChanceAnswer, type AskChanceCriteria, type AskChanceQuestion, type AskChoiceAnswer, type AskChoiceCriteria, type AskChoiceLabels, type AskChoiceQuestion, type AskEntry, type AskError, type AskIfQuestion, type AskJson, type AskModel, type AskOptions, type AskQuestion, type AskQuestions, type AskResult, type AskSchema, type AskScoreAnswer, type AskScoreCriteria, type AskScoreQuestion, type AskSwitchQuestion, type ChatGPTGateway, type CloudflareAccessOptions, type CloudflareGatewayOptions, type TypesafeGatewayOptions, type VercelGatewayOptions, aiGatewayEnv, anthropic, ask, askWithModel, chatgpt, cliproxy, cloudflare, cloudflareAccess, defineAiGateway, litellm, ollama, openai, openrouter, typesafe, vercel };
|
|
1
|
+
import { A as AskScoreAnswer, B as askWithModel, C as AskChoiceLabels, D as AskJson, E as AskIfQuestion, F as AskError, I as AskModel, L as AskOptions, M as AskScoreQuestion, N as AskSwitchQuestion, O as AskQuestion, P as ask, R as AskResult, S as AskChoiceCriteria, T as AskEntry, _ as AskAnswers, a as AiGatewayAskResult, b as AskChanceQuestion, c as AiGatewayDefinition, d as AiGatewaySealedSecret, f as AiGatewaySecret, g as AskAnswerType, h as AskAnswer, i as AiGatewayAskOptions, j as AskScoreCriteria, k as AskQuestions, l as AiGatewayDriver, m as AiGatewayValue, n as AiGatewayAsk, o as AiGatewayCapabilities, p as AiGatewayUsage, r as AiGatewayAskError, s as AiGatewayContext, t as AiGateway, u as AiGatewayRoute, v as AskChanceAnswer, w as AskChoiceQuestion, x as AskChoiceAnswer, y as AskChanceCriteria, z as AskSchema } from "./types-CYigOOA5.js";
|
|
2
|
+
import { A as chatgpt, D as aiGatewayEnv, S as vercel, _ as litellm, a as CloudflareAccessOptions, b as openrouter, c as TypesafeGatewayOptions, f as cliproxy, g as emulate, h as defineAiGateway, i as AiModelGateway, k as ChatGPTGateway, l as VercelGatewayOptions, m as cloudflareAccess, n as AiGatewayPresetOptions, o as CloudflareGatewayOptions, p as cloudflare, r as AiHostedGatewayOptions, s as EmulateGatewayOptions, t as AiAskGatewayOptions, u as anthropic, v as ollama, w as AiGatewayEnvField, x as typesafe, y as openai } from "./presets-xSYbZBJS.js";
|
|
3
|
+
export { type AiAskGatewayOptions, type AiGateway, type AiGatewayAsk, type AiGatewayAskError, type AiGatewayAskOptions, type AiGatewayAskResult, type AiGatewayCapabilities, type AiGatewayContext, type AiGatewayDefinition, type AiGatewayDriver, type AiGatewayEnvField, type AiGatewayPresetOptions, type AiGatewayRoute, type AiGatewaySealedSecret, type AiGatewaySecret, type AiGatewayUsage, type AiGatewayValue, type AiHostedGatewayOptions, type AiModelGateway, type AskAnswer, type AskAnswerType, type AskAnswers, type AskChanceAnswer, type AskChanceCriteria, type AskChanceQuestion, type AskChoiceAnswer, type AskChoiceCriteria, type AskChoiceLabels, type AskChoiceQuestion, type AskEntry, type AskError, type AskIfQuestion, type AskJson, type AskModel, type AskOptions, type AskQuestion, type AskQuestions, type AskResult, type AskSchema, type AskScoreAnswer, type AskScoreCriteria, type AskScoreQuestion, type AskSwitchQuestion, type ChatGPTGateway, type CloudflareAccessOptions, type CloudflareGatewayOptions, type EmulateGatewayOptions, type TypesafeGatewayOptions, type VercelGatewayOptions, aiGatewayEnv, anthropic, ask, askWithModel, chatgpt, cliproxy, cloudflare, cloudflareAccess, defineAiGateway, emulate, litellm, ollama, openai, openrouter, typesafe, vercel };
|