Open History to see the last commit
1import { BaseEvaluateAdapter } from '@tanstack/ai/adapters'
2import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
3import {
4 getVercelGatewayApiKeyFromEnv,
5 withVercelGatewayDefaults,
6} from '../utils/client'
7import { mapGatewayModelOptions } from '../utils/map-gateway-options'
8import type {
9 EvaluateAdapterResult,
10 EvaluateOptions,
11 WireAnswer,
12 WireQuestion,
13} from '@tanstack/ai/adapters'
14import type { VercelGatewayClientConfig } from '../utils/client'
15import type { VercelGatewayRoutingOptions } from '../text/text-provider-options'
16
17export interface VercelGatewayEvaluateConfig extends VercelGatewayClientConfig {}
18
19export type VercelGatewayEvaluateModel = 'typesafe-ai/jev'
20
21export 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 */
31const EVALUATE_PATH = '/v4/ai/evaluation-model'
32const DEFAULT_EVALUATE_URL = `https://ai-gateway.vercel.sh${EVALUATE_PATH}`
33
34/** The gateway rejects the request with 400 when this header is absent. */
35const GATEWAY_PROTOCOL_VERSION = '0.0.1'
36
37function isRecord(value: unknown): value is Record<string, unknown> {
38 return typeof value === 'object' && value !== null && !Array.isArray(value)
39}
40
41function 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
50function 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
59function 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
91function 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
100function 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
121function 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
132function readCount(candidates: Array<unknown>) {
133 for (const candidate of candidates) {
134 if (typeof candidate === 'number') return candidate
135 }
136 return 0
137}
138
139function 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
163function 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
171function 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
182function 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
230function 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 */
254export 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 */
350export 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 */
384export 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}