| Crates.io | anthropic-api |
| lib.rs | anthropic-api |
| version | 0.0.5 |
| created_at | 2025-03-12 10:36:31.177446+00 |
| updated_at | 2025-03-25 09:23:03.219631+00 |
| description | An unofficial Rust library for the Anthropic API. |
| homepage | https://github.com/Swiftyos/anthropic |
| repository | https://github.com/Swiftyos/anthropic |
| max_upload_size | |
| id | 1589625 |
| size | 212,748 |
An unofficial Rust library for interacting with the Anthropic API. This library provides an asynchronous interface to Anthropic's services, allowing Rust developers to seamlessly integrate Anthropic's AI capabilities—such as message-based interactions and tool use—into their applications.
Note: This is an unofficial library and is not maintained by Anthropic.
Follow these steps to start using the Anthropic Rust SDK in your project:
Add the library to your project using Cargo:
cargo add anthropic-api
To use this library, you need an Anthropic API key. Set the ANTHROPIC_API_KEY environment variable with your key:
export ANTHROPIC_API_KEY="your-api-key-here"
The library will automatically load this key when you create a Credentials object with Credentials::from_env().
Here’s a simple example of sending a message to the Anthropic API and receiving a response:
use anthropic_api::{messages::*, Credentials};
#[tokio::main]
async fn main() {
// Load credentials from the environment
let credentials = Credentials::from_env();
// Create a message
let messages = vec![Message {
role: MessageRole::User,
content: MessageContent::Text("Hello, Claude!".to_string()),
}];
// Send the message to the Anthropic API
let response = MessageBuilder::builder("claude-3-sonnet-20240229", messages, 1024)
.credentials(credentials)
.create()
.await
.unwrap();
// Print the assistant's response
if let Some(ResponseContentBlock::Text { text }) = response.content.first() {
println!("Assistant: {}", text.trim());
}
}
This example uses the claude-3-sonnet-20240229 model. Replace it with the desired Anthropic model name as per their official documentation.
The Anthropic Rust SDK currently supports the following features:
More features are planned for future releases—stay tuned!
Detailed examples can be found in the examples directory. Below are two key examples to get you started:
This example demonstrates a basic conversation loop with the Anthropic API:
use anthropic_api::{messages::*, Credentials};
use std::io::{stdin, stdout, Write};
#[tokio::main]
async fn main() {
let credentials = Credentials::from_env();
let mut messages = vec![Message {
role: MessageRole::User,
content: MessageContent::Text("You are a helpful AI assistant. Please introduce yourself briefly.".to_string()),
}];
// Initial message
let response = MessagesBuilder::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
.credentials(credentials.clone())
.create()
.await
.unwrap();
if let Some(ResponseContentBlock::Text { text }) = response.content.first() {
println!("Assistant: {}", text.trim());
messages.push(Message {
role: MessageRole::Assistant,
content: MessageContent::Text(text.clone()),
});
}
// Conversation loop
loop {
print!("User: ");
stdout().flush().unwrap();
let mut user_input = String::new();
stdin().read_line(&mut user_input).unwrap();
messages.push(Message {
role: MessageRole::User,
content: MessageContent::Text(user_input),
});
let response =MessagesBuilder::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
.credentials(credentials.clone())
.create()
.await
.unwrap();
if let Some(ResponseContentBlock::Text { text }) = response.content.first() {
println!("Assistant: {}", text.trim());
messages.push(Message {
role: MessageRole::Assistant,
content: MessageContent::Text(text.clone()),
});
}
}
}
This example shows how to use a calculator tool with the API:
use anthropic_api::{messages::*, Credentials};
use serde_json::json;
#[tokio::main]
async fn main() {
let credentials = Credentials::from_env();
// Define a calculator tool
let calculator_tool = Tool {
name: "calculator".to_string(),
description: "A calculator for basic arithmetic operations".to_string(),
input_schema: json!({
"type": "object",
"properties": {
"operation": {"type": "string", "enum": ["add", "subtract", "multiply", "divide"]},
"operands": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}
},
"required": ["operation", "operands"]
}),
};
let mut messages = vec![Message {
role: MessageRole::User,
content: MessageContent::Text("Calculate 15 + 27 using the calculator tool.".to_string()),
}];
// Send message with tool
let response = MessagesBuilder::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
.credentials(credentials)
.tools(vec![calculator_tool])
.tool_choice(ToolChoice::Any)
.create()
.await
.unwrap();
// Process response
for content in response.content {
match content {
ResponseContentBlock::Text { text } => println!("Assistant: {}", text.trim()),
ResponseContentBlock::ToolUse { name, input, .. } => println!("Tool use - {}: {}", name, input),
}
}
}
For more advanced examples, including streaming, check the examples directory.
Contributions are warmly welcomed! Whether you spot a bug, have a feature suggestion, or want to improve the examples, please feel free to:
To ensure high-quality contributions:
cargo fmt to keep the codebase consistent.cargo clippy to catch potential issues.Run the test suite with:
cargo test
██████████ Messages
░░░░░░░░░░ Batch Messages
██████████ Members
██████████ Invites
██████████ Workspaces
██████████ Workspace Members
██████████ API Keys
This project is licensed under the MIT License. See the LICENSE file for details.
Notice
This library was heavily inspired by and based on the OpenAI Rust SDK by Lorenzo Fontoura. A huge thanks to their foundational work!