tool_use/
tool_use.rs

1//! # Tool Use Example
2//!
3//! This example demonstrates how to use Claude's tool use capabilities.
4//! It creates a calculator tool that Claude can use to perform basic arithmetic operations.
5//!
6//! ## Features
7//!
8//! - Defines a calculator tool with a JSON schema
9//! - Allows Claude to use the tool when appropriate
10//! - Maintains conversation history for context
11//! - Simple command-line interface for user input
12//!
13//! ## Usage
14//!
15//! Run this example with:
16//!
17//! ```bash
18//! cargo run --example tool_use
19//! ```
20//!
21//! Make sure you have set the `ANTHROPIC_API_KEY` environment variable.
22
23use anthropic_api::{messages::*, Credentials};
24use serde_json::json;
25
26#[tokio::main]
27async fn main() {
28    let credentials = Credentials::from_env();
29
30    // Define a calculator tool
31    let calculator_tool = Tool {
32        name: "calculator".to_string(),
33        description: "A calculator that can perform basic arithmetic operations".to_string(),
34        input_schema: json!({
35            "type": "object",
36            "properties": {
37                "operation": {
38                    "type": "string",
39                    "enum": ["add", "subtract", "multiply", "divide"]
40                },
41                "operands": {
42                    "type": "array",
43                    "items": {"type": "number"},
44                    "minItems": 2,
45                    "maxItems": 2
46                }
47            },
48            "required": ["operation", "operands"]
49        }),
50    };
51
52    let content =
53        "You are a helpful AI assistant. Please calculate 15 + 27 using the calculator tool.";
54    let mut messages = vec![Message {
55        role: MessageRole::User,
56        content: MessageContent::Text(content.to_string()),
57    }];
58
59    println!("Claude: {}", content);
60
61    // Create message request with tool
62    let response = MessagesAPI::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
63        .credentials(credentials.clone())
64        .tools(vec![calculator_tool.clone()])
65        .tool_choice(ToolChoice::Any)
66        .create()
67        .await
68        .unwrap();
69
70    // Print assistant's response and tool usage
71    for content in response.content {
72        match content {
73            ResponseContentBlock::Text { text } => {
74                println!("Assistant: {}", text.trim());
75                messages.push(Message {
76                    role: MessageRole::Assistant,
77                    content: MessageContent::Text(text),
78                });
79            }
80            ResponseContentBlock::ToolUse { name, input, .. } => {
81                println!("Claude decided to use the tool: {}: {}", name, input);
82            }
83        }
84    }
85}