Elffuss BraidHub

kikocis/continue public

a36aa2a5e5e6 · 10.2 KiBRawPermalink
1import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
2import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
3import Bedrock from "./Bedrock.js";
4import {
5 ChatMessage,
6 Chunk,
7 CompletionOptions,
8 UserChatMessage,
9} from "../../index.js";
10
11// Mock AWS SDK
12jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
13 BedrockRuntimeClient: jest.fn().mockImplementation(() => ({
14 send: jest.fn(),
15 middlewareStack: { add: jest.fn() },
16 })),
17 ConverseStreamCommand: jest.fn(),
18 InvokeModelCommand: jest.fn(),
19}));
20
21// Mock credential provider
22jest.mock("@aws-sdk/credential-providers", () => ({
23 fromNodeProviderChain: jest.fn().mockImplementation(() => async () => ({
24 accessKeyId: "test-access-key",
25 secretAccessKey: "test-secret-key",
26 sessionToken: "test-session-token",
27 })),
28}));
29
30// Extend CompletionOptions for testing
31interface TestCompletionOptions extends CompletionOptions {
32 mockError?: string;
33 mockToolUse?: boolean;
34}
35
36// Create a test class that overrides the protected methods
37class TestBedrock extends Bedrock {
38 // Make _streamChat public for testing
39 public async *streamChat(
40 messages: ChatMessage[],
41 signal: AbortSignal,
42 options: TestCompletionOptions,
43 ): AsyncGenerator<ChatMessage> {
44 if (options.mockError) {
45 throw new Error(options.mockError);
46 }
47
48 if (options.mockToolUse) {
49 yield {
50 role: "assistant",
51 content: "",
52 toolCalls: [
53 {
54 id: "tool-1",
55 type: "function",
56 function: {
57 name: "test_tool",
58 arguments: '{"arg1":"value1"}',
59 },
60 },
61 ],
62 };
63 return;
64 }
65
66 yield { role: "assistant", content: "Hello" };
67 yield { role: "assistant", content: " world" };
68 }
69
70 // Override embed to avoid making real API calls
71 async embed(chunks: string[]): Promise<number[][]> {
72 if (chunks[0] === "error") {
73 throw new Error("Embedding Error");
74 }
75 return [[0.1, 0.2, 0.3]];
76 }
77
78 // Override rerank to avoid making real API calls
79 async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
80 if (!query || !chunks.length) {
81 throw new Error("Query and chunks must not be empty");
82 }
83
84 if (query === "error") {
85 throw new Error("Reranking Error");
86 }
87
88 return chunks.map((_, i) => 0.8 - i * 0.3);
89 }
90}
91
92describe("Bedrock", () => {
93 beforeEach(() => {
94 jest.clearAllMocks();
95 });
96
97 describe("constructor", () => {
98 it("should initialize with default options", () => {
99 const bedrock = new TestBedrock({
100 apiKey: "test-key",
101 model: "anthropic.claude-3-sonnet-20240229-v1:0",
102 region: "us-east-1",
103 });
104
105 expect(bedrock.region).toBe("us-east-1");
106 expect(bedrock.profile).toBe("bedrock");
107 expect(bedrock.apiBase).toBe(
108 "https://bedrock-runtime.us-east-1.amazonaws.com",
109 );
110 });
111
112 it("should use custom options when provided", () => {
113 const bedrock = new TestBedrock({
114 apiKey: "test-key",
115 model: "anthropic.claude-3-sonnet-20240229-v1:0",
116 region: "us-west-2",
117 profile: "custom-profile",
118 apiBase: "https://custom-endpoint.amazonaws.com/",
119 });
120
121 expect(bedrock.region).toBe("us-west-2");
122 expect(bedrock.profile).toBe("custom-profile");
123 expect(bedrock.apiBase).toBe("https://custom-endpoint.amazonaws.com/");
124 });
125 });
126
127 describe("streamChat", () => {
128 let bedrock: TestBedrock;
129 const mockAbortSignal = new AbortController().signal;
130 const defaultOptions: TestCompletionOptions = {
131 model: "anthropic.claude-3-sonnet-20240229-v1:0",
132 };
133
134 beforeEach(() => {
135 bedrock = new TestBedrock({
136 apiKey: "test-key",
137 model: "anthropic.claude-3-sonnet-20240229-v1:0",
138 region: "us-east-1",
139 });
140 });
141
142 it("should handle text streaming correctly", async () => {
143 const messages: ChatMessage[] = [
144 {
145 role: "user",
146 content: "Hi",
147 } as UserChatMessage,
148 ];
149
150 const results = [];
151
152 for await (const message of bedrock.streamChat(
153 messages,
154 mockAbortSignal,
155 defaultOptions,
156 )) {
157 results.push(message);
158 }
159
160 expect(results).toEqual([
161 { role: "assistant", content: "Hello" },
162 { role: "assistant", content: " world" },
163 ]);
164 });
165
166 it("should handle tool use streaming correctly", async () => {
167 const messages: ChatMessage[] = [
168 {
169 role: "user",
170 content: "Use a tool",
171 } as UserChatMessage,
172 ];
173
174 const results = [];
175 const options: TestCompletionOptions = {
176 ...defaultOptions,
177 mockToolUse: true,
178 };
179
180 for await (const message of bedrock.streamChat(
181 messages,
182 mockAbortSignal,
183 options,
184 )) {
185 results.push(message);
186 }
187
188 expect(results).toEqual([
189 {
190 role: "assistant",
191 content: "",
192 toolCalls: [
193 {
194 id: "tool-1",
195 type: "function",
196 function: {
197 name: "test_tool",
198 arguments: '{"arg1":"value1"}',
199 },
200 },
201 ],
202 },
203 ]);
204 });
205
206 it("should handle API errors", async () => {
207 const messages: ChatMessage[] = [
208 {
209 role: "user",
210 content: "Hi",
211 } as UserChatMessage,
212 ];
213
214 const options: TestCompletionOptions = {
215 ...defaultOptions,
216 mockError: "API Error",
217 };
218
219 await expect(async () => {
220 for await (const _ of bedrock.streamChat(
221 messages,
222 mockAbortSignal,
223 options,
224 )) {
225 // consume generator
226 }
227 }).rejects.toThrow("API Error");
228 });
229 });
230
231 describe("embed", () => {
232 let bedrock: TestBedrock;
233
234 beforeEach(() => {
235 bedrock = new TestBedrock({
236 apiKey: "test-key",
237 model: "cohere.embed-english-v3",
238 region: "us-east-1",
239 });
240 });
241
242 it("should handle embedding requests correctly", async () => {
243 const result = await bedrock.embed(["test text"]);
244 expect(result).toEqual([[0.1, 0.2, 0.3]]);
245 });
246
247 it("should handle embedding errors", async () => {
248 await expect(bedrock.embed(["error"])).rejects.toThrow("Embedding Error");
249 });
250 });
251
252 describe("rerank", () => {
253 let bedrock: TestBedrock;
254
255 beforeEach(() => {
256 bedrock = new TestBedrock({
257 apiKey: "test-key",
258 model: "cohere.rerank-english-v2.0",
259 region: "us-east-1",
260 });
261 });
262
263 it("should handle reranking requests correctly", async () => {
264 const chunks: Chunk[] = [
265 {
266 content: "doc1",
267 digest: "digest1",
268 filepath: "file1",
269 index: 0,
270 startLine: 1,
271 endLine: 1,
272 },
273 {
274 content: "doc2",
275 digest: "digest2",
276 filepath: "file2",
277 index: 1,
278 startLine: 1,
279 endLine: 1,
280 },
281 ];
282
283 const result = await bedrock.rerank("query", chunks);
284 expect(result).toEqual([0.8, 0.5]);
285 });
286
287 it("should handle reranking errors", async () => {
288 const chunk: Chunk = {
289 content: "doc1",
290 digest: "digest1",
291 filepath: "file1",
292 index: 0,
293 startLine: 1,
294 endLine: 1,
295 };
296
297 await expect(bedrock.rerank("error", [chunk])).rejects.toThrow(
298 "Reranking Error",
299 );
300 });
301
302 it("should throw error for empty input", async () => {
303 await expect(bedrock.rerank("", [])).rejects.toThrow(
304 "Query and chunks must not be empty",
305 );
306 });
307 });
308
309 describe("message conversion", () => {
310 let bedrock: TestBedrock;
311
312 beforeEach(() => {
313 bedrock = new TestBedrock({
314 apiKey: "test-key",
315 model: "anthropic.claude-3-sonnet-20240229-v1:0",
316 region: "us-east-1",
317 });
318 });
319
320 it("should convert text messages correctly", () => {
321 const message: ChatMessage = {
322 role: "user",
323 content: "Hello",
324 } as UserChatMessage;
325 const converted = bedrock["_convertMessage"](message);
326 expect(converted).toEqual({
327 role: "user",
328 content: [{ text: "Hello" }],
329 });
330 });
331
332 it("should convert tool responses correctly", () => {
333 const message: ChatMessage = {
334 role: "tool",
335 content: "Tool result",
336 toolCallId: "tool-1",
337 };
338 const converted = bedrock["_convertMessage"](message);
339 expect(converted).toEqual({
340 role: "user",
341 content: [
342 {
343 toolResult: {
344 toolUseId: "tool-1",
345 content: [{ text: "Tool result" }],
346 },
347 },
348 ],
349 });
350 });
351
352 it("should convert tool calls correctly", () => {
353 const message: ChatMessage = {
354 role: "assistant",
355 content: "",
356 toolCalls: [
357 {
358 id: "tool-1",
359 type: "function" as const,
360 function: {
361 name: "test_tool",
362 arguments: '{"arg":"value"}',
363 },
364 },
365 ],
366 };
367 const converted = bedrock["_convertMessage"](message);
368 expect(converted).toEqual({
369 role: "assistant",
370 content: [
371 {
372 toolUse: {
373 toolUseId: "tool-1",
374 name: "test_tool",
375 input: { arg: "value" },
376 },
377 },
378 ],
379 });
380 });
381
382 it("should handle multimodal content correctly", () => {
383 const message: ChatMessage = {
384 role: "user",
385 content: [
386 { type: "text", text: "Look at this image:" },
387 {
388 type: "imageUrl",
389 imageUrl: {
390 url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
391 },
392 },
393 ],
394 } as UserChatMessage;
395 const converted = bedrock["_convertMessage"](message);
396 expect(converted).toEqual({
397 role: "user",
398 content: [
399 { text: "Look at this image:" },
400 {
401 image: {
402 format: "jpeg",
403 source: {
404 bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"),
405 },
406 },
407 },
408 ],
409 });
410 });
411 });
412});