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

evaluate.md

483 lines14.2 KB

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 six adapters:

  • Ollaya (@tanstack/ai-ollaya): ollayaDecider('laya:latest'). Local server at http://127.0.0.1:11435. No API key.
  • TypeSafe (@tanstack/ai-typesafe): typesafeDecider('jev-latest'). Reads TYPESAFE_API_KEY.
  • OpenRouter (@tanstack/ai-openrouter): openRouterDecider('~typesafe/jev-latest'). Reads OPENROUTER_API_KEY.
  • Vercel AI Gateway (@tanstack/ai-vercel-gateway): vercelGatewayDecider('typesafe-ai/jev'). Reads AI_GATEWAY_API_KEY.
  • Cloudflare (@tanstack/ai-cloudflare): cloudflareDecider('typesafe/jev'). Uses a Worker binding, or CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN.
  • OpenAI (@tanstack/ai-openai): openaiDecider('gpt-6-luna'). Reads OPENAI_API_KEY.

All six 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
  • OpenAI: @tanstack/ai-openai

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: .value is the selected option key. .probability is P(selected). .probabilities is the full map.
  • 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.
  • boolean: When P(true) is 0.5 or more, .value is true. .probability is P(true). No .confidence.

Options

decide()

OptionTypeDescription
adapterEvaluateAdapterAn evaluate adapter created with a model (required)
statestring | object | arrayShared content every question judges (required)
questionsRecord<string, Question>Map of choice, score, and boolean questions (required)
abortSignalAbortSignalCancel the in-flight request
modelOptionsprovider optionsProvider-specific options
middlewareArray<GenerationMiddleware>Observe-only lifecycle hooks (usage, finish, error, abort)
debugDebugOptionDebug 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 (or VERCEL_OIDC_TOKEN)
  • Cloudflare REST: CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_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. If the provider answers but decide() cannot map an answer, decide() throws. For example, an answer is missing, has the wrong type, or has no probability for its value. onUsage and the evaluate:usage event still get the token usage of that call, before onError runs. onFinish does not run.

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.

  1. Copy .env.example to .env.
  2. If you pick a hosted adapter, add its key in .env.
  3. If you pick Ollaya, run ollaya serve.
  4. If you pick Ollaya, run ollaya pull laya:latest.
  5. 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:

Hosted: