0xPlaygrounds/rig · 上手攻略
- 仓库:0xPlaygrounds/rig
- 链接:https://github.com/0xPlaygrounds/rig
- 分类:ai / llm-infra
- 作者:Tom
- 更新:2026-07-10
这是什么
Rig 是用 Rust 构建模块化、可扩展 LLM 应用的库。它提供了一套统一抽象,覆盖 20+ 大模型提供商、10+ 向量数据库,并内置 Agent 编排、RAG、工具调用、多轮对话等能力,全部用 Rust 的类型安全和并发性能加持。
解决什么问题: 在 Rust 生态里,之前缺乏一个统一、好用的 LLM 应用抽象层。开发者要么自己封装各个 Provider SDK(OpenAI、Cohere、Anthropic…),要么引入不成熟的库。Rig 用一个接口屏蔽所有底层差异,同时保持 Rust 的零成本抽象和内存安全性。
⚠️ 稳定性提示:官方在 README 中明确标注了「Here be dragons」,当前仍处于快速发展期,会有 Breaking Changes。生产使用前请锁定版本号,并关注 Migration Guide。
快速安装
# 核心库(含基础 Provider 抽象)
cargo add rig
# 如只需核心抽象(不含集成),用 rig-core:
# cargo add rig-core
# 完整向量数据库支持(示例:LanceDB)
cargo add rig --features lancedb
# 如果用到 async runtime
cargo add tokio --features macros,rt-multi-thread
从 crates.io 安装稳定版本,或从 GitHub 添加最新版依赖。
核心概念
Rig 的设计围绕三个层次:
| 层次 | 说明 |
|---|---|
| Provider | OpenAI、Cohere、Anthropic 等模型提供商的统一封装 |
| Agent | 结合 Model + System Prompt + Tools + Context 的高级编排单元 |
| Vector Store | 向量数据库抽象( LanceDB、MongoDB、Qdrant、Neo4j …) |
核心用法
1. 最简 Agent(Completion)
use rig::client::{CompletionClient, ProviderClient};
use rig::completion::Prompt;
use rig::providers::openai;
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
// 创建 OpenAI 客户端(从环境变量 OPENAI_API_KEY 读取)
let client = openai::Client::from_env()?;
// 创建 Agent(单条 System Prompt)
let comedian_agent = client
.agent(openai::GPT_5_2)
.preamble("You are a comedian here to entertain the user.")
.build();
// Prompt 并获取回复
let response = comedian_agent.prompt("Entertain me!").await?;
println!("{response}");
Ok(())
}
⚠️ 注意:
#[tokio::main]需要启用 tokio 的macros和rt-multi-threadfeatures(或者直接用features = ["full"])。
2. 带工具调用的 Agent(Tool Use)
// 定义工具
use rig::agent::ToolCall;
let weather_agent = client
.agent(model)
.preamble("You are a helpful weather assistant.")
.tool(
"get_weather", // 工具名
|| async { "Sunny, 25°C" }, // 工具实现(async fn)
)
.build();
// Agent 会自动判断何时调用工具
let response = weather_agent.prompt("What's the weather in Tokyo?").await?;
3. RAG(检索增强生成)
将文档写入向量存储,Agent 自动从中获取相关上下文:
use rig::vector_store::VectorStoreIndex;
// 假设 vec_store 是已配置的 VectorStoreIndex 实例
let rag_agent = client
.agent(model)
.preamble("You answer questions based on the retrieved documents.")
.context_from_vec_store(vec_store, top_k = 5) // 取最相似的5条
.build();
let response = rag_agent
.prompt("What did the report say about revenue?")
.await?;
4. Prompt Hooks(自定义行为)
用于在 Agent 的 Prompt 循环中注入可观测性或自定义逻辑:
use rig::agent::PromptHook;
struct MyHook;
impl PromptHook for MyHook {
fn on_completion(&self, prompt: &str, response: &str) {
println!("[Hook] Prompt: {prompt}\nResponse: {response}");
}
}
agent.with_hook(MyHook);
可拦截的内容包括:completion request、completion response、tool calls、tool responses。支持通过 hook 中取消 agent 循环(返回 Cancelled 错误)。
5. 多轮对话(Conversation)
let agent = client
.agent(model)
.preamble("You are a helpful assistant.")
.build();
// 多轮对话,每次 prompt 会自动维护上下文历史
agent.prompt("My name is Alice.").await?;
let response = agent.prompt("What is my name?").await?;
支持的模型提供商(非完整列表)
OpenAI、Cohere、Anthropic、AWS Bedrock、Google Vertex、Azure OpenAI、Mistral、ollama 本地模型 等。
完整列表参考:docs.rig.rs 模型提供商文档。
支持的向量数据库
LanceDB、MongoDB Atlas、Qdrant、Neo4j、SurrealDB、Cloudflare Vectorize、AWS S3 Vectors 等。
典型适用场景
- Rust 原生 AI 应用:在 Rust 后端服务中直接集成 LLM 能力,无需另起 Python 服务
- 高性能 AI 代理:需要低延迟、高并发处理大量 LLM 请求的场景(Rust 天然并发优势)
- 本地 LLM 部署:通过 Ollama 集成 Llama/Qwen 等开源模型,保持完全本地化
- 多模型路由:同一个接口切换 OpenAI / Anthropic / 本地模型,方便做 A/B 测试或成本优化
- 生产级 RAG 系统:配合 LanceDB 或 Qdrant,构建生产级别的检索增强流水线
坑与注意
⚠️ Breaking Changes 频繁:README 明确警告,当前版本接口会有 Breaking Changes。生产项目务必锁定具体版本号(如 rig = "0.36.0"),不要用 * 宽泛版本。
⚠️ 文档不如 Python 生态完善:Rust 的 AI 生态相对年轻,详细示例和教程比 LangChain 等少很多,遇到问题更依赖读源码。
⚠️ 错误处理需小心:anyhow::Error 在示例中广泛使用,但生产环境可能需要更精确的错误类型定义。
⚠️ tokio runtime 必须:#[tokio::main] 或其他 async runtime 是必须的,Rig 的所有网络调用都是 async 的。
⚠️ 向量数据库驱动重量:引入 rig 并开启 lancedb 等 features 会拉取较大依赖,编译时间会明显增加。CI/CD 需预留时间。
⚠️ MCP 集成需额外工作:Rig 本身不直接支持 MCP 协议,如需让 Rig 构建的 Agent 通过 MCP 调用外部工具,需要自行实现 MCP client 封装。
与同类对比
| 项目 | 语言 | Agent 抽象 | 向量库 | 生产成熟度 | 上手难度 |
|---|---|---|---|---|---|
| Rig | Rust | ✅ 内置 | ✅ 10+ | ⭐⭐ 快速演进 | ⭐⭐⭐⭐ Rust 门槛 |
| LangChain | Python | ✅ 完善 | ✅ 丰富 | ⭐⭐⭐⭐⭐ | ⭐⭐ |
| LlamaIndex | Python | ✅ RAG 专注 | ✅ 丰富 | ⭐⭐⭐⭐⭐ | ⭐⭐ |
| daptics | Python | ✅ | ✅ | ⭐⭐⭐ | ⭐⭐ |
| Motia | Python | ✅ | ⚠️ 少 | ⭐⭐⭐ | ⭐⭐ |
Rust 生态里,Rig 是目前最完整的 LLM 应用框架。如果你已经用 Rust 写服务、想要避免 Python 微服务的运维负担,Rig 是首选。如果你在 Python 生态、需求是快速搭 RAG 或 Agent pipeline,LangChain/LlamaIndex 更成熟。
一句话推荐结论
在 Rust 后端里直接集成 LLM 能力?Rig 用一套统一接口覆盖 20+ 模型 + 10+ 向量库,零运行时 GC 压力,值得投入学习曲线。 但当前版本变更频繁,生产使用记得锁定版本。