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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
|
- import { AwsBedrockKnowledgeBaseProvider } from '../../src/providers/bedrockKnowledgeBase';
- const mockSend = jest.fn();
- const mockBedrockClient = {
- send: mockSend,
- };
- jest.mock('@aws-sdk/client-bedrock-agent-runtime', () => ({
- BedrockAgentRuntimeClient: jest.fn().mockImplementation(() => mockBedrockClient),
- RetrieveAndGenerateCommand: jest.fn().mockImplementation((params) => params),
- }));
- const { BedrockAgentRuntimeClient, RetrieveAndGenerateCommand } = jest.requireMock(
- '@aws-sdk/client-bedrock-agent-runtime',
- );
- jest.mock('@smithy/node-http-handler', () => {
- return {
- NodeHttpHandler: jest.fn(),
- };
- });
- jest.mock('proxy-agent', () => jest.fn());
- const mockGet = jest.fn();
- const mockSet = jest.fn();
- const mockIsCacheEnabled = jest.fn().mockReturnValue(false);
- jest.mock('../../src/cache', () => ({
- getCache: jest.fn().mockImplementation(() => ({
- get: mockGet,
- set: mockSet,
- })),
- isCacheEnabled: () => mockIsCacheEnabled(),
- }));
- describe('AwsBedrockKnowledgeBaseProvider', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- delete process.env.AWS_BEDROCK_MAX_RETRIES;
- });
- afterEach(() => {
- jest.clearAllMocks();
- });
- it('should throw an error if knowledgeBaseId is not provided', () => {
- expect(() => {
- new AwsBedrockKnowledgeBaseProvider('us.anthropic.claude-3-7-sonnet-20241022-v2:0', {
- config: {} as any,
- });
- }).toThrow('Knowledge Base ID is required');
- });
- it('should create provider with required options', () => {
- const provider = new AwsBedrockKnowledgeBaseProvider(
- 'us.anthropic.claude-3-7-sonnet-20241022-v2:0',
- {
- config: {
- knowledgeBaseId: 'kb-123',
- region: 'us-east-1',
- },
- },
- );
- expect(provider).toBeDefined();
- expect(provider.kbConfig.knowledgeBaseId).toBe('kb-123');
- expect(provider.getRegion()).toBe('us-east-1');
- });
- it('should create knowledge base client without proxy settings', async () => {
- const provider = new AwsBedrockKnowledgeBaseProvider(
- 'us.anthropic.claude-3-7-sonnet-20241022-v2:0',
- {
- config: {
- knowledgeBaseId: 'kb-123',
- region: 'us-east-1',
- },
- },
- );
- await provider.getKnowledgeBaseClient();
- expect(BedrockAgentRuntimeClient).toHaveBeenCalledWith({
- region: 'us-east-1',
- retryMode: 'adaptive',
- maxAttempts: 10,
- });
- });
- it('should create knowledge base client with credentials', async () => {
- const provider = new AwsBedrockKnowledgeBaseProvider(
- 'us.anthropic.claude-3-7-sonnet-20241022-v2:0',
- {
- config: {
- knowledgeBaseId: 'kb-123',
- region: 'us-east-1',
- accessKeyId: 'test-access-key',
- secretAccessKey: 'test-secret-key',
- },
- },
- );
- await provider.getKnowledgeBaseClient();
- expect(BedrockAgentRuntimeClient).toHaveBeenCalledWith({
- region: 'us-east-1',
- retryMode: 'adaptive',
- maxAttempts: 10,
- credentials: {
- accessKeyId: 'test-access-key',
- secretAccessKey: 'test-secret-key',
- },
- });
- });
- it('should respect AWS_BEDROCK_MAX_RETRIES environment variable', async () => {
- process.env.AWS_BEDROCK_MAX_RETRIES = '5';
- const provider = new AwsBedrockKnowledgeBaseProvider(
- 'us.anthropic.claude-3-7-sonnet-20241022-v2:0',
- {
- config: {
- knowledgeBaseId: 'kb-123',
- region: 'us-east-1',
- },
- },
- );
- await provider.getKnowledgeBaseClient();
- expect(BedrockAgentRuntimeClient).toHaveBeenCalledWith({
- region: 'us-east-1',
- retryMode: 'adaptive',
- maxAttempts: 5,
- });
- });
- it('should call the knowledge base API with correct parameters', async () => {
- const mockResponse = {
- output: {
- text: 'This is the response from the knowledge base',
- },
- citations: [
- {
- retrievedReferences: [
- {
- content: {
- text: 'This is a citation',
- },
- location: {
- type: 's3',
- s3Location: {
- uri: 's3://bucket/key',
- },
- },
- },
- ],
- generatedResponsePart: {
- textResponsePart: {
- text: 'part of the response',
- span: {
- start: 0,
- end: 10,
- },
- },
- },
- },
- ],
- };
- mockSend.mockResolvedValueOnce(mockResponse);
- const provider = new AwsBedrockKnowledgeBaseProvider(
- 'us.anthropic.claude-3-7-sonnet-20241022-v2:0',
- {
- config: {
- knowledgeBaseId: 'kb-123',
- region: 'us-east-1',
- },
- },
- );
- const result = await provider.callApi('What is the capital of France?');
- const expectedCommand = {
- input: { text: 'What is the capital of France?' },
- retrieveAndGenerateConfiguration: {
- type: 'KNOWLEDGE_BASE',
- knowledgeBaseConfiguration: {
- knowledgeBaseId: 'kb-123',
- modelArn:
- 'arn:aws:bedrock:us-east-1:aws:foundation-model/us.anthropic.claude-3-7-sonnet-20241022-v2:0',
- },
- },
- };
- expect(RetrieveAndGenerateCommand).toHaveBeenCalledWith(expectedCommand);
- expect(mockSend).toHaveBeenCalledWith(expectedCommand);
- expect(result).toEqual({
- output: 'This is the response from the knowledge base',
- metadata: { citations: mockResponse.citations },
- tokenUsage: {},
- });
- });
- it('should handle API errors gracefully', async () => {
- mockSend.mockRejectedValueOnce(new Error('API error'));
- const provider = new AwsBedrockKnowledgeBaseProvider(
- 'us.anthropic.claude-3-7-sonnet-20241022-v2:0',
- {
- config: {
- knowledgeBaseId: 'kb-123',
- region: 'us-east-1',
- },
- },
- );
- const result = await provider.callApi('What is the capital of France?');
- expect(result).toEqual({
- error: 'Bedrock Knowledge Base API error: Error: API error',
- });
- });
- it('should use custom modelArn if provided', async () => {
- const mockResponse = {
- output: {
- text: 'This is the response from the knowledge base',
- },
- citations: [],
- };
- mockSend.mockResolvedValueOnce(mockResponse);
- const provider = new AwsBedrockKnowledgeBaseProvider('amazon.nova-lite-v1:0', {
- config: {
- knowledgeBaseId: 'kb-123',
- region: 'us-east-1',
- modelArn: 'custom:model:arn',
- },
- });
- await provider.callApi('What is the capital of France?');
- const expectedCommand = {
- input: { text: 'What is the capital of France?' },
- retrieveAndGenerateConfiguration: {
- type: 'KNOWLEDGE_BASE',
- knowledgeBaseConfiguration: {
- knowledgeBaseId: 'kb-123',
- modelArn: 'custom:model:arn',
- },
- },
- };
- expect(RetrieveAndGenerateCommand).toHaveBeenCalledWith(expectedCommand);
- });
- it('should pass along config parameters but not create generationConfiguration', async () => {
- const mockResponse = {
- output: {
- text: 'This is the response from the knowledge base',
- },
- citations: [],
- };
- mockSend.mockResolvedValueOnce(mockResponse);
- const provider = new AwsBedrockKnowledgeBaseProvider('amazon.nova-lite-v1:0', {
- config: {
- knowledgeBaseId: 'kb-123',
- region: 'us-east-1',
- } as any,
- });
- await provider.callApi('What is the capital of France?');
- const expectedCommand = {
- input: { text: 'What is the capital of France?' },
- retrieveAndGenerateConfiguration: {
- type: 'KNOWLEDGE_BASE',
- knowledgeBaseConfiguration: {
- knowledgeBaseId: 'kb-123',
- modelArn: 'arn:aws:bedrock:us-east-1:aws:foundation-model/amazon.nova-lite-v1:0',
- },
- },
- };
- expect(RetrieveAndGenerateCommand).toHaveBeenCalledWith(expectedCommand);
- });
- it('should retrieve citations from cache when available', async () => {
- mockIsCacheEnabled.mockReturnValue(true);
- const cachedResponse = JSON.stringify({
- output: 'Cached response from knowledge base',
- citations: [
- {
- retrievedReferences: [
- {
- content: { text: 'Citation from cache' },
- location: { s3Location: { uri: 'https://example.com/cached' } },
- },
- ],
- },
- ],
- });
- mockGet.mockResolvedValueOnce(cachedResponse);
- const provider = new AwsBedrockKnowledgeBaseProvider(
- 'us.anthropic.claude-3-7-sonnet-20241022-v2:0',
- {
- config: {
- knowledgeBaseId: 'kb-123',
- region: 'us-east-1',
- },
- },
- );
- const result = await provider.callApi('What is the capital of France?');
- expect(mockGet).toHaveBeenCalledWith(
- expect.stringMatching(/^bedrock-kb:.*:What is the capital of France\?$/),
- );
- expect(result).toEqual({
- output: 'Cached response from knowledge base',
- metadata: {
- citations: [
- {
- retrievedReferences: [
- {
- content: { text: 'Citation from cache' },
- location: { s3Location: { uri: 'https://example.com/cached' } },
- },
- ],
- },
- ],
- },
- tokenUsage: {},
- cached: true,
- });
- mockIsCacheEnabled.mockReturnValue(false);
- });
- it('should use custom modelArn in cache key when provided', async () => {
- mockIsCacheEnabled.mockReturnValue(true);
- const provider = new AwsBedrockKnowledgeBaseProvider('amazon.nova-lite-v1:0', {
- config: {
- knowledgeBaseId: 'kb-123',
- region: 'us-east-1',
- modelArn: 'custom:model:arn',
- },
- });
- mockGet.mockResolvedValueOnce(null);
- const mockResponse = {
- output: {
- text: 'Response with custom model ARN',
- },
- citations: [],
- };
- mockSend.mockResolvedValueOnce(mockResponse);
- await provider.callApi('What is the capital of France?');
- expect(mockGet).toHaveBeenCalledWith(
- expect.stringMatching(/^bedrock-kb:.*:What is the capital of France\?$/),
- );
- expect(mockSet).toHaveBeenCalledWith(
- expect.stringMatching(/^bedrock-kb:.*:What is the capital of France\?$/),
- expect.any(String),
- );
- mockIsCacheEnabled.mockReturnValue(false);
- });
- });
|