Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions } from '@tanstack/ai'
3import { createOpenRouterText } from '@tanstack/ai-openrouter'
4import { webSearchTool, webFetchTool } from '@tanstack/ai-openrouter/tools'
5import { HTTPClient } from '@openrouter/sdk'
6
7const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
8const DUMMY_KEY = 'sk-e2e-test-dummy-key'
9
10/**
11 * Drives the OpenRouter chat-completions adapter with both `webSearchTool()`
12 * and `webFetchTool()` so the companion spec can inspect aimock's journal
13 * (`GET /v1/_requests`) and assert what wire bytes actually crossed the SDK
14 * boundary.
15 *
16 * Both factories emit the SDK's canonical
17 * `{type: 'openrouter:web_*', parameters: {...}}` shape, so caller-passed
18 * options survive `ChatRequest$outboundSchema` and reach OpenRouter. The
19 * spec asserts the captured request body's `tools[*]` against that shape.
20 *
21 * The spec uses this route purely to generate the captured request; the
22 * response content here is irrelevant to the wire-format assertion.
23 */
24export const Route = createFileRoute('/api/openrouter-web-tools-wire')({
25 server: {
26 handlers: {
27 POST: async ({ request }) => {
28 const url = new URL(request.url)
29 const testId = url.searchParams.get('testId') ?? undefined
30
31 // Same X-Test-Id injection pattern as `providers.ts` so this route
32 // gets its own aimock test bucket and doesn't collide with other
33 // openrouter specs.
34 const httpClient = new HTTPClient()
35 if (testId) {
36 httpClient.addHook('beforeRequest', (req) => {
37 const next = new Request(req)
38 next.headers.set('X-Test-Id', testId)
39 return next
40 })
41 }
42
43 const adapter = createOpenRouterText('openai/gpt-4o', DUMMY_KEY, {
44 serverURL: `${LLMOCK_DEFAULT_BASE}/v1`,
45 httpClient,
46 })
47
48 try {
49 for await (const _ of chat({
50 ...createChatOptions({ adapter }),
51 messages: [
52 {
53 role: 'user',
54 content: '[wire-test] check tools serialization',
55 },
56 ],
57 tools: [
58 webSearchTool({
59 engine: 'exa',
60 maxResults: 10,
61 allowedDomains: ['example.com'],
62 }),
63 webFetchTool({
64 engine: 'openrouter',
65 maxContentTokens: 4000,
66 allowedDomains: ['example.com'],
67 blockedDomains: ['evil.example'],
68 }),
69 ],
70 })) {
71 // Drain the stream.
72 }
73 } catch (error) {
74 return new Response(
75 JSON.stringify({
76 ok: false,
77 error: error instanceof Error ? error.message : String(error),
78 }),
79 { status: 200, headers: { 'Content-Type': 'application/json' } },
80 )
81 }
82
83 return new Response(JSON.stringify({ ok: true }), {
84 status: 200,
85 headers: { 'Content-Type': 'application/json' },
86 })
87 },
88 },
89 },
90})