Skip to main content

aither_agent/specialized/
subagent.rs

1//! `SubAgent` - Wrap an agent configuration as a callable tool.
2//!
3//! Allows composing agents by delegating tasks to specialized sub-agents.
4//! Each call spawns a fresh agent instance.
5
6use std::borrow::Cow;
7
8use aither_core::llm::ToolContext;
9use aither_core::{
10    LanguageModel,
11    llm::{Tool, ToolResult},
12};
13use schemars::JsonSchema;
14use serde::Deserialize;
15
16use crate::Agent;
17
18/// A sub-agent tool that spawns a fresh agent for each call.
19///
20/// This allows building hierarchies of agents, where a main agent
21/// can delegate specific tasks to specialized sub-agents.
22///
23/// The subagent uses a single model for all tiers (advanced/balanced/fast).
24///
25/// # Example
26///
27/// ```rust,ignore
28/// let reviewer_tool = SubAgentTool::new(claude.clone())
29///     .name("code-reviewer")
30///     .description("Reviews code for security and quality issues")
31///     .system_prompt("You are a code reviewer...");
32///
33/// let main_agent = Agent::builder(claude)
34///     .tool(reviewer_tool)
35///     .build();
36///
37/// // Main agent can now delegate review tasks
38/// main_agent.query("Write and review a new function").await?;
39/// ```
40pub struct SubAgentTool<LLM> {
41    llm: LLM,
42    name: String,
43    system_prompt: Option<String>,
44}
45
46impl<LLM> std::fmt::Debug for SubAgentTool<LLM> {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.debug_struct("SubAgentTool")
49            .field("name", &self.name)
50            .field("has_system_prompt", &self.system_prompt.is_some())
51            .finish_non_exhaustive()
52    }
53}
54
55impl<LLM: Clone> SubAgentTool<LLM> {
56    /// Creates a new sub-agent tool with the given LLM.
57    pub fn new(llm: LLM) -> Self {
58        Self {
59            llm,
60            name: "subagent".to_string(),
61            system_prompt: None,
62        }
63    }
64
65    /// Sets the tool name.
66    #[must_use]
67    pub fn name(mut self, name: impl Into<String>) -> Self {
68        self.name = name.into();
69        self
70    }
71
72    /// Sets the system prompt for the sub-agent.
73    #[must_use]
74    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
75        self.system_prompt = Some(prompt.into());
76        self
77    }
78}
79
80/// Delegate a task to a sub-agent.
81///
82/// Sub-agents run autonomously in their own context and return results.
83/// Use for delegating complex or specialized tasks.
84#[derive(Debug, Clone, JsonSchema, Deserialize)]
85pub struct SubAgentQuery {
86    /// The task to delegate to this sub-agent.
87    /// Be specific about what you want the sub-agent to do.
88    pub task: String,
89}
90
91impl<LLM> Tool for SubAgentTool<LLM>
92where
93    LLM: LanguageModel + Clone + 'static,
94{
95    fn name(&self) -> Cow<'static, str> {
96        Cow::Owned(self.name.clone())
97    }
98
99    type Arguments = SubAgentQuery;
100    type Res = ToolResult;
101
102    async fn call(
103        &self,
104        args: Self::Arguments,
105        _cx: ToolContext,
106    ) -> aither_core::Result<Self::Res> {
107        // Create a fresh agent for this call
108        let mut builder = Agent::builder(self.llm.clone());
109
110        if let Some(ref prompt) = self.system_prompt {
111            builder = builder.system_prompt(prompt);
112        }
113
114        let mut agent = builder.build();
115
116        let result = agent
117            .query(&args.task)
118            .await
119            .map_err(|e| anyhow::anyhow!("{e}"))?;
120        Ok(ToolResult::text(result))
121    }
122}
123
124/// Extension trait for creating sub-agent tools from an LLM.
125pub trait IntoSubAgent: LanguageModel + Clone + Sized {
126    /// Creates a sub-agent tool from this LLM.
127    fn into_subagent(self) -> SubAgentTool<Self> {
128        SubAgentTool::new(self)
129    }
130}
131
132impl<LLM: LanguageModel + Clone> IntoSubAgent for LLM {}