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

api.lone-surrogates-wire.ts

120 lines3.3 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat } from '@tanstack/ai'
3import { createAnthropicChat } from '@tanstack/ai-anthropic'
4​
5const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
6​
7/** Text with two lone surrogates and one valid pair (an emoji). */
8const LONE = 'a\ud800b\udc00cπŸ˜€'
9​
10const textEvents = [
11 {
12 type: 'message_start',
13 message: {
14 id: 'msg_lone_surrogates_wire',
15 type: 'message',
16 role: 'assistant',
17 content: [],
18 model: 'claude-sonnet-4-5',
19 stop_reason: null,
20 stop_sequence: null,
21 usage: { input_tokens: 5, output_tokens: 0 },
22 },
23 },
24 {
25 type: 'content_block_start',
26 index: 0,
27 content_block: { type: 'text', text: '' },
28 },
29 {
30 type: 'content_block_delta',
31 index: 0,
32 delta: { type: 'text_delta', text: 'ok' },
33 },
34 { type: 'content_block_stop', index: 0 },
35 {
36 type: 'message_delta',
37 delta: { stop_reason: 'end_turn', stop_sequence: null },
38 usage: { output_tokens: 1 },
39 },
40 { type: 'message_stop' },
42​
43/**
44 * A lone surrogate is invalid on the wire, and Anthropic rejects the whole
45 * request. The capturing `fetch` returns the raw request body, so this needs
46 * no fixture.
47 */
48export const Route = createFileRoute('/api/lone-surrogates-wire')({
49 server: {
50 handlers: {
51 POST: async () => {
52 const requestBodies: Array<string> = []
53​
54 const capturingFetch: typeof fetch = async (input, init) => {
55 const req =
56 input instanceof Request ? input : new Request(input, init)
57 requestBodies.push(await req.text())
58 const encoder = new TextEncoder()
59 const body = new ReadableStream<Uint8Array>({
60 start(controller) {
61 for (const event of textEvents) {
62 controller.enqueue(
63 encoder.encode(
64 `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,
65 ),
66 )
67 }
68 controller.close()
69 },
70 })
71 return new Response(body, {
72 status: 200,
73 headers: { 'Content-Type': 'text/event-stream' },
74 })
75 }
76​
77 const adapter = createAnthropicChat('claude-sonnet-4-5', DUMMY_KEY, {
78 fetch: capturingFetch,
79 })
80​
81 try {
82 const stream = chat({
83 threadId: 'lone-surrogates-wire',
84 adapter,
85 systemPrompts: [LONE],
86 messages: [
87 { role: 'user', content: LONE },
88 {
89 role: 'assistant',
90 content: null,
91 toolCalls: [
92 {
93 id: 'toolu_lone',
94 type: 'function',
95 function: {
96 name: 'lookup',
97 arguments: '{"q":"a\\ud800b"}',
98 },
99 },
100 ],
101 },
102 { role: 'tool', toolCallId: 'toolu_lone', content: LONE },
103 ],
104 stream: true,
105 })
106 for await (const _chunk of stream) {
107 // drain
108 }
109 } catch (error) {
110 return Response.json({
111 ok: false,
112 error: error instanceof Error ? error.message : String(error),
113 })
114 }
115​
116 return Response.json({ ok: true, requestBodies })
117 },
118 },
119 },
120})