Skip to main content

mojentic/llm/tools/
ask_user_tool.rs

1use crate::error::Result;
2use crate::llm::tools::{FunctionDescriptor, LlmTool, ToolDescriptor};
3use async_trait::async_trait;
4use serde_json::{json, Value};
5use std::collections::HashMap;
6use std::io::{self, Write};
7
8/// Tool for prompting the user for input or assistance
9///
10/// This tool allows the LLM to ask the user questions or request help when it
11/// doesn't have enough information to proceed. The user's response is returned
12/// as the tool's result.
13///
14/// # Examples
15///
16/// ```
17/// use mojentic::llm::tools::ask_user_tool::AskUserTool;
18/// use mojentic::llm::tools::LlmTool;
19/// use std::collections::HashMap;
20/// use serde_json::json;
21///
22/// let tool = AskUserTool::new();
23/// let mut args = HashMap::new();
24/// args.insert("user_request".to_string(), json!("What is your favorite color?"));
25///
26/// // This would prompt the user for input
27/// // let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
28/// ```
29#[derive(Clone)]
30pub struct AskUserTool;
31
32impl AskUserTool {
33    /// Creates a new AskUserTool instance
34    pub fn new() -> Self {
35        Self
36    }
37
38    /// Prompt the user with a message and read their response
39    fn prompt_user(&self, request: &str) -> Result<String> {
40        println!("\n\n\nI NEED YOUR HELP!\n{}", request);
41        print!("Your response: ");
42        io::stdout().flush().map_err(crate::error::MojenticError::IoError)?;
43
44        let mut response = String::new();
45        io::stdin()
46            .read_line(&mut response)
47            .map_err(crate::error::MojenticError::IoError)?;
48
49        Ok(response.trim().to_string())
50    }
51}
52
53impl Default for AskUserTool {
54    fn default() -> Self {
55        Self::new()
56    }
57}
58
59#[async_trait]
60impl LlmTool for AskUserTool {
61    async fn run(
62        &self,
63        args: &HashMap<String, Value>,
64        _ctx: &crate::llm::tools::ToolRunCtx,
65    ) -> Result<Value> {
66        let user_request = args.get("user_request").and_then(|v| v.as_str()).ok_or_else(|| {
67            crate::error::MojenticError::ToolError(
68                "Missing required argument: user_request".to_string(),
69            )
70        })?;
71
72        let response = self.prompt_user(user_request)?;
73        Ok(json!(response))
74    }
75
76    fn descriptor(&self) -> ToolDescriptor {
77        ToolDescriptor {
78            r#type: "function".to_string(),
79            function: FunctionDescriptor {
80                name: "ask_user".to_string(),
81                description: "If you do not know how to proceed, ask the user a question, or ask them for help or to do something for you.".to_string(),
82                parameters: json!({
83                    "type": "object",
84                    "properties": {
85                        "user_request": {
86                            "type": "string",
87                            "description": "The question you need the user to answer, or the task you need the user to do for you."
88                        }
89                    },
90                    "required": ["user_request"]
91                }),
92            },
93        }
94    }
95
96    fn clone_box(&self) -> Box<dyn LlmTool> {
97        Box::new(self.clone())
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn test_descriptor() {
107        let tool = AskUserTool::new();
108        let descriptor = tool.descriptor();
109
110        assert_eq!(descriptor.r#type, "function");
111        assert_eq!(descriptor.function.name, "ask_user");
112        assert!(descriptor.function.description.contains("ask the user a question"));
113
114        // Verify parameters structure
115        let params = &descriptor.function.parameters;
116        assert_eq!(params["type"], "object");
117        assert!(params["properties"]["user_request"].is_object());
118        assert_eq!(params["properties"]["user_request"]["type"], "string");
119        assert!(params["required"].as_array().unwrap().contains(&json!("user_request")));
120    }
121
122    #[test]
123    fn test_tool_matches() {
124        let tool = AskUserTool::new();
125        assert!(tool.matches("ask_user"));
126        assert!(!tool.matches("other_tool"));
127    }
128
129    #[tokio::test]
130    async fn test_missing_argument() {
131        let tool = AskUserTool::new();
132        let args = HashMap::new();
133
134        let result = tool.run(&args, &crate::llm::tools::ToolRunCtx::default()).await;
135        assert!(result.is_err());
136        assert!(matches!(result.unwrap_err(), crate::error::MojenticError::ToolError(_)));
137    }
138
139    #[test]
140    fn test_default_implementation() {
141        let tool = AskUserTool;
142        let descriptor = tool.descriptor();
143
144        assert_eq!(descriptor.function.name, "ask_user");
145    }
146}