Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x | import { AIProvider, AIResponse, ChatOptions, Message } from '../core/interfaces';
export class AnthropicProvider implements AIProvider {
readonly name = 'Anthropic Claude';
readonly type = 'anthropic' as const;
constructor(
private readonly apiKey: string,
readonly modelName: string,
private readonly baseUrl: string,
private readonly timeout: number
) {}
async isAvailable(): Promise<boolean> {
Iif (!this.apiKey) return false;
try {
const resp = await fetch(`${this.baseUrl}/models`, {
headers: { 'x-api-key': this.apiKey, 'anthropic-version': '2023-06-01' },
signal: AbortSignal.timeout(3000),
});
return resp.ok;
} catch {
return false;
}
}
async chat(messages: Message[], options: ChatOptions = {}): Promise<AIResponse> {
const system = options.systemPrompt ?? messages.find(m => m.role === 'system')?.content;
const filtered = messages.filter(m => m.role !== 'system');
const body: Record<string, unknown> = {
model: this.modelName,
max_tokens: options.maxTokens ?? 4096,
messages: filtered,
};
Iif (system) body['system'] = system;
const resp = await fetch(`${this.baseUrl}/messages`, {
method: 'POST',
headers: {
'x-api-key': this.apiKey,
'anthropic-version': '2023-06-01',
'content-type': 'application/json',
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(this.timeout),
});
Iif (!resp.ok) {
const err = await resp.text();
throw new Error(`Anthropic ${resp.status}: ${err}`);
}
const data = await resp.json() as {
content: Array<{ text: string }>;
model: string;
usage: { input_tokens: number; output_tokens: number };
};
return {
content: data.content[0]?.text ?? '',
model: data.model,
usage: { promptTokens: data.usage.input_tokens, completionTokens: data.usage.output_tokens },
};
}
async complete(prompt: string, options?: ChatOptions): Promise<string> {
const resp = await this.chat([{ role: 'user', content: prompt }], options);
return resp.content;
}
}
|