1#![allow(dead_code)]
2#![allow(unused_variables)]
3use crate::chat::{ChatMessage, ChatSession};
4use crate::config::Config;
5use crate::error::{HeliosError, Result};
6use crate::llm::{LLMClient, LLMProviderType};
7use crate::tools::{ToolRegistry, ToolResult};
8use serde_json::Value;
9
10const AGENT_MEMORY_PREFIX: &str = "agent:";
11
12pub struct Agent {
13 name: String,
14 llm_client: LLMClient,
15 tool_registry: ToolRegistry,
16 chat_session: ChatSession,
17 max_iterations: usize,
18}
19
20impl Agent {
21 pub async fn new(name: impl Into<String>, config: Config) -> Result<Self> {
22 let provider_type = if let Some(local_config) = config.local {
23 LLMProviderType::Local(local_config)
24 } else {
25 LLMProviderType::Remote(config.llm)
26 };
27
28 let llm_client = LLMClient::new(provider_type).await?;
29
30 Ok(Self {
31 name: name.into(),
32 llm_client,
33 tool_registry: ToolRegistry::new(),
34 chat_session: ChatSession::new(),
35 max_iterations: 10,
36 })
37 }
38
39 pub fn builder(name: impl Into<String>) -> AgentBuilder {
40 AgentBuilder::new(name)
41 }
42
43 pub fn name(&self) -> &str {
44 &self.name
45 }
46
47 pub fn set_system_prompt(&mut self, prompt: impl Into<String>) {
48 self.chat_session = self.chat_session.clone().with_system_prompt(prompt);
49 }
50
51 pub fn register_tool(&mut self, tool: Box<dyn crate::tools::Tool>) {
52 self.tool_registry.register(tool);
53 }
54
55 pub fn tool_registry(&self) -> &ToolRegistry {
56 &self.tool_registry
57 }
58
59 pub fn tool_registry_mut(&mut self) -> &mut ToolRegistry {
60 &mut self.tool_registry
61 }
62
63 pub fn chat_session(&self) -> &ChatSession {
64 &self.chat_session
65 }
66
67 pub fn chat_session_mut(&mut self) -> &mut ChatSession {
68 &mut self.chat_session
69 }
70
71 pub fn clear_history(&mut self) {
72 self.chat_session.clear();
73 }
74
75 pub async fn send_message(&mut self, message: impl Into<String>) -> Result<String> {
76 let user_message = message.into();
77 self.chat_session.add_user_message(user_message.clone());
78
79 let response = self.execute_with_tools().await?;
81
82 Ok(response)
83 }
84
85 async fn execute_with_tools(&mut self) -> Result<String> {
86 let mut iterations = 0;
87 let tool_definitions = self.tool_registry.get_definitions();
88
89 loop {
90 if iterations >= self.max_iterations {
91 return Err(HeliosError::AgentError(
92 "Maximum iterations reached".to_string(),
93 ));
94 }
95
96 let messages = self.chat_session.get_messages();
97 let tools_option = if tool_definitions.is_empty() {
98 None
99 } else {
100 Some(tool_definitions.clone())
101 };
102
103 let response = self.llm_client.chat(messages, tools_option).await?;
104
105 if let Some(ref tool_calls) = response.tool_calls {
107 self.chat_session.add_message(response.clone());
109
110 for tool_call in tool_calls {
112 let tool_name = &tool_call.function.name;
113 let tool_args: Value = serde_json::from_str(&tool_call.function.arguments)
114 .unwrap_or(Value::Object(serde_json::Map::new()));
115
116 let tool_result = self
117 .tool_registry
118 .execute(tool_name, tool_args)
119 .await
120 .unwrap_or_else(|e| {
121 ToolResult::error(format!("Tool execution failed: {}", e))
122 });
123
124 let tool_message = ChatMessage::tool(tool_result.output, tool_call.id.clone());
126 self.chat_session.add_message(tool_message);
127 }
128
129 iterations += 1;
130 continue;
131 }
132
133 self.chat_session.add_message(response.clone());
135 return Ok(response.content);
136 }
137 }
138
139 pub async fn chat(&mut self, message: impl Into<String>) -> Result<String> {
140 self.send_message(message).await
141 }
142
143 pub fn set_max_iterations(&mut self, max: usize) {
144 self.max_iterations = max;
145 }
146
147 pub fn get_session_summary(&self) -> String {
148 self.chat_session.get_summary()
149 }
150
151 pub fn clear_memory(&mut self) {
152 self.chat_session
154 .metadata
155 .retain(|k, _| !k.starts_with(AGENT_MEMORY_PREFIX));
156 }
157
158 #[inline]
159 fn prefixed_key(key: &str) -> String {
160 format!("{}{}", AGENT_MEMORY_PREFIX, key)
161 }
162
163 pub fn set_memory(&mut self, key: impl Into<String>, value: impl Into<String>) {
165 let key = key.into();
166 self.chat_session
167 .set_metadata(Self::prefixed_key(&key), value);
168 }
169
170 pub fn get_memory(&self, key: &str) -> Option<&String> {
171 self.chat_session.get_metadata(&Self::prefixed_key(key))
172 }
173
174 pub fn remove_memory(&mut self, key: &str) -> Option<String> {
175 self.chat_session.remove_metadata(&Self::prefixed_key(key))
176 }
177
178 pub fn increment_counter(&mut self, key: &str) -> u32 {
180 let current = self
181 .get_memory(key)
182 .and_then(|v| v.parse::<u32>().ok())
183 .unwrap_or(0);
184 let next = current + 1;
185 self.set_memory(key, next.to_string());
186 next
187 }
188
189 pub fn increment_tasks_completed(&mut self) -> u32 {
190 self.increment_counter("tasks_completed")
191 }
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197 use crate::config::Config;
198 use crate::tools::{CalculatorTool, Tool, ToolParameter, ToolResult};
199 use serde_json::Value;
200 use std::collections::HashMap;
201
202 #[tokio::test]
203 async fn test_agent_new() {
204 let config = Config::new_default();
205 let agent = Agent::new("test_agent", config).await;
206 assert!(agent.is_ok());
207 }
208
209 #[tokio::test]
210 async fn test_agent_memory_namespacing_set_get_remove() {
211 let config = Config::new_default();
212 let mut agent = Agent::new("test_agent", config).await.unwrap();
213
214 agent.set_memory("working_directory", "/tmp");
216 assert_eq!(
217 agent.get_memory("working_directory"),
218 Some(&"/tmp".to_string())
219 );
220
221 assert_eq!(
223 agent
224 .chat_session()
225 .get_metadata("agent:working_directory"),
226 Some(&"/tmp".to_string())
227 );
228 assert!(agent.chat_session().get_metadata("working_directory").is_none());
230
231 let removed = agent.remove_memory("working_directory");
233 assert_eq!(removed.as_deref(), Some("/tmp"));
234 assert!(agent.get_memory("working_directory").is_none());
235 }
236
237 #[tokio::test]
238 async fn test_agent_clear_memory_scoped() {
239 let config = Config::new_default();
240 let mut agent = Agent::new("test_agent", config).await.unwrap();
241
242 agent.set_memory("tasks_completed", "3");
244 agent
245 .chat_session_mut()
246 .set_metadata("session_start", "now");
247
248 agent.clear_memory();
250
251 assert!(agent.get_memory("tasks_completed").is_none());
253 assert_eq!(
255 agent.chat_session().get_metadata("session_start"),
256 Some(&"now".to_string())
257 );
258 }
259
260 #[tokio::test]
261 async fn test_agent_increment_helpers() {
262 let config = Config::new_default();
263 let mut agent = Agent::new("test_agent", config).await.unwrap();
264
265 let n1 = agent.increment_tasks_completed();
267 assert_eq!(n1, 1);
268 assert_eq!(agent.get_memory("tasks_completed"), Some(&"1".to_string()));
269
270 let n2 = agent.increment_tasks_completed();
271 assert_eq!(n2, 2);
272 assert_eq!(agent.get_memory("tasks_completed"), Some(&"2".to_string()));
273
274 let f1 = agent.increment_counter("files_accessed");
276 assert_eq!(f1, 1);
277 let f2 = agent.increment_counter("files_accessed");
278 assert_eq!(f2, 2);
279 assert_eq!(agent.get_memory("files_accessed"), Some(&"2".to_string()));
280 }
281
282 #[tokio::test]
283 async fn test_agent_builder() {
284 let config = Config::new_default();
285 let agent = Agent::builder("test_agent")
286 .config(config)
287 .system_prompt("You are a helpful assistant")
288 .max_iterations(5)
289 .tool(Box::new(CalculatorTool))
290 .build()
291 .await
292 .unwrap();
293
294 assert_eq!(agent.name(), "test_agent");
295 assert_eq!(agent.max_iterations, 5);
296 assert_eq!(
297 agent.tool_registry().list_tools(),
298 vec!["calculator".to_string()]
299 );
300 }
301
302 #[tokio::test]
303 async fn test_agent_system_prompt() {
304 let config = Config::new_default();
305 let mut agent = Agent::new("test_agent", config).await.unwrap();
306 agent.set_system_prompt("You are a test agent");
307
308 let session = agent.chat_session();
310 assert_eq!(
311 session.system_prompt,
312 Some("You are a test agent".to_string())
313 );
314 }
315
316 #[tokio::test]
317 async fn test_agent_tool_registry() {
318 let config = Config::new_default();
319 let mut agent = Agent::new("test_agent", config).await.unwrap();
320
321 assert!(agent.tool_registry().list_tools().is_empty());
323
324 agent.register_tool(Box::new(CalculatorTool));
326 assert_eq!(
327 agent.tool_registry().list_tools(),
328 vec!["calculator".to_string()]
329 );
330 }
331
332 #[tokio::test]
333 async fn test_agent_clear_history() {
334 let config = Config::new_default();
335 let mut agent = Agent::new("test_agent", config).await.unwrap();
336
337 agent.chat_session_mut().add_user_message("Hello");
339 assert!(!agent.chat_session().messages.is_empty());
340
341 agent.clear_history();
343 assert!(agent.chat_session().messages.is_empty());
344 }
345
346 struct MockTool;
348
349 #[async_trait::async_trait]
350 impl Tool for MockTool {
351 fn name(&self) -> &str {
352 "mock_tool"
353 }
354
355 fn description(&self) -> &str {
356 "A mock tool for testing"
357 }
358
359 fn parameters(&self) -> HashMap<String, ToolParameter> {
360 let mut params = HashMap::new();
361 params.insert(
362 "input".to_string(),
363 ToolParameter {
364 param_type: "string".to_string(),
365 description: "Input parameter".to_string(),
366 required: Some(true),
367 },
368 );
369 params
370 }
371
372 async fn execute(&self, args: Value) -> crate::Result<ToolResult> {
373 let input = args
374 .get("input")
375 .and_then(|v| v.as_str())
376 .unwrap_or("default");
377 Ok(ToolResult::success(format!("Mock tool output: {}", input)))
378 }
379 }
380}
381
382pub struct AgentBuilder {
383 name: String,
384 config: Option<Config>,
385 system_prompt: Option<String>,
386 tools: Vec<Box<dyn crate::tools::Tool>>,
387 max_iterations: usize,
388}
389
390impl AgentBuilder {
391 pub fn new(name: impl Into<String>) -> Self {
392 Self {
393 name: name.into(),
394 config: None,
395 system_prompt: None,
396 tools: Vec::new(),
397 max_iterations: 10,
398 }
399 }
400
401 pub fn config(mut self, config: Config) -> Self {
402 self.config = Some(config);
403 self
404 }
405
406 pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
407 self.system_prompt = Some(prompt.into());
408 self
409 }
410
411 pub fn tool(mut self, tool: Box<dyn crate::tools::Tool>) -> Self {
412 self.tools.push(tool);
413 self
414 }
415
416 pub fn max_iterations(mut self, max: usize) -> Self {
417 self.max_iterations = max;
418 self
419 }
420
421 pub async fn build(self) -> Result<Agent> {
422 let config = self
423 .config
424 .ok_or_else(|| HeliosError::AgentError("Config is required".to_string()))?;
425
426 let mut agent = Agent::new(self.name, config).await?;
427
428 if let Some(prompt) = self.system_prompt {
429 agent.set_system_prompt(prompt);
430 }
431
432 for tool in self.tools {
433 agent.register_tool(tool);
434 }
435
436 agent.set_max_iterations(self.max_iterations);
437
438 Ok(agent)
439 }
440}