Open History to see the last commit
1---
2title: Evaluate
3id: evaluate
4order: 1
5description: "Ask typed choice, score, and boolean questions about shared state with decide()."
6keywords:
7 - tanstack ai
8 - evaluate
9 - decide
10 - typed decisions
11 - choice
12 - score
13 - boolean
14 - typesafe
15 - jev
16 - ollaya
17 - laya
18---
19
20You have a ticket, a record, or a log, and you need answers your code can branch on.
21A queue name. An urgency level. A yes or no.
22By the end of this guide you call `decide()` once and read typed fields like `result.queue.value`.
23
24`decide()` takes an adapter, a state, and a map of questions. There is no stream.
25
26## Providers
27
28Evaluate talks to a decision model through six adapters:
29
30- **[Ollaya](../adapters/ollaya)** (`@tanstack/ai-ollaya`): `ollayaDecider('laya:latest')`. Local server at `http://127.0.0.1:11435`. No API key.
31- **TypeSafe** (`@tanstack/ai-typesafe`): `typesafeDecider('jev-latest')`. Reads `TYPESAFE_API_KEY`.
32- **OpenRouter** (`@tanstack/ai-openrouter`): `openRouterDecider('~typesafe/jev-latest')`. Reads `OPENROUTER_API_KEY`.
33- **Vercel AI Gateway** (`@tanstack/ai-vercel-gateway`): `vercelGatewayDecider('typesafe-ai/jev')`. Reads `AI_GATEWAY_API_KEY`.
34- **Cloudflare** (`@tanstack/ai-cloudflare`): `cloudflareDecider('typesafe/jev')`. Uses a Worker binding, or `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN`.
35- **[OpenAI](../adapters/openai#evaluate)** (`@tanstack/ai-openai`): `openaiDecider('gpt-6-luna')`. Reads `OPENAI_API_KEY`.
36
37All six implement the same `evaluate` activity. Swap the adapter. Keep the `decide()` call.
38
39## Installation
40
41TypeSafe:
42
43<!-- ::start:tabs variant="package-manager" mode="install" -->
44
45react: @tanstack/ai-typesafe
46vue: @tanstack/ai-typesafe
47solid: @tanstack/ai-typesafe
48svelte: @tanstack/ai-typesafe
49preact: @tanstack/ai-typesafe
50angular: @tanstack/ai-typesafe
51vanilla: @tanstack/ai-typesafe
52octane: @tanstack/ai-typesafe
53
54<!-- ::end:tabs -->
55
56Peer dependency:
57
58<!-- ::start:tabs variant="package-manager" mode="install" -->
59
60react: @tanstack/ai
61vue: @tanstack/ai
62solid: @tanstack/ai
63svelte: @tanstack/ai
64preact: @tanstack/ai
65angular: @tanstack/ai
66vanilla: @tanstack/ai
67octane: @tanstack/ai
68
69<!-- ::end:tabs -->
70
71Other adapters:
72
73- [Ollaya](../adapters/ollaya): `@tanstack/ai-ollaya`
74- OpenRouter: `@tanstack/ai-openrouter`
75- Vercel AI Gateway: `@tanstack/ai-vercel-gateway`
76- Cloudflare: `@tanstack/ai-cloudflare`
77- [OpenAI](../adapters/openai#evaluate): `@tanstack/ai-openai`
78
79## Basic Usage
80
81Call `decide()` with an `adapter`, a `state`, and a map of `questions`.
82
83```typescript
84import { decide, choice, score, boolean } from '@tanstack/ai'
85import { typesafeDecider } from '@tanstack/ai-typesafe'
86
87const ticket = {
88 subject: 'Charged twice for the same invoice',
89 body: 'Please refund the extra payment.',
90}
91
92const result = await decide({
93 adapter: typesafeDecider('jev-latest'),
94 state: ticket,
95 questions: {
96 queue: choice({
97 instructions: 'Which team should handle this ticket?',
98 options: {
99 billing: 'Payments, invoices, refunds',
100 tech: 'Bugs, outages, integrations',
101 sales: 'Pricing, upgrades, new accounts',
102 },
103 }),
104 urgency: score({
105 instructions: 'How urgent is this ticket?',
106 levels: ['low', 'medium', 'high'],
107 }),
108 refund: boolean({
109 instructions: 'Is the customer asking for a refund?',
110 }),
111 },
112})
113
114console.log(result.queue.value)
115console.log(result.queue.probability)
116console.log(result.queue.confidence)
117console.log(result.meta.usage)
118```
119
120`decide()` is async. `typesafeDecider` reads `TYPESAFE_API_KEY` from the environment.
121To pass a key yourself, use `createTypesafeDecider('jev-latest', 'ts-...')`.
122
123To evaluate through OpenRouter, swap the adapter. Everything else stays the same:
124
125```typescript
126import { decide, choice, score, boolean } from '@tanstack/ai'
127import { openRouterDecider } from '@tanstack/ai-openrouter'
128
129const ticket = {
130 subject: 'Charged twice for the same invoice',
131 body: 'Please refund the extra payment.',
132}
133
134const result = await decide({
135 adapter: openRouterDecider('~typesafe/jev-latest'),
136 state: ticket,
137 questions: {
138 queue: choice({
139 instructions: 'Which team should handle this ticket?',
140 options: {
141 billing: 'Payments, invoices, refunds',
142 tech: 'Bugs, outages, integrations',
143 sales: 'Pricing, upgrades, new accounts',
144 },
145 }),
146 urgency: score({
147 instructions: 'How urgent is this ticket?',
148 levels: ['low', 'medium', 'high'],
149 }),
150 refund: boolean({
151 instructions: 'Is the customer asking for a refund?',
152 }),
153 },
154})
155
156console.log(result.queue.value)
157```
158
159`openRouterDecider` reads `OPENROUTER_API_KEY` from the environment.
160
161## Questions
162
163Pass a map of questions. Each key becomes a property on the result.
164The key `meta` is reserved.
165
166`state` and `instructions` can be a string, an object, or an array.
167An array is one state, not a batch.
168
169### `choice()`
170
171The model picks one key from `options`. Option keys become the union on `.value`.
172When a key needs no extra description, use `null`.
173
174```typescript
175import { choice } from '@tanstack/ai'
176
177const queue = choice({
178 instructions: 'Which team should handle this ticket?',
179 options: {
180 billing: 'Payments, invoices, refunds',
181 tech: 'Bugs, outages, integrations',
182 sales: 'Pricing, upgrades, new accounts',
183 },
184})
185```
186
187### `score()`
188
189The model rates `state` on ordered `levels`. You must pass at least two levels.
190`.value` is the nearest level label. `.score` is the raw fraction.
191
192```typescript
193import { score } from '@tanstack/ai'
194
195const urgency = score({
196 instructions: 'How urgent is this ticket?',
197 levels: ['low', 'medium', 'high'],
198})
199```
200
201### `boolean()`
202
203A yes or no question. When `probability` is 0.5 or more, `.value` is `true`.
204There is no `.confidence`. On the TypeSafe wire, this type is named `noul`.
205
206```typescript
207import { boolean } from '@tanstack/ai'
208
209const refund = boolean({
210 instructions: 'Is the customer asking for a refund?',
211})
212```
213
214You can pass `criteria: { true: '...', false: '...' }` to describe each side.
215
216## Result Shape
217
218Each question key is a top-level answer. Usage and the resolved model sit on `meta`.
219
220```typescript
221import { decide, choice, score, boolean } from '@tanstack/ai'
222import { typesafeDecider } from '@tanstack/ai-typesafe'
223
224const result = await decide({
225 adapter: typesafeDecider('jev-latest'),
226 state: 'Please refund the extra payment.',
227 questions: {
228 queue: choice({
229 instructions: 'Which team should handle this ticket?',
230 options: {
231 billing: 'Payments, invoices, refunds',
232 tech: 'Bugs, outages, integrations',
233 },
234 }),
235 urgency: score({
236 instructions: 'How urgent is this ticket?',
237 levels: ['low', 'medium', 'high'],
238 }),
239 refund: boolean({
240 instructions: 'Is the customer asking for a refund?',
241 }),
242 },
243})
244
245console.log(result.queue.value)
246console.log(result.queue.probability)
247console.log(result.queue.confidence)
248console.log(result.queue.probabilities)
249
250console.log(result.urgency.value)
251console.log(result.urgency.score)
252console.log(result.urgency.probability)
253console.log(result.urgency.confidence)
254console.log(result.urgency.legend)
255console.log(result.urgency.probabilities)
256
257console.log(result.refund.value)
258console.log(result.refund.probability)
259
260console.log(result.meta.model)
261console.log(result.meta.usage)
262```
263
264- **choice**: `.value` is the selected option key. `.probability` is P(selected). `.probabilities` is the full map.
265- **score**: `.value` is the nearest level. `.score` is the raw fraction. `.probability` is P(that level). `.legend` maps each level index to its label. `.probabilities` is the full map, keyed by level index.
266- **boolean**: When P(true) is 0.5 or more, `.value` is `true`. `.probability` is P(true). No `.confidence`.
267
268## Options
269
270### `decide()`
271
272| Option | Type | Description |
273| -------------- | ----------------------------- | ------------------------------------------------------------ |
274| `adapter` | `EvaluateAdapter` | An evaluate adapter created with a model (required) |
275| `state` | `string \| object \| array` | Shared content every question judges (required) |
276| `questions` | `Record<string, Question>` | Map of `choice`, `score`, and `boolean` questions (required) |
277| `abortSignal` | `AbortSignal` | Cancel the in-flight request |
278| `modelOptions` | provider options | Provider-specific options |
279| `middleware` | `Array<GenerationMiddleware>` | Observe-only lifecycle hooks (usage, finish, error, abort) |
280| `debug` | `DebugOption` | Debug logging |
281
282## Server Endpoint
283
284Evaluate runs on the server. The call needs your API key. Wrap it in an API
285route. Call it from the client over `fetch`:
286
287```typescript ignore
288// routes/api/evaluate.ts
289import { decide, choice, score, boolean } from '@tanstack/ai'
290import { typesafeDecider } from '@tanstack/ai-typesafe'
291import { createFileRoute } from '@tanstack/react-router'
292
293const ADAPTER = typesafeDecider('jev-latest')
294
295export const Route = createFileRoute('/api/evaluate')({
296 server: {
297 handlers: {
298 POST: async ({ request }) => {
299 const body: unknown = await request.json()
300 if (
301 typeof body !== 'object' ||
302 body === null ||
303 !('ticket' in body)
304 ) {
305 return new Response('Invalid request body', { status: 400 })
306 }
307 const { ticket } = body
308
309 const result = await decide({
310 adapter: ADAPTER,
311 state: ticket,
312 questions: {
313 queue: choice({
314 instructions: 'Which team should handle this ticket?',
315 options: {
316 billing: 'Payments, invoices, refunds',
317 tech: 'Bugs, outages, integrations',
318 sales: 'Pricing, upgrades, new accounts',
319 },
320 }),
321 urgency: score({
322 instructions: 'How urgent is this ticket?',
323 levels: ['low', 'medium', 'high'],
324 }),
325 refund: boolean({
326 instructions: 'Is the customer asking for a refund?',
327 }),
328 },
329 })
330
331 return Response.json(result)
332 },
333 },
334 },
335})
336```
337
338```typescript ignore
339// client.ts
340async function evaluateTicket(ticket: { subject: string; body: string }) {
341 const res = await fetch('/api/evaluate', {
342 method: 'POST',
343 headers: { 'Content-Type': 'application/json' },
344 body: JSON.stringify({ ticket }),
345 })
346 return res.json()
347}
348```
349
350## Cancellation
351
352Pass an `abortSignal` to cancel an in-flight request:
353
354```typescript
355import { decide, boolean } from '@tanstack/ai'
356import { typesafeDecider } from '@tanstack/ai-typesafe'
357
358const controller = new AbortController()
359setTimeout(() => controller.abort(), 5000)
360
361const result = await decide({
362 adapter: typesafeDecider('jev-latest'),
363 state: 'Please refund the extra payment.',
364 questions: {
365 refund: boolean({
366 instructions: 'Is the customer asking for a refund?',
367 }),
368 },
369 abortSignal: controller.signal,
370})
371
372console.log(result.refund.value)
373```
374
375## Observability
376
377Attach observe-only middleware to track usage, completion, errors, and
378cancellation. This is the same `GenerationMiddleware` contract the media
379activities use:
380
381```typescript
382import { decide, boolean } from '@tanstack/ai'
383import { typesafeDecider } from '@tanstack/ai-typesafe'
384
385const result = await decide({
386 adapter: typesafeDecider('jev-latest'),
387 state: 'Please refund the extra payment.',
388 questions: {
389 refund: boolean({
390 instructions: 'Is the customer asking for a refund?',
391 }),
392 },
393 middleware: [
394 {
395 name: 'usage-logger',
396 onUsage: (_ctx, usage) => {
397 console.log(`prompt tokens: ${usage.promptTokens}`)
398 },
399 },
400 ],
401})
402
403console.log(result.refund.value)
404```
405
406> **Tip:** Pass `otelMiddleware()` to emit OpenTelemetry spans for evaluate
407> calls. See [OpenTelemetry](../advanced/otel).
408
409## Environment Variables
410
411Each adapter reads its own key:
412
413- TypeSafe: `TYPESAFE_API_KEY`
414- OpenRouter: `OPENROUTER_API_KEY`
415- Vercel AI Gateway: `AI_GATEWAY_API_KEY` (or `VERCEL_OIDC_TOKEN`)
416- Cloudflare REST: `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN`
417
418You only need the key for the adapter you pick.
419
420## Error Handling
421
422```typescript
423import { decide, boolean } from '@tanstack/ai'
424import { typesafeDecider } from '@tanstack/ai-typesafe'
425
426try {
427 const result = await decide({
428 adapter: typesafeDecider('jev-latest'),
429 state: 'Please refund the extra payment.',
430 questions: {
431 refund: boolean({
432 instructions: 'Is the customer asking for a refund?',
433 }),
434 },
435 })
436 console.log(result.refund.value)
437} catch (error) {
438 if (error instanceof Error) {
439 console.error('Evaluate failed:', error.message)
440 }
441}
442```
443
444If `questions` is empty, `decide()` throws before any request.
445If a question key is `meta`, `decide()` throws.
446If the provider answers but `decide()` cannot map an answer, `decide()` throws.
447For example, an answer is missing, has the wrong type, or has no probability
448for its value. `onUsage` and the `evaluate:usage` event still get the token
449usage of that call, before `onError` runs. `onFinish` does not run.
450
451## Runnable Example
452
453`examples/react/evaluate` is a small TanStack Start app that runs this page.
454Paste a support ticket. The UI shows queue, urgency, and refund.
455The dropdown lists five adapters. Each call to `decide()` uses the same questions.
456
4571. Copy `.env.example` to `.env`.
4582. If you pick a hosted adapter, add its key in `.env`.
4593. If you pick Ollaya, run `ollaya serve`.
4604. If you pick Ollaya, run `ollaya pull laya:latest`.
4615. Run the dev server with the command below.
462
463Ollaya does not need an API key.
464
465```bash
466pnpm --filter evaluate dev
467```
468
469Open http://localhost:3100.
470
471## Next Steps
472
473Local:
474
475- [Ollaya Adapter](../adapters/ollaya) - Local `laya` decisions. No API key.
476- [TypeSafe Adapter](../adapters/typesafe) - Direct Jev, models, and explicit API keys
477- [Evaluate a ticket](../tutorials/evaluate) - Build a Start route that routes a ticket
478
479Hosted:
480
481- [OpenRouter Adapter](../adapters/openrouter) - Evaluate through your OpenRouter key
482- [Vercel AI Gateway](../adapters/vercel-gateway) - Evaluate through the Gateway
483- [Cloudflare Adapter](../adapters/cloudflare) - Evaluate from a Worker or REST