1import Anthropic from '@anthropic-ai/sdk';
2import {
3 inventoryTool,
4 runInventoryQuery,
5} from './tools';
6
7const anthropic = new Anthropic({
8 apiKey: process.env.ANTHROPIC_API_KEY,
9});
10
11export async function askAgent(
12 question: string
13) {
14 const messages: any[] = [
15 { role: 'user', content: question },
16 ];
17
18 let response = await anthropic.messages.create({
19 model: 'claude-sonnet-4-5',
20 max_tokens: 1024,
21 tools: [inventoryTool],
22 messages,
23 });
24
25 while (response.stop_reason === 'tool_use') {
26 const toolUse = response.content.find(
27 (b: any) => b.type === 'tool_use'
28 );
29 if (!toolUse) break;
30
31 const result = await runInventoryQuery(
32 toolUse.input as { category?: string }
33 );
34
35 messages.push({
36 role: 'assistant',
37 content: response.content,
38 });
39 messages.push({
40 role: 'user',
41 content: [
42 {
43 type: 'tool_result',
44 tool_use_id: toolUse.id,
45 content: JSON.stringify(result),
46 },
47 ],
48 });
49
50 response = await anthropic.messages.create({
51 model: 'claude-sonnet-4-5',
52 max_tokens: 1024,
53 tools: [inventoryTool],
54 messages,
55 });
56 }
57
58 const finalText = response.content.find(
59 (b: any) => b.type === 'text'
60 );
61 return finalText ? finalText.text : '';
62}