-
-
Notifications
You must be signed in to change notification settings - Fork 9.5k
/
index.ts
157 lines (133 loc) · 4.82 KB
/
index.ts
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import {
BedrockRuntimeClient,
InvokeModelWithResponseStreamCommand,
} from '@aws-sdk/client-bedrock-runtime';
import { experimental_buildLlama2Prompt } from 'ai/prompts';
import { LobeRuntimeAI } from '../BaseAI';
import { AgentRuntimeErrorType } from '../error';
import { ChatCompetitionOptions, ChatStreamPayload, ModelProvider } from '../types';
import { buildAnthropicMessages, buildAnthropicTools } from '../utils/anthropicHelpers';
import { AgentRuntimeError } from '../utils/createError';
import { debugStream } from '../utils/debugStream';
import { StreamingResponse } from '../utils/response';
import {
AWSBedrockClaudeStream,
AWSBedrockLlamaStream,
createBedrockStream,
} from '../utils/streams';
export interface LobeBedrockAIParams {
accessKeyId?: string;
accessKeySecret?: string;
region?: string;
sessionToken?: string;
}
export class LobeBedrockAI implements LobeRuntimeAI {
private client: BedrockRuntimeClient;
region: string;
constructor({ region, accessKeyId, accessKeySecret, sessionToken }: LobeBedrockAIParams = {}) {
if (!(accessKeyId && accessKeySecret))
throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidBedrockCredentials);
this.region = region ?? 'us-east-1';
this.client = new BedrockRuntimeClient({
credentials: {
accessKeyId: accessKeyId,
secretAccessKey: accessKeySecret,
sessionToken: sessionToken,
},
region: this.region,
});
}
async chat(payload: ChatStreamPayload, options?: ChatCompetitionOptions) {
if (payload.model.startsWith('meta')) return this.invokeLlamaModel(payload, options);
return this.invokeClaudeModel(payload, options);
}
private invokeClaudeModel = async (
payload: ChatStreamPayload,
options?: ChatCompetitionOptions,
): Promise<Response> => {
const { max_tokens, messages, model, temperature, top_p, tools } = payload;
const system_message = messages.find((m) => m.role === 'system');
const user_messages = messages.filter((m) => m.role !== 'system');
const command = new InvokeModelWithResponseStreamCommand({
accept: 'application/json',
body: JSON.stringify({
anthropic_version: 'bedrock-2023-05-31',
max_tokens: max_tokens || 4096,
messages: await buildAnthropicMessages(user_messages),
system: system_message?.content as string,
temperature: temperature / 2,
tools: buildAnthropicTools(tools),
top_p: top_p,
}),
contentType: 'application/json',
modelId: model,
});
try {
// Ask Claude for a streaming chat completion given the prompt
const res = await this.client.send(command, { abortSignal: options?.signal });
const claudeStream = createBedrockStream(res);
const [prod, debug] = claudeStream.tee();
if (process.env.DEBUG_BEDROCK_CHAT_COMPLETION === '1') {
debugStream(debug).catch(console.error);
}
// Respond with the stream
return StreamingResponse(AWSBedrockClaudeStream(prod, options?.callback), {
headers: options?.headers,
});
} catch (e) {
const err = e as Error & { $metadata: any };
throw AgentRuntimeError.chat({
error: {
body: err.$metadata,
message: err.message,
type: err.name,
},
errorType: AgentRuntimeErrorType.ProviderBizError,
provider: ModelProvider.Bedrock,
region: this.region,
});
}
};
private invokeLlamaModel = async (
payload: ChatStreamPayload,
options?: ChatCompetitionOptions,
): Promise<Response> => {
const { max_tokens, messages, model } = payload;
const command = new InvokeModelWithResponseStreamCommand({
accept: 'application/json',
body: JSON.stringify({
max_gen_len: max_tokens || 400,
prompt: experimental_buildLlama2Prompt(messages as any),
}),
contentType: 'application/json',
modelId: model,
});
try {
// Ask Claude for a streaming chat completion given the prompt
const res = await this.client.send(command);
const stream = createBedrockStream(res);
const [prod, debug] = stream.tee();
if (process.env.DEBUG_BEDROCK_CHAT_COMPLETION === '1') {
debugStream(debug).catch(console.error);
}
// Respond with the stream
return StreamingResponse(AWSBedrockLlamaStream(prod, options?.callback), {
headers: options?.headers,
});
} catch (e) {
const err = e as Error & { $metadata: any };
throw AgentRuntimeError.chat({
error: {
body: err.$metadata,
message: err.message,
region: this.region,
type: err.name,
},
errorType: AgentRuntimeErrorType.ProviderBizError,
provider: ModelProvider.Bedrock,
region: this.region,
});
}
};
}
export default LobeBedrockAI;