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

api.cloudflare-binding-wire.ts

205 lines5.8 KB

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>
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 )
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' },
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 },
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 }
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
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 adapter: createAnthropicChat(
146 'claude-opus-5-5',
147 'cloudflare-binding',
148 {
149 fetch: cloudflareBindingFetch({
150 binding,
151 vendor: 'anthropic',
152 gateway: { id: 'e2e-gateway' },
153 }),
154 },
155 ),
156 systemPrompts: ['Be brief.'],
157 messages: [{ role: 'user', content: 'Hi' }],
158 tools: [lookup],
159 // A beta header goes to the binding as `extraHeaders`.
160 wrapFetch: (next) => (input, init) => {
161 const headers = new Headers(init?.headers)
162 headers.set('anthropic-beta', 'files-api-2025-04-14')
163 return next(input, { ...init, headers })
164 },
165 }),
166 )
167​
168 const gptText = await answerText(
169 chat({
170 adapter: createOpenaiChat('gpt-6.1-sol', 'cloudflare-binding', {
171 fetch: cloudflareBindingFetch({ binding, vendor: 'openai' }),
172 }),
173 systemPrompts: ['Be brief.'],
174 messages: [{ role: 'user', content: 'Hi' }],
175 tools: [lookup],
176 }),
177 )
178​
179 return Response.json({
180 ok: true,
181 claudeText,
182 gptText,
183 calls: workersAi.calls.map((call) => ({
184 model: call.model,
185 modelInBody: 'model' in call.inputs,
186 betasInBody: 'betas' in call.inputs,
187 systemSent: JSON.stringify(call.inputs).includes('Be brief.'),
188 toolNames: Array.isArray(call.inputs.tools)
189 ? call.inputs.tools.map((tool: { name?: string }) => tool.name)
190 : [],
191 returnRawResponse: call.options.returnRawResponse,
192 gateway: call.options.gateway,
193 extraHeaders: call.options.extraHeaders,
194 })),
195 })
196 } catch (error) {
197 return Response.json({
198 ok: false,
199 error: error instanceof Error ? error.message : String(error),
200 })
201 }
202 },
203 },
204 },
205})