aither_agent/specialized/
subagent.rs1use 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
18pub 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 pub fn new(llm: LLM) -> Self {
58 Self {
59 llm,
60 name: "subagent".to_string(),
61 system_prompt: None,
62 }
63 }
64
65 #[must_use]
67 pub fn name(mut self, name: impl Into<String>) -> Self {
68 self.name = name.into();
69 self
70 }
71
72 #[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#[derive(Debug, Clone, JsonSchema, Deserialize)]
85pub struct SubAgentQuery {
86 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 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
124pub trait IntoSubAgent: LanguageModel + Clone + Sized {
126 fn into_subagent(self) -> SubAgentTool<Self> {
128 SubAgentTool::new(self)
129 }
130}
131
132impl<LLM: LanguageModel + Clone> IntoSubAgent for LLM {}