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