blob: b9aae377b3abd39e6cfd110aa0d7a833ac7c57c7 (
plain)
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
|
import Anthropic from '@anthropic-ai/sdk';
let client: Anthropic | null = null;
function getClient(): Anthropic {
if (!client) {
const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) throw new Error('ANTHROPIC_API_KEY not configured');
client = new Anthropic({ apiKey });
}
return client;
}
export interface ClaudeResponse {
content: string;
tokensUsed: number;
model: string;
}
export async function callClaude(opts: {
model: string;
systemPrompt: string;
userMessage: string;
maxTokens?: number;
}): Promise<ClaudeResponse> {
const anthropic = getClient();
const response = await anthropic.messages.create({
model: opts.model,
max_tokens: opts.maxTokens || 8192,
system: opts.systemPrompt,
messages: [{ role: 'user', content: opts.userMessage }],
});
const content = response.content
.filter(block => block.type === 'text')
.map(block => (block as { type: 'text'; text: string }).text)
.join('\n');
const tokensUsed = (response.usage?.input_tokens || 0) + (response.usage?.output_tokens || 0);
return {
content,
tokensUsed,
model: opts.model,
};
}
|