You have a ticket, a record, or a log, and you need answers your code can branch on.
A queue name. An urgency level. A yes or no.
By the end of this guide you call decide() once and read typed fields like result.queue.value.
decide() takes an adapter, a state, and a map of questions. There is no stream.
Providers#
Evaluate talks to a decision model through five adapters:
- Ollaya (
@tanstack/ai-ollaya):ollayaDecider('laya:latest'). Local server athttp://127.0.0.1:11435. No API key. - TypeSafe (
@tanstack/ai-typesafe):typesafeDecider('jev-latest'). ReadsTYPESAFE_API_KEY. - OpenRouter (
@tanstack/ai-openrouter):openRouterDecider('~typesafe/jev-latest'). ReadsOPENROUTER_API_KEY. - Vercel AI Gateway (
@tanstack/ai-vercel-gateway):vercelGatewayDecider('typesafe-ai/jev'). ReadsAI_GATEWAY_API_KEY. - Cloudflare (
@tanstack/ai-cloudflare):cloudflareDecider('typesafe/jev'). Uses a Worker binding, orCLOUDFLARE_ACCOUNT_IDandCLOUDFLARE_API_TOKEN.
All five implement the same evaluate activity. Swap the adapter. Keep the decide() call.
Installation#
TypeSafe:
react: @tanstack/ai-typesafe vue: @tanstack/ai-typesafe solid: @tanstack/ai-typesafe svelte: @tanstack/ai-typesafe preact: @tanstack/ai-typesafe angular: @tanstack/ai-typesafe vanilla: @tanstack/ai-typesafe octane: @tanstack/ai-typesafe
Peer dependency:
react: @tanstack/ai vue: @tanstack/ai solid: @tanstack/ai svelte: @tanstack/ai preact: @tanstack/ai angular: @tanstack/ai vanilla: @tanstack/ai octane: @tanstack/ai
Other adapters:
- Ollaya:
@tanstack/ai-ollaya - OpenRouter:
@tanstack/ai-openrouter - Vercel AI Gateway:
@tanstack/ai-vercel-gateway - Cloudflare:
@tanstack/ai-cloudflare
Basic Usage#
Call decide() with an adapter, a state, and a map of questions.
import { decide, choice, score, boolean } from '@tanstack/ai'
import { typesafeDecider } from '@tanstack/ai-typesafe'
const ticket = {
subject: 'Charged twice for the same invoice',
body: 'Please refund the extra payment.',
}
const result = await decide({
adapter: typesafeDecider('jev-latest'),
state: ticket,
questions: {
queue: choice({
instructions: 'Which team should handle this ticket?',
options: {
billing: 'Payments, invoices, refunds',
tech: 'Bugs, outages, integrations',
sales: 'Pricing, upgrades, new accounts',
},
}),
urgency: score({
instructions: 'How urgent is this ticket?',
levels: ['low', 'medium', 'high'],
}),
refund: boolean({
instructions: 'Is the customer asking for a refund?',
}),
},
})
console.log(result.queue.value)
console.log(result.queue.probability)
console.log(result.queue.confidence)
console.log(result.meta.usage)
decide() is async. typesafeDecider reads TYPESAFE_API_KEY from the environment.
To pass a key yourself, use createTypesafeDecider('jev-latest', 'ts-...').
To evaluate through OpenRouter, swap the adapter. Everything else stays the same:
import { decide, choice, score, boolean } from '@tanstack/ai'
import { openRouterDecider } from '@tanstack/ai-openrouter'
const ticket = {
subject: 'Charged twice for the same invoice',
body: 'Please refund the extra payment.',
}
const result = await decide({
adapter: openRouterDecider('~typesafe/jev-latest'),
state: ticket,
questions: {
queue: choice({
instructions: 'Which team should handle this ticket?',
options: {
billing: 'Payments, invoices, refunds',
tech: 'Bugs, outages, integrations',
sales: 'Pricing, upgrades, new accounts',
},
}),
urgency: score({
instructions: 'How urgent is this ticket?',
levels: ['low', 'medium', 'high'],
}),
refund: boolean({
instructions: 'Is the customer asking for a refund?',
}),
},
})
console.log(result.queue.value)
openRouterDecider reads OPENROUTER_API_KEY from the environment.
Questions#
Pass a map of questions. Each key becomes a property on the result.
The key meta is reserved.
state and instructions can be a string, an object, or an array.
An array is one state, not a batch.
choice()#
The model picks one key from options. Option keys become the union on .value.
When a key needs no extra description, use null.
import { choice } from '@tanstack/ai'
const queue = choice({
instructions: 'Which team should handle this ticket?',
options: {
billing: 'Payments, invoices, refunds',
tech: 'Bugs, outages, integrations',
sales: 'Pricing, upgrades, new accounts',
},
})
score()#
The model rates state on ordered levels. You must pass at least two levels.
.value is the nearest level label. .score is the raw fraction.
import { score } from '@tanstack/ai'
const urgency = score({
instructions: 'How urgent is this ticket?',
levels: ['low', 'medium', 'high'],
})
boolean()#
A yes or no question. When probability is 0.5 or more, .value is true.
There is no .confidence. On the TypeSafe wire, this type is named noul.
import { boolean } from '@tanstack/ai'
const refund = boolean({
instructions: 'Is the customer asking for a refund?',
})
You can pass criteria: { true: '...', false: '...' } to describe each side.
Result Shape#
Each question key is a top-level answer. Usage and the resolved model sit on meta.
import { decide, choice, score, boolean } from '@tanstack/ai'
import { typesafeDecider } from '@tanstack/ai-typesafe'
const result = await decide({
adapter: typesafeDecider('jev-latest'),
state: 'Please refund the extra payment.',
questions: {
queue: choice({
instructions: 'Which team should handle this ticket?',
options: {
billing: 'Payments, invoices, refunds',
tech: 'Bugs, outages, integrations',
},
}),
urgency: score({
instructions: 'How urgent is this ticket?',
levels: ['low', 'medium', 'high'],
}),
refund: boolean({
instructions: 'Is the customer asking for a refund?',
}),
},
})
console.log(result.queue.value)
console.log(result.queue.probability)
console.log(result.queue.confidence)
console.log(result.queue.probabilities)
console.log(result.urgency.value)
console.log(result.urgency.score)
console.log(result.urgency.probability)
console.log(result.urgency.confidence)
console.log(result.urgency.legend)
console.log(result.urgency.probabilities)
console.log(result.refund.value)
console.log(result.refund.probability)
console.log(result.meta.model)
console.log(result.meta.usage)
- choice:
.valueis the selected option key..probabilityis P(selected)..probabilitiesis the full map. - score:
.valueis the nearest level..scoreis the raw fraction..probabilityis P(that level)..legendmaps each level index to its label..probabilitiesis the full map, keyed by level index. - boolean: When P(true) is 0.5 or more,
.valueistrue..probabilityis P(true). No.confidence.
Options#
decide()#
| Option | Type | Description |
|---|---|---|
adapter | EvaluateAdapter | An evaluate adapter created with a model (required) |
state | string | object | array | Shared content every question judges (required) |
questions | Record<string, Question> | Map of choice, score, and boolean questions (required) |
abortSignal | AbortSignal | Cancel the in-flight request |
modelOptions | provider options | Provider-specific options |
middleware | Array<GenerationMiddleware> | Observe-only lifecycle hooks (usage, finish, error, abort) |
debug | DebugOption | Debug logging |
Server Endpoint#
Evaluate runs on the server. The call needs your API key. Wrap it in an API
route. Call it from the client over fetch:
// routes/api/evaluate.ts
import { decide, choice, score, boolean } from '@tanstack/ai'
import { typesafeDecider } from '@tanstack/ai-typesafe'
import { createFileRoute } from '@tanstack/react-router'
const ADAPTER = typesafeDecider('jev-latest')
export const Route = createFileRoute('/api/evaluate')({
server: {
handlers: {
POST: async ({ request }) => {
const body: unknown = await request.json()
if (
typeof body !== 'object' ||
body === null ||
!('ticket' in body)
) {
return new Response('Invalid request body', { status: 400 })
}
const { ticket } = body
const result = await decide({
adapter: ADAPTER,
state: ticket,
questions: {
queue: choice({
instructions: 'Which team should handle this ticket?',
options: {
billing: 'Payments, invoices, refunds',
tech: 'Bugs, outages, integrations',
sales: 'Pricing, upgrades, new accounts',
},
}),
urgency: score({
instructions: 'How urgent is this ticket?',
levels: ['low', 'medium', 'high'],
}),
refund: boolean({
instructions: 'Is the customer asking for a refund?',
}),
},
})
return Response.json(result)
},
},
},
})
// client.ts
async function evaluateTicket(ticket: { subject: string; body: string }) {
const res = await fetch('/api/evaluate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ticket }),
})
return res.json()
}
Cancellation#
Pass an abortSignal to cancel an in-flight request:
import { decide, boolean } from '@tanstack/ai'
import { typesafeDecider } from '@tanstack/ai-typesafe'
const controller = new AbortController()
setTimeout(() => controller.abort(), 5000)
const result = await decide({
adapter: typesafeDecider('jev-latest'),
state: 'Please refund the extra payment.',
questions: {
refund: boolean({
instructions: 'Is the customer asking for a refund?',
}),
},
abortSignal: controller.signal,
})
console.log(result.refund.value)
Observability#
Attach observe-only middleware to track usage, completion, errors, and
cancellation. This is the same GenerationMiddleware contract the media
activities use:
import { decide, boolean } from '@tanstack/ai'
import { typesafeDecider } from '@tanstack/ai-typesafe'
const result = await decide({
adapter: typesafeDecider('jev-latest'),
state: 'Please refund the extra payment.',
questions: {
refund: boolean({
instructions: 'Is the customer asking for a refund?',
}),
},
middleware: [
{
name: 'usage-logger',
onUsage: (_ctx, usage) => {
console.log(`prompt tokens: ${usage.promptTokens}`)
},
},
],
})
console.log(result.refund.value)
Tip: Pass
otelMiddleware()to emit OpenTelemetry spans for evaluate calls. See OpenTelemetry.
Environment Variables#
Each adapter reads its own key:
- TypeSafe:
TYPESAFE_API_KEY - OpenRouter:
OPENROUTER_API_KEY - Vercel AI Gateway:
AI_GATEWAY_API_KEY(orVERCEL_OIDC_TOKEN) - Cloudflare REST:
CLOUDFLARE_ACCOUNT_IDandCLOUDFLARE_API_TOKEN
You only need the key for the adapter you pick.
Error Handling#
import { decide, boolean } from '@tanstack/ai'
import { typesafeDecider } from '@tanstack/ai-typesafe'
try {
const result = await decide({
adapter: typesafeDecider('jev-latest'),
state: 'Please refund the extra payment.',
questions: {
refund: boolean({
instructions: 'Is the customer asking for a refund?',
}),
},
})
console.log(result.refund.value)
} catch (error) {
if (error instanceof Error) {
console.error('Evaluate failed:', error.message)
}
}
If questions is empty, decide() throws before any request.
If a question key is meta, decide() throws.
Runnable Example#
examples/react/evaluate is a small TanStack Start app that runs this page.
Paste a support ticket. The UI shows queue, urgency, and refund.
The dropdown lists five adapters. Each call to decide() uses the same questions.
- Copy
.env.exampleto.env. - If you pick a hosted adapter, add its key in
.env. - If you pick Ollaya, run
ollaya serve. - If you pick Ollaya, run
ollaya pull laya:latest. - Run the dev server with the command below.
Ollaya does not need an API key.
pnpm --filter evaluate dev
Open http://localhost:3100.
Next Steps#
Local:
- Ollaya Adapter - Local
layadecisions. No API key. - TypeSafe Adapter - Direct Jev, models, and explicit API keys
- Evaluate a ticket - Build a Start route that routes a ticket
Hosted:
- OpenRouter Adapter - Evaluate through your OpenRouter key
- Vercel AI Gateway - Evaluate through the Gateway
- Cloudflare Adapter - Evaluate from a Worker or REST