|
| 1 | +import Anthropic from '@anthropic-ai/sdk'; |
| 2 | +import * as Sentry from '@sentry/node'; |
| 3 | +import express from 'express'; |
| 4 | + |
| 5 | +const MODEL = 'claude-3-haiku-20240307'; |
| 6 | + |
| 7 | +// The first turn calls the weather tool and the second answers. Ids are `msg_<mode>_<turn>`, so each span can be told apart. |
| 8 | +function reply(mode, turn) { |
| 9 | + const id = `msg_${mode}_${turn}`; |
| 10 | + return turn === 'tools' |
| 11 | + ? { |
| 12 | + id, |
| 13 | + content: [{ type: 'tool_use', id: `toolu_${mode}`, name: 'weather', input: { city: 'Vienna' } }], |
| 14 | + stop_reason: 'tool_use', |
| 15 | + usage: { input_tokens: 10, output_tokens: 20 }, |
| 16 | + } |
| 17 | + : { |
| 18 | + id, |
| 19 | + content: [{ type: 'text', text: 'Sunny.' }], |
| 20 | + stop_reason: 'end_turn', |
| 21 | + usage: { input_tokens: 30, output_tokens: 5 }, |
| 22 | + }; |
| 23 | +} |
| 24 | + |
| 25 | +function streamEvents({ id, content, stop_reason, usage }) { |
| 26 | + const events = [ |
| 27 | + { |
| 28 | + type: 'message_start', |
| 29 | + message: { |
| 30 | + id, |
| 31 | + type: 'message', |
| 32 | + role: 'assistant', |
| 33 | + model: MODEL, |
| 34 | + content: [], |
| 35 | + usage: { input_tokens: usage.input_tokens }, |
| 36 | + }, |
| 37 | + }, |
| 38 | + ]; |
| 39 | + content.forEach((block, index) => { |
| 40 | + if (block.type === 'tool_use') { |
| 41 | + events.push( |
| 42 | + { type: 'content_block_start', index, content_block: { ...block, input: {} } }, |
| 43 | + { |
| 44 | + type: 'content_block_delta', |
| 45 | + index, |
| 46 | + delta: { type: 'input_json_delta', partial_json: JSON.stringify(block.input) }, |
| 47 | + }, |
| 48 | + ); |
| 49 | + } else { |
| 50 | + events.push( |
| 51 | + { type: 'content_block_start', index, content_block: { type: 'text', text: '' } }, |
| 52 | + { type: 'content_block_delta', index, delta: { type: 'text_delta', text: block.text } }, |
| 53 | + ); |
| 54 | + } |
| 55 | + events.push({ type: 'content_block_stop', index }); |
| 56 | + }); |
| 57 | + events.push( |
| 58 | + { |
| 59 | + type: 'message_delta', |
| 60 | + delta: { stop_reason, stop_sequence: null }, |
| 61 | + usage: { output_tokens: usage.output_tokens }, |
| 62 | + }, |
| 63 | + { type: 'message_stop' }, |
| 64 | + ); |
| 65 | + return events; |
| 66 | +} |
| 67 | + |
| 68 | +let recoveredReplies = 0; |
| 69 | + |
| 70 | +function startMockAnthropicServer() { |
| 71 | + const app = express(); |
| 72 | + app.use(express.json()); |
| 73 | + |
| 74 | + app.post('/anthropic/v1/messages', (req, res) => { |
| 75 | + const mode = req.headers['x-mode']; |
| 76 | + if (mode === 'thread_stream_error') { |
| 77 | + res.status(400).json({ type: 'error', error: { type: 'invalid_request_error', message: 'Bad thread' } }); |
| 78 | + return; |
| 79 | + } |
| 80 | + const answersTool = req.body.messages.some( |
| 81 | + message => Array.isArray(message.content) && message.content.some(block => block.type === 'tool_result'), |
| 82 | + ); |
| 83 | + // The server lost the thread, so the SDK replays the turn that continues it. |
| 84 | + if (mode === 'thread_stream_recovered' && req.body.thread?.type === 'continue') { |
| 85 | + res.status(404).json({ |
| 86 | + type: 'error', |
| 87 | + error: { type: 'not_found_error', message: 'Thread not found', details: { error_code: 'thread_not_found' } }, |
| 88 | + }); |
| 89 | + return; |
| 90 | + } |
| 91 | + if (mode === 'thread_stream_failed_signal_reuse' && !answersTool) { |
| 92 | + res.status(400).json({ type: 'error', error: { type: 'invalid_request_error', message: 'Bad thread' } }); |
| 93 | + return; |
| 94 | + } |
| 95 | + const message = |
| 96 | + mode === 'thread_stream_recovered' |
| 97 | + ? { ...reply(mode, 'final'), id: `msg_${mode}_${(recoveredReplies += 1)}` } |
| 98 | + : reply(mode, answersTool ? 'final' : 'tools'); |
| 99 | + |
| 100 | + if (!req.body.stream) { |
| 101 | + res.json({ type: 'message', role: 'assistant', model: MODEL, stop_sequence: null, ...message }); |
| 102 | + return; |
| 103 | + } |
| 104 | + |
| 105 | + res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }); |
| 106 | + // The body closes after the first tool input delta, without `message_stop`. |
| 107 | + const events = mode === 'thread_stream_truncated' ? streamEvents(message).slice(0, 3) : streamEvents(message); |
| 108 | + events.forEach((event, index) => { |
| 109 | + setTimeout(() => { |
| 110 | + res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`); |
| 111 | + if (index === events.length - 1) { |
| 112 | + res.end(); |
| 113 | + } |
| 114 | + }, index * 5); |
| 115 | + }); |
| 116 | + }); |
| 117 | + |
| 118 | + return new Promise(resolve => { |
| 119 | + const server = app.listen(0, () => { |
| 120 | + resolve(server); |
| 121 | + }); |
| 122 | + }); |
| 123 | +} |
| 124 | + |
| 125 | +const tools = [ |
| 126 | + { |
| 127 | + name: 'weather', |
| 128 | + description: 'Get the weather by city', |
| 129 | + input_schema: { type: 'object', properties: { city: { type: 'string' } } }, |
| 130 | + run: () => 'sunny', |
| 131 | + }, |
| 132 | +]; |
| 133 | +const params = { model: MODEL, max_tokens: 100, messages: [{ role: 'user', content: 'Weather in Vienna?' }] }; |
| 134 | + |
| 135 | +async function streamFollowUp(client, signal) { |
| 136 | + const answer = { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_1', content: 'sunny' }] }; |
| 137 | + const followUp = await client.beta.messages.create( |
| 138 | + { ...params, messages: [...params.messages, answer], stream: true }, |
| 139 | + { signal }, |
| 140 | + ); |
| 141 | + for await (const _event of followUp) { |
| 142 | + // consume |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +const MODES = { |
| 147 | + async runner_stream_eager(client) { |
| 148 | + for await (const stream of client.beta.messages.toolRunner({ |
| 149 | + ...params, |
| 150 | + tools, |
| 151 | + stream: true, |
| 152 | + runToolsEagerly: true, |
| 153 | + })) { |
| 154 | + await stream.finalMessage(); |
| 155 | + } |
| 156 | + }, |
| 157 | + async runner_stream(client) { |
| 158 | + for await (const stream of client.beta.messages.toolRunner({ ...params, tools, stream: true })) { |
| 159 | + await stream.finalMessage(); |
| 160 | + } |
| 161 | + }, |
| 162 | + // How Bedrock and Vertex clients, which have no threads, run every tool runner. |
| 163 | + async runner_stream_unthreaded(client) { |
| 164 | + for await (const stream of client.beta.messages.toolRunner({ ...params, tools, stream: true, thread: false })) { |
| 165 | + await stream.finalMessage(); |
| 166 | + } |
| 167 | + }, |
| 168 | + async runner(client) { |
| 169 | + for await (const _message of client.beta.messages.toolRunner({ ...params, tools })) { |
| 170 | + // consume |
| 171 | + } |
| 172 | + }, |
| 173 | + async thread_send(client) { |
| 174 | + await client.beta.messages.thread({ model: MODEL, max_tokens: 100 }).send(params.messages); |
| 175 | + }, |
| 176 | + async thread_stream(client) { |
| 177 | + await client.beta.messages.thread({ model: MODEL, max_tokens: 100 }).stream(params.messages).finalMessage(); |
| 178 | + }, |
| 179 | + // A later request sent with a finished thread stream's signal is not that stream's request. |
| 180 | + async thread_stream_signal_reuse(client) { |
| 181 | + const stream = client.beta.messages.thread({ model: MODEL, max_tokens: 100 }).stream(params.messages); |
| 182 | + await stream.finalMessage(); |
| 183 | + await streamFollowUp(client, stream.controller.signal); |
| 184 | + }, |
| 185 | + async thread_stream_failed_signal_reuse(client) { |
| 186 | + const stream = client.beta.messages.thread({ model: MODEL, max_tokens: 100 }).stream(params.messages); |
| 187 | + await stream.finalMessage().catch(() => {}); |
| 188 | + await streamFollowUp(client, stream.controller.signal); |
| 189 | + }, |
| 190 | + async thread_stream_abort(client) { |
| 191 | + const stream = client.beta.messages.thread({ model: MODEL, max_tokens: 100 }).stream(params.messages); |
| 192 | + stream.once('streamEvent', () => stream.abort()); |
| 193 | + await stream.finalMessage().catch(() => {}); |
| 194 | + }, |
| 195 | + async thread_stream_abort_early(client) { |
| 196 | + const stream = client.beta.messages.thread({ model: MODEL, max_tokens: 100 }).stream(params.messages); |
| 197 | + stream.abort(); |
| 198 | + await stream.finalMessage().catch(() => {}); |
| 199 | + }, |
| 200 | + async thread_stream_truncated(client) { |
| 201 | + await client.beta.messages |
| 202 | + .thread({ model: MODEL, max_tokens: 100 }) |
| 203 | + .stream(params.messages) |
| 204 | + .finalMessage() |
| 205 | + .catch(() => {}); |
| 206 | + }, |
| 207 | + async thread_stream_recovered(client) { |
| 208 | + const thread = client.beta.messages.thread({ model: MODEL, max_tokens: 100 }); |
| 209 | + await thread.stream(params.messages).finalMessage(); |
| 210 | + await thread.stream([{ role: 'user', content: 'And tomorrow?' }]).finalMessage(); |
| 211 | + }, |
| 212 | + async thread_stream_error(client) { |
| 213 | + await client.beta.messages |
| 214 | + .thread({ model: MODEL, max_tokens: 100 }) |
| 215 | + .stream(params.messages) |
| 216 | + .finalMessage() |
| 217 | + .catch(() => {}); |
| 218 | + }, |
| 219 | +}; |
| 220 | + |
| 221 | +async function run() { |
| 222 | + const server = await startMockAnthropicServer(); |
| 223 | + const baseURL = `http://localhost:${server.address().port}/anthropic`; |
| 224 | + |
| 225 | + await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { |
| 226 | + for (const [mode, call] of Object.entries(MODES)) { |
| 227 | + await Sentry.startSpan({ name: mode }, () => |
| 228 | + call(new Anthropic({ apiKey: 'mock-api-key', baseURL, maxRetries: 0, defaultHeaders: { 'x-mode': mode } })), |
| 229 | + ); |
| 230 | + } |
| 231 | + }); |
| 232 | + |
| 233 | + await Sentry.flush(2000); |
| 234 | + |
| 235 | + server.close(); |
| 236 | +} |
| 237 | + |
| 238 | +run(); |
0 commit comments