1use std::fmt;
11use std::sync::atomic::{AtomicU64, Ordering};
12use std::sync::Arc;
13
14use serde_json::Value;
15
16use super::messages::{ChatOptions, Message, ToolDefinition};
17use super::provider::{AiProvider, ProviderError};
18
19pub const DEFAULT_AGENT_MAX_TURNS: usize = 10;
22
23#[derive(Debug, thiserror::Error)]
25#[error("agent tool '{name}' failed: {message}")]
26pub struct ToolError {
27 pub name: String,
29 pub message: String,
31}
32
33impl ToolError {
34 pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
36 Self {
37 name: name.into(),
38 message: message.into(),
39 }
40 }
41}
42
43pub struct AgentTool {
47 name: String,
48 description: String,
49 parameters: Value,
50 handler: Arc<dyn Fn(Value) -> Result<Value, ToolError> + Send + Sync>,
51}
52
53impl fmt::Debug for AgentTool {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 f.debug_struct("AgentTool")
56 .field("name", &self.name)
57 .field("description", &self.description)
58 .field("parameters", &self.parameters)
59 .finish_non_exhaustive()
60 }
61}
62
63impl AgentTool {
64 pub fn from(name: impl Into<String>, description: impl Into<String>) -> Self {
67 Self {
68 name: name.into(),
69 description: description.into(),
70 parameters: Value::Object(Default::default()),
71 handler: Arc::new(|_| Ok(Value::Null)),
72 }
73 }
74
75 pub fn using<F>(mut self, handler: F) -> Self
80 where
81 F: Fn(Value) -> Result<Value, ToolError> + Send + Sync + 'static,
82 {
83 self.handler = Arc::new(handler);
84 self
85 }
86
87 pub fn with_parameters(mut self, parameters: Value) -> Self {
89 self.parameters = parameters;
90 self
91 }
92
93 pub fn name(&self) -> &str {
95 &self.name
96 }
97
98 pub fn definition(&self) -> ToolDefinition {
100 ToolDefinition::new(
101 self.name.clone(),
102 self.description.clone(),
103 self.parameters.clone(),
104 )
105 }
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub enum AgentTaskStatus {
112 Running,
114 Completed,
116 Failed,
118}
119
120#[derive(Debug, Clone)]
122pub struct AgentResult {
123 completion: String,
124}
125
126impl AgentResult {
127 pub fn completion(&self) -> &str {
129 &self.completion
130 }
131}
132
133#[derive(Debug, Clone)]
135pub struct AgentTask {
136 id: String,
137 status: AgentTaskStatus,
138 messages: Vec<Message>,
139 result: AgentResult,
140}
141
142impl AgentTask {
143 pub fn id(&self) -> &str {
145 &self.id
146 }
147
148 pub fn status(&self) -> AgentTaskStatus {
150 self.status
151 }
152
153 pub fn messages(&self) -> &[Message] {
155 &self.messages
156 }
157
158 pub fn result(&self) -> &AgentResult {
160 &self.result
161 }
162
163 pub fn completion(&self) -> &str {
165 self.result.completion()
166 }
167}
168
169pub struct Agent {
172 name: String,
173 provider: Arc<dyn AiProvider>,
174 prompt: Option<String>,
175 tools: Vec<AgentTool>,
176 model: Option<String>,
177 max_turns: usize,
178}
179
180impl fmt::Debug for Agent {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 f.debug_struct("Agent")
183 .field("name", &self.name)
184 .field("prompt", &self.prompt)
185 .field("tools", &self.tools)
186 .field("model", &self.model)
187 .field("max_turns", &self.max_turns)
188 .finish_non_exhaustive()
189 }
190}
191
192impl Agent {
193 pub fn new(name: impl Into<String>, provider: Arc<dyn AiProvider>) -> Self {
195 Self {
196 name: name.into(),
197 provider,
198 prompt: None,
199 tools: Vec::new(),
200 model: None,
201 max_turns: DEFAULT_AGENT_MAX_TURNS,
202 }
203 }
204
205 pub fn name(&self) -> &str {
207 &self.name
208 }
209
210 pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
212 self.prompt = Some(prompt.into());
213 self
214 }
215
216 pub fn using_tools(mut self, tools: Vec<AgentTool>) -> Self {
218 self.tools = tools;
219 self
220 }
221
222 pub fn using_model(mut self, model: impl Into<String>) -> Self {
225 self.model = Some(model.into());
226 self
227 }
228
229 pub fn with_max_turns(mut self, turns: usize) -> Self {
231 self.max_turns = turns.max(1);
232 self
233 }
234
235 pub async fn ask(&self, query: &str) -> Result<AgentTask, ProviderError> {
238 let mut messages = Vec::new();
239 if let Some(prompt) = &self.prompt {
240 messages.push(Message::system(prompt));
241 }
242 messages.push(Message::user(query));
243
244 let tools: Vec<ToolDefinition> = self.tools.iter().map(AgentTool::definition).collect();
245
246 for _ in 0..self.max_turns {
247 let options = ChatOptions {
248 model: self.model.clone(),
249 tools: tools.clone(),
250 ..Default::default()
251 };
252 let response = self.provider.chat(&messages, &options).await?;
253
254 if response.tool_calls.is_empty() {
255 let completion = response.text;
256 messages.push(Message::assistant(&completion));
257 let task = AgentTask {
258 id: agent_task_id(),
259 status: AgentTaskStatus::Completed,
260 messages,
261 result: AgentResult { completion },
262 };
263 return Ok(task);
264 }
265
266 let content = if response.text.is_empty() {
267 None
268 } else {
269 Some(response.text)
270 };
271 messages.push(Message::assistant_with_tool_calls(
272 content,
273 response.tool_calls.clone(),
274 ));
275
276 for call in &response.tool_calls {
277 let result = match self.tools.iter().find(|tool| tool.name == call.name) {
278 Some(tool) => match (tool.handler)(call.arguments.clone()) {
279 Ok(value) => value.to_string(),
280 Err(error) => error.to_string(),
281 },
282 None => format!("Unknown tool: {}", call.name),
283 };
284 messages.push(Message::tool(&call.id, result));
285 }
286 }
287
288 Err(ProviderError::Request(format!(
289 "agent '{}' exceeded its {} turn limit without producing a final response",
290 self.name, self.max_turns
291 )))
292 }
293
294 pub async fn run(&self, query: &str) -> Result<AgentTask, ProviderError> {
297 self.ask(query).await
298 }
299}
300
301static AGENT_TASK_COUNTER: AtomicU64 = AtomicU64::new(0);
302
303fn agent_task_id() -> String {
304 let nanos = std::time::SystemTime::now()
305 .duration_since(std::time::UNIX_EPOCH)
306 .map(|d| d.as_nanos())
307 .unwrap_or_default();
308 let counter = AGENT_TASK_COUNTER.fetch_add(1, Ordering::Relaxed);
309 format!("{nanos:x}-{counter:x}")
310}
311
312#[cfg(test)]
317mod tests {
318 use super::*;
319 use crate::ai::FakeAi;
320 use crate::ai::Role;
321 use tokio::io::{AsyncReadExt, AsyncWriteExt};
322 use tokio::net::TcpListener;
323
324 async fn mock_server_multi(
327 responses: Vec<String>,
328 ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
329 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
330 let addr = listener.local_addr().unwrap();
331 let bodies = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
332 let bodies_clone = bodies.clone();
333
334 tokio::spawn(async move {
335 for response in responses {
336 let Ok((mut socket, _)) = listener.accept().await else {
337 break;
338 };
339 let mut request = Vec::new();
340 let mut buf = [0u8; 4096];
341 loop {
342 let n = socket.read(&mut buf).await.unwrap();
343 if n == 0 {
344 break;
345 }
346 request.extend_from_slice(&buf[..n]);
347 if request.windows(4).any(|w| w == b"\r\n\r\n") {
348 break;
349 }
350 }
351 let request = String::from_utf8_lossy(&request).to_string();
352 if let Some(body_start) = request.find("\r\n\r\n") {
353 bodies_clone
354 .lock()
355 .unwrap()
356 .push(request[body_start + 4..].trim().to_string());
357 }
358 let headers = format!(
359 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
360 response.len()
361 );
362 let _ = socket.write_all(headers.as_bytes()).await;
363 let _ = socket.write_all(response.as_bytes()).await;
364 }
365 });
366
367 (format!("http://{addr}/v1"), bodies)
368 }
369
370 fn tool_response(call_id: &str, name: &str, arguments: &str) -> String {
371 format!(
372 r#"{{
373 "choices": [{{
374 "message": {{
375 "role": "assistant",
376 "content": null,
377 "tool_calls": [{{
378 "id": "{call_id}",
379 "type": "function",
380 "function": {{ "name": "{name}", "arguments": "{arguments}" }}
381 }}]
382 }},
383 "finish_reason": "tool_calls"
384 }}]
385 }}"#
386 )
387 }
388
389 fn text_response(text: &str) -> String {
390 format!(
391 r#"{{"choices": [{{"message": {{"role": "assistant", "content": "{text}"}}, "finish_reason": "stop"}}]}}"#
392 )
393 }
394
395 #[tokio::test]
396 async fn test_agent_tool_round_trip() {
397 let (base, bodies) = mock_server_multi(vec![
398 tool_response("call_1", "get_weather", r#"{\"city\":\"Jakarta\"}"#),
399 text_response("Sunny, 31C."),
400 ])
401 .await;
402 let provider: Arc<dyn AiProvider> = Arc::new(crate::ai::OpenAICompatibleProvider::new(
403 &base,
404 "test-key",
405 "gpt-4o-mini",
406 "text-embedding-3-small",
407 ));
408
409 let calls = Arc::new(std::sync::Mutex::new(Vec::new()));
410 let calls_clone = calls.clone();
411 let tool = AgentTool::from("get_weather", "Get the weather for a city.")
412 .with_parameters(serde_json::json!({
413 "type": "object",
414 "properties": { "city": { "type": "string" } },
415 "required": ["city"],
416 }))
417 .using(move |arguments| {
418 calls_clone.lock().unwrap().push(arguments.clone());
419 Ok(serde_json::json!({ "temp": 31 }))
420 });
421
422 let agent = Agent::new("weather", provider)
423 .prompt("You are a weather assistant.")
424 .using_tools(vec![tool]);
425
426 let task = agent.ask("What is the weather in Jakarta?").await.unwrap();
427
428 assert_eq!(task.status(), AgentTaskStatus::Completed);
429 assert_eq!(task.completion(), "Sunny, 31C.");
430 assert_eq!(
431 calls.lock().unwrap().as_slice(),
432 [serde_json::json!({"city": "Jakarta"})]
433 );
434
435 let bodies = bodies.lock().unwrap();
436 let first: Value = serde_json::from_str(&bodies[0]).unwrap();
437 assert_eq!(first["tools"][0]["type"], "function");
438 assert_eq!(first["tools"][0]["function"]["name"], "get_weather");
439 assert_eq!(first["tool_choice"], "auto");
440 assert_eq!(first["messages"][0]["role"], "system");
441 assert_eq!(
442 first["messages"][1]["content"],
443 "What is the weather in Jakarta?"
444 );
445
446 let second: Value = serde_json::from_str(&bodies[1]).unwrap();
447 let messages = second["messages"].as_array().unwrap();
448 let tool_message = messages
449 .iter()
450 .find(|m| m["role"] == "tool")
451 .expect("second request must carry the tool result");
452 assert_eq!(tool_message["tool_call_id"], "call_1");
453 assert_eq!(tool_message["content"], r#"{"temp":31}"#);
454 let assistant = messages
455 .iter()
456 .find(|m| m["role"] == "assistant" && m.get("tool_calls").is_some())
457 .expect("second request must carry the assistant tool call");
458 assert_eq!(
459 assistant["tool_calls"][0]["function"]["name"],
460 "get_weather"
461 );
462 }
463
464 #[tokio::test]
465 async fn test_agent_without_tools() {
466 let (base, bodies) = mock_server_multi(vec![text_response("Hello!")]).await;
467 let provider: Arc<dyn AiProvider> = Arc::new(crate::ai::OpenAICompatibleProvider::new(
468 &base,
469 "test-key",
470 "gpt-4o-mini",
471 "text-embedding-3-small",
472 ));
473
474 let task = Agent::new("chatty", provider).ask("Hi").await.unwrap();
475
476 assert_eq!(task.completion(), "Hello!");
477 assert_eq!(bodies.lock().unwrap().len(), 1);
478 let body: Value = serde_json::from_str(&bodies.lock().unwrap()[0]).unwrap();
479 assert!(body.get("tools").is_none());
480 }
481
482 #[tokio::test]
483 async fn test_agent_tool_error_feeds_back_to_model() {
484 let (base, _) = mock_server_multi(vec![
485 tool_response("call_1", "boom", "{}"),
486 text_response("I could not do that."),
487 ])
488 .await;
489 let provider: Arc<dyn AiProvider> = Arc::new(crate::ai::OpenAICompatibleProvider::new(
490 &base,
491 "test-key",
492 "gpt-4o-mini",
493 "text-embedding-3-small",
494 ));
495
496 let tool = AgentTool::from("boom", "Always fails.")
497 .using(|_| Err(ToolError::new("boom", "permission denied")));
498
499 let agent = Agent::new("failing", provider).using_tools(vec![tool]);
500
501 let task = agent.ask("do it").await.unwrap();
502 assert_eq!(task.completion(), "I could not do that.");
503 let tool_messages: Vec<&Message> = task
504 .messages()
505 .iter()
506 .filter(|m| m.role == Role::Tool)
507 .collect();
508 assert_eq!(tool_messages.len(), 1);
509 assert!(tool_messages[0]
510 .content()
511 .unwrap()
512 .contains("permission denied"));
513 }
514
515 #[tokio::test]
516 async fn test_agent_unknown_tool_continues() {
517 let (base, _) = mock_server_multi(vec![
518 tool_response("call_1", "missing_tool", "{}"),
519 text_response("ok"),
520 ])
521 .await;
522 let provider: Arc<dyn AiProvider> = Arc::new(crate::ai::OpenAICompatibleProvider::new(
523 &base,
524 "test-key",
525 "gpt-4o-mini",
526 "text-embedding-3-small",
527 ));
528
529 let agent = Agent::new("solo", provider);
530 let task = agent.ask("hi").await.unwrap();
531 assert_eq!(task.completion(), "ok");
532 assert!(task.messages().iter().any(|m| m
533 .content()
534 .is_some_and(|c| c.contains("Unknown tool: missing_tool"))));
535 }
536
537 #[tokio::test]
538 async fn test_agent_max_turns_guard() {
539 let (base, _) = mock_server_multi(vec![
540 tool_response("call_1", "loop", "{}"),
541 tool_response("call_2", "loop", "{}"),
542 ])
543 .await;
544 let provider: Arc<dyn AiProvider> = Arc::new(crate::ai::OpenAICompatibleProvider::new(
545 &base,
546 "test-key",
547 "gpt-4o-mini",
548 "text-embedding-3-small",
549 ));
550
551 let tool = AgentTool::from("loop", "Never finishes.").using(|_| Ok(Value::Null));
552 let agent = Agent::new("looper", provider)
553 .using_tools(vec![tool])
554 .with_max_turns(2);
555
556 let err = agent.ask("go").await.unwrap_err();
557 assert!(err.to_string().contains("turn limit"), "got: {err}");
558 }
559
560 #[tokio::test]
561 async fn test_agent_with_fake_provider() {
562 let fake = Arc::new(FakeAi::new());
563 fake.add_response("Fake completion");
564 let agent = Agent::new("fake-agent", fake);
565 let task = agent.ask("Hi").await.unwrap();
566 assert_eq!(task.completion(), "Fake completion");
567 assert_eq!(task.status(), AgentTaskStatus::Completed);
568 assert!(!task.id().is_empty());
569 assert_eq!(task.result().completion(), "Fake completion");
570 }
571
572 #[test]
573 fn test_agent_task_ids_unique() {
574 let a = agent_task_id();
575 let b = agent_task_id();
576 assert_ne!(a, b);
577 }
578}