Rust 快速开始
Rust 快速开始
Section titled “Rust 快速开始”以下示例与仓库中的 basic_usage 一致。
[dependencies]ai-lib-rust = "1.2.0"tokio = { version = "1", features = ["full"] }futures = "0.3" # only needed for streaming可选能力:
ai-lib-rust = { version = "1.2.0", features = ["embeddings", "telemetry"] }# or features = ["full"]API 密钥
Section titled “API 密钥”export DEEPSEEK_API_KEY="your-key-here"use ai_lib_rust::{AiClient, Message};
#[tokio::main]async fn main() -> ai_lib_rust::Result<()> { let client = AiClient::new("deepseek/deepseek-chat").await?;
let response = client .chat() .messages(vec![ Message::system("You are a helpful assistant."), Message::user("Explain quantum computing in simple terms."), ]) .temperature(0.7) .max_tokens(500) .execute() .await?;
println!("{}", response.content); Ok(())}事件变体为 PartialContentDelta(不是 ContentDelta):
use ai_lib_rust::{AiClient, Message, StreamingEvent};use futures::StreamExt;
#[tokio::main]async fn main() -> ai_lib_rust::Result<()> { let client = AiClient::new("deepseek/deepseek-chat").await?;
let mut stream = client .chat() .messages(vec![Message::user("Write a haiku about Rust.")]) .stream() .execute_stream() .await?;
while let Some(event) = stream.next().await { match event? { StreamingEvent::PartialContentDelta { content, .. } => print!("{content}"), StreamingEvent::StreamEnd { .. } => break, _ => {} } } Ok(())}工具调用(流式)
Section titled “工具调用(流式)”use ai_lib_rust::{AiClient, Message, StreamingEvent, ToolDefinition};use futures::StreamExt;use serde_json::json;
#[tokio::main]async fn main() -> ai_lib_rust::Result<()> { let client = AiClient::new("openai/gpt-4o").await?;
let weather_tool = ToolDefinition { name: "get_weather".into(), description: Some("Get current weather".into()), parameters: json!({ "type": "object", "properties": { "city": { "type": "string" } }, "required": ["city"] }), };
let mut stream = client .chat() .messages(vec![Message::user("What's the weather in Tokyo?")]) .tools(vec![weather_tool]) .stream() .execute_stream() .await?;
while let Some(event) = stream.next().await { match event? { StreamingEvent::ToolCallStarted { tool_name, .. } => { println!("Calling: {tool_name}"); } StreamingEvent::PartialToolCall { arguments, .. } => print!("{arguments}"), StreamingEvent::PartialContentDelta { content, .. } => print!("{content}"), _ => {} } } Ok(())}跨任务共享 AiClient
Section titled “跨任务共享 AiClient”use ai_lib_rust::AiClient;use std::sync::Arc;
let client = Arc::new(AiClient::new("openai/gpt-4o").await?);设置本地 ai-protocol 检出路径:
export AI_PROTOCOL_DIR="/path/to/ai-protocol"或在代码中传入基路径:
use ai_lib_rust::protocol::ProtocolLoader;
let loader = ProtocolLoader::new().with_base_path("./ai-protocol");let manifest = loader.load_provider("openai").await?;运行附带示例
Section titled “运行附带示例”cd ai-lib-rustDEEPSEEK_API_KEY=your_key cargo run --example basic_usage- 概述 — 架构与能力边界
- Client API — builder 参考
- 流式处理 — pipeline 算子
- 韧性模式 — 按需策略层