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