1use std::borrow::Cow;
4
5use aither_core::llm::tool::{Tool, ToolResult};
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8
9use crate::tool_request::{
10 ToolRequest, ToolRequestBroker, ToolRequestQueue, channel as tool_request_channel,
11};
12
13#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
15pub struct Question {
16 pub section: String,
18 pub question: String,
20 #[serde(alias = "options")]
22 pub option: Vec<String>,
23 #[serde(default)]
25 pub multi_select: bool,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
48pub struct AskUserArgs {
49 #[serde(default)]
51 pub question: Option<String>,
52 #[serde(default, alias = "options", alias = "choices")]
54 pub option: Vec<String>,
55 #[serde(default)]
57 pub multi_select: bool,
58 #[serde(default)]
60 pub questions: Vec<Question>,
61}
62
63impl AskUserArgs {
64 #[must_use]
68 pub fn into_questions(self) -> Vec<Question> {
69 if !self.questions.is_empty() {
70 return self.questions;
71 }
72 if let Some(q) = self.question {
73 vec![Question {
74 section: String::new(),
75 question: q,
76 option: self.option,
77 multi_select: self.multi_select,
78 }]
79 } else {
80 Vec::new()
81 }
82 }
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct QuestionAnswer {
88 pub section: String,
90 pub answer: AnswerValue,
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize)]
96#[serde(untagged)]
97pub enum AnswerValue {
98 Selected(Vec<String>),
100 Custom(String),
102 Skipped,
104}
105
106pub type AskUserRequest = ToolRequest<AskUserRequestPayload, Vec<QuestionAnswer>>;
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct AskUserRequestPayload {
112 pub session_id: String,
114 pub request: AskUserArgs,
116}
117
118pub type AskUserBroker = ToolRequestBroker<AskUserRequestPayload, Vec<QuestionAnswer>>;
120
121pub type AskUserQueue = ToolRequestQueue<AskUserRequestPayload, Vec<QuestionAnswer>>;
123
124#[must_use]
126pub fn channel() -> (AskUserBroker, AskUserQueue) {
127 tool_request_channel()
128}
129
130#[derive(Debug, Clone)]
132pub struct AskUserTool {
133 broker: AskUserBroker,
134 session_id: String,
135}
136
137impl AskUserTool {
138 #[must_use]
140 pub fn new(session_id: impl Into<String>, broker: AskUserBroker) -> Self {
141 Self {
142 broker,
143 session_id: session_id.into(),
144 }
145 }
146}
147
148impl Tool for AskUserTool {
149 fn name(&self) -> Cow<'static, str> {
150 "ask_user".into()
151 }
152
153 type Arguments = AskUserArgs;
154 type Res = ToolResult;
155
156 async fn call(&self, args: Self::Arguments) -> aither_core::Result<Self::Res> {
157 let response = self
158 .broker
159 .request(AskUserRequestPayload {
160 session_id: self.session_id.clone(),
161 request: args,
162 })
163 .await?;
164 ToolResult::json(&response)
165 }
166}
167
168#[cfg(test)]
169mod tests {
170 use super::*;
171
172 #[test]
173 fn test_deser_option_array() {
174 let json = serde_json::json!({
175 "question": "请选择你喜欢的水果?",
176 "option": ["苹果", "香蕉", "橘子", "梨"]
177 });
178 let args: AskUserArgs = serde_json::from_value(json).unwrap();
179 assert_eq!(args.option.len(), 4);
180 assert_eq!(args.option, vec!["苹果", "香蕉", "橘子", "梨"]);
181 let questions = args.into_questions();
182 assert_eq!(questions.len(), 1);
183 assert_eq!(questions[0].option.len(), 4);
184 }
185
186 #[test]
187 fn test_schema_option_is_array() {
188 let schema = schemars::schema_for!(AskUserArgs);
189 let val = serde_json::to_value(schema).unwrap();
190 tracing::debug!(
191 "AskUserArgs schema:\n{}",
192 serde_json::to_string_pretty(&val).unwrap()
193 );
194
195 let props = val.get("properties").unwrap().as_object().unwrap();
196 let opt = props.get("option").unwrap();
197 tracing::debug!(
198 "option field schema: {}",
199 serde_json::to_string_pretty(opt).unwrap()
200 );
201
202 let opt_type = opt.get("type").and_then(|t| t.as_str());
203 assert_eq!(
204 opt_type,
205 Some("array"),
206 "option must be array type in schema"
207 );
208 }
209
210 #[test]
211 fn test_cli_to_json_with_real_schema() {
212 let schema = schemars::schema_for!(AskUserArgs);
213 let schema_val = serde_json::to_value(schema).unwrap();
214
215 let result = aither_sandbox::cli_to_json(
216 &schema_val,
217 &[
218 "--question".into(),
219 "请选择你喜欢的水果?".into(),
220 "--option".into(),
221 "苹果".into(),
222 "--option".into(),
223 "香蕉".into(),
224 "--option".into(),
225 "橘子".into(),
226 "--option".into(),
227 "梨".into(),
228 ],
229 )
230 .unwrap();
231
232 tracing::debug!(
233 "cli_to_json result: {}",
234 serde_json::to_string_pretty(&result).unwrap()
235 );
236
237 let args: AskUserArgs = serde_json::from_value(result).unwrap();
238 assert_eq!(
239 args.option.len(),
240 4,
241 "expected 4 options, got: {:?}",
242 args.option
243 );
244 assert_eq!(args.option, vec!["苹果", "香蕉", "橘子", "梨"]);
245 }
246}