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

api.harness-continue.ts

147 lines4.0 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { createAnthropicChat } from '@tanstack/ai-anthropic'
3import {
4 createHarnessHost,
5 defineHarness,
6 retryTransientErrors,
7} from '@tanstack/ai-harness'
8​
9/**
10 * Wire check for a turn that continues a partial answer.
11 *
12 * The first model call streams "Hello wor", then the stream sends an
13 * `overloaded_error`. `retryTransientErrors()` answers `'continue'`. The
14 * second call answers "ld". A custom `fetch` records each request body and
15 * answers with a canned stream, so no aimock fixture is needed. aimock can
16 * cut a stream, but a cut stream ends without an error event.
17 */
18​
19const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
20const MODEL = 'claude-sonnet-5-5'
21​
22const start = (id: string) => [
23 {
24 type: 'message_start',
25 message: {
26 id,
27 type: 'message',
28 role: 'assistant',
29 content: [],
30 model: MODEL,
31 stop_reason: null,
32 stop_sequence: null,
33 usage: { input_tokens: 5, output_tokens: 0 },
34 },
35 },
36 {
37 type: 'content_block_start',
38 index: 0,
39 content_block: { type: 'text', text: '' },
40 },
42​
43const delta = (text: string) => ({
44 type: 'content_block_delta',
45 index: 0,
46 delta: { type: 'text_delta', text },
47})
48​
49/** Streams some text, then fails in the middle of the stream. */
50const FAILED_REPLY = [
51 ...start('msg_harness_continue_1'),
52 delta('Hello wor'),
53 {
54 type: 'error',
55 error: { type: 'overloaded_error', message: 'Overloaded' },
56 },
58​
59const CONTINUED_REPLY = [
60 ...start('msg_harness_continue_2'),
61 delta('ld'),
62 { type: 'content_block_stop', index: 0 },
63 {
64 type: 'message_delta',
65 delta: { stop_reason: 'end_turn', stop_sequence: null },
66 usage: { output_tokens: 1 },
67 },
68 { type: 'message_stop' },
70​
71/** The fields of an Anthropic Messages request body that the spec reads. */
72interface WireBody {
73 messages: Array<{
74 role: string
75 content: string | Array<{ type: string; text?: string }>
76 }>
78​
79/** The text of one wire message. */
80const textOf = (content: WireBody['messages'][number]['content']) =>
81 typeof content === 'string'
82 ? content
83 : content.map((part) => part.text ?? '').join('')
84​
85export const Route = createFileRoute('/api/harness-continue')({
86 server: {
87 handlers: {
88 POST: async () => {
89 const bodies: Array<WireBody> = []
90 const scriptedFetch: typeof fetch = async (input, init) => {
91 bodies.push(await new Request(input, init).json())
92 const events = bodies.length === 1 ? FAILED_REPLY : CONTINUED_REPLY
93 const sse = events
94 .map(
95 (event) =>
96 `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,
97 )
98 .join('')
99 return new Response(sse, {
100 headers: { 'Content-Type': 'text/event-stream' },
101 })
102 }
103​
104 const host = createHarnessHost()
105 const deltas: Array<string> = []
106 let text: string
107 try {
108 const session = await host.open(
109 defineHarness({
110 name: 'e2e/harness-continue',
111 adapter: createAnthropicChat(MODEL, DUMMY_KEY, {
112 fetch: scriptedFetch,
113 }),
114 turn: {
115 onModelError: retryTransientErrors({ baseDelayMs: 1 }),
116 },
117 }),
118 {
119 threadId: 'e2e-harness-continue',
120 },
121 )
122 session.onEvent('TEXT_MESSAGE_CONTENT', ({ event }) => {
123 deltas.push(event.delta)
124 })
125 text = (await session.send('[harness-continue] say hello world')).text
126 } catch (error) {
127 return Response.json({
128 error: error instanceof Error ? error.message : String(error),
129 })
130 } finally {
131 await host.close()
132 }
133​
134 return Response.json({
135 text,
136 deltas,
137 requests: bodies.map((body) =>
138 body.messages.map((message) => ({
139 role: message.role,
140 text: textOf(message.content),
141 })),
142 ),
143 })
144 },
145 },
146 },
147})