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

api.bedrock-converse-cache.ts

101 lines3.5 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions, toolDefinition } from '@tanstack/ai'
3import { BedrockConverseTextAdapter } from '@tanstack/ai-bedrock'
4import { NodeHttpHandler } from '@smithy/node-http-handler'
5import { z } from 'zod'
6import type { ResolvedBedrockAuth } from '@tanstack/ai-bedrock'
7​
8const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
9const DUMMY_KEY = 'sk-e2e-test-dummy-key'
10// Haiku 4.5 supports prompt caching on system prompts, messages, and tools.
11const MODEL = 'us.anthropic.claude-haiku-4-5-20251001-v1:0'
12​
13/**
14 * `@aws-sdk/client-bedrock-runtime` defaults to HTTP/2 for streaming calls and
15 * aimock speaks HTTP/1.1, so the E2E client pins the HTTP/1.1 handler. The
16 * adapter's request building and stream decoding are untouched.
17 */
18class Http1ConverseAdapter extends BedrockConverseTextAdapter<typeof MODEL> {
19 protected override buildClientConfig(
20 resolved: ResolvedBedrockAuth,
21 region: string,
22 endpoint: string | undefined,
23 ) {
24 return {
25 ...super.buildClientConfig(resolved, region, endpoint),
26 requestHandler: new NodeHttpHandler(),
27 }
28 }
30​
31export const Route = createFileRoute('/api/bedrock-converse-cache')({
32 server: {
33 handlers: {
34 POST: async () => {
35 const adapter = new Http1ConverseAdapter(
36 {
37 apiKey: DUMMY_KEY,
38 baseURL: `${LLMOCK_DEFAULT_BASE}/bedrock-converse-cache`,
39 region: 'us-east-1',
40 },
41 MODEL,
42 )
43 const lookup = toolDefinition({
44 name: 'lookup',
45 description: 'Looks nothing up.',
46 inputSchema: z.object({ query: z.string() }),
47 outputSchema: z.string(),
48 metadata: { cachePoint: { type: 'default' } },
49 }).server(async () => '')
50​
51 let text = ''
52 let usage: Record<string, unknown> | undefined
53 let runError: string | undefined
54 try {
55 for await (const chunk of chat({
56 ...createChatOptions({ adapter }),
57 systemPrompts: [
58 {
59 content: 'Stable instructions.',
60 metadata: { cachePoint: { type: 'default' } },
61 },
62 ],
63 tools: [lookup],
64 messages: [
65 {
66 role: 'user',
67 content: [
68 {
69 type: 'text',
70 content: 'go',
71 metadata: { cachePoint: { type: 'default' } },
72 },
73 ],
74 },
75 ],
76 })) {
77 if (chunk.type === 'TEXT_MESSAGE_CONTENT') text += chunk.delta
78 if (chunk.type === 'RUN_FINISHED') {
79 usage = chunk.usage as Record<string, unknown> | undefined
80 }
81 // The adapter reports SDK failures as RUN_ERROR instead of throwing.
82 if (chunk.type === 'RUN_ERROR') runError = chunk.message
83 }
84 if (runError !== undefined) throw new Error(runError)
85 return new Response(
86 JSON.stringify({ ok: true, observed: JSON.parse(text), usage }),
87 { status: 200, headers: { 'Content-Type': 'application/json' } },
88 )
89 } catch (error) {
90 return new Response(
91 JSON.stringify({
92 ok: false,
93 error: error instanceof Error ? error.message : String(error),
94 }),
95 { status: 200, headers: { 'Content-Type': 'application/json' } },
96 )
97 }
98 },
99 },
100 },
101})