rig::integrations::cli_chatbot 将 Agent 转换为交互式终端 REPL。它从标准输入读取内容,保留对话历史以提供各轮上下文,将 Agent 回答流式输出到标准输出,并在输入 exit 时停止。无需自己编写输入循环,就能快速在本地试用 Agent。
最小示例#
创建 Agent 并交给 ChatBotBuilder:
rust
use rig::integrations::cli_chatbot::ChatBotBuilder;
use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let agent = AgentBuilder::new(OpenAI::from_env()?.completion(openai::GPT_5_5))
.preamble("You are a helpful assistant.")
.build();
// Start the REPL. Type "exit" to quit.
ChatBotBuilder::new().agent(agent).build().run().await?;
Ok(())
}运行后会出现 > 提示符。答案随生成过程流式显示,每一轮提交的消息,包括工具调用及结果,都会追加到下一轮使用的历史中。
配置选项#
聊天机器人包装 Agent 时,构建器提供两个选项:
rust
ChatBotBuilder::new()
.agent(agent)
.max_turns(5) // model-call budget per prompt, so the agent can use tools
.show_usage() // print input/output token counts after each answer
.build()
.run()
.await?;max_turns 默认为 1,足够普通问答 Agent 使用。Agent 带工具时需要提高这个值,因为每次工具往返都需要模型调用。
RAG 聊天机器人#
任何 Agent 都可以使用,包括每轮都从向量存储提取上下文的 Agent:
rust
use rig::embeddings::EmbeddingsBuilder;
use rig::integrations::cli_chatbot::ChatBotBuilder;
use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};
use rig::vector_store::in_memory_store::InMemoryVectorStore;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let client = OpenAI::from_env()?;
let embedding_model = client.embedding(openai::TEXT_EMBEDDING_3_SMALL, None).erase();
let embeddings = EmbeddingsBuilder::new(embedding_model.clone())
.documents(vec![
"Rig is a Rust library for building LLM applications.".to_string(),
"A Rig agent combines a model, a preamble, context and tools.".to_string(),
])?
.build()
.await?;
let index = InMemoryVectorStore::from_documents(embeddings).index(embedding_model);
let agent = AgentBuilder::new(client.completion(openai::GPT_5_5))
.preamble("Answer using the retrieved context.")
.dynamic_context(2, index)
.build();
ChatBotBuilder::new().agent(agent).build().run().await?;
Ok(())
}如何把真实文档加载到存储中,见向量存储与 RAG。
使用自定义聊天类型#
如果希望 REPL 背后使用 Agent 以外的类型,实现 cli_chatbot::Chat trait,再将值传给 .chat(..),而不是 .agent(..)。该 trait 只有一个方法:针对调用方持有的历史运行一轮,追加本轮提交的消息,并返回回答文本。
rust
use rig::completion::PromptError;
use rig::integrations::cli_chatbot::{Chat, ChatBotBuilder};
use rig::message::Message;
use rig::wasm_compat::WasmCompatSend;
/// Replies with the length of the conversation so far.
struct Echo;
impl Chat for Echo {
async fn chat(
&self,
prompt: impl Into<Message> + WasmCompatSend,
history: &mut Vec<Message>,
) -> Result<String, PromptError> {
let prompt: Message = prompt.into();
history.push(prompt);
let reply = format!("turn {}", history.len());
history.push(Message::assistant(reply.clone()));
Ok(reply)
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
ChatBotBuilder::new().chat(Echo).build().run().await?;
Ok(())
}自定义 Chat 会在轮次结束后一次性打印完整回答,只有 Agent 路径支持流式输出。