本指南从空项目开始,带你运行一个 AI Agent。Agent 将模型、系统提示词(preamble)和可选工具组合起来。Rig 负责请求和响应的衔接,你只需调用 .prompt(...)。
完成后,你将得到一个向 OpenAI 的 gpt-5.5 提问并打印回答的程序。
1. 创建项目#
需要 Rust 1.97.1 或更新版本。创建一个新的二进制 crate:
cargo init my-first-agent
cd my-first-agent2. 添加依赖#
添加 rig、为 #[tokio::main] 入口提供支持的 Tokio,以及用于错误处理的 anyhow:
cargo add rig@=0.46.0 anyhow
cargo add tokio --features macros,rt-multi-thread提示
rig 的默认 feature 已包含 Agent 运行时和 HTTP 传输层,足够运行本指南。向量存储、MCP、图像、音频等可选 feature 见安装。
3. 设置 API Key#
服务商客户端从环境变量读取凭证。使用 OpenAI 时设置 OPENAI_API_KEY:
export OPENAI_API_KEY="sk-..."使用 Anthropic、Gemini 或 DeepSeek 等其他服务商?每家都有自己的环境变量,见模型服务商。
4. 创建 Agent 并提问#
将 src/main.rs 的内容替换为:
use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
// A client for OpenAI, configured from OPENAI_API_KEY.
let client = OpenAI::from_env()?;
// An agent: a completion model plus a system prompt (the "preamble").
let agent = AgentBuilder::new(client.completion(openai::GPT_5_5))
.preamble("You are a helpful assistant.")
.build();
// Send a prompt and await the model's reply.
let response = agent.prompt("What is the Rust programming language?").await?;
println!("{}", response.output());
Ok(())
}完整程序就是这几步:创建客户端、选择模型、构建 Agent,再调用 .prompt(...)。
提示
use rig::prelude::*; 会导入最常用的类型,包括 AgentBuilder、Message、EmbeddingsBuilder 和 VectorStoreIndex。提问方法是 Agent 的普通方法,无需额外导入 trait。
5. 运行#
cargo run终端会打印模型的回答,例如:
Rust is a modern, statically typed systems programming language focused on
safety, speed, and concurrency without a garbage collector. Its ownership and
borrowing model guarantees memory safety at compile time, while zero-cost
abstractions keep it as fast as C/C++...每次运行的具体文字可能不同,这是模型生成的正常现象。
如果编译不通过或运行失败,参见排错。
刚才发生了什么#
OpenAI::from_env()使用 API Key 创建服务商客户端,通过 Rig 的共享 HTTP 客户端发送请求。client.completion(openai::GPT_5_5)返回一个Model,代表该服务商的一个模型。可以直接调用它,也可以交给 Agent。AgentBuilder::new(model)开始构建 Agent;.preamble(...)设置系统提示词;.build()完成构建。.prompt(...)运行 Agent 并返回PromptResponse。.output()是最终文本;响应还包含 tokenusage和本次运行的messages。
Agent 不止能做单轮问答:添加工具可让模型调用你的代码;接入知识库可实现检索增强生成(RAG);使用 .stream() 可逐段接收输出;也可以保留对话历史。
下一步#
另请参阅#
- 核心概念:理解服务商、模型、Agent 和工作流。
- 架构:Rig 的 crate 和抽象层如何配合。
- docs.rs 上的 rig API 参考:完整的类型和方法签名。