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