Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat } from '@tanstack/ai'
3import { createAnthropicChat } from '@tanstack/ai-anthropic'
4
5const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
6const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
7
8/**
9 * Streams one Anthropic chat with server-side fallback on, against the aimock
10 * fixture in `fixtures/refusal`. aimock answers with `stop_reason: "refusal"`,
11 * the case where no fallback model served the request. Returns the
12 * `RUN_FINISHED` finish reason and whether a `RUN_ERROR` was seen.
13 */
14export const Route = createFileRoute('/api/anthropic-refusal')({
15 server: {
16 handlers: {
17 POST: async () => {
18 const adapter = createAnthropicChat('claude-opus-5-5', DUMMY_KEY, {
19 baseURL: LLMOCK_DEFAULT_BASE,
20 })
21
22 let finishReason: string | null | undefined
23 let sawRunError = false
24 try {
25 for await (const chunk of chat({
26 adapter,
27 threadId: 'anthropic-refusal',
28 modelOptions: { fallbacks: 'default' },
29 messages: [
30 {
31 role: 'user',
32 content: '[anthropic-refusal] describe a dangerous lab method',
33 },
34 ],
35 })) {
36 // chat() moves the finish reason into metadata.tanstack.
37 if (chunk.type === 'RUN_FINISHED') {
38 finishReason = chunk.metadata?.tanstack?.finishReason
39 }
40 if (chunk.type === 'RUN_ERROR') sawRunError = true
41 }
42 } catch (error) {
43 return Response.json({
44 ok: false,
45 error: error instanceof Error ? error.message : String(error),
46 })
47 }
48
49 return Response.json({ ok: true, finishReason, sawRunError })
50 },
51 },
52 },
53})