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(
122                        tool_result.output,
123                        tool_call.id.clone(),
124                    );
125                    self.chat_session.add_message(tool_message);
126                }
127
128                iterations += 1;
129                continue;
130            }
131
132            // No tool calls, we have the final response
133            self.chat_session.add_message(response.clone());
134            return Ok(response.content);
135        }
136    }
137
138    pub async fn chat(&mut self, message: impl Into<String>) -> Result<String> {
139        self.send_message(message).await
140    }
141
142    pub fn set_max_iterations(&mut self, max: usize) {
143        self.max_iterations = max;
144    }
145}
146
147pub struct AgentBuilder {
148    name: String,
149    config: Option<Config>,
150    system_prompt: Option<String>,
151    tools: Vec<Box<dyn crate::tools::Tool>>,
152    max_iterations: usize,
153}
154
155impl AgentBuilder {
156    pub fn new(name: impl Into<String>) -> Self {
157        Self {
158            name: name.into(),
159            config: None,
160            system_prompt: None,
161            tools: Vec::new(),
162            max_iterations: 10,
163        }
164    }
165
166    pub fn config(mut self, config: Config) -> Self {
167        self.config = Some(config);
168        self
169    }
170
171    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
172        self.system_prompt = Some(prompt.into());
173        self
174    }
175
176    pub fn tool(mut self, tool: Box<dyn crate::tools::Tool>) -> Self {
177        self.tools.push(tool);
178        self
179    }
180
181    pub fn max_iterations(mut self, max: usize) -> Self {
182        self.max_iterations = max;
183        self
184    }
185
186    pub async fn build(self) -> Result<Agent> {
187        let config = self
188            .config
189            .ok_or_else(|| HeliosError::AgentError("Config is required".to_string()))?;
190
191        let mut agent = Agent::new(self.name, config).await?;
192
193        if let Some(prompt) = self.system_prompt {
194            agent.set_system_prompt(prompt);
195        }
196
197        for tool in self.tools {
198            agent.register_tool(tool);
199        }
200
201        agent.set_max_iterations(self.max_iterations);
202
203        Ok(agent)
204    }
205}