anthropic-sdk

Library Listed Dormant

Anthropic Rust SDK.

Checked · Sources

Downloads
723
Dependents
3
Stars
38
Forks
5
Contributors
2
Commits
35
Latest release
0.1.5 ·

About

From the project README ·

Anthropic SDK for Rust

The Anthropic SDK for Rust provides a simple and efficient way to interact with the Anthropic API, allowing you to send requests and process responses asynchronously. This SDK supports both streaming and non-streaming responses, making it versatile for different use cases.

Features ✨
  • Asynchronous request handling 🚀
  • Support for streaming API responses 🌊
  • Easy configuration for authentication and request parameters 🔧
  • Error handling with detailed messages 🛠️💬
  • Optional verbose mode for raw response output 📃
Installation

Add the following to your Cargo.toml file:

[dependencies]
anthropic_sdk = "0.1.5"
dotenv = "0.15.0"
serde_json = "1.0"
tokio = { version = "1.0", features = ["full"] }
Usage
Basic Usage

For non-streaming responses, you can use the SDK as follows:

Read the full README
// examples/basic_usage.rs

use anthropic_sdk::Client;
use dotenv::dotenv;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenv().ok();
    let secret_key = std::env::var("ANTHROPIC_API_KEY").unwrap_or_default();

    let request = Client::new()
        .version("2023-06-01")
        .auth(secret_key.as_str())
        .model("claude-3-opus-20240229")
        .messages(&json!([
            {"role": "user", "content": "Write me a poem about bravery"}
        ]))
        .max_tokens(1024)
        // .verbose(true) // Uncomment to return the response as it is from Anthropic
        .build()?;

    if let Err(error) = request
        .execute(|text| async move { println!("{text}") })
        .await
    {
        eprintln!("Error: {error}");
    }

    Ok(())
}

This example demonstrates how to send a request to the Anthropic API and print the response.

Streaming Usage

For streaming responses, the SDK can be used as follows:

// examples/streaming_usage.rs

use anthropic_sdk::Client;
use dotenv::dotenv;
use serde_json::json;
use std::sync::{Arc, Mutex};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenv().ok();
    let secret_key = std::env::var("ANTHROPIC_API_KEY").unwrap_or_default();

    let request = Client::new()
        .auth(secret_key.as_str())
        .model("claude-3-opus-20240229")
        .messages(&json!([
            {"role": "user", "content": "Write me a poem about bravery"}
        ]))
        .system("Make it sound like Edgar Allan Poe")
        .temperature(0.1)
        .max_tokens(1024)
        .stream(true)
        .build()?;

    let message = Arc::new(Mutex::new(String::new()));
    let message_clone = message.clone();

    if let Err(error) = request
        .execute(move |text| {
            let message_clone = message_clone.clone();
            async move {
                println!("{text}");

                {
                    let mut message = message_clone.lock().unwrap();
                    *message = format!("{}{}", *message, text);
                }
            }
        })
        .await
    {
        eprintln!("Error: {error}");
    }

    let final_message = message.lock().unwrap();
    println!("Message: {}", *final_message); // or get the whole message at the end

    Ok(())
}

In this example, the response is processed as it streams in. Each chunk of text is printed as soon as it's received, and the entire message is also available at the end.

Tool Use

For using Anthropic Tool use, the SDK can be used as follows:

// examples/tool_use_usage.rs

use anthropic_sdk::{Client, ToolChoice};
use dotenv::dotenv;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenv().ok();
    let secret_key = std::env::var("ANTHROPIC_API_KEY").unwrap_or_default();

    let request = Client::new()
        .auth(secret_key.as_str())
        .model("claude-3-opus-20240229")
        .beta("tools-2024-04-04") // add the beta header
        .tools(&json!([
          {
            "name": "get_weather",
            "description": "Get the current weather in a given location",
            "input_schema": {
              "type": "object",
              "properties": {
                "location": {
                  "type": "string",
                  "description": "The city and state, e.g. San Francisco, CA"
                }
              },
              "required": ["location"]
            }
          }
        ]))
        .tool_choice(ToolChoice::Auto)
        .messages(&json!([
          {
            "role": "user",
            "content": "What is the weather like in San Francisco?"
          }
        ]))
        .max_tokens(1024)
        .build()?;

    if let Err(error) = request
        .execute(|text| async move { println!("{text}") })
        .await
    {
        eprintln!("Error: {error}");
    }

    Ok(())
}

This example demonstrates how to use tools with the Anthropic API to perform specific tasks, such as getting the weather.

Fields Explanation
  • version: (Optional) Specifies the version of the API to use.
  • auth: Sets the authentication token for the API.
  • model: Defines the model to use for generating responses.
  • messages: Contains the input messages for the API to process.
  • max_tokens: (Optional) Limits the number of tokens in the response.
  • stream: (Optional) Enables streaming mode for receiving responses in real-time.
  • temperature: (Optional) Adjusts the randomness of the response generation.
  • system: (Optional) Provides additional context or instructions for the response.
  • tools: (Optional) Specifies tools to use for specialized tasks.
  • tool_choice: (Optional) Specifies the tool to use when multiple tools are available.
  • verbose: (Optional) When set to true, returns the raw response from the API.
  • metadata: (Optional) Includes additional information about the request.
  • stop_sequences: (Optional) Specifies sequences where the API should stop generating further tokens.
  • top_k: (Optional) Limits the model to only sample from the top K most likely next tokens.
  • top_p: (Optional) Uses nucleus sampling to limit the model to a cumulative probability.
Configuration

Before running the examples, make sure to set your Anthropic API key in an .env file at the root of your project:

ANTHROPIC_API_KEY=your_api_key_here

Alternatively, you can set the ANTHROPIC_API_KEY environment variable in your system.

Feature Requests 📬

If you have any ideas or requests for new features, we'd love to hear from you! Please send your suggestions to hello@mixpeal.com, and we'll be sure to consider them for future updates. Your input is invaluable in helping us improve! 🌟🚀

Runs on
GPU support unknown
What shows it
  • no dependency or feature matches a backend row
Native code
None found
  • No native code found
Python bindings
No Python binding crate found
License
MIT

Compare with similar projects

Order: strongest tier first, then most downloads, then name, with unmeasured values last. A library counts downloads over 30 days. An app counts binary downloads per release. An app with none counts its crate downloads over 30 days. ML Rust runs this catalogue, so its closest project always gets a row.

anthropic-sdk beside the projects that share a topic with it
ProjectDownloadsDependentsStarsLatest releaseRuns on (GPU)Native codeLicense
anthropic-sdk This page Listed Dormant

Anthropic Rust SDK.

723 downloads over 30 days 3 38 0.1.5 GPU support unknown No native code found MIT
rust-genai Featured

Multi-AI Providers Library for Rust. (OpenAI, Gemini, Anthropic, DeepSeek, Ollama, OMLX, AWS Bedrock, Vertex, Xai, Groq, Kimi, GLM and many more)

118,643 downloads over 30 days 81 938 0.7.3 GPU support unknown No native code found Apache-2.0 OR MIT
aisdk Listed

An open-source Rust library for building AI-powered applications, inspired by the Vercel AI SDK. It provides a robust, type-safe, and easy-to-use interface for interacting with various Large Language Models (LLMs).

36,877 downloads over 30 days 4 263 0.6.1 GPU support unknown No native code found MIT

A type-safe OpenRouter Rust SDK

8,599 downloads over 30 days 3 98 0.24.0 GPU support unknown No native code found MIT

An unofficial Rust SDK for Anthropic's Claude AI API

2,116 downloads over 30 days 4 18 0.2.27 GPU support unknown No native code found MIT
antrhopic-rs Listed Dormant

Anthropic Rust SDK.

1,949 downloads over 30 days 6 Not measured 0.0.8 GPU support unknown No native code found MIT
axp App Listed

An open protocol that gives AI agents a secure, sandboxed place to run code and use tools — with lean context usage. AXP works alongside MCP

Not measured Not applicable 3 Not measured Not measured Not measured Apache-2.0
Why ListedNo archive, New or Featured rule places it, so it is Listed.

What it lacks for Featured

  • It has 2 active dependents and 2 new dependents in 365 days. Featured needs 11 active dependents or 9 new dependents in 365 days. The repository route reads 38 stars, 5 forks and 2 contributors. It needs 4,539 stars, 434 forks and 79 contributors together.
  • The project is dormant and not finished. Dormancy rule

What else the check found

  • The last activity is on 23 Jul 2024, 839 days ago. That reaches the 450 days the rules expect, so the project is dormant. Dormancy rule
  • The oldest outside issue waits 875 days for a reply, past the limit of 270. No maintainer replied in 365 days. Rot signals rule
  • The latest release requires the deprecated dependency dotenv. RUSTSEC-2021-0141 Rot signals rule
  • The project is dormant with 2 rot signals, which reaches the limit of 2. This is dead check 1 of 2, so the entry is not yet archived. Dead rule

Not measured: Latest release fails cargo check.

Exact rules: Listed, Featured library. The check on applied thresholds version 9.

Every rule outcome, as the check records it
  • expected-interval: version 0.1.5 base 450: E = 450 days
  • dormancy: last activity 2024-07-23, 839 days ago, E = 450: dormant
  • rot: oldest unanswered issue 875 days (limit 270), no maintainer reply in 365 days
  • rot: deprecated requirement `dotenv (RUSTSEC-2021-0141, https://rustsec.org/advisories/RUSTSEC-2021-0141.html)`
  • dead: dormant with 2 rot signals (limit 2): dead on check 1 of 2, not yet archived
  • featured: not featured: active_users 2 < 11 and new_adopters 2 < 9 and repository route stars 38 (needs 4539), forks 5 (needs 434), contributors 2 (needs 79); dormant and not stable
  • listed: listed: no archive, new or featured rule applies

Measurements and sources

Each signal row shows the raw value, its source and the fetch date. The Sources list gathers every distinct source on this page. Movement needs more history.

Sources6 sources
Adoption2 active dependents, 2 new dependents in 365 days1 not measured
Adoption measurements
SignalValueSourceFetchedCounts
Active dependents2crates.io database dumpYes
New dependents (365 days)2crates.io database dumpYes
Peak active dependents3crates.io database dumpYes
Active dependents as a share of the peak1crates.io database dumpYes
Binary downloads per releaseNot measuredYes
MaintenanceLatest human commit: 2 years ago3 not measured
Maintenance measurements
SignalValueSourceFetchedCounts
Latest human commit2024-07-23GitHub repositoryYes
Latest release2024-07-23crates.io database dumpYes
First release2024-03-29crates.io database dumpYes
Latest version0.1.5crates.io database dumpYes
Days the oldest outside issue waits for a reply875GitHub repositoryYes
Maintainer replies over 365 days0GitHub repositoryYes
Repository archivedfalseGitHub repositoryYes
Repository gonefalseGitHub repositoryYes
Release commit or manifest in the repotruecrates.io packageYes
Published docstruecrates.io database dumpYes
Latest release fails cargo checkNot measuredYes
Build check dateNot measuredYes
Build check toolchainNot measuredYes
SecurityUnpatched vulnerabilities: none
Security measurements
SignalValueSourceFetchedCounts
Unpatched vulnerabilities past the grace windownoneRustSec advisory databaseYes
RustSec unmaintained advisorynoneRustSec advisory databaseYes
Deprecation noticenonecrates.io database dumpYes
Deprecated requirementdotenv (RUSTSEC-2021-0141, https://rustsec.org/advisories/RUSTSEC-2021-0141.html)crates.io database dumpYes
Distribution15 releases, 723 downloads over 30 days5 not measured
Distribution measurements
SignalValueSourceFetchedCounts
Releases15crates.io database dumpYes
Downloads over 30 days723crates.io database dumpYes
Binary downloads over the last 3 releasesNot measuredYes
Homebrew installs on request over 365 daysNot measuredYes
Repology repository familiesNot measuredYes
Docker pull growth over 90 daysNot measuredYes
Docker pulls at the growth baselineNot measuredYes
Every version a prereleasefalsecrates.io database dumpYes
Every version 0.0.xfalsecrates.io database dumpYes
Every version yankedfalsecrates.io database dumpYes
Crate deleted from crates.iofalsecrates.io database dumpYes
Repository38 stars, 5 forks, 2 contributors, 35 commits. Stars alone never qualify a project.
Repository measurements
SignalValueSourceFetchedCounts
GitHub stars38GitHub repositoryYes — one part of the repository route
GitHub forks5GitHub repositoryYes — one part of the repository route
Contributors with a GitHub account2GitHub contributorsYes — one part of the repository route
Commits on the default branch35GitHub repositoryNo
Repository's main crate left out of the entrynonecrates.io database dumpYes
Facts that never count
Facts that never count measurements
SignalValueSourceFetchedCounts
LicenseMITcrates.io database dumpNo
Runs on, from listed crates and their direct dependenciesGPU support unknowncrates.io database dumpNo
What shows each backendno dependency or feature matches a backend rowcrates.io database dumpNo
Native code, from listed crates and their dependenciesNo native code foundcrates.io database dumpNo
Python bindings, from direct dependencies of listed cratesNo Python binding crate foundcrates.io database dumpNo
Crates that depend on a listed crate directly3crates.io database dumpNo

Corrections and review history

Report a correction

No correction applies to this entry.

Judgments

A judgment enters only through an approved issue and a merged pull request.

No judgment applies to this entry.