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

api.evaluate-usage-on-failure.ts

56 lines1.9 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { choice, decide } from '@tanstack/ai'
3import { createOpenaiDecider } from '@tanstack/ai-openai'
4​
5const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
6const DUMMY_KEY = 'sk-e2e-test-dummy-key'
7​
8/**
9 * Drives `decide()` through the OpenAI evaluate adapter against the
10 * `/evaluate-usage-on-failure` aimock mount. The mount answers with valid
11 * usage but picks a choice with no entry in `probabilities`, so `decide()`
12 * fails while mapping the answer. The route reports the rejection together
13 * with the usage seen by the `onUsage` middleware hook.
14 */
15export const Route = createFileRoute('/api/evaluate-usage-on-failure')({
16 server: {
17 handlers: {
18 POST: async () => {
19 const adapter = createOpenaiDecider('gpt-6-luna', DUMMY_KEY, {
20 baseURL: `${LLMOCK_DEFAULT_BASE}/evaluate-usage-on-failure/v1`,
21 })
22​
23 const onUsageReports: Array<unknown> = []
24​
25 let error: { name: string; message: string } | undefined
26 try {
27 await decide({
28 adapter,
29 state: { ticket: 'I was charged twice this month.' },
30 questions: {
31 queue: choice({
32 instructions: 'Which team should handle this ticket?',
33 options: { billing: null, tech: null },
34 }),
35 },
36 middleware: [
37 {
38 name: 'usage-observer',
39 onUsage: (_ctx, usage) => {
40 onUsageReports.push(usage)
41 },
42 },
43 ],
44 })
45 } catch (caught) {
46 error =
47 caught instanceof Error
48 ? { name: caught.name, message: caught.message }
49 : { name: 'Unknown', message: String(caught) }
50 }
51​
52 return Response.json({ error, onUsageReports })
53 },
54 },
55 },
56})