forked from firebase/genkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanthropic-client.ts
More file actions
390 lines (364 loc) · 9.7 KB
/
anthropic-client.ts
File metadata and controls
390 lines (364 loc) · 9.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
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
384
385
386
387
388
389
390
/**
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type Anthropic from '@anthropic-ai/sdk';
import type {
BetaMessage,
BetaRawMessageStreamEvent,
} from '@anthropic-ai/sdk/resources/beta/messages.mjs';
import type {
Message,
MessageStreamEvent,
} from '@anthropic-ai/sdk/resources/messages.mjs';
import { mock } from 'node:test';
export interface MockAnthropicClientOptions {
messageResponse?: Partial<Message>;
sequentialResponses?: Partial<Message>[]; // For tool calling - multiple responses
streamChunks?: MessageStreamEvent[];
modelList?: Array<{ id: string; display_name?: string }>;
shouldError?: Error;
streamErrorAfterChunk?: number; // Throw error after this many chunks
streamError?: Error; // Error to throw during streaming
abortSignal?: AbortSignal; // Abort signal to check
}
/**
* Creates a mock Anthropic client for testing
*/
export function createMockAnthropicClient(
options: MockAnthropicClientOptions = {}
): Anthropic {
const messageResponse = {
...mockDefaultMessage(),
...options.messageResponse,
};
const betaMessageResponse = toBetaMessage(messageResponse);
// Support sequential responses for tool calling workflows
let callCount = 0;
const createStub = options.shouldError
? mock.fn(async () => {
throw options.shouldError;
})
: options.sequentialResponses
? mock.fn(async () => {
const response =
options.sequentialResponses![callCount] || messageResponse;
callCount++;
return {
...mockDefaultMessage(),
...response,
};
})
: mock.fn(async () => messageResponse);
let betaCallCount = 0;
const betaCreateStub = options.shouldError
? mock.fn(async () => {
throw options.shouldError;
})
: options.sequentialResponses
? mock.fn(async () => {
const response =
options.sequentialResponses![betaCallCount] || messageResponse;
betaCallCount++;
return toBetaMessage({
...mockDefaultMessage(),
...response,
});
})
: mock.fn(async () => betaMessageResponse);
const streamStub = options.shouldError
? mock.fn(() => {
throw options.shouldError;
})
: mock.fn((_body: any, opts?: { signal?: AbortSignal }) => {
// Check abort signal before starting stream
if (opts?.signal?.aborted) {
throw new Error('AbortError');
}
return createMockStream(
options.streamChunks || [],
messageResponse as Message,
options.streamErrorAfterChunk,
options.streamError,
opts?.signal
);
});
const betaStreamStub = options.shouldError
? mock.fn(() => {
throw options.shouldError;
})
: mock.fn((_body: any, opts?: { signal?: AbortSignal }) => {
if (opts?.signal?.aborted) {
throw new Error('AbortError');
}
const betaChunks = (options.streamChunks || []).map((chunk) =>
toBetaStreamEvent(chunk)
);
return createMockStream(
betaChunks,
toBetaMessage(messageResponse),
options.streamErrorAfterChunk,
options.streamError,
opts?.signal
);
});
const listStub = options.shouldError
? mock.fn(async () => {
throw options.shouldError;
})
: mock.fn(async () => ({
data: options.modelList || mockDefaultModels(),
}));
return {
messages: {
create: createStub,
stream: streamStub,
},
models: {
list: listStub,
},
beta: {
messages: {
create: betaCreateStub,
stream: betaStreamStub,
},
},
} as unknown as Anthropic;
}
/**
* Creates a mock async iterable stream for streaming responses
*/
function createMockStream<TMessageType, TEventType>(
chunks: TEventType[],
finalMsg: TMessageType,
errorAfterChunk?: number,
streamError?: Error,
abortSignal?: AbortSignal
) {
let index = 0;
return {
[Symbol.asyncIterator]() {
return {
async next() {
// Check abort signal
if (abortSignal?.aborted) {
const error = new Error('AbortError');
error.name = 'AbortError';
throw error;
}
// Check if we should throw an error after this chunk
if (
errorAfterChunk !== undefined &&
streamError &&
index >= errorAfterChunk
) {
throw streamError;
}
if (index < chunks.length) {
return { value: chunks[index++] as TEventType, done: false };
}
return { value: undefined as unknown as TEventType, done: true };
},
};
},
async finalMessage() {
// Check abort signal before returning final message
if (abortSignal?.aborted) {
const error = new Error('AbortError');
error.name = 'AbortError';
throw error;
}
return finalMsg as TMessageType;
},
};
}
export interface CreateMockAnthropicMessageOptions {
id?: string;
text?: string;
toolUse?: {
id?: string;
name: string;
input: any;
};
stopReason?: Message['stop_reason'];
usage?: Partial<Message['usage']>;
}
/**
* Creates a customizable mock Anthropic Message response
*
* @example
* // Simple text response
* createMockAnthropicMessage({ text: 'Hi there!' })
*
* // Tool use response
* createMockAnthropicMessage({
* toolUse: { name: 'get_weather', input: { city: 'NYC' } }
* })
*
* // Custom usage
* createMockAnthropicMessage({ usage: { input_tokens: 5, output_tokens: 15 } })
*/
export function createMockAnthropicMessage(
options: CreateMockAnthropicMessageOptions = {}
): Message {
const content: Message['content'] = [];
if (options.toolUse) {
content.push({
type: 'tool_use',
id: options.toolUse.id || 'toolu_test123',
name: options.toolUse.name,
input: options.toolUse.input,
});
} else {
content.push({
type: 'text',
text: options.text || 'Hello! How can I help you today?',
citations: null,
});
}
const usage: Message['usage'] = {
cache_creation: null,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
input_tokens: 10,
output_tokens: 20,
server_tool_use: null,
service_tier: null,
...(options.usage ?? {}),
};
return {
id: options.id || 'msg_test123',
type: 'message',
role: 'assistant',
model: 'claude-3-5-sonnet-20241022',
content,
stop_reason:
options.stopReason || (options.toolUse ? 'tool_use' : 'end_turn'),
stop_sequence: null,
usage,
};
}
/**
* Creates a default mock Message response
*/
export function mockDefaultMessage(): Message {
return createMockAnthropicMessage();
}
/**
* Creates a mock text content block chunk event
*/
export function mockTextChunk(text: string): MessageStreamEvent {
return {
type: 'content_block_delta',
index: 0,
delta: {
type: 'text_delta',
text,
},
} as MessageStreamEvent;
}
/**
* Creates a mock content block start event with text
*/
export function mockContentBlockStart(text: string): MessageStreamEvent {
return {
type: 'content_block_start',
index: 0,
content_block: {
type: 'text',
text,
},
} as MessageStreamEvent;
}
/**
* Creates a mock tool use content block
*/
export function mockToolUseChunk(
id: string,
name: string,
input: any
): MessageStreamEvent {
return {
type: 'content_block_start',
index: 0,
content_block: {
type: 'tool_use',
id,
name,
input,
},
} as MessageStreamEvent;
}
/**
* Creates a default list of mock models
*/
export function mockDefaultModels() {
return [
{ id: 'claude-3-5-sonnet-20241022', display_name: 'Claude 3.5 Sonnet' },
{ id: 'claude-3-5-haiku-20241022', display_name: 'Claude 3.5 Haiku' },
{ id: 'claude-3-opus-20240229', display_name: 'Claude 3 Opus' },
];
}
/**
* Creates a mock Message with tool use
*/
export function mockMessageWithToolUse(
toolName: string,
toolInput: any
): Partial<Message> {
return {
content: [
{
type: 'tool_use',
id: 'toolu_test123',
name: toolName,
input: toolInput,
},
],
stop_reason: 'tool_use',
};
}
/**
* Creates a mock Message with custom content
*/
export function mockMessageWithContent(
content: Message['content']
): Partial<Message> {
return {
content,
stop_reason: 'end_turn',
};
}
function toBetaMessage(message: Message): BetaMessage {
// @ts-ignore
return {
...message,
container: null,
context_management: null,
usage: {
cache_creation: message.usage.cache_creation,
cache_creation_input_tokens: message.usage.cache_creation_input_tokens,
cache_read_input_tokens: message.usage.cache_read_input_tokens,
input_tokens: message.usage.input_tokens,
output_tokens: message.usage.output_tokens,
server_tool_use: message.usage.server_tool_use as any,
service_tier: message.usage.service_tier,
},
};
}
function toBetaStreamEvent(
event: MessageStreamEvent
): BetaRawMessageStreamEvent {
return event as unknown as BetaRawMessageStreamEvent;
}