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

api.keyed-adapter.ts

93 lines3.1 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat } from '@tanstack/ai'
3import { keyedAdapter, keyedAdapters } from '@tanstack/ai/byok'
4import {
5 byokMissing,
6 getByokKey,
7 keyedAdapterFromRequest,
8} from '@tanstack/ai/byok/server'
9import { createAnthropicChat } from '@tanstack/ai-anthropic'
10import { createOpenaiChat } from '@tanstack/ai-openai'
11​
12const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
13​
14const messages = [
15 {
16 role: 'user' as const,
17 content: '[oneshot] what is your most popular guitar',
18 },
20​
21/**
22 * `?mode=many`: `keyedAdapters` with OpenAI and Anthropic. The route builds the
23 * adapter of the provider whose key the user sent, and reports which provider
24 * got which credential.
25 */
26async function many(request: Request, testId: string | undefined) {
27 const sent: { provider?: string; credential?: string | null } = {}
28 const record =
29 (provider: string, header: string): typeof fetch =>
30 (input, init) => {
31 sent.provider = provider
32 sent.credential = new Headers(init?.headers).get(header)
33 return fetch(input, init)
34 }
35 const defaultHeaders = testId ? { 'X-Test-Id': testId } : undefined
36 const models = keyedAdapters({
37 openai: (key) =>
38 createOpenaiChat('gpt-5.2', key, {
39 baseURL: `${LLMOCK_DEFAULT_BASE}/v1`,
40 defaultHeaders,
41 fetch: record('openai', 'authorization'),
42 }),
43 anthropic: (key) =>
44 createAnthropicChat('claude-haiku-4-5', key, {
45 baseURL: LLMOCK_DEFAULT_BASE,
46 defaultHeaders,
47 fetch: record('anthropic', 'x-api-key'),
48 }),
49 })
50 const adapter = keyedAdapterFromRequest(request, models)
51 if (!adapter) return byokMissing('openai')
52 const { text } = await chat({ adapter, messages, stream: false })
53 return Response.json({ text, ...sent })
55​
56/**
57 * Builds a `keyedAdapter` with the user's key from the BYOK request header,
58 * then chats against aimock. aimock redacts `authorization` in its journal,
59 * so the adapter's `fetch` records the header the provider gets.
60 */
61export const Route = createFileRoute('/api/keyed-adapter')({
62 server: {
63 handlers: {
64 POST: async ({ request }) => {
65 let authorization: string | null = null
66 const testId = request.headers.get('x-test-id') ?? undefined
67 if (new URL(request.url).searchParams.get('mode') === 'many') {
68 return many(request, testId)
69 }
70 const adapter = keyedAdapter('openai', (key) =>
71 createOpenaiChat('gpt-5.2', key, {
72 baseURL: `${LLMOCK_DEFAULT_BASE}/v1`,
73 defaultHeaders: testId ? { 'X-Test-Id': testId } : undefined,
74 fetch: (input, init) => {
75 authorization = new Headers(init?.headers).get('authorization')
76 return fetch(input, init)
77 },
78 }),
79 )
80​
81 const key = getByokKey(request, adapter.provider)
82 if (!key) return byokMissing('openai')
83​
84 const { text } = await chat({
85 adapter: adapter.create(key),
86 messages,
87 stream: false,
88 })
89 return Response.json({ text, authorization })
90 },
91 },
92 },
93})