agents_runtime/agent/
builder.rs

1//! Fluent builder API for constructing Deep Agents
2//!
3//! This module provides the ConfigurableAgentBuilder that offers a fluent interface
4//! for building Deep Agents, mirroring the Python SDK's ergonomic construction patterns.
5
6use super::api::{create_async_deep_agent_from_config, create_deep_agent_from_config};
7use super::config::{DeepAgentConfig, SubAgentConfig, SummarizationConfig};
8use super::runtime::DeepAgent;
9use crate::middleware::HitlPolicy;
10use crate::planner::LlmBackedPlanner;
11use crate::providers::{
12    AnthropicConfig, AnthropicMessagesModel, GeminiChatModel, GeminiConfig, OpenAiChatModel,
13    OpenAiConfig,
14};
15use agents_core::agent::PlannerHandle;
16use agents_core::llm::LanguageModel;
17use agents_core::persistence::Checkpointer;
18use agents_core::tools::ToolBox;
19use std::collections::{HashMap, HashSet};
20use std::sync::Arc;
21
22/// Builder API to assemble a DeepAgent in a single fluent flow, mirroring the Python
23/// `create_configurable_agent` experience. Prefer this for ergonomic construction.
24pub struct ConfigurableAgentBuilder {
25    instructions: String,
26    planner: Option<Arc<dyn PlannerHandle>>,
27    tools: Vec<ToolBox>,
28    subagents: Vec<SubAgentConfig>,
29    summarization: Option<SummarizationConfig>,
30    tool_interrupts: HashMap<String, HitlPolicy>,
31    builtin_tools: Option<HashSet<String>>,
32    auto_general_purpose: bool,
33    enable_prompt_caching: bool,
34    checkpointer: Option<Arc<dyn Checkpointer>>,
35}
36
37impl ConfigurableAgentBuilder {
38    pub fn new(instructions: impl Into<String>) -> Self {
39        Self {
40            instructions: instructions.into(),
41            planner: None,
42            tools: Vec::new(),
43            subagents: Vec::new(),
44            summarization: None,
45            tool_interrupts: HashMap::new(),
46            builtin_tools: None,
47            auto_general_purpose: true,
48            enable_prompt_caching: false,
49            checkpointer: None,
50        }
51    }
52
53    /// Set the language model for the agent (mirrors Python's `model` parameter)
54    pub fn with_model(mut self, model: Arc<dyn LanguageModel>) -> Self {
55        let planner: Arc<dyn PlannerHandle> = Arc::new(LlmBackedPlanner::new(model));
56        self.planner = Some(planner);
57        self
58    }
59
60    /// Low-level planner API (for advanced use cases)
61    pub fn with_planner(mut self, planner: Arc<dyn PlannerHandle>) -> Self {
62        self.planner = Some(planner);
63        self
64    }
65
66    /// Convenience method for OpenAI models (equivalent to model=OpenAiChatModel)
67    pub fn with_openai_chat(self, config: OpenAiConfig) -> anyhow::Result<Self> {
68        let model = Arc::new(OpenAiChatModel::new(config)?);
69        Ok(self.with_model(model))
70    }
71
72    /// Convenience method for Anthropic models (equivalent to model=AnthropicMessagesModel)  
73    pub fn with_anthropic_messages(self, config: AnthropicConfig) -> anyhow::Result<Self> {
74        let model = Arc::new(AnthropicMessagesModel::new(config)?);
75        Ok(self.with_model(model))
76    }
77
78    /// Convenience method for Gemini models (equivalent to model=GeminiChatModel)
79    pub fn with_gemini_chat(self, config: GeminiConfig) -> anyhow::Result<Self> {
80        let model = Arc::new(GeminiChatModel::new(config)?);
81        Ok(self.with_model(model))
82    }
83
84    /// Add a tool to the agent
85    pub fn with_tool(mut self, tool: ToolBox) -> Self {
86        self.tools.push(tool);
87        self
88    }
89
90    /// Add multiple tools
91    pub fn with_tools<I>(mut self, tools: I) -> Self
92    where
93        I: IntoIterator<Item = ToolBox>,
94    {
95        self.tools.extend(tools);
96        self
97    }
98
99    pub fn with_subagent_config<I>(mut self, cfgs: I) -> Self
100    where
101        I: IntoIterator<Item = SubAgentConfig>,
102    {
103        self.subagents.extend(cfgs);
104        self
105    }
106
107    /// Convenience method: automatically create subagents from a list of tools.
108    /// Each tool becomes a specialized subagent with that single tool.
109    pub fn with_subagent_tools<I>(mut self, tools: I) -> Self
110    where
111        I: IntoIterator<Item = ToolBox>,
112    {
113        for tool in tools {
114            let tool_name = tool.schema().name.clone();
115            let subagent_config = SubAgentConfig::new(
116                format!("{}-agent", tool_name),
117                format!("Specialized agent for {} operations", tool_name),
118                format!(
119                    "You are a specialized agent. Use the {} tool to complete tasks efficiently.",
120                    tool_name
121                ),
122            )
123            .with_tools(vec![tool]);
124            self.subagents.push(subagent_config);
125        }
126        self
127    }
128
129    pub fn with_summarization(mut self, config: SummarizationConfig) -> Self {
130        self.summarization = Some(config);
131        self
132    }
133
134    pub fn with_tool_interrupt(mut self, tool_name: impl Into<String>, policy: HitlPolicy) -> Self {
135        self.tool_interrupts.insert(tool_name.into(), policy);
136        self
137    }
138
139    pub fn with_builtin_tools<I, S>(mut self, names: I) -> Self
140    where
141        I: IntoIterator<Item = S>,
142        S: Into<String>,
143    {
144        self.builtin_tools = Some(names.into_iter().map(|s| s.into()).collect());
145        self
146    }
147
148    pub fn with_auto_general_purpose(mut self, enabled: bool) -> Self {
149        self.auto_general_purpose = enabled;
150        self
151    }
152
153    pub fn with_prompt_caching(mut self, enabled: bool) -> Self {
154        self.enable_prompt_caching = enabled;
155        self
156    }
157
158    pub fn with_checkpointer(mut self, checkpointer: Arc<dyn Checkpointer>) -> Self {
159        self.checkpointer = Some(checkpointer);
160        self
161    }
162
163    pub fn build(self) -> anyhow::Result<DeepAgent> {
164        self.finalize(create_deep_agent_from_config)
165    }
166
167    /// Build an agent using the async constructor alias. This mirrors the Python
168    /// async_create_deep_agent entry point, while reusing the same runtime internals.
169    pub fn build_async(self) -> anyhow::Result<DeepAgent> {
170        self.finalize(create_async_deep_agent_from_config)
171    }
172
173    fn finalize(self, ctor: fn(DeepAgentConfig) -> DeepAgent) -> anyhow::Result<DeepAgent> {
174        let Self {
175            instructions,
176            planner,
177            tools,
178            subagents,
179            summarization,
180            tool_interrupts,
181            builtin_tools,
182            auto_general_purpose,
183            enable_prompt_caching,
184            checkpointer,
185        } = self;
186
187        let planner = planner
188            .ok_or_else(|| anyhow::anyhow!("model must be set (use with_model or with_*_chat)"))?;
189
190        let mut cfg = DeepAgentConfig::new(instructions, planner)
191            .with_auto_general_purpose(auto_general_purpose)
192            .with_prompt_caching(enable_prompt_caching);
193
194        if let Some(ckpt) = checkpointer {
195            cfg = cfg.with_checkpointer(ckpt);
196        }
197        if let Some(sum) = summarization {
198            cfg = cfg.with_summarization(sum);
199        }
200        if let Some(selected) = builtin_tools {
201            cfg = cfg.with_builtin_tools(selected);
202        }
203        for (name, policy) in tool_interrupts {
204            cfg = cfg.with_tool_interrupt(name, policy);
205        }
206        for tool in tools {
207            cfg = cfg.with_tool(tool);
208        }
209        for sub_cfg in subagents {
210            cfg = cfg.with_subagent_config(sub_cfg);
211        }
212
213        Ok(ctor(cfg))
214    }
215}