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

api.judge.ts

75 lines2.6 KB

1import { z } from 'zod'
2import { createFileRoute } from '@tanstack/react-router'
3import { anthropicText } from '@tanstack/ai-anthropic'
4import { chat } from '@tanstack/ai'
5​
6const adapter = anthropicText('claude-opus-4-6')
7​
8const judgeSchema = z.object({
9 accuracy: z.number().min(1).max(10).describe('Accuracy rating from 1-10'),
10 comprehensiveness: z
11 .number()
12 .min(1)
13 .max(10)
14 .describe('Comprehensiveness rating from 1-10'),
15 summary: z.string().describe('Two sentence summary of the evaluation'),
16})
17​
18const JUDGE_SYSTEM_PROMPT = `You are a strict evaluator comparing an AI-generated data analysis report against a gold-standard reference report.
19​
20You will receive:
211. The original user query
222. The gold-standard report (the ideal answer)
233. The candidate report to evaluate
24​
25Rate the candidate on two dimensions, each on a scale from 1 to 10 (10 = best):
26​
27- **Accuracy**: Are the numbers, rankings, and factual claims correct compared to the gold standard?
28- **Comprehensiveness**: Does the candidate cover all the data points, breakdowns, and insights present in the gold standard?
29​
30Provide a two sentence summary of your evaluation.`
31​
32export const Route = createFileRoute('/_database-demo/api/judge' as any)({
33 server: {
34 handlers: {
35 POST: async ({ request }) => {
36 try {
37 const { query, goldReport, candidateReport } = await request.json()
38​
39 if (!query || !goldReport || !candidateReport) {
40 return new Response(
41 JSON.stringify({ error: 'Missing required fields' }),
42 { status: 400, headers: { 'Content-Type': 'application/json' } },
43 )
44 }
45​
46 const result = await chat({
47 adapter,
48 messages: [
49 {
50 role: 'user' as const,
51 content: `## Query\n${query}\n\n## Gold-Standard Report\n${goldReport}\n\n## Candidate Report\n${candidateReport}`,
52 },
53 ],
54 systemPrompts: [JUDGE_SYSTEM_PROMPT],
55 outputSchema: judgeSchema,
56 // Sampling lives in provider-native `modelOptions` now (Anthropic: `max_tokens`).
57 modelOptions: { max_tokens: 512 },
58 })
59​
60 return new Response(JSON.stringify(result), {
61 headers: { 'Content-Type': 'application/json' },
62 })
63 } catch (error) {
64 console.error('[API Judge] Error:', error)
65 return new Response(
66 JSON.stringify({
67 error: error instanceof Error ? error.message : 'Judging failed',
68 }),
69 { status: 500, headers: { 'Content-Type': 'application/json' } },
70 )
71 }
72 },
73 },
74 },
75})