Skip to content
This repository has been archived by the owner on Sep 7, 2024. It is now read-only.
/ anthropic-rs Public archive

Anthropic Rust SDK

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
Notifications You must be signed in to change notification settings

roushou/anthropic-rs

Repository files navigation

Anthropic Rust SDK

Crates.io MIT licensed APACHE-2.0 licensed Build Status

Note

The repository has been moved to https://github.com/roushou/mesh

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 messages.

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("environment variable 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.