mojentic/llm/tools/ephemeral_task_manager/
prepend_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)]
11pub struct PrependTaskTool {
12 task_list: Arc<Mutex<TaskList>>,
13}
14
15impl PrependTaskTool {
16 pub fn new(task_list: Arc<Mutex<TaskList>>) -> Self {
18 Self { task_list }
19 }
20}
21
22#[async_trait]
23impl LlmTool for PrependTaskTool {
24 async fn run(
25 &self,
26 args: &HashMap<String, Value>,
27 _ctx: &crate::llm::tools::ToolRunCtx,
28 ) -> Result<Value> {
29 let description =
30 args.get("description").and_then(|v| v.as_str()).unwrap_or("").to_string();
31
32 let mut task_list = self.task_list.lock().unwrap();
33 let task = task_list.prepend_task(description);
34
35 Ok(json!({
36 "id": task.id,
37 "description": task.description,
38 "status": task.status.as_str(),
39 "summary": format!("Task '{}' prepended successfully", task.id)
40 }))
41 }
42
43 fn descriptor(&self) -> ToolDescriptor {
44 ToolDescriptor {
45 r#type: "function".to_string(),
46 function: FunctionDescriptor {
47 name: "prepend_task".to_string(),
48 description: "Prepend a new task to the beginning of the task list with a description. The task will start with 'pending' status.".to_string(),
49 parameters: json!({
50 "type": "object",
51 "properties": {
52 "description": {
53 "type": "string",
54 "description": "The description of the task"
55 }
56 },
57 "required": ["description"]
58 }),
59 },
60 }
61 }
62 fn clone_box(&self) -> Box<dyn LlmTool> {
63 Box::new(self.clone())
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70 use crate::llm::tools::ToolRunCtx;
71
72 #[tokio::test]
73 async fn test_prepend_task_run() {
74 let task_list = Arc::new(Mutex::new(TaskList::new()));
75 let tool = PrependTaskTool::new(Arc::clone(&task_list));
76 let mut args = HashMap::new();
77 args.insert("description".to_string(), serde_json::Value::from("first task"));
78 let result = tool.run(&args, &ToolRunCtx::default()).await.unwrap();
79 assert_eq!(result["description"], "first task");
80 assert_eq!(result["status"], "pending");
81 }
82
83 #[test]
84 fn test_descriptor() {
85 let task_list = Arc::new(Mutex::new(TaskList::new()));
86 let tool = PrependTaskTool::new(task_list);
87 assert_eq!(tool.descriptor().function.name, "prepend_task");
88 }
89}