mojentic/llm/tools/ephemeral_task_manager/
complete_task.rs1use super::task_list::TaskList;
2use crate::error::Result;
3use crate::llm::tools::{FunctionDescriptor, LlmTool, ToolDescriptor};
4use async_trait::async_trait;
5use serde_json::{json, Value};
6use std::collections::HashMap;
7use std::sync::{Arc, Mutex};
8
9#[derive(Clone)]
13pub struct CompleteTaskTool {
14 task_list: Arc<Mutex<TaskList>>,
15}
16
17impl CompleteTaskTool {
18 pub fn new(task_list: Arc<Mutex<TaskList>>) -> Self {
20 Self { task_list }
21 }
22}
23
24#[async_trait]
25impl LlmTool for CompleteTaskTool {
26 async fn run(
27 &self,
28 args: &HashMap<String, Value>,
29 _ctx: &crate::llm::tools::ToolRunCtx,
30 ) -> Result<Value> {
31 let task_id = args.get("id").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
32
33 let mut task_list = self.task_list.lock().unwrap();
34 let task = task_list.complete_task(task_id)?;
35
36 Ok(json!({
37 "id": task.id,
38 "description": task.description,
39 "status": task.status.as_str(),
40 "summary": format!("Task '{}' completed successfully", task_id)
41 }))
42 }
43
44 fn descriptor(&self) -> ToolDescriptor {
45 ToolDescriptor {
46 r#type: "function".to_string(),
47 function: FunctionDescriptor {
48 name: "complete_task".to_string(),
49 description:
50 "Complete a task by changing its status from IN_PROGRESS to COMPLETED."
51 .to_string(),
52 parameters: json!({
53 "type": "object",
54 "properties": {
55 "id": {
56 "type": "integer",
57 "description": "The ID of the task to complete"
58 }
59 },
60 "required": ["id"]
61 }),
62 },
63 }
64 }
65 fn clone_box(&self) -> Box<dyn LlmTool> {
66 Box::new(self.clone())
67 }
68}
69
70#[cfg(test)]
71mod tests {
72 use super::*;
73 use crate::llm::tools::ToolRunCtx;
74
75 #[tokio::test]
76 async fn test_complete_task_run() {
77 let task_list = Arc::new(Mutex::new(TaskList::new()));
78 {
79 let mut list = task_list.lock().unwrap();
80 let task = list.append_task("do something".to_string());
81 list.start_task(task.id).unwrap();
82 }
83 let tool = CompleteTaskTool::new(Arc::clone(&task_list));
84 let mut args = HashMap::new();
85 args.insert("id".to_string(), serde_json::Value::from(1u64));
86 let result = tool.run(&args, &ToolRunCtx::default()).await.unwrap();
87 assert_eq!(result["status"], "completed");
88 }
89
90 #[test]
91 fn test_descriptor() {
92 let task_list = Arc::new(Mutex::new(TaskList::new()));
93 let tool = CompleteTaskTool::new(task_list);
94 let desc = tool.descriptor();
95 assert_eq!(desc.function.name, "complete_task");
96 }
97}