|
| 1 | +import * as Sentry from '@sentry/aws-serverless'; |
| 2 | +import { |
| 3 | + BedrockRuntimeClient, |
| 4 | + ConverseStreamCommand, |
| 5 | + InvokeModelWithResponseStreamCommand, |
| 6 | +} from '@aws-sdk/client-bedrock-runtime'; |
| 7 | +// Force the HTTP/1 handler so `nock` can intercept the request instead of hitting real AWS. |
| 8 | +import { NodeHttpHandler } from '@smithy/node-http-handler'; |
| 9 | +import { EventStreamCodec } from '@smithy/core/event-streams'; |
| 10 | +import nock from 'nock'; |
| 11 | +import { Buffer } from 'node:buffer'; |
| 12 | + |
| 13 | +nock.disableNetConnect(); |
| 14 | + |
| 15 | +const region = 'us-east-1'; |
| 16 | +const credentials = { accessKeyId: 'aws-test-key', secretAccessKey: 'aws-test-secret' }; |
| 17 | +const host = `https://bedrock-runtime.${region}.amazonaws.com`; |
| 18 | +const modelId = 'anthropic.claude-3-5-sonnet-20240620-v1:0'; |
| 19 | + |
| 20 | +// Bedrock streams responses in the binary AWS event stream format, not JSON. The SDK decodes and |
| 21 | +// checks each message (headers, payload, CRC32), so the mocked response must use the same format. |
| 22 | +// The SDK's own codec encodes the messages. It needs UTF-8 helpers to encode the header strings. |
| 23 | +// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTSelectObjectAppendix.html |
| 24 | +const codec = new EventStreamCodec( |
| 25 | + bytes => Buffer.from(bytes).toString('utf8'), |
| 26 | + text => Buffer.from(text), |
| 27 | +); |
| 28 | + |
| 29 | +// The codec needs a type for each header value. All Bedrock headers are strings. |
| 30 | +function encodeMessage(headers, payload) { |
| 31 | + return codec.encode({ |
| 32 | + headers: Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, { type: 'string', value }])), |
| 33 | + body: Buffer.from(JSON.stringify(payload)), |
| 34 | + }); |
| 35 | +} |
| 36 | + |
| 37 | +// The SDK reads `:event-type` to find the stream member (for example `messageStart` or `chunk`). |
| 38 | +function event(eventType, payload) { |
| 39 | + return encodeMessage( |
| 40 | + { ':message-type': 'event', ':event-type': eventType, ':content-type': 'application/json' }, |
| 41 | + payload, |
| 42 | + ); |
| 43 | +} |
| 44 | + |
| 45 | +// An exception message makes the SDK throw while the caller iterates the stream. This is how a |
| 46 | +// stream fails after the response starts. |
| 47 | +function exception(exceptionType, payload) { |
| 48 | + return encodeMessage( |
| 49 | + { ':message-type': 'exception', ':exception-type': exceptionType, ':content-type': 'application/json' }, |
| 50 | + payload, |
| 51 | + ); |
| 52 | +} |
| 53 | + |
| 54 | +// InvokeModelWithResponseStream wraps each model chunk as base64 JSON in a `chunk` event. |
| 55 | +function invokeModelChunk(chunk) { |
| 56 | + return event('chunk', { bytes: Buffer.from(JSON.stringify(chunk)).toString('base64') }); |
| 57 | +} |
| 58 | + |
| 59 | +function mockStream(path, messages) { |
| 60 | + nock(host).post(path).reply(200, Buffer.concat(messages), { 'content-type': 'application/vnd.amazon.eventstream' }); |
| 61 | +} |
| 62 | + |
| 63 | +function createClient() { |
| 64 | + return new BedrockRuntimeClient({ region, credentials, maxAttempts: 1, requestHandler: new NodeHttpHandler() }); |
| 65 | +} |
| 66 | + |
| 67 | +async function converseStream() { |
| 68 | + mockStream(/\/model\/.*\/converse-stream$/, [ |
| 69 | + event('messageStart', { role: 'assistant' }), |
| 70 | + event('contentBlockDelta', { contentBlockIndex: 0, delta: { text: 'Hello ' } }), |
| 71 | + event('contentBlockDelta', { contentBlockIndex: 0, delta: { text: 'from Bedrock' } }), |
| 72 | + event('contentBlockStop', { contentBlockIndex: 0 }), |
| 73 | + event('contentBlockStart', { |
| 74 | + contentBlockIndex: 1, |
| 75 | + start: { toolUse: { toolUseId: 'tooluse_1', name: 'get_weather' } }, |
| 76 | + }), |
| 77 | + event('contentBlockDelta', { contentBlockIndex: 1, delta: { toolUse: { input: '{"city":' } } }), |
| 78 | + event('contentBlockDelta', { contentBlockIndex: 1, delta: { toolUse: { input: '"Vienna"}' } } }), |
| 79 | + event('contentBlockStop', { contentBlockIndex: 1 }), |
| 80 | + event('messageStop', { stopReason: 'tool_use' }), |
| 81 | + event('metadata', { usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 }, metrics: { latencyMs: 100 } }), |
| 82 | + ]); |
| 83 | + |
| 84 | + const response = await createClient().send( |
| 85 | + new ConverseStreamCommand({ |
| 86 | + modelId, |
| 87 | + system: [{ text: 'You are a helpful assistant.' }], |
| 88 | + messages: [{ role: 'user', content: [{ text: 'Hello' }] }], |
| 89 | + }), |
| 90 | + ); |
| 91 | + |
| 92 | + let text = ''; |
| 93 | + for await (const item of response.stream) { |
| 94 | + text += item.contentBlockDelta?.delta?.text ?? ''; |
| 95 | + } |
| 96 | + if (text !== 'Hello from Bedrock') { |
| 97 | + throw new Error(`Unexpected streamed text: ${text}`); |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +async function invokeModelWithResponseStream() { |
| 102 | + mockStream(/\/model\/.*\/invoke-with-response-stream$/, [ |
| 103 | + invokeModelChunk({ |
| 104 | + type: 'message_start', |
| 105 | + message: { id: 'msg_bdrk_2', model: 'claude-3-5-sonnet-20240620', usage: { input_tokens: 15, output_tokens: 1 } }, |
| 106 | + }), |
| 107 | + invokeModelChunk({ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }), |
| 108 | + invokeModelChunk({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'Streamed ' } }), |
| 109 | + invokeModelChunk({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'reply' } }), |
| 110 | + invokeModelChunk({ type: 'content_block_stop', index: 0 }), |
| 111 | + invokeModelChunk({ type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 9 } }), |
| 112 | + invokeModelChunk({ type: 'message_stop' }), |
| 113 | + ]); |
| 114 | + |
| 115 | + const response = await createClient().send( |
| 116 | + new InvokeModelWithResponseStreamCommand({ |
| 117 | + modelId, |
| 118 | + contentType: 'application/json', |
| 119 | + body: JSON.stringify({ |
| 120 | + anthropic_version: 'bedrock-2023-05-31', |
| 121 | + max_tokens: 100, |
| 122 | + messages: [{ role: 'user', content: 'Stream please' }], |
| 123 | + }), |
| 124 | + }), |
| 125 | + ); |
| 126 | + |
| 127 | + let chunks = 0; |
| 128 | + for await (const item of response.body) { |
| 129 | + if (item.chunk?.bytes) { |
| 130 | + chunks++; |
| 131 | + } |
| 132 | + } |
| 133 | + if (chunks !== 7) { |
| 134 | + throw new Error(`Unexpected chunk count: ${chunks}`); |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +async function failingConverseStream() { |
| 139 | + mockStream(/\/model\/.*\/converse-stream$/, [ |
| 140 | + event('messageStart', { role: 'assistant' }), |
| 141 | + event('contentBlockDelta', { contentBlockIndex: 0, delta: { text: 'Partial' } }), |
| 142 | + exception('modelStreamErrorException', { message: 'The model stream failed', originalStatusCode: 500 }), |
| 143 | + ]); |
| 144 | + |
| 145 | + const response = await createClient().send( |
| 146 | + new ConverseStreamCommand({ |
| 147 | + modelId: 'amazon.nova-pro-v1:0', |
| 148 | + messages: [{ role: 'user', content: [{ text: 'Fail please' }] }], |
| 149 | + }), |
| 150 | + ); |
| 151 | + |
| 152 | + try { |
| 153 | + for await (const _ of response.stream) { |
| 154 | + // drain |
| 155 | + } |
| 156 | + } catch (error) { |
| 157 | + if (error.name !== 'ModelStreamErrorException') { |
| 158 | + throw error; |
| 159 | + } |
| 160 | + return; |
| 161 | + } |
| 162 | + throw new Error('Expected the stream to fail'); |
| 163 | +} |
| 164 | + |
| 165 | +async function abortedConverseStream() { |
| 166 | + mockStream(/\/model\/.*\/converse-stream$/, [ |
| 167 | + event('messageStart', { role: 'assistant' }), |
| 168 | + event('contentBlockDelta', { contentBlockIndex: 0, delta: { text: 'Partial' } }), |
| 169 | + exception('modelStreamErrorException', { message: 'The model stream failed', originalStatusCode: 500 }), |
| 170 | + ]); |
| 171 | + |
| 172 | + const controller = new AbortController(); |
| 173 | + const response = await createClient().send( |
| 174 | + new ConverseStreamCommand({ |
| 175 | + modelId: 'amazon.nova-lite-v1:0', |
| 176 | + messages: [{ role: 'user', content: [{ text: 'Stop please' }] }], |
| 177 | + }), |
| 178 | + { abortSignal: controller.signal }, |
| 179 | + ); |
| 180 | + |
| 181 | + try { |
| 182 | + for await (const _ of response.stream) { |
| 183 | + controller.abort(); |
| 184 | + } |
| 185 | + } catch { |
| 186 | + return; |
| 187 | + } |
| 188 | + throw new Error('Expected the stream to fail'); |
| 189 | +} |
| 190 | + |
| 191 | +async function run() { |
| 192 | + await Sentry.startSpan({ name: 'Test Transaction' }, async () => { |
| 193 | + await converseStream(); |
| 194 | + await invokeModelWithResponseStream(); |
| 195 | + await failingConverseStream(); |
| 196 | + await abortedConverseStream(); |
| 197 | + }); |
| 198 | +} |
| 199 | + |
| 200 | +run(); |
0 commit comments