pub struct AgentBuilder { /* private fields */ }Expand description
Agent 链式构建器 — 推荐的 Agent 创建方式。
内部收集静态工具和动态目录,build() 时组装为 ToolCatalog,
再传给 ToolUseLoop::new()。所有 setter 返回 self(不借用),
支持流畅的链式调用。
Implementations§
Source§impl AgentBuilder
impl AgentBuilder
Sourcepub fn new(model: ResolvedModel) -> Self
pub fn new(model: ResolvedModel) -> Self
创建构建器,绑定模型。
Sourcepub fn tool(self, reg: ExecutableTool) -> Self
pub fn tool(self, reg: ExecutableTool) -> Self
注册工具。
Sourcepub fn tools(
self,
registrations: impl IntoIterator<Item = ExecutableTool>,
) -> Self
pub fn tools( self, registrations: impl IntoIterator<Item = ExecutableTool>, ) -> Self
批量注册工具。
Sourcepub fn catalog(self, catalog: Arc<dyn ToolCatalog>) -> Self
pub fn catalog(self, catalog: Arc<dyn ToolCatalog>) -> Self
绑定动态工具目录(MCP、插件系统等)。
可调用多次。按注册顺序,先绑定的优先级高于后绑定的。
静态工具(.tool())永远拥有最高优先级。
§示例
use std::sync::Arc;
use lellm_agent::{AgentBuilder, ToolCatalog};
use lellm_mcp::{McpCatalog, McpClient};
let client = Arc::new(McpClient::with_transport(transport));
let catalog = McpCatalog::discover(client).await?;
let agent = AgentBuilder::new(model)
.catalog(Arc::new(catalog))
.build();Sourcepub fn max_iterations(self, max: usize) -> Self
pub fn max_iterations(self, max: usize) -> Self
设置最大迭代轮次(默认 10)。
Sourcepub fn max_output_tokens(self, max: u32) -> Self
pub fn max_output_tokens(self, max: u32) -> Self
设置每次 LLM 请求的最大输出 token 数(默认 4k)。
Sourcepub fn max_total_output_tokens(self, max: u32) -> Self
pub fn max_total_output_tokens(self, max: u32) -> Self
设置整个 Agent Run 的最大输出 token 总数。
Sourcepub fn system(self, system: impl Into<Prompt>) -> Self
pub fn system(self, system: impl Into<Prompt>) -> Self
设置系统提示。
支持简单文本或分层 Prompt(通过 From<String> 自动转换)。
§示例
// 简单文本
let agent = AgentBuilder::new(model)
.system("你是一个有帮助的助手。")
.build();
// 分层构建 — 最大化前缀缓存
use lellm_core::Prompt;
let agent = AgentBuilder::new(model)
.system(
Prompt::new()
.stable("核心身份…")
.stable("工具指南…")
.dynamic("会话上下文…")
.build(),
)
.build();Sourcepub fn system_prompt(self, prompt: String) -> Self
👎Deprecated since 0.5.0: Use .system() instead
pub fn system_prompt(self, prompt: String) -> Self
Use .system() instead
设置系统提示(纯文本)。
这是 .system() 的别名,保留用于向后兼容。
Sourcepub fn tool_cache_policy(self, policy: ToolCachePolicy) -> Self
pub fn tool_cache_policy(self, policy: ToolCachePolicy) -> Self
设置工具缓存策略(默认 Auto)。
Auto:为未设置cache_control的工具自动添加BreakpointPreserve:不修改用户设置的cache_controlDisabled:清除所有工具的cache_control
Sourcepub fn request_options(self, opts: RequestOptions) -> Self
pub fn request_options(self, opts: RequestOptions) -> Self
设置完整的 RequestOptions(覆盖所有生成参数)。
Sourcepub fn temperature(self, t: f64) -> Self
pub fn temperature(self, t: f64) -> Self
设置生成温度(0.0 ~ 2.0)。
Sourcepub fn tool_choice(self, choice: ToolChoice) -> Self
pub fn tool_choice(self, choice: ToolChoice) -> Self
设置工具选择策略(仅首轮生效)。
Sourcepub fn stop_sequences(self, seqs: Vec<String>) -> Self
pub fn stop_sequences(self, seqs: Vec<String>) -> Self
设置停止序列。
Sourcepub fn reasoning(self, r: ReasoningConfig) -> Self
pub fn reasoning(self, r: ReasoningConfig) -> Self
设置推理配置(控制模型是否进行深度推理)。
Sourcepub fn stream_thinking(self, enable: bool) -> Self
pub fn stream_thinking(self, enable: bool) -> Self
设置是否流式输出推理过程。
Sourcepub fn reasoning_budget(self, max: u32) -> Self
pub fn reasoning_budget(self, max: u32) -> Self
设置单轮推理 Token 上限。
Sourcepub fn max_total_reasoning_tokens(self, max: u32) -> Self
pub fn max_total_reasoning_tokens(self, max: u32) -> Self
设置整个 Agent Run 的最大推理 Token 总数。
Sourcepub fn fallback(self, fallback: Arc<dyn FallbackStrategy>) -> Self
pub fn fallback(self, fallback: Arc<dyn FallbackStrategy>) -> Self
设置 Fallback 策略。
Sourcepub fn retry_policy(self, policy: RetryPolicy) -> Self
pub fn retry_policy(self, policy: RetryPolicy) -> Self
设置工具重试策略。
Sourcepub fn context_budget(self, budget: ContextBudget) -> Self
pub fn context_budget(self, budget: ContextBudget) -> Self
设置上下文预算(Token 上限 + 压缩策略)。
若要关闭限制,设置 max_tokens = usize::MAX。
Sourcepub fn canonical_hash(&self) -> u64
pub fn canonical_hash(&self) -> u64
计算 canonical AST hash — 保持 DSL 输入顺序。
Hash 输入来自 DSL 层(model, tools, system prompt, config), 不依赖 compiled graph 的 HashMap 迭代顺序。 这保证:相同 DSL 输入永远产生相同 hash,Checkpoint 不会因此失效。
§Hash 输入
- provider_id(稳定字符串标识,如 “openai”, “anthropic”)
- model name
- tool names(保持 DSL 插入顺序,不排序)
- system prompt hash
- max_iterations
- max_output_tokens
§设计原则
canonical = DSL 原貌,不做语义归一化。
.tools([A, B]) 和 .tools([B, A]) 产生不同 hash,
因为它们是不同的 DSL 输入。
Sourcepub fn build(self) -> Arc<Graph<AgentState, AgentStateMerge>> ⓘ
pub fn build(self) -> Arc<Graph<AgentState, AgentStateMerge>> ⓘ
构建 ReAct Graph — 返回 Arc<Graph<AgentState>>。
这是核心 API,返回共享的 Graph,可直接用 graph.run_inline() 执行。
Graph 携带 canonical_hash,用于 Checkpoint 的 graph compatibility 校验。
§示例
let graph = AgentBuilder::new(model).tools([...]).build();
// 直接执行
let mut state = AgentState::from_messages(messages);
let mut ctx = ExecutionContext::new(
&mut state,
None,
CancellationToken::new(),
None, // 不需要自动 checkpoint
None, // 不需要 Barrier
);
graph.run_inline(&mut ctx, max_steps).await?;Sourcepub fn compile(self) -> ToolUseLoop
pub fn compile(self) -> ToolUseLoop
编译为 ToolUseLoop — Facade 层。
返回 ToolUseLoop,持有共享的 Graph,提供 invoke() / invoke_stream() 等高级 API。
内部调用 Graph::run_inline(),封装了 State 初始化和结果提取。
等价于手动组合:
let graph = AgentBuilder::new(model).tools([...]).build();
let agent = ToolUseLoop::new(graph, config);§示例
let result = AgentBuilder::new(model)
.tools([search_tool, weather_tool])
.compile()
.invoke(messages)
.await?;