8 releases

0.1.7 Sep 7, 2024
0.1.6 Sep 5, 2024
0.1.5 Aug 18, 2024

#207 in Machine learning

Download history 481/week @ 2024-08-16 15/week @ 2024-08-23 88/week @ 2024-08-30 340/week @ 2024-09-06 62/week @ 2024-09-13 59/week @ 2024-09-20 37/week @ 2024-09-27 18/week @ 2024-10-04 15/week @ 2024-10-11 10/week @ 2024-10-18 3/week @ 2024-10-25 18/week @ 2024-11-01 16/week @ 2024-11-08 26/week @ 2024-11-15 19/week @ 2024-11-22 12/week @ 2024-11-29

76 downloads per month
Used in 2 crates

MIT AND Apache-2.0

40KB
988 lines

Anthropic Rust SDK

Crates.io MIT licensed APACHE-2.0 licensed Build Status

Documentation

This is an unofficial Rust SDK for the Anthropic API.

Installation

Add anthropic-rs as a dependency to your Cargo.toml

cargo add anthropic-rs

Usage

An example to stream a message.

use anthropic_rs::{
    api::{
        message::{Content, ContentType, Message, MessageRequest, Role},
        stream::StreamEvent,
    },
    client::Client,
    config::Config,
    models::model::Model,
};
use futures_util::StreamExt;
use std::io::Write;

#[tokio::main]
async fn main() {
    let api_key = std::env::var("ANTHROPIC_API_KEY").expect("ANTHROPIC_API_KEY should be defined");

    let config = Config::new(api_key);
    let client = Client::new(config).unwrap();

    let message = MessageRequest {
        model: Model::Claude35Sonnet,
        stream: Some(true),
        max_tokens: 1024,
        messages: vec![Message {
            role: Role::User,
            content: vec![Content {
                content_type: ContentType::Text,
                text: "Explain the theory of relativity".to_string(),
            }],
        }],
        ..Default::default()
    };

    let mut stream = client.stream_message(message.clone()).await.unwrap();

    while let Some(event) = stream.next().await {
        let event = event.unwrap();
        match event {
            StreamEvent::ContentBlockDelta(content) => {
                print!("{}", content.delta.text);
                std::io::stdout().flush().unwrap();
            }
            StreamEvent::MessageStop => break,
            _ => {}
        }
    }
}

License

This project is licensed under the MIT license and Apache-2.0 license.

Dependencies

~7–18MB
~233K SLoC