Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat, toolDefinition } from '@tanstack/ai'
3import { createAnthropicChat } from '@tanstack/ai-anthropic'
4import { cloudflareBindingFetch } from '@tanstack/ai-cloudflare'
5import { createOpenaiChat } from '@tanstack/ai-openai'
6import { z } from 'zod'
7
8type RunCall = {
9 model: string
10 inputs: Record<string, unknown>
11 options: Record<string, unknown>
12}
13
14function sse(events: Array<Record<string, unknown>>) {
15 return new Response(
16 events
17 .map(
18 (event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,
19 )
20 .join(''),
21 { status: 200, headers: { 'Content-Type': 'text/event-stream' } },
22 )
23}
24
25/** A Claude answer, as Anthropic Messages streams it. */
26const claudeAnswer = [
27 {
28 type: 'message_start',
29 message: {
30 id: 'msg_binding',
31 type: 'message',
32 role: 'assistant',
33 content: [],
34 model: 'claude-opus-5-5',
35 stop_reason: null,
36 stop_sequence: null,
37 usage: { input_tokens: 5, output_tokens: 0 },
38 },
39 },
40 {
41 type: 'content_block_start',
42 index: 0,
43 content_block: { type: 'text', text: '' },
44 },
45 {
46 type: 'content_block_delta',
47 index: 0,
48 delta: { type: 'text_delta', text: 'Hi from Claude.' },
49 },
50 { type: 'content_block_stop', index: 0 },
51 {
52 type: 'message_delta',
53 delta: { stop_reason: 'end_turn', stop_sequence: null },
54 usage: { output_tokens: 4 },
55 },
56 { type: 'message_stop' },
57]
58
59/** A GPT answer, as OpenAI Responses streams it. */
60const gptAnswer = [
61 {
62 type: 'response.created',
63 response: {
64 id: 'resp_binding',
65 object: 'response',
66 status: 'in_progress',
67 model: 'gpt-6.1-sol',
68 output: [],
69 },
70 },
71 {
72 type: 'response.completed',
73 response: {
74 id: 'resp_binding',
75 object: 'response',
76 status: 'completed',
77 model: 'gpt-6.1-sol',
78 output: [
79 {
80 id: 'msg_binding',
81 type: 'message',
82 role: 'assistant',
83 status: 'completed',
84 content: [
85 { type: 'output_text', text: 'Hi from GPT.', annotations: [] },
86 ],
87 },
88 ],
89 usage: { input_tokens: 5, output_tokens: 4, total_tokens: 9 },
90 },
91 },
92]
93
94/** A stand-in for `env.AI` that records each `run` call. */
95function fakeWorkersAi() {
96 const calls: Array<RunCall> = []
97 const binding = {
98 run: async (
99 model: string,
100 inputs: Record<string, unknown>,
101 options: Record<string, unknown>,
102 ) => {
103 calls.push({ model, inputs, options })
104 return model.startsWith('anthropic/') ? sse(claudeAnswer) : sse(gptAnswer)
105 },
106 }
107 return { calls, binding }
108}
109
110const lookup = toolDefinition({
111 name: 'lookup',
112 description: 'Look something up',
113 inputSchema: z.object({ query: z.string() }),
114})
115
116async function answerText(stream: AsyncIterable<{ type: string }>) {
117 let text = ''
118 for await (const chunk of stream) {
119 if (chunk.type === 'TEXT_MESSAGE_CONTENT' && 'delta' in chunk) {
120 text += String(chunk.delta)
121 }
122 }
123 return text
124}
125
126/**
127 * The real Anthropic and OpenAI adapters, sending through
128 * `cloudflareBindingFetch` to a fake `env.AI`. Returns what each `run` call
129 * got and the streamed answers.
130 */
131export const Route = createFileRoute('/api/cloudflare-binding-wire')({
132 server: {
133 handlers: {
134 POST: async () => {
135 try {
136 const workersAi = fakeWorkersAi()
137 // The real binding exists only inside a Worker. The stand-in has the
138 // one method the fetch calls.
139 const binding = workersAi.binding as unknown as Parameters<
140 typeof cloudflareBindingFetch
141 >[0]['binding']
142
143 const claudeText = await answerText(
144 chat({
145 threadId: 'cloudflare-binding-wire',
146 adapter: createAnthropicChat(
147 'claude-opus-5-5',
148 'cloudflare-binding',
149 {
150 fetch: cloudflareBindingFetch({
151 binding,
152 vendor: 'anthropic',
153 gateway: { id: 'e2e-gateway' },
154 }),
155 },
156 ),
157 systemPrompts: ['Be brief.'],
158 messages: [{ role: 'user', content: 'Hi' }],
159 tools: [lookup],
160 // A beta header goes to the binding as `extraHeaders`.
161 wrapFetch: (next) => (input, init) => {
162 const headers = new Headers(init?.headers)
163 headers.set('anthropic-beta', 'files-api-2025-04-14')
164 return next(input, { ...init, headers })
165 },
166 }),
167 )
168
169 const gptText = await answerText(
170 chat({
171 threadId: 'cloudflare-binding-wire',
172 adapter: createOpenaiChat('gpt-6.1-sol', 'cloudflare-binding', {
173 fetch: cloudflareBindingFetch({ binding, vendor: 'openai' }),
174 }),
175 systemPrompts: ['Be brief.'],
176 messages: [{ role: 'user', content: 'Hi' }],
177 tools: [lookup],
178 }),
179 )
180
181 return Response.json({
182 ok: true,
183 claudeText,
184 gptText,
185 calls: workersAi.calls.map((call) => ({
186 model: call.model,
187 modelInBody: 'model' in call.inputs,
188 betasInBody: 'betas' in call.inputs,
189 systemSent: JSON.stringify(call.inputs).includes('Be brief.'),
190 toolNames: Array.isArray(call.inputs.tools)
191 ? call.inputs.tools.map((tool: { name?: string }) => tool.name)
192 : [],
193 returnRawResponse: call.options.returnRawResponse,
194 gateway: call.options.gateway,
195 extraHeaders: call.options.extraHeaders,
196 })),
197 })
198 } catch (error) {
199 return Response.json({
200 ok: false,
201 error: error instanceof Error ? error.message : String(error),
202 })
203 }
204 },
205 },
206 },
207})