helios_engine/
agent.rs

1use crate::chat::{ChatMessage, ChatSession};
2use crate::config::Config;
3use crate::error::{HeliosError, Result};
4use crate::llm::{LLMClient, LLMProviderType};
5use crate::tools::{ToolRegistry, ToolResult};
6use serde_json::Value;
7
8pub struct Agent {
9    name: String,
10    llm_client: LLMClient,
11    tool_registry: ToolRegistry,
12    chat_session: ChatSession,
13    max_iterations: usize,
14}
15
16impl Agent {
17    pub async fn new(name: impl Into<String>, config: Config) -> Result<Self> {
18        let provider_type = if let Some(local_config) = config.local {
19            LLMProviderType::Local(local_config)
20        } else {
21            LLMProviderType::Remote(config.llm)
22        };
23
24        let llm_client = LLMClient::new(provider_type).await?;
25
26        Ok(Self {
27            name: name.into(),
28            llm_client,
29            tool_registry: ToolRegistry::new(),
30            chat_session: ChatSession::new(),
31            max_iterations: 10,
32        })
33    }
34
35    pub fn builder(name: impl Into<String>) -> AgentBuilder {
36        AgentBuilder::new(name)
37    }
38
39    pub fn name(&self) -> &str {
40        &self.name
41    }
42
43    pub fn set_system_prompt(&mut self, prompt: impl Into<String>) {
44        self.chat_session = self.chat_session.clone().with_system_prompt(prompt);
45    }
46
47    pub fn register_tool(&mut self, tool: Box<dyn crate::tools::Tool>) {
48        self.tool_registry.register(tool);
49    }
50
51    pub fn tool_registry(&self) -> &ToolRegistry {
52        &self.tool_registry
53    }
54
55    pub fn tool_registry_mut(&mut self) -> &mut ToolRegistry {
56        &mut self.tool_registry
57    }
58
59    pub fn chat_session(&self) -> &ChatSession {
60        &self.chat_session
61    }
62
63    pub fn chat_session_mut(&mut self) -> &mut ChatSession {
64        &mut self.chat_session
65    }
66
67    pub fn clear_history(&mut self) {
68        self.chat_session.clear();
69    }
70
71    pub async fn send_message(&mut self, message: impl Into<String>) -> Result<String> {
72        let user_message = message.into();
73        self.chat_session.add_user_message(user_message.clone());
74
75        // Execute agent loop with tool calling
76        let response = self.execute_with_tools().await?;
77
78        Ok(response)
79    }
80
81    async fn execute_with_tools(&mut self) -> Result<String> {
82        let mut iterations = 0;
83        let tool_definitions = self.tool_registry.get_definitions();
84
85        loop {
86            if iterations >= self.max_iterations {
87                return Err(HeliosError::AgentError(
88                    "Maximum iterations reached".to_string(),
89                ));
90            }
91
92            let messages = self.chat_session.get_messages();
93            let tools_option = if tool_definitions.is_empty() {
94                None
95            } else {
96                Some(tool_definitions.clone())
97            };
98
99            let response = self.llm_client.chat(messages, tools_option).await?;
100
101            // Check if the response includes tool calls
102            if let Some(ref tool_calls) = response.tool_calls {
103                // Add assistant message with tool calls
104                self.chat_session.add_message(response.clone());
105
106                // Execute each tool call
107                for tool_call in tool_calls {
108                    let tool_name = &tool_call.function.name;
109                    let tool_args: Value = serde_json::from_str(&tool_call.function.arguments)
110                        .unwrap_or(Value::Object(serde_json::Map::new()));
111
112                    let tool_result = self
113                        .tool_registry
114                        .execute(tool_name, tool_args)
115                        .await
116                        .unwrap_or_else(|e| {
117                            ToolResult::error(format!("Tool execution failed: {}", e))
118                        });
119
120                    // Add tool result message
121                    let tool_message = ChatMessage::tool(tool_result.output, tool_call.id.clone());
122                    self.chat_session.add_message(tool_message);
123                }
124
125                iterations += 1;
126                continue;
127            }
128
129            // No tool calls, we have the final response
130            self.chat_session.add_message(response.clone());
131            return Ok(response.content);
132        }
133    }
134
135    pub async fn chat(&mut self, message: impl Into<String>) -> Result<String> {
136        self.send_message(message).await
137    }
138
139    pub fn set_max_iterations(&mut self, max: usize) {
140        self.max_iterations = max;
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147    use crate::config::Config;
148    use crate::tools::{CalculatorTool, Tool, ToolParameter, ToolResult};
149    use serde_json::Value;
150    use std::collections::HashMap;
151
152    #[tokio::test]
153    async fn test_agent_new() {
154        let config = Config::new_default();
155        let agent = Agent::new("test_agent", config).await;
156        assert!(agent.is_ok());
157    }
158
159    #[tokio::test]
160    async fn test_agent_builder() {
161        let config = Config::new_default();
162        let mut agent = Agent::builder("test_agent")
163            .config(config)
164            .system_prompt("You are a helpful assistant")
165            .max_iterations(5)
166            .tool(Box::new(CalculatorTool))
167            .build()
168            .await
169            .unwrap();
170
171        assert_eq!(agent.name(), "test_agent");
172        assert_eq!(agent.max_iterations, 5);
173        assert_eq!(
174            agent.tool_registry().list_tools(),
175            vec!["calculator".to_string()]
176        );
177    }
178
179    #[tokio::test]
180    async fn test_agent_system_prompt() {
181        let config = Config::new_default();
182        let mut agent = Agent::new("test_agent", config).await.unwrap();
183        agent.set_system_prompt("You are a test agent");
184
185        // Check that the system prompt is set in chat session
186        let session = agent.chat_session();
187        assert_eq!(
188            session.system_prompt,
189            Some("You are a test agent".to_string())
190        );
191    }
192
193    #[tokio::test]
194    async fn test_agent_tool_registry() {
195        let config = Config::new_default();
196        let mut agent = Agent::new("test_agent", config).await.unwrap();
197
198        // Initially no tools
199        assert!(agent.tool_registry().list_tools().is_empty());
200
201        // Register a tool
202        agent.register_tool(Box::new(CalculatorTool));
203        assert_eq!(
204            agent.tool_registry().list_tools(),
205            vec!["calculator".to_string()]
206        );
207    }
208
209    #[tokio::test]
210    async fn test_agent_clear_history() {
211        let config = Config::new_default();
212        let mut agent = Agent::new("test_agent", config).await.unwrap();
213
214        // Add a message to the chat session
215        agent.chat_session_mut().add_user_message("Hello");
216        assert!(!agent.chat_session().messages.is_empty());
217
218        // Clear history
219        agent.clear_history();
220        assert!(agent.chat_session().messages.is_empty());
221    }
222
223    // Mock tool for testing
224    struct MockTool;
225
226    #[async_trait::async_trait]
227    impl Tool for MockTool {
228        fn name(&self) -> &str {
229            "mock_tool"
230        }
231
232        fn description(&self) -> &str {
233            "A mock tool for testing"
234        }
235
236        fn parameters(&self) -> HashMap<String, ToolParameter> {
237            let mut params = HashMap::new();
238            params.insert(
239                "input".to_string(),
240                ToolParameter {
241                    param_type: "string".to_string(),
242                    description: "Input parameter".to_string(),
243                    required: Some(true),
244                },
245            );
246            params
247        }
248
249        async fn execute(&self, args: Value) -> crate::Result<ToolResult> {
250            let input = args
251                .get("input")
252                .and_then(|v| v.as_str())
253                .unwrap_or("default");
254            Ok(ToolResult::success(format!("Mock tool output: {}", input)))
255        }
256    }
257}
258
259pub struct AgentBuilder {
260    name: String,
261    config: Option<Config>,
262    system_prompt: Option<String>,
263    tools: Vec<Box<dyn crate::tools::Tool>>,
264    max_iterations: usize,
265}
266
267impl AgentBuilder {
268    pub fn new(name: impl Into<String>) -> Self {
269        Self {
270            name: name.into(),
271            config: None,
272            system_prompt: None,
273            tools: Vec::new(),
274            max_iterations: 10,
275        }
276    }
277
278    pub fn config(mut self, config: Config) -> Self {
279        self.config = Some(config);
280        self
281    }
282
283    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
284        self.system_prompt = Some(prompt.into());
285        self
286    }
287
288    pub fn tool(mut self, tool: Box<dyn crate::tools::Tool>) -> Self {
289        self.tools.push(tool);
290        self
291    }
292
293    pub fn max_iterations(mut self, max: usize) -> Self {
294        self.max_iterations = max;
295        self
296    }
297
298    pub async fn build(self) -> Result<Agent> {
299        let config = self
300            .config
301            .ok_or_else(|| HeliosError::AgentError("Config is required".to_string()))?;
302
303        let mut agent = Agent::new(self.name, config).await?;
304
305        if let Some(prompt) = self.system_prompt {
306            agent.set_system_prompt(prompt);
307        }
308
309        for tool in self.tools {
310            agent.register_tool(tool);
311        }
312
313        agent.set_max_iterations(self.max_iterations);
314
315        Ok(agent)
316    }
317}