Rust SDK
Rust 生态目前没有 Anthropic 官方 SDK,下面分两块:
- OpenAI 兼容:用社区维护的
async-openaicrate,把api_base指到 Sakrylle。 - Anthropic 原生:直接用
reqwest拼 HTTP 请求;如果对 SDK 体验有要求,可以关注社区项目(见末尾)。
Anthropic 暂未发布官方 Rust SDK。本页给出的 reqwest 示例只覆盖最小用法,请以 Anthropic API 官方文档 为准。
准备
bash
export SAKRYLLE_API_KEY="sk-xxxxxxxxxxxxxxxx"需要 Rust 1.75+。
OpenAI 兼容
安装
bash
cargo add async-openai
cargo add tokio --features full
cargo add futures最小可用调用
OpenAIConfig::with_api_base + with_api_key 一起把请求重定向到 Sakrylle:
rust
use async_openai::{
config::OpenAIConfig,
types::chat::{
ChatCompletionRequestSystemMessageArgs, ChatCompletionRequestUserMessageArgs,
CreateChatCompletionRequestArgs,
},
Client,
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = OpenAIConfig::new()
.with_api_key(std::env::var("SAKRYLLE_API_KEY")?)
.with_api_base("https://api.sakrylle.com/v1");
let client = Client::with_config(config);
let request = CreateChatCompletionRequestArgs::default()
.model("gpt-5.6-sol")
.max_tokens(512u32)
.messages([
ChatCompletionRequestSystemMessageArgs::default()
.content("你是一名简洁的助手。")
.build()?
.into(),
ChatCompletionRequestUserMessageArgs::default()
.content("用一句话解释什么是向量数据库。")
.build()?
.into(),
])
.build()?;
let response = client.chat().create(request).await?;
for choice in response.choices {
println!("{:?}", choice.message.content);
}
Ok(())
}流式响应
rust
use async_openai::{
config::OpenAIConfig,
types::chat::{ChatCompletionRequestUserMessageArgs, CreateChatCompletionRequestArgs},
Client,
};
use futures::StreamExt;
use std::io::{stdout, Write};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = OpenAIConfig::new()
.with_api_key(std::env::var("SAKRYLLE_API_KEY")?)
.with_api_base("https://api.sakrylle.com/v1");
let client = Client::with_config(config);
let request = CreateChatCompletionRequestArgs::default()
.model("gpt-5.6-sol")
.max_tokens(512u32)
.messages([ChatCompletionRequestUserMessageArgs::default()
.content("数到 5。")
.build()?
.into()])
.build()?;
let mut stream = client.chat().create_stream(request).await?;
let mut out = stdout().lock();
while let Some(result) = stream.next().await {
match result {
Ok(chunk) => {
for choice in chunk.choices.iter() {
if let Some(content) = &choice.delta.content {
write!(out, "{content}")?;
out.flush()?;
}
}
}
Err(e) => eprintln!("\nstream error: {e:?}"),
}
}
Ok(())
}工具调用
rust
use async_openai::types::chat::{
ChatCompletionRequestUserMessageArgs, ChatCompletionToolArgs, ChatCompletionToolType,
CreateChatCompletionRequestArgs, FunctionObjectArgs,
};
use serde_json::json;
let tool = ChatCompletionToolArgs::default()
.r#type(ChatCompletionToolType::Function)
.function(
FunctionObjectArgs::default()
.name("get_weather")
.description("查询给定城市的当前天气")
.parameters(json!({
"type": "object",
"properties": {
"city": { "type": "string" }
},
"required": ["city"],
}))
.build()?,
)
.build()?;
let request = CreateChatCompletionRequestArgs::default()
.model("gpt-5.6-sol")
.max_tokens(256u32)
.tools(vec![tool])
.messages([ChatCompletionRequestUserMessageArgs::default()
.content("上海今天天气怎么样?")
.build()?
.into()])
.build()?;
let response = client.chat().create(request).await?;
println!("{:?}", response.choices[0].message.tool_calls);
async-openai是社区项目,类型名可能随版本变动,最终以 crate 文档 为准。
Anthropic 原生
Sakrylle 的 /v1/messages 接口与 Anthropic 官方协议兼容,下面是最小直连示例:
依赖
bash
cargo add reqwest --features json,rustls-tls
cargo add tokio --features full
cargo add serde --features derive
cargo add serde_json调用 /v1/messages
rust
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::json;
#[derive(Debug, Deserialize)]
struct ContentBlock {
#[serde(rename = "type")]
kind: String,
text: Option<String>,
}
#[derive(Debug, Deserialize)]
struct MessageResponse {
content: Vec<ContentBlock>,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let api_key = std::env::var("SAKRYLLE_API_KEY")?;
let body = json!({
"model": "claude-haiku-4-5-20251001",
"max_tokens": 1024,
"messages": [
{ "role": "user", "content": "用一句话介绍 Claude。" }
]
});
let resp: MessageResponse = Client::new()
.post("https://api.sakrylle.com/v1/messages")
.header("x-api-key", api_key)
.header("anthropic-version", "2023-06-01")
.json(&body)
.send()
.await?
.error_for_status()?
.json()
.await?;
for block in resp.content {
if let (Some(text), "text") = (block.text, block.kind.as_str()) {
println!("{text}");
}
}
Ok(())
}鉴权头优先用
x-api-key(Anthropic 原生格式);Sakrylle 也接受Authorization: Bearer <key>,二选一即可。 流式响应需要解析 SSE,建议直接走上面的 OpenAI 兼容路径,或者用eventsource-stream配合 reqwest 自己处理。
社区 Anthropic crate
如果接受社区维护,目前可以关注:
成熟度都不如 async-openai,建议在评估具体功能(流式、tool use)后再决定。
错误处理
rust
match client.chat().create(request).await {
Ok(resp) => println!("{resp:?}"),
Err(async_openai::error::OpenAIError::ApiError(e)) => {
eprintln!("status={:?} type={:?} msg={}", e.code, e.r#type, e.message);
}
Err(e) => eprintln!("transport error: {e:?}"),
}完整错误码表见 错误码。
