@tanstack/ai-vercel-gateway 0.2.11 → 0.2.14

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-vercel-gateway",
3
- "version": "0.2.11",
3
+ "version": "0.2.14",
4
4
  "description": "Vercel AI Gateway adapter for TanStack AI chat, embeddings, and image generation.",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -56,12 +56,12 @@
56
56
  "vite": "^8.2.1"
57
57
  },
58
58
  "peerDependencies": {
59
- "@tanstack/ai": "^0.55.0"
59
+ "@tanstack/ai": "^0.57.0"
60
60
  },
61
61
  "dependencies": {
62
62
  "openai": "^6.41.0",
63
63
  "@tanstack/ai-utils": "^0.4.0",
64
- "@tanstack/openai-base": "^0.10.12"
64
+ "@tanstack/openai-base": "^0.10.14"
65
65
  },
66
66
  "scripts": {
67
67
  "build": "vite build",
@@ -0,0 +1,393 @@
1
+ import { BaseEvaluateAdapter } from '@tanstack/ai/adapters'
2
+ import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
3
+ import {
4
+ getVercelGatewayApiKeyFromEnv,
5
+ withVercelGatewayDefaults,
6
+ } from '../utils/client'
7
+ import { mapGatewayModelOptions } from '../utils/map-gateway-options'
8
+ import type {
9
+ EvaluateAdapterResult,
10
+ EvaluateOptions,
11
+ WireAnswer,
12
+ WireQuestion,
13
+ } from '@tanstack/ai/adapters'
14
+ import type { VercelGatewayClientConfig } from '../utils/client'
15
+ import type { VercelGatewayRoutingOptions } from '../text/text-provider-options'
16
+
17
+ export interface VercelGatewayEvaluateConfig extends VercelGatewayClientConfig {}
18
+
19
+ export type VercelGatewayEvaluateModel = 'typesafe-ai/jev'
20
+
21
+ export type VercelGatewayEvaluateProviderOptions = Record<string, unknown> & {
22
+ gateway?: VercelGatewayRoutingOptions
23
+ }
24
+
25
+ /**
26
+ * Documented evaluate URL from Vercel AI SDK `GatewayEvaluationModel.getUrl()`:
27
+ * `${baseURL}/evaluation-model` with default baseURL
28
+ * `https://ai-gateway.vercel.sh/v4/ai`. Not `/v1/chat/completions`.
29
+ * https://github.com/vercel/ai/blob/main/packages/gateway/src/gateway-evaluation-model.ts
30
+ */
31
+ const EVALUATE_PATH = '/v4/ai/evaluation-model'
32
+ const DEFAULT_EVALUATE_URL = `https://ai-gateway.vercel.sh${EVALUATE_PATH}`
33
+
34
+ /** The gateway rejects the request with 400 when this header is absent. */
35
+ const GATEWAY_PROTOCOL_VERSION = '0.0.1'
36
+
37
+ function isRecord(value: unknown): value is Record<string, unknown> {
38
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
39
+ }
40
+
41
+ function isNumberRecord(value: unknown): value is Record<string, number> {
42
+ if (!isRecord(value)) return false
43
+ const values = Object.values(value)
44
+ for (const item of values) {
45
+ if (typeof item !== 'number') return false
46
+ }
47
+ return true
48
+ }
49
+
50
+ function isStringRecord(value: unknown): value is Record<string, string> {
51
+ if (!isRecord(value)) return false
52
+ const values = Object.values(value)
53
+ for (const item of values) {
54
+ if (typeof item !== 'string') return false
55
+ }
56
+ return true
57
+ }
58
+
59
+ function extraRequestHeaders(defaultHeaders: unknown) {
60
+ if (defaultHeaders == null) return {}
61
+ if (typeof Headers !== 'undefined' && defaultHeaders instanceof Headers) {
62
+ const headers: Record<string, string> = {}
63
+ const entries = defaultHeaders.entries()
64
+ for (const [key, value] of entries) {
65
+ headers[key] = value
66
+ }
67
+ return headers
68
+ }
69
+ if (Array.isArray(defaultHeaders)) {
70
+ const headers: Record<string, string> = {}
71
+ for (const entry of defaultHeaders) {
72
+ if (!Array.isArray(entry) || entry.length < 2) continue
73
+ const key = entry[0]
74
+ const value = entry[1]
75
+ if (typeof key === 'string' && typeof value === 'string') {
76
+ headers[key] = value
77
+ }
78
+ }
79
+ return headers
80
+ }
81
+ if (!isRecord(defaultHeaders)) return {}
82
+ const headers: Record<string, string> = {}
83
+ const keys = Object.keys(defaultHeaders)
84
+ for (const key of keys) {
85
+ const value = defaultHeaders[key]
86
+ if (typeof value === 'string') headers[key] = value
87
+ }
88
+ return headers
89
+ }
90
+
91
+ function resolveEvaluateUrl(baseURL: string | null | undefined) {
92
+ if (!baseURL) return DEFAULT_EVALUATE_URL
93
+ try {
94
+ return `${new URL(baseURL).origin}${EVALUATE_PATH}`
95
+ } catch {
96
+ return DEFAULT_EVALUATE_URL
97
+ }
98
+ }
99
+
100
+ function toGatewayQuestion(question: WireQuestion) {
101
+ switch (question.type) {
102
+ case 'noul': {
103
+ if (question.criteria === undefined) {
104
+ return {
105
+ type: 'boolean' as const,
106
+ instructions: question.instructions,
107
+ }
108
+ }
109
+ return {
110
+ type: 'boolean' as const,
111
+ instructions: question.instructions,
112
+ criteria: question.criteria,
113
+ }
114
+ }
115
+ case 'choice':
116
+ case 'score':
117
+ return question
118
+ }
119
+ }
120
+
121
+ function toGatewayQuestions(questions: Record<string, WireQuestion>) {
122
+ const mapped: Record<string, unknown> = {}
123
+ const keys = Object.keys(questions)
124
+ for (const key of keys) {
125
+ const question = questions[key]
126
+ if (question === undefined) continue
127
+ mapped[key] = toGatewayQuestion(question)
128
+ }
129
+ return mapped
130
+ }
131
+
132
+ function readCount(candidates: Array<unknown>) {
133
+ for (const candidate of candidates) {
134
+ if (typeof candidate === 'number') return candidate
135
+ }
136
+ return 0
137
+ }
138
+
139
+ function toTokenUsage(usage: unknown) {
140
+ if (!isRecord(usage)) {
141
+ return { promptTokens: 0, completionTokens: 0, totalTokens: 0 }
142
+ }
143
+ const promptTokens = readCount([
144
+ usage.inputTokens,
145
+ usage.input_tokens,
146
+ usage.promptTokens,
147
+ usage.prompt_tokens,
148
+ ])
149
+ const completionTokens = readCount([
150
+ usage.outputTokens,
151
+ usage.output_tokens,
152
+ usage.completionTokens,
153
+ usage.completion_tokens,
154
+ ])
155
+ const totalTokens = readCount([
156
+ usage.totalTokens,
157
+ usage.total_tokens,
158
+ promptTokens + completionTokens,
159
+ ])
160
+ return { promptTokens, completionTokens, totalTokens }
161
+ }
162
+
163
+ function confidenceMap(providerMetadata: unknown) {
164
+ if (!isRecord(providerMetadata)) return {}
165
+ const typesafe = providerMetadata.typesafe
166
+ if (!isRecord(typesafe)) return {}
167
+ if (!isNumberRecord(typesafe.confidence)) return {}
168
+ return typesafe.confidence
169
+ }
170
+
171
+ function confidenceFor(
172
+ key: string,
173
+ answer: Record<string, unknown>,
174
+ byKey: Record<string, number>,
175
+ ) {
176
+ if (typeof answer.confidence === 'number') return answer.confidence
177
+ const fromMeta = byKey[key]
178
+ if (typeof fromMeta === 'number') return fromMeta
179
+ return 0
180
+ }
181
+
182
+ function toWireAnswer(answer: Record<string, unknown>, confidence: number) {
183
+ switch (answer.type) {
184
+ case 'boolean': {
185
+ if (typeof answer.probability !== 'number') {
186
+ throw new Error(
187
+ 'Vercel Gateway evaluate boolean answer was missing probability',
188
+ )
189
+ }
190
+ return { type: 'noul' as const, noul: answer.probability }
191
+ }
192
+ case 'choice': {
193
+ if (typeof answer.choice !== 'string') {
194
+ throw new Error(
195
+ 'Vercel Gateway evaluate choice answer was missing choice',
196
+ )
197
+ }
198
+ return {
199
+ type: 'choice' as const,
200
+ choice: answer.choice,
201
+ probabilities: isNumberRecord(answer.probabilities)
202
+ ? answer.probabilities
203
+ : {},
204
+ confidence,
205
+ }
206
+ }
207
+ case 'score': {
208
+ if (typeof answer.score !== 'number') {
209
+ throw new Error(
210
+ 'Vercel Gateway evaluate score answer was missing score',
211
+ )
212
+ }
213
+ return {
214
+ type: 'score' as const,
215
+ score: answer.score,
216
+ legend: isStringRecord(answer.legend) ? answer.legend : {},
217
+ probabilities: isNumberRecord(answer.probabilities)
218
+ ? answer.probabilities
219
+ : {},
220
+ confidence,
221
+ }
222
+ }
223
+ default:
224
+ throw new Error(
225
+ `Vercel Gateway evaluate answer had an unexpected type: ${String(answer.type)}`,
226
+ )
227
+ }
228
+ }
229
+
230
+ function toWireAnswers(answers: unknown, byKey: Record<string, number>) {
231
+ if (!isRecord(answers)) {
232
+ throw new Error('Vercel Gateway evaluate response was missing answers')
233
+ }
234
+ const mapped: Record<string, WireAnswer> = {}
235
+ const keys = Object.keys(answers)
236
+ for (const key of keys) {
237
+ const answer = answers[key]
238
+ if (!isRecord(answer)) {
239
+ throw new Error(
240
+ `Vercel Gateway evaluate answer "${key}" had an unexpected shape`,
241
+ )
242
+ }
243
+ mapped[key] = toWireAnswer(answer, confidenceFor(key, answer, byKey))
244
+ }
245
+ return mapped
246
+ }
247
+
248
+ /**
249
+ * Vercel AI Gateway evaluate adapter.
250
+ *
251
+ * Talks to `POST /v4/ai/evaluation-model` with `fetch`. Jev is not a chat
252
+ * model; this adapter does not use `/v1/chat/completions`.
253
+ */
254
+ export class VercelGatewayEvaluateAdapter<
255
+ TModel extends VercelGatewayEvaluateModel,
256
+ > extends BaseEvaluateAdapter<TModel, VercelGatewayEvaluateProviderOptions> {
257
+ readonly name = 'vercel-gateway' as const
258
+
259
+ private readonly apiKey: string
260
+ private readonly evaluateUrl: string
261
+ private readonly extraHeaders: Record<string, string>
262
+
263
+ constructor(config: VercelGatewayEvaluateConfig, model: TModel) {
264
+ super({}, model)
265
+ const defaults = withVercelGatewayDefaults(config)
266
+ this.apiKey = config.apiKey
267
+ this.evaluateUrl = resolveEvaluateUrl(defaults.baseURL)
268
+ this.extraHeaders = extraRequestHeaders(defaults.defaultHeaders)
269
+ }
270
+
271
+ async evaluate(
272
+ options: EvaluateOptions<VercelGatewayEvaluateProviderOptions>,
273
+ ) {
274
+ const { model, state, questions, modelOptions, abortSignal, logger } =
275
+ options
276
+ const mapped = mapGatewayModelOptions(modelOptions)
277
+
278
+ logger.request(`activity=evaluate provider=${this.name} model=${model}`, {
279
+ provider: this.name,
280
+ model,
281
+ })
282
+
283
+ try {
284
+ const response = await fetch(this.evaluateUrl, {
285
+ method: 'POST',
286
+ headers: {
287
+ ...this.extraHeaders,
288
+ Authorization: `Bearer ${this.apiKey}`,
289
+ 'Content-Type': 'application/json',
290
+ 'ai-gateway-protocol-version': GATEWAY_PROTOCOL_VERSION,
291
+ 'ai-evaluation-model-specification-version': '4',
292
+ 'ai-model-id': model,
293
+ },
294
+ body: JSON.stringify({
295
+ ...mapped,
296
+ model,
297
+ state,
298
+ questions: toGatewayQuestions(questions),
299
+ }),
300
+ ...(abortSignal ? { signal: abortSignal } : {}),
301
+ })
302
+
303
+ if (!response.ok) {
304
+ const detail = await response.text().catch(() => '')
305
+ throw new Error(
306
+ `Vercel Gateway evaluate request failed: ${response.status} ${response.statusText}${
307
+ detail ? ` — ${detail}` : ''
308
+ }`,
309
+ )
310
+ }
311
+
312
+ const json: unknown = await response.json()
313
+ if (!isRecord(json)) {
314
+ throw new Error(
315
+ 'Vercel Gateway evaluate response had an unexpected shape',
316
+ )
317
+ }
318
+
319
+ const result: EvaluateAdapterResult = {
320
+ model: typeof json.model === 'string' ? json.model : model,
321
+ answers: toWireAnswers(
322
+ json.answers,
323
+ confidenceMap(json.providerMetadata),
324
+ ),
325
+ usage: toTokenUsage(json.usage),
326
+ }
327
+ return result
328
+ } catch (error: unknown) {
329
+ logger.errors(`${this.name}.evaluate fatal`, {
330
+ error: toRunErrorPayload(error, `${this.name}.evaluate failed`),
331
+ source: `${this.name}.evaluate`,
332
+ })
333
+ throw error
334
+ }
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Create a Vercel AI Gateway evaluate adapter with an explicit API key.
340
+ *
341
+ * @param model Evaluate model id. Use `typesafe-ai/jev`.
342
+ * @param apiKey Vercel AI Gateway API key.
343
+ * @param config Optional client config (`baseURL`, `httpReferer`, `xTitle`).
344
+ *
345
+ * @example
346
+ * ```ts
347
+ * const adapter = createVercelGatewayDecider('typesafe-ai/jev', 'vck_...')
348
+ * ```
349
+ */
350
+ export function createVercelGatewayDecider<
351
+ TModel extends VercelGatewayEvaluateModel,
352
+ >(
353
+ model: TModel,
354
+ apiKey: string,
355
+ config?: Omit<VercelGatewayEvaluateConfig, 'apiKey'>,
356
+ ) {
357
+ return new VercelGatewayEvaluateAdapter({ apiKey, ...config }, model)
358
+ }
359
+
360
+ /**
361
+ * Create a Vercel AI Gateway evaluate adapter.
362
+ *
363
+ * Reads `AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN`.
364
+ *
365
+ * @param model Evaluate model id. Use `typesafe-ai/jev`.
366
+ * @param config Optional client config (`baseURL`, `httpReferer`, `xTitle`).
367
+ *
368
+ * @example
369
+ * ```ts
370
+ * import { decide, boolean } from '@tanstack/ai'
371
+ * import { vercelGatewayDecider } from '@tanstack/ai-vercel-gateway'
372
+ *
373
+ * const result = await decide({
374
+ * adapter: vercelGatewayDecider('typesafe-ai/jev'),
375
+ * state: ticket,
376
+ * questions: {
377
+ * refund: boolean({
378
+ * instructions: 'Is the customer asking for a refund?',
379
+ * }),
380
+ * },
381
+ * })
382
+ * ```
383
+ */
384
+ export function vercelGatewayDecider<TModel extends VercelGatewayEvaluateModel>(
385
+ model: TModel,
386
+ config?: Omit<VercelGatewayEvaluateConfig, 'apiKey'>,
387
+ ) {
388
+ return createVercelGatewayDecider(
389
+ model,
390
+ getVercelGatewayApiKeyFromEnv(),
391
+ config,
392
+ )
393
+ }
package/src/index.ts CHANGED
@@ -47,6 +47,13 @@ export {
47
47
  type VercelGatewayImageConfig,
48
48
  } from './adapters/image'
49
49
 
50
+ export {
51
+ VercelGatewayEvaluateAdapter,
52
+ createVercelGatewayDecider,
53
+ vercelGatewayDecider,
54
+ type VercelGatewayEvaluateConfig,
55
+ } from './adapters/evaluate'
56
+
50
57
  export type { VercelGatewayEmbeddingProviderOptions } from './embedding/embedding-provider-options'
51
58
  export type { VercelGatewayImageProviderOptions } from './image/image-provider-options'
52
59
  export type {
package/src/model-meta.ts CHANGED
@@ -124,10 +124,6 @@ export const VERCEL_GATEWAY_CHAT_MODELS = [
124
124
  'inference-net/schematron-v2-small',
125
125
  'inference-net/schematron-v2-turbo',
126
126
  'interfaze/interfaze-beta',
127
- 'kwaipilot/kat-coder-air-v2.5',
128
- 'kwaipilot/kat-coder-pro-v1',
129
- 'kwaipilot/kat-coder-pro-v2',
130
- 'kwaipilot/kat-coder-pro-v2.5',
131
127
  'meta/llama-3.1-70b',
132
128
  'meta/llama-3.1-8b',
133
129
  'meta/llama-3.3-70b',
@@ -274,6 +270,7 @@ export const VERCEL_GATEWAY_CHAT_MODELS = [
274
270
  'tencent/hy4-preview',
275
271
  'thinkingmachines/inkling',
276
272
  'thinkingmachines/inkling-small',
273
+ 'typesafe-ai/jev',
277
274
  'xiaomi/mimo-v2.5',
278
275
  'xiaomi/mimo-v2.5-pro',
279
276
  'zai/glm-4.5',
@@ -312,7 +309,6 @@ export const VERCEL_GATEWAY_PROVIDERS = [
312
309
  'inference-net',
313
310
  'interfaze',
314
311
  'klingai',
315
- 'kwaipilot',
316
312
  'meta',
317
313
  'minimax',
318
314
  'mistral',
@@ -330,6 +326,7 @@ export const VERCEL_GATEWAY_PROVIDERS = [
330
326
  'stepfun',
331
327
  'tencent',
332
328
  'thinkingmachines',
329
+ 'typesafe-ai',
333
330
  'voyage',
334
331
  'xiaomi',
335
332
  'zai',
@@ -1333,41 +1330,6 @@ export type VercelGatewayChatModelProviderOptionsByName = {
1333
1330
  | 'reasoning'
1334
1331
  | 'include_reasoning'
1335
1332
  >
1336
- 'kwaipilot/kat-coder-air-v2.5': VercelGatewayCommonOptions &
1337
- Pick<
1338
- VercelGatewayBaseOptions,
1339
- | 'max_tokens'
1340
- | 'max_output_tokens'
1341
- | 'temperature'
1342
- | 'stop'
1343
- | 'reasoning'
1344
- | 'include_reasoning'
1345
- >
1346
- 'kwaipilot/kat-coder-pro-v1': VercelGatewayCommonOptions &
1347
- Pick<
1348
- VercelGatewayBaseOptions,
1349
- 'max_tokens' | 'max_output_tokens' | 'temperature' | 'stop'
1350
- >
1351
- 'kwaipilot/kat-coder-pro-v2': VercelGatewayCommonOptions &
1352
- Pick<
1353
- VercelGatewayBaseOptions,
1354
- | 'max_tokens'
1355
- | 'max_output_tokens'
1356
- | 'temperature'
1357
- | 'stop'
1358
- | 'reasoning'
1359
- | 'include_reasoning'
1360
- >
1361
- 'kwaipilot/kat-coder-pro-v2.5': VercelGatewayCommonOptions &
1362
- Pick<
1363
- VercelGatewayBaseOptions,
1364
- | 'max_tokens'
1365
- | 'max_output_tokens'
1366
- | 'temperature'
1367
- | 'stop'
1368
- | 'reasoning'
1369
- | 'include_reasoning'
1370
- >
1371
1333
  'meta/llama-3.1-70b': VercelGatewayCommonOptions &
1372
1334
  Pick<
1373
1335
  VercelGatewayBaseOptions,
@@ -2533,6 +2495,7 @@ export type VercelGatewayChatModelProviderOptionsByName = {
2533
2495
  | 'reasoning'
2534
2496
  | 'include_reasoning'
2535
2497
  >
2498
+ 'typesafe-ai/jev': VercelGatewayCommonOptions
2536
2499
  'xiaomi/mimo-v2.5': VercelGatewayCommonOptions &
2537
2500
  Pick<
2538
2501
  VercelGatewayBaseOptions,
@@ -2836,10 +2799,6 @@ export type VercelGatewayModelInputModalitiesByName = {
2836
2799
  'inference-net/schematron-v2-small': readonly ['text']
2837
2800
  'inference-net/schematron-v2-turbo': readonly ['text']
2838
2801
  'interfaze/interfaze-beta': readonly ['text', 'image', 'document']
2839
- 'kwaipilot/kat-coder-air-v2.5': readonly ['text', 'image']
2840
- 'kwaipilot/kat-coder-pro-v1': readonly ['text']
2841
- 'kwaipilot/kat-coder-pro-v2': readonly ['text']
2842
- 'kwaipilot/kat-coder-pro-v2.5': readonly ['text', 'image']
2843
2802
  'meta/llama-3.1-70b': readonly ['text']
2844
2803
  'meta/llama-3.1-8b': readonly ['text']
2845
2804
  'meta/llama-3.3-70b': readonly ['text']
@@ -2869,7 +2828,7 @@ export type VercelGatewayModelInputModalitiesByName = {
2869
2828
  'mistral/mistral-small': readonly ['text', 'image']
2870
2829
  'moonshotai/kimi-k2': readonly ['text']
2871
2830
  'moonshotai/kimi-k2-thinking': readonly ['text']
2872
- 'moonshotai/kimi-k2.5': readonly ['text', 'image', 'video']
2831
+ 'moonshotai/kimi-k2.5': readonly ['text', 'image']
2873
2832
  'moonshotai/kimi-k2.6': readonly ['text', 'image', 'video']
2874
2833
  'moonshotai/kimi-k2.7-code': readonly ['text', 'image', 'document', 'video']
2875
2834
  'moonshotai/kimi-k2.7-code-highspeed': readonly [
@@ -2995,6 +2954,7 @@ export type VercelGatewayModelInputModalitiesByName = {
2995
2954
  'tencent/hy4-preview': readonly ['text']
2996
2955
  'thinkingmachines/inkling': readonly ['text', 'image', 'document']
2997
2956
  'thinkingmachines/inkling-small': readonly ['text', 'image', 'document']
2957
+ 'typesafe-ai/jev': readonly ['text']
2998
2958
  'xiaomi/mimo-v2.5': readonly ['text', 'image']
2999
2959
  'xiaomi/mimo-v2.5-pro': readonly ['text']
3000
2960
  'zai/glm-4.5': readonly ['text']