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

api.file-source-wire.ts

125 lines4.4 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions } from '@tanstack/ai'
3import { createTextAdapter } from '@/lib/providers'
4import { ALL_PROVIDERS } from '@/lib/types'
5import type { ModelMessage } from '@tanstack/ai'
6import type { Provider } from '@/lib/types'
7​
8function isProvider(value: string): value is Provider {
9 return (ALL_PROVIDERS as ReadonlyArray<string>).includes(value)
11​
12/**
13 * Wire-format verification for `{ type: 'file' }` content sources (#909).
14 *
15 * A message image part can reference a provider-issued Files API handle
16 * instead of inline base64 / a URL. This route drives a single `chat()` call
17 * whose user message carries a file source so the companion spec can inspect
18 * aimock's journal (`GET /v1/_requests`) and assert the adapter emitted the
19 * provider's native file reference (OpenAI `input_image.file_id`, Anthropic
20 * `file_id` source, Gemini `fileData.fileUri`).
21 *
22 * `handleProvider` defaults to the target provider (the supported case); pass
23 * a different one to drive the cross-provider rejection path.
24 */
25export const Route = createFileRoute('/api/file-source-wire')({
26 server: {
27 handlers: {
28 POST: async ({ request }) => {
29 const url = new URL(request.url)
30 const providerParam = url.searchParams.get('provider') ?? 'openai'
31 const handleParam = url.searchParams.get('handleProvider')
32 if (!isProvider(providerParam)) {
33 return new Response(
34 JSON.stringify({
35 ok: false,
36 error: `Unknown provider: ${providerParam}`,
37 }),
38 { status: 400, headers: { 'Content-Type': 'application/json' } },
39 )
40 }
41 const provider = providerParam
42 if (handleParam !== null && !isProvider(handleParam)) {
43 return new Response(
44 JSON.stringify({
45 ok: false,
46 error: `Unknown handleProvider: ${handleParam}`,
47 }),
48 { status: 400, headers: { 'Content-Type': 'application/json' } },
49 )
50 }
51 const handleProvider = handleParam ?? provider
52 const testId = url.searchParams.get('testId') ?? undefined
53​
54 const { adapter } = createTextAdapter(
55 provider,
56 undefined,
57 undefined,
58 testId,
59 )
60​
61 // A synthetic handle in each provider's shape — uploads themselves
62 // can't run against aimock, but the wire mapping doesn't care where
63 // the handle came from.
64 const handleValue =
65 handleProvider === 'gemini'
66 ? 'https://generativelanguage.googleapis.com/v1beta/files/e2e-abc'
67 : 'file-e2e-abc'
68​
69 const messages: Array<ModelMessage> = [
70 {
71 role: 'user',
72 content: [
73 { type: 'text', content: 'Describe the attached image.' },
74 {
75 type: 'image',
76 source: {
77 type: 'file',
78 value: handleValue,
79 provider: handleProvider,
80 },
81 },
82 ],
83 },
84 ]
85​
86 // Adapters differ in how the cross-provider guard surfaces: some
87 // yield a RUN_ERROR chunk, others throw before the stream starts.
88 // Report both the same way so the spec has one shape to assert.
89 // Aimock can also emit RUN_ERROR after a successful mapping (it
90 // does not model `file_id`). Only file-source mapping/lookup
91 // errors fail this route.
92 let runError: string | undefined
93 try {
94 for await (const chunk of chat({
95 threadId: 'file-source-wire',
96 ...createChatOptions({ adapter }),
97 messages,
98 })) {
99 if (
100 chunk.type === 'RUN_ERROR' &&
101 /file/.test(chunk.message ?? '')
102 ) {
103 runError = chunk.message
104 }
105 }
106 } catch (error) {
107 return new Response(
108 JSON.stringify({
109 ok: false,
110 error: error instanceof Error ? error.message : String(error),
111 }),
112 { status: 200, headers: { 'Content-Type': 'application/json' } },
113 )
114 }
115​
116 return new Response(
117 JSON.stringify(
118 runError ? { ok: false, error: runError } : { ok: true },
119 ),
120 { status: 200, headers: { 'Content-Type': 'application/json' } },
121 )
122 },
123 },
124 },
125})