Skip to Content
JavaScriptUse ToolsAnthropic Example

Using Tools with Anthropic

// chatbot.js import readline from "readline"; import Anthropic from "@anthropic-ai/sdk"; import { AnthropicAdapter } from "@reacter/openapitools"; // Initialize Anthropic client const anthropic = new Anthropic({ apiKey: "your-anthropic-api-key", }); // Initialize tools adapter const toolsAdapter = new AnthropicAdapter( "your OpenAPI Tools Apikey - https://openapitools.com/dashboard/settings", { autoRefreshCount: 50, // Refresh tools after 50 calls verbose: true, } ); // Create readline interface const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); // Function to ask a question and get input function askQuestion(query) { return new Promise((resolve) => rl.question(query, resolve)); } async function main() { console.log("Initializing tools..."); // Get tools in Anthropic format const tools = await toolsAdapter.getAnthropicTools(); console.log(`Loaded ${tools.length} tools`); // Create tool handler const toolHandler = await toolsAdapter.createAnthropicToolHandler(); // Start conversation console.log("\n=== AI Assistant with Tools ==="); console.log("Type 'exit' to quit, 'reset' to start a new conversation"); // Store conversation history const messages = [ { role: "assistant", content: "Hello! I'm your AI assistant with tool capabilities. How can I help you today?", }, ]; console.log( "\nAssistant: Hello! I'm your AI assistant with tool capabilities. How can I help you today?" ); // Chat loop while (true) { const userInput = await askQuestion("\nYou: "); if (userInput.toLowerCase() === "exit") { console.log("Goodbye!"); rl.close(); break; } if (userInput.toLowerCase() === "reset") { messages.length = 0; messages.push({ role: "assistant", content: "Conversation reset. How can I help you?", }); console.log("\nConversation reset."); console.log("\nAssistant: Conversation reset. How can I help you?"); continue; } // Add user message to history messages.push({ role: "user", content: userInput, }); // Show "thinking" indicator const thinkingInterval = setInterval(() => { process.stdout.write("."); }, 500); try { // Create API call options const apiOptions = { model: "claude-3-7-sonnet-20250219", max_tokens: 4096, temperature: 0.7, messages: messages, }; // Add tools if available if (tools && tools.length > 0) { apiOptions.tools = tools; } // Call Anthropic API const response = await anthropic.messages.create(apiOptions); // Clear the thinking indicator clearInterval(thinkingInterval); process.stdout.write("\n"); // Process the response for (const content of response.content) { if (content.type === "text") { console.log(`\nAssistant: ${content.text}`); // Add assistant message to history messages.push({ role: "assistant", content: content.text, }); } else if (content.type === "tool_use") { console.log(`\nAssistant is using tool: ${content.name}`); console.log(`Tool input: ${JSON.stringify(content.input, null, 2)}`); // Add the assistant's tool use message to history messages.push({ role: "assistant", content: response.content, }); // Execute the tool try { const toolResult = await toolHandler({ id: content.id, name: content.name, input: content.input, }); // Add tool response to messages if (toolResult.error) { console.log(`\nTool Error: ${toolResult.error}`); messages.push({ role: "user", content: [ { type: "tool_result", tool_use_id: content.id, content: JSON.stringify({ error: toolResult.error }), }, ], }); } else { console.log(`\nTool Result: ${toolResult.output}`); messages.push({ role: "user", content: [ { type: "tool_result", tool_use_id: content.id, content: JSON.stringify({ output: toolResult.output }), }, ], }); } // Get continuation from AI after tool use const continuation = await anthropic.messages.create({ model: "claude-3-7-sonnet-20250219", max_tokens: 4096, temperature: 0.7, messages: messages, }); const continuationText = continuation.content .filter((item) => item.type === "text") .map((item) => item.text) .join(""); console.log(`\nAssistant: ${continuationText}`); // Add continuation to history messages.push({ role: "assistant", content: continuationText, }); } catch (error) { console.error(`\nTool execution error: ${error.message}`); messages.push({ role: "user", content: [ { type: "tool_result", tool_use_id: content.id, content: JSON.stringify({ error: `Failed to execute tool: ${error.message}`, }), }, ], }); } } } } catch (error) { // Clear the thinking indicator clearInterval(thinkingInterval); process.stdout.write("\n"); console.error(`\nError: ${error.message}`); } } } main().catch((error) => { console.error("Fatal error:", error); rl.close(); });
Last updated on