59 lines
1.4 KiB
TypeScript
59 lines
1.4 KiB
TypeScript
import 'dotenv/config';
|
|
import Anthropic from '@anthropic-ai/sdk';
|
|
|
|
export interface BaseTool {
|
|
readonly name: string;
|
|
readonly input_schema: {
|
|
readonly type: 'object';
|
|
readonly properties: Record<string, unknown>;
|
|
readonly required?: readonly string[];
|
|
readonly description?: string;
|
|
};
|
|
}
|
|
|
|
export type ToolUseBlock = {
|
|
type: 'tool_use';
|
|
id: string;
|
|
name: string;
|
|
input: Record<string, any>;
|
|
};
|
|
|
|
export async function makeRequest<T extends BaseTool>(prompt: string, tool: T) {
|
|
if (!process.env.ANTHROPIC_API_KEY) {
|
|
throw Error('No Anthropic API key found.');
|
|
}
|
|
|
|
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
|
|
|
|
try {
|
|
const response = await client.messages.create({
|
|
model: 'claude-sonnet-4-0',
|
|
max_tokens: 8192,
|
|
temperature: 1,
|
|
tools: [tool],
|
|
messages: [{ role: 'user', content: prompt }]
|
|
});
|
|
|
|
if (response.stop_reason && response.stop_reason !== 'tool_use') {
|
|
throw Error(JSON.stringify(response));
|
|
}
|
|
|
|
if (response.content.length != 2) {
|
|
throw Error(JSON.stringify(response));
|
|
}
|
|
|
|
const content = response.content;
|
|
|
|
const toolUse = content.find((block): block is ToolUseBlock => block.type === 'tool_use');
|
|
|
|
if (!toolUse) {
|
|
throw new Error('No tool_use block found in response');
|
|
}
|
|
|
|
return toolUse.input;
|
|
} catch (error) {
|
|
console.error('Error making request:', error);
|
|
throw Error('Anthropic client error.');
|
|
}
|
|
}
|