Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

evaluate.md

477 lines13.8 KB

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