@tanstack/ai-vercel-gateway 0.2.12 → 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.
@@ -0,0 +1,61 @@
1
+ import { BaseEvaluateAdapter, EvaluateAdapterResult, EvaluateOptions } from '@tanstack/ai/adapters';
2
+ import { VercelGatewayClientConfig } from '../utils/client.js';
3
+ import { VercelGatewayRoutingOptions } from '../text/text-provider-options.js';
4
+ export interface VercelGatewayEvaluateConfig extends VercelGatewayClientConfig {
5
+ }
6
+ export type VercelGatewayEvaluateModel = 'typesafe-ai/jev';
7
+ export type VercelGatewayEvaluateProviderOptions = Record<string, unknown> & {
8
+ gateway?: VercelGatewayRoutingOptions;
9
+ };
10
+ /**
11
+ * Vercel AI Gateway evaluate adapter.
12
+ *
13
+ * Talks to `POST /v4/ai/evaluation-model` with `fetch`. Jev is not a chat
14
+ * model; this adapter does not use `/v1/chat/completions`.
15
+ */
16
+ export declare class VercelGatewayEvaluateAdapter<TModel extends VercelGatewayEvaluateModel> extends BaseEvaluateAdapter<TModel, VercelGatewayEvaluateProviderOptions> {
17
+ readonly name: "vercel-gateway";
18
+ private readonly apiKey;
19
+ private readonly evaluateUrl;
20
+ private readonly extraHeaders;
21
+ constructor(config: VercelGatewayEvaluateConfig, model: TModel);
22
+ evaluate(options: EvaluateOptions<VercelGatewayEvaluateProviderOptions>): Promise<EvaluateAdapterResult>;
23
+ }
24
+ /**
25
+ * Create a Vercel AI Gateway evaluate adapter with an explicit API key.
26
+ *
27
+ * @param model Evaluate model id. Use `typesafe-ai/jev`.
28
+ * @param apiKey Vercel AI Gateway API key.
29
+ * @param config Optional client config (`baseURL`, `httpReferer`, `xTitle`).
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * const adapter = createVercelGatewayDecider('typesafe-ai/jev', 'vck_...')
34
+ * ```
35
+ */
36
+ export declare function createVercelGatewayDecider<TModel extends VercelGatewayEvaluateModel>(model: TModel, apiKey: string, config?: Omit<VercelGatewayEvaluateConfig, 'apiKey'>): VercelGatewayEvaluateAdapter<TModel>;
37
+ /**
38
+ * Create a Vercel AI Gateway evaluate adapter.
39
+ *
40
+ * Reads `AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN`.
41
+ *
42
+ * @param model Evaluate model id. Use `typesafe-ai/jev`.
43
+ * @param config Optional client config (`baseURL`, `httpReferer`, `xTitle`).
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * import { decide, boolean } from '@tanstack/ai'
48
+ * import { vercelGatewayDecider } from '@tanstack/ai-vercel-gateway'
49
+ *
50
+ * const result = await decide({
51
+ * adapter: vercelGatewayDecider('typesafe-ai/jev'),
52
+ * state: ticket,
53
+ * questions: {
54
+ * refund: boolean({
55
+ * instructions: 'Is the customer asking for a refund?',
56
+ * }),
57
+ * },
58
+ * })
59
+ * ```
60
+ */
61
+ export declare function vercelGatewayDecider<TModel extends VercelGatewayEvaluateModel>(model: TModel, config?: Omit<VercelGatewayEvaluateConfig, 'apiKey'>): VercelGatewayEvaluateAdapter<TModel>;
@@ -0,0 +1,288 @@
1
+ import { getVercelGatewayApiKeyFromEnv, withVercelGatewayDefaults } from "../utils/client.js";
2
+ import { mapGatewayModelOptions } from "../utils/map-gateway-options.js";
3
+ import { BaseEvaluateAdapter } from "@tanstack/ai/adapters";
4
+ import { toRunErrorPayload } from "@tanstack/ai/adapter-internals";
5
+ //#region src/adapters/evaluate.ts
6
+ /**
7
+ * Documented evaluate URL from Vercel AI SDK `GatewayEvaluationModel.getUrl()`:
8
+ * `${baseURL}/evaluation-model` with default baseURL
9
+ * `https://ai-gateway.vercel.sh/v4/ai`. Not `/v1/chat/completions`.
10
+ * https://github.com/vercel/ai/blob/main/packages/gateway/src/gateway-evaluation-model.ts
11
+ */
12
+ var EVALUATE_PATH = "/v4/ai/evaluation-model";
13
+ var DEFAULT_EVALUATE_URL = `https://ai-gateway.vercel.sh${EVALUATE_PATH}`;
14
+ /** The gateway rejects the request with 400 when this header is absent. */
15
+ var GATEWAY_PROTOCOL_VERSION = "0.0.1";
16
+ function isRecord(value) {
17
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18
+ }
19
+ function isNumberRecord(value) {
20
+ if (!isRecord(value)) return false;
21
+ const values = Object.values(value);
22
+ for (const item of values) if (typeof item !== "number") return false;
23
+ return true;
24
+ }
25
+ function isStringRecord(value) {
26
+ if (!isRecord(value)) return false;
27
+ const values = Object.values(value);
28
+ for (const item of values) if (typeof item !== "string") return false;
29
+ return true;
30
+ }
31
+ function extraRequestHeaders(defaultHeaders) {
32
+ if (defaultHeaders == null) return {};
33
+ if (typeof Headers !== "undefined" && defaultHeaders instanceof Headers) {
34
+ const headers = {};
35
+ const entries = defaultHeaders.entries();
36
+ for (const [key, value] of entries) headers[key] = value;
37
+ return headers;
38
+ }
39
+ if (Array.isArray(defaultHeaders)) {
40
+ const headers = {};
41
+ for (const entry of defaultHeaders) {
42
+ if (!Array.isArray(entry) || entry.length < 2) continue;
43
+ const key = entry[0];
44
+ const value = entry[1];
45
+ if (typeof key === "string" && typeof value === "string") headers[key] = value;
46
+ }
47
+ return headers;
48
+ }
49
+ if (!isRecord(defaultHeaders)) return {};
50
+ const headers = {};
51
+ const keys = Object.keys(defaultHeaders);
52
+ for (const key of keys) {
53
+ const value = defaultHeaders[key];
54
+ if (typeof value === "string") headers[key] = value;
55
+ }
56
+ return headers;
57
+ }
58
+ function resolveEvaluateUrl(baseURL) {
59
+ if (!baseURL) return DEFAULT_EVALUATE_URL;
60
+ try {
61
+ return `${new URL(baseURL).origin}${EVALUATE_PATH}`;
62
+ } catch {
63
+ return DEFAULT_EVALUATE_URL;
64
+ }
65
+ }
66
+ function toGatewayQuestion(question) {
67
+ switch (question.type) {
68
+ case "noul":
69
+ if (question.criteria === void 0) return {
70
+ type: "boolean",
71
+ instructions: question.instructions
72
+ };
73
+ return {
74
+ type: "boolean",
75
+ instructions: question.instructions,
76
+ criteria: question.criteria
77
+ };
78
+ case "choice":
79
+ case "score": return question;
80
+ }
81
+ }
82
+ function toGatewayQuestions(questions) {
83
+ const mapped = {};
84
+ const keys = Object.keys(questions);
85
+ for (const key of keys) {
86
+ const question = questions[key];
87
+ if (question === void 0) continue;
88
+ mapped[key] = toGatewayQuestion(question);
89
+ }
90
+ return mapped;
91
+ }
92
+ function readCount(candidates) {
93
+ for (const candidate of candidates) if (typeof candidate === "number") return candidate;
94
+ return 0;
95
+ }
96
+ function toTokenUsage(usage) {
97
+ if (!isRecord(usage)) return {
98
+ promptTokens: 0,
99
+ completionTokens: 0,
100
+ totalTokens: 0
101
+ };
102
+ const promptTokens = readCount([
103
+ usage.inputTokens,
104
+ usage.input_tokens,
105
+ usage.promptTokens,
106
+ usage.prompt_tokens
107
+ ]);
108
+ const completionTokens = readCount([
109
+ usage.outputTokens,
110
+ usage.output_tokens,
111
+ usage.completionTokens,
112
+ usage.completion_tokens
113
+ ]);
114
+ return {
115
+ promptTokens,
116
+ completionTokens,
117
+ totalTokens: readCount([
118
+ usage.totalTokens,
119
+ usage.total_tokens,
120
+ promptTokens + completionTokens
121
+ ])
122
+ };
123
+ }
124
+ function confidenceMap(providerMetadata) {
125
+ if (!isRecord(providerMetadata)) return {};
126
+ const typesafe = providerMetadata.typesafe;
127
+ if (!isRecord(typesafe)) return {};
128
+ if (!isNumberRecord(typesafe.confidence)) return {};
129
+ return typesafe.confidence;
130
+ }
131
+ function confidenceFor(key, answer, byKey) {
132
+ if (typeof answer.confidence === "number") return answer.confidence;
133
+ const fromMeta = byKey[key];
134
+ if (typeof fromMeta === "number") return fromMeta;
135
+ return 0;
136
+ }
137
+ function toWireAnswer(answer, confidence) {
138
+ switch (answer.type) {
139
+ case "boolean":
140
+ if (typeof answer.probability !== "number") throw new Error("Vercel Gateway evaluate boolean answer was missing probability");
141
+ return {
142
+ type: "noul",
143
+ noul: answer.probability
144
+ };
145
+ case "choice":
146
+ if (typeof answer.choice !== "string") throw new Error("Vercel Gateway evaluate choice answer was missing choice");
147
+ return {
148
+ type: "choice",
149
+ choice: answer.choice,
150
+ probabilities: isNumberRecord(answer.probabilities) ? answer.probabilities : {},
151
+ confidence
152
+ };
153
+ case "score":
154
+ if (typeof answer.score !== "number") throw new Error("Vercel Gateway evaluate score answer was missing score");
155
+ return {
156
+ type: "score",
157
+ score: answer.score,
158
+ legend: isStringRecord(answer.legend) ? answer.legend : {},
159
+ probabilities: isNumberRecord(answer.probabilities) ? answer.probabilities : {},
160
+ confidence
161
+ };
162
+ default: throw new Error(`Vercel Gateway evaluate answer had an unexpected type: ${String(answer.type)}`);
163
+ }
164
+ }
165
+ function toWireAnswers(answers, byKey) {
166
+ if (!isRecord(answers)) throw new Error("Vercel Gateway evaluate response was missing answers");
167
+ const mapped = {};
168
+ const keys = Object.keys(answers);
169
+ for (const key of keys) {
170
+ const answer = answers[key];
171
+ if (!isRecord(answer)) throw new Error(`Vercel Gateway evaluate answer "${key}" had an unexpected shape`);
172
+ mapped[key] = toWireAnswer(answer, confidenceFor(key, answer, byKey));
173
+ }
174
+ return mapped;
175
+ }
176
+ /**
177
+ * Vercel AI Gateway evaluate adapter.
178
+ *
179
+ * Talks to `POST /v4/ai/evaluation-model` with `fetch`. Jev is not a chat
180
+ * model; this adapter does not use `/v1/chat/completions`.
181
+ */
182
+ var VercelGatewayEvaluateAdapter = class extends BaseEvaluateAdapter {
183
+ name = "vercel-gateway";
184
+ apiKey;
185
+ evaluateUrl;
186
+ extraHeaders;
187
+ constructor(config, model) {
188
+ super({}, model);
189
+ const defaults = withVercelGatewayDefaults(config);
190
+ this.apiKey = config.apiKey;
191
+ this.evaluateUrl = resolveEvaluateUrl(defaults.baseURL);
192
+ this.extraHeaders = extraRequestHeaders(defaults.defaultHeaders);
193
+ }
194
+ async evaluate(options) {
195
+ const { model, state, questions, modelOptions, abortSignal, logger } = options;
196
+ const mapped = mapGatewayModelOptions(modelOptions);
197
+ logger.request(`activity=evaluate provider=${this.name} model=${model}`, {
198
+ provider: this.name,
199
+ model
200
+ });
201
+ try {
202
+ const response = await fetch(this.evaluateUrl, {
203
+ method: "POST",
204
+ headers: {
205
+ ...this.extraHeaders,
206
+ Authorization: `Bearer ${this.apiKey}`,
207
+ "Content-Type": "application/json",
208
+ "ai-gateway-protocol-version": GATEWAY_PROTOCOL_VERSION,
209
+ "ai-evaluation-model-specification-version": "4",
210
+ "ai-model-id": model
211
+ },
212
+ body: JSON.stringify({
213
+ ...mapped,
214
+ model,
215
+ state,
216
+ questions: toGatewayQuestions(questions)
217
+ }),
218
+ ...abortSignal ? { signal: abortSignal } : {}
219
+ });
220
+ if (!response.ok) {
221
+ const detail = await response.text().catch(() => "");
222
+ throw new Error(`Vercel Gateway evaluate request failed: ${response.status} ${response.statusText}${detail ? ` — ${detail}` : ""}`);
223
+ }
224
+ const json = await response.json();
225
+ if (!isRecord(json)) throw new Error("Vercel Gateway evaluate response had an unexpected shape");
226
+ return {
227
+ model: typeof json.model === "string" ? json.model : model,
228
+ answers: toWireAnswers(json.answers, confidenceMap(json.providerMetadata)),
229
+ usage: toTokenUsage(json.usage)
230
+ };
231
+ } catch (error) {
232
+ logger.errors(`${this.name}.evaluate fatal`, {
233
+ error: toRunErrorPayload(error, `${this.name}.evaluate failed`),
234
+ source: `${this.name}.evaluate`
235
+ });
236
+ throw error;
237
+ }
238
+ }
239
+ };
240
+ /**
241
+ * Create a Vercel AI Gateway evaluate adapter with an explicit API key.
242
+ *
243
+ * @param model Evaluate model id. Use `typesafe-ai/jev`.
244
+ * @param apiKey Vercel AI Gateway API key.
245
+ * @param config Optional client config (`baseURL`, `httpReferer`, `xTitle`).
246
+ *
247
+ * @example
248
+ * ```ts
249
+ * const adapter = createVercelGatewayDecider('typesafe-ai/jev', 'vck_...')
250
+ * ```
251
+ */
252
+ function createVercelGatewayDecider(model, apiKey, config) {
253
+ return new VercelGatewayEvaluateAdapter({
254
+ apiKey,
255
+ ...config
256
+ }, model);
257
+ }
258
+ /**
259
+ * Create a Vercel AI Gateway evaluate adapter.
260
+ *
261
+ * Reads `AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN`.
262
+ *
263
+ * @param model Evaluate model id. Use `typesafe-ai/jev`.
264
+ * @param config Optional client config (`baseURL`, `httpReferer`, `xTitle`).
265
+ *
266
+ * @example
267
+ * ```ts
268
+ * import { decide, boolean } from '@tanstack/ai'
269
+ * import { vercelGatewayDecider } from '@tanstack/ai-vercel-gateway'
270
+ *
271
+ * const result = await decide({
272
+ * adapter: vercelGatewayDecider('typesafe-ai/jev'),
273
+ * state: ticket,
274
+ * questions: {
275
+ * refund: boolean({
276
+ * instructions: 'Is the customer asking for a refund?',
277
+ * }),
278
+ * },
279
+ * })
280
+ * ```
281
+ */
282
+ function vercelGatewayDecider(model, config) {
283
+ return createVercelGatewayDecider(model, getVercelGatewayApiKeyFromEnv(), config);
284
+ }
285
+ //#endregion
286
+ export { VercelGatewayEvaluateAdapter, createVercelGatewayDecider, vercelGatewayDecider };
287
+
288
+ //# sourceMappingURL=evaluate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evaluate.js","names":[],"sources":["../../../src/adapters/evaluate.ts"],"sourcesContent":["import { BaseEvaluateAdapter } from '@tanstack/ai/adapters'\nimport { toRunErrorPayload } from '@tanstack/ai/adapter-internals'\nimport {\n getVercelGatewayApiKeyFromEnv,\n withVercelGatewayDefaults,\n} from '../utils/client'\nimport { mapGatewayModelOptions } from '../utils/map-gateway-options'\nimport type {\n EvaluateAdapterResult,\n EvaluateOptions,\n WireAnswer,\n WireQuestion,\n} from '@tanstack/ai/adapters'\nimport type { VercelGatewayClientConfig } from '../utils/client'\nimport type { VercelGatewayRoutingOptions } from '../text/text-provider-options'\n\nexport interface VercelGatewayEvaluateConfig extends VercelGatewayClientConfig {}\n\nexport type VercelGatewayEvaluateModel = 'typesafe-ai/jev'\n\nexport type VercelGatewayEvaluateProviderOptions = Record<string, unknown> & {\n gateway?: VercelGatewayRoutingOptions\n}\n\n/**\n * Documented evaluate URL from Vercel AI SDK `GatewayEvaluationModel.getUrl()`:\n * `${baseURL}/evaluation-model` with default baseURL\n * `https://ai-gateway.vercel.sh/v4/ai`. Not `/v1/chat/completions`.\n * https://github.com/vercel/ai/blob/main/packages/gateway/src/gateway-evaluation-model.ts\n */\nconst EVALUATE_PATH = '/v4/ai/evaluation-model'\nconst DEFAULT_EVALUATE_URL = `https://ai-gateway.vercel.sh${EVALUATE_PATH}`\n\n/** The gateway rejects the request with 400 when this header is absent. */\nconst GATEWAY_PROTOCOL_VERSION = '0.0.1'\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isNumberRecord(value: unknown): value is Record<string, number> {\n if (!isRecord(value)) return false\n const values = Object.values(value)\n for (const item of values) {\n if (typeof item !== 'number') return false\n }\n return true\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n if (!isRecord(value)) return false\n const values = Object.values(value)\n for (const item of values) {\n if (typeof item !== 'string') return false\n }\n return true\n}\n\nfunction extraRequestHeaders(defaultHeaders: unknown) {\n if (defaultHeaders == null) return {}\n if (typeof Headers !== 'undefined' && defaultHeaders instanceof Headers) {\n const headers: Record<string, string> = {}\n const entries = defaultHeaders.entries()\n for (const [key, value] of entries) {\n headers[key] = value\n }\n return headers\n }\n if (Array.isArray(defaultHeaders)) {\n const headers: Record<string, string> = {}\n for (const entry of defaultHeaders) {\n if (!Array.isArray(entry) || entry.length < 2) continue\n const key = entry[0]\n const value = entry[1]\n if (typeof key === 'string' && typeof value === 'string') {\n headers[key] = value\n }\n }\n return headers\n }\n if (!isRecord(defaultHeaders)) return {}\n const headers: Record<string, string> = {}\n const keys = Object.keys(defaultHeaders)\n for (const key of keys) {\n const value = defaultHeaders[key]\n if (typeof value === 'string') headers[key] = value\n }\n return headers\n}\n\nfunction resolveEvaluateUrl(baseURL: string | null | undefined) {\n if (!baseURL) return DEFAULT_EVALUATE_URL\n try {\n return `${new URL(baseURL).origin}${EVALUATE_PATH}`\n } catch {\n return DEFAULT_EVALUATE_URL\n }\n}\n\nfunction toGatewayQuestion(question: WireQuestion) {\n switch (question.type) {\n case 'noul': {\n if (question.criteria === undefined) {\n return {\n type: 'boolean' as const,\n instructions: question.instructions,\n }\n }\n return {\n type: 'boolean' as const,\n instructions: question.instructions,\n criteria: question.criteria,\n }\n }\n case 'choice':\n case 'score':\n return question\n }\n}\n\nfunction toGatewayQuestions(questions: Record<string, WireQuestion>) {\n const mapped: Record<string, unknown> = {}\n const keys = Object.keys(questions)\n for (const key of keys) {\n const question = questions[key]\n if (question === undefined) continue\n mapped[key] = toGatewayQuestion(question)\n }\n return mapped\n}\n\nfunction readCount(candidates: Array<unknown>) {\n for (const candidate of candidates) {\n if (typeof candidate === 'number') return candidate\n }\n return 0\n}\n\nfunction toTokenUsage(usage: unknown) {\n if (!isRecord(usage)) {\n return { promptTokens: 0, completionTokens: 0, totalTokens: 0 }\n }\n const promptTokens = readCount([\n usage.inputTokens,\n usage.input_tokens,\n usage.promptTokens,\n usage.prompt_tokens,\n ])\n const completionTokens = readCount([\n usage.outputTokens,\n usage.output_tokens,\n usage.completionTokens,\n usage.completion_tokens,\n ])\n const totalTokens = readCount([\n usage.totalTokens,\n usage.total_tokens,\n promptTokens + completionTokens,\n ])\n return { promptTokens, completionTokens, totalTokens }\n}\n\nfunction confidenceMap(providerMetadata: unknown) {\n if (!isRecord(providerMetadata)) return {}\n const typesafe = providerMetadata.typesafe\n if (!isRecord(typesafe)) return {}\n if (!isNumberRecord(typesafe.confidence)) return {}\n return typesafe.confidence\n}\n\nfunction confidenceFor(\n key: string,\n answer: Record<string, unknown>,\n byKey: Record<string, number>,\n) {\n if (typeof answer.confidence === 'number') return answer.confidence\n const fromMeta = byKey[key]\n if (typeof fromMeta === 'number') return fromMeta\n return 0\n}\n\nfunction toWireAnswer(answer: Record<string, unknown>, confidence: number) {\n switch (answer.type) {\n case 'boolean': {\n if (typeof answer.probability !== 'number') {\n throw new Error(\n 'Vercel Gateway evaluate boolean answer was missing probability',\n )\n }\n return { type: 'noul' as const, noul: answer.probability }\n }\n case 'choice': {\n if (typeof answer.choice !== 'string') {\n throw new Error(\n 'Vercel Gateway evaluate choice answer was missing choice',\n )\n }\n return {\n type: 'choice' as const,\n choice: answer.choice,\n probabilities: isNumberRecord(answer.probabilities)\n ? answer.probabilities\n : {},\n confidence,\n }\n }\n case 'score': {\n if (typeof answer.score !== 'number') {\n throw new Error(\n 'Vercel Gateway evaluate score answer was missing score',\n )\n }\n return {\n type: 'score' as const,\n score: answer.score,\n legend: isStringRecord(answer.legend) ? answer.legend : {},\n probabilities: isNumberRecord(answer.probabilities)\n ? answer.probabilities\n : {},\n confidence,\n }\n }\n default:\n throw new Error(\n `Vercel Gateway evaluate answer had an unexpected type: ${String(answer.type)}`,\n )\n }\n}\n\nfunction toWireAnswers(answers: unknown, byKey: Record<string, number>) {\n if (!isRecord(answers)) {\n throw new Error('Vercel Gateway evaluate response was missing answers')\n }\n const mapped: Record<string, WireAnswer> = {}\n const keys = Object.keys(answers)\n for (const key of keys) {\n const answer = answers[key]\n if (!isRecord(answer)) {\n throw new Error(\n `Vercel Gateway evaluate answer \"${key}\" had an unexpected shape`,\n )\n }\n mapped[key] = toWireAnswer(answer, confidenceFor(key, answer, byKey))\n }\n return mapped\n}\n\n/**\n * Vercel AI Gateway evaluate adapter.\n *\n * Talks to `POST /v4/ai/evaluation-model` with `fetch`. Jev is not a chat\n * model; this adapter does not use `/v1/chat/completions`.\n */\nexport class VercelGatewayEvaluateAdapter<\n TModel extends VercelGatewayEvaluateModel,\n> extends BaseEvaluateAdapter<TModel, VercelGatewayEvaluateProviderOptions> {\n readonly name = 'vercel-gateway' as const\n\n private readonly apiKey: string\n private readonly evaluateUrl: string\n private readonly extraHeaders: Record<string, string>\n\n constructor(config: VercelGatewayEvaluateConfig, model: TModel) {\n super({}, model)\n const defaults = withVercelGatewayDefaults(config)\n this.apiKey = config.apiKey\n this.evaluateUrl = resolveEvaluateUrl(defaults.baseURL)\n this.extraHeaders = extraRequestHeaders(defaults.defaultHeaders)\n }\n\n async evaluate(\n options: EvaluateOptions<VercelGatewayEvaluateProviderOptions>,\n ) {\n const { model, state, questions, modelOptions, abortSignal, logger } =\n options\n const mapped = mapGatewayModelOptions(modelOptions)\n\n logger.request(`activity=evaluate provider=${this.name} model=${model}`, {\n provider: this.name,\n model,\n })\n\n try {\n const response = await fetch(this.evaluateUrl, {\n method: 'POST',\n headers: {\n ...this.extraHeaders,\n Authorization: `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n 'ai-gateway-protocol-version': GATEWAY_PROTOCOL_VERSION,\n 'ai-evaluation-model-specification-version': '4',\n 'ai-model-id': model,\n },\n body: JSON.stringify({\n ...mapped,\n model,\n state,\n questions: toGatewayQuestions(questions),\n }),\n ...(abortSignal ? { signal: abortSignal } : {}),\n })\n\n if (!response.ok) {\n const detail = await response.text().catch(() => '')\n throw new Error(\n `Vercel Gateway evaluate request failed: ${response.status} ${response.statusText}${\n detail ? ` — ${detail}` : ''\n }`,\n )\n }\n\n const json: unknown = await response.json()\n if (!isRecord(json)) {\n throw new Error(\n 'Vercel Gateway evaluate response had an unexpected shape',\n )\n }\n\n const result: EvaluateAdapterResult = {\n model: typeof json.model === 'string' ? json.model : model,\n answers: toWireAnswers(\n json.answers,\n confidenceMap(json.providerMetadata),\n ),\n usage: toTokenUsage(json.usage),\n }\n return result\n } catch (error: unknown) {\n logger.errors(`${this.name}.evaluate fatal`, {\n error: toRunErrorPayload(error, `${this.name}.evaluate failed`),\n source: `${this.name}.evaluate`,\n })\n throw error\n }\n }\n}\n\n/**\n * Create a Vercel AI Gateway evaluate adapter with an explicit API key.\n *\n * @param model Evaluate model id. Use `typesafe-ai/jev`.\n * @param apiKey Vercel AI Gateway API key.\n * @param config Optional client config (`baseURL`, `httpReferer`, `xTitle`).\n *\n * @example\n * ```ts\n * const adapter = createVercelGatewayDecider('typesafe-ai/jev', 'vck_...')\n * ```\n */\nexport function createVercelGatewayDecider<\n TModel extends VercelGatewayEvaluateModel,\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<VercelGatewayEvaluateConfig, 'apiKey'>,\n) {\n return new VercelGatewayEvaluateAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Create a Vercel AI Gateway evaluate adapter.\n *\n * Reads `AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN`.\n *\n * @param model Evaluate model id. Use `typesafe-ai/jev`.\n * @param config Optional client config (`baseURL`, `httpReferer`, `xTitle`).\n *\n * @example\n * ```ts\n * import { decide, boolean } from '@tanstack/ai'\n * import { vercelGatewayDecider } from '@tanstack/ai-vercel-gateway'\n *\n * const result = await decide({\n * adapter: vercelGatewayDecider('typesafe-ai/jev'),\n * state: ticket,\n * questions: {\n * refund: boolean({\n * instructions: 'Is the customer asking for a refund?',\n * }),\n * },\n * })\n * ```\n */\nexport function vercelGatewayDecider<TModel extends VercelGatewayEvaluateModel>(\n model: TModel,\n config?: Omit<VercelGatewayEvaluateConfig, 'apiKey'>,\n) {\n return createVercelGatewayDecider(\n model,\n getVercelGatewayApiKeyFromEnv(),\n config,\n )\n}\n"],"mappings":";;;;;;;;;;;AA8BA,IAAM,gBAAgB;AACtB,IAAM,uBAAuB,+BAA+B;;AAG5D,IAAM,2BAA2B;AAEjC,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,eAAe,OAAiD;CACvE,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,MAAM,SAAS,OAAO,OAAO,KAAK;CAClC,KAAK,MAAM,QAAQ,QACjB,IAAI,OAAO,SAAS,UAAU,OAAO;CAEvC,OAAO;AACT;AAEA,SAAS,eAAe,OAAiD;CACvE,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,MAAM,SAAS,OAAO,OAAO,KAAK;CAClC,KAAK,MAAM,QAAQ,QACjB,IAAI,OAAO,SAAS,UAAU,OAAO;C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,MACF;AACF"}
@@ -9,6 +9,7 @@ export { VercelGatewayResponsesTextAdapter, createVercelGatewayResponsesText, ve
9
9
  export { createVercelGatewaySummarize, vercelGatewaySummarize, type VercelGatewaySummarizeConfig, type VercelGatewaySummarizeModel, } from './adapters/summarize.js';
10
10
  export { VercelGatewayEmbeddingAdapter, createVercelGatewayEmbedding, vercelGatewayEmbedding, type VercelGatewayEmbeddingConfig, } from './adapters/embedding.js';
11
11
  export { VercelGatewayImageAdapter, createVercelGatewayImage, vercelGatewayImage, type VercelGatewayImageConfig, } from './adapters/image.js';
12
+ export { VercelGatewayEvaluateAdapter, createVercelGatewayDecider, vercelGatewayDecider, type VercelGatewayEvaluateConfig, } from './adapters/evaluate.js';
12
13
  export type { VercelGatewayEmbeddingProviderOptions } from './embedding/embedding-provider-options.js';
13
14
  export type { VercelGatewayImageProviderOptions } from './image/image-provider-options.js';
14
15
  export type { VercelGatewayBaseOptions, VercelGatewayCommonOptions, VercelGatewayRoutingOptions, } from './text/text-provider-options.js';
package/dist/esm/index.js CHANGED
@@ -5,5 +5,6 @@ import { createVercelGatewayText, vercelGatewayText } from "./adapters/factory.j
5
5
  import { createVercelGatewaySummarize, vercelGatewaySummarize } from "./adapters/summarize.js";
6
6
  import { VercelGatewayEmbeddingAdapter, createVercelGatewayEmbedding, vercelGatewayEmbedding } from "./adapters/embedding.js";
7
7
  import { VercelGatewayImageAdapter, createVercelGatewayImage, vercelGatewayImage } from "./adapters/image.js";
8
+ import { VercelGatewayEvaluateAdapter, createVercelGatewayDecider, vercelGatewayDecider } from "./adapters/evaluate.js";
8
9
  import { VERCEL_GATEWAY_CHAT_MODELS, VERCEL_GATEWAY_EMBEDDING_MODELS, VERCEL_GATEWAY_IMAGE_MODELS, VERCEL_GATEWAY_MODEL_TAGS, VERCEL_GATEWAY_PROVIDERS } from "./model-meta.js";
9
- export { VERCEL_GATEWAY_CHAT_MODELS, VERCEL_GATEWAY_EMBEDDING_MODELS, VERCEL_GATEWAY_IMAGE_MODELS, VERCEL_GATEWAY_MODEL_TAGS, VERCEL_GATEWAY_PROVIDERS, VercelGatewayEmbeddingAdapter, VercelGatewayImageAdapter, VercelGatewayResponsesTextAdapter, VercelGatewayTextAdapter, createVercelGatewayEmbedding, createVercelGatewayImage, createVercelGatewayResponsesText, createVercelGatewaySummarize, createVercelGatewayText, getVercelGatewayApiKeyFromEnv, vercelGatewayEmbedding, vercelGatewayImage, vercelGatewayResponsesText, vercelGatewaySummarize, vercelGatewayText };
10
+ export { VERCEL_GATEWAY_CHAT_MODELS, VERCEL_GATEWAY_EMBEDDING_MODELS, VERCEL_GATEWAY_IMAGE_MODELS, VERCEL_GATEWAY_MODEL_TAGS, VERCEL_GATEWAY_PROVIDERS, VercelGatewayEmbeddingAdapter, VercelGatewayEvaluateAdapter, VercelGatewayImageAdapter, VercelGatewayResponsesTextAdapter, VercelGatewayTextAdapter, createVercelGatewayDecider, createVercelGatewayEmbedding, createVercelGatewayImage, createVercelGatewayResponsesText, createVercelGatewaySummarize, createVercelGatewayText, getVercelGatewayApiKeyFromEnv, vercelGatewayDecider, vercelGatewayEmbedding, vercelGatewayImage, vercelGatewayResponsesText, vercelGatewaySummarize, vercelGatewayText };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-vercel-gateway",
3
- "version": "0.2.12",
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 {