-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathindex.js
More file actions
65 lines (56 loc) · 1.7 KB
/
index.js
File metadata and controls
65 lines (56 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const {
BedrockRuntimeClient,
InvokeModelWithResponseStreamCommand,
} = require("@aws-sdk/client-bedrock-runtime");
const client = new BedrockRuntimeClient();
const MODEL_ID = process.env.MODEL_ID;
exports.handler = awslambda.streamifyResponse(
async (event, responseStream, _context) => {
const body = JSON.parse(event.body || "{}");
const prompt = body.prompt || "Hello";
const httpMetadata = {
statusCode: 200,
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
};
responseStream = awslambda.HttpResponseStream.from(
responseStream,
httpMetadata
);
try {
const command = new InvokeModelWithResponseStreamCommand({
modelId: MODEL_ID,
contentType: "application/json",
accept: "application/json",
body: JSON.stringify({
anthropic_version: "bedrock-2023-05-31",
max_tokens: 2048,
messages: [{ role: "user", content: prompt }],
}),
});
const response = await client.send(command);
for await (const event of response.body) {
if (event.chunk) {
const parsed = JSON.parse(
new TextDecoder().decode(event.chunk.bytes)
);
if (
parsed.type === "content_block_delta" &&
parsed.delta?.text
) {
responseStream.write(`data: ${JSON.stringify({ text: parsed.delta.text })}\n\n`);
}
}
}
responseStream.write("data: [DONE]\n\n");
} catch (err) {
responseStream.write(
`data: ${JSON.stringify({ error: err.message })}\n\n`
);
}
responseStream.end();
}
);