use std::borrow::Cow;
use askama::Template;
use aither_core::llm::ToolContext;
use aither_core::llm::tool::{Tool, ToolResult};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::external_hook::{self, ExternalHooks};
use crate::tool_request::{
ToolRequest, ToolRequestBroker, ToolRequestQueue, channel as tool_request_channel,
};
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Question {
pub section: String,
pub question: String,
#[serde(alias = "options")]
pub option: Vec<String>,
#[serde(default)]
pub multi_select: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AskUserArgs {
#[serde(default)]
pub question: Option<String>,
#[serde(default, alias = "options", alias = "choices")]
pub option: Vec<String>,
#[serde(default)]
pub multi_select: bool,
#[serde(default)]
pub questions: Vec<Question>,
}
impl AskUserArgs {
#[must_use]
pub fn into_questions(self) -> Vec<Question> {
if !self.questions.is_empty() {
return self.questions;
}
if let Some(q) = self.question {
vec![Question {
section: String::new(),
question: q,
option: self.option,
multi_select: self.multi_select,
}]
} else {
Vec::new()
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct QuestionAnswer {
pub section: String,
pub answer: AnswerValue,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum AnswerValue {
Selected(Vec<String>),
Custom(String),
Skipped,
}
impl std::fmt::Display for AnswerValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Selected(options) => write!(f, "{}", options.join(", ")),
Self::Custom(text) => f.write_str(text),
Self::Skipped => f.write_str("(skipped)"),
}
}
}
#[derive(Template)]
#[template(path = "ask_user_result.txt", escape = "none")]
struct AskUserResultTemplate<'a> {
answers: &'a [QuestionAnswer],
}
pub type AskUserRequest = ToolRequest<AskUserRequestPayload, Vec<QuestionAnswer>>;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AskUserRequestPayload {
pub session_id: String,
pub request: AskUserArgs,
}
pub type AskUserBroker = ToolRequestBroker<AskUserRequestPayload, Vec<QuestionAnswer>>;
pub type AskUserQueue = ToolRequestQueue<AskUserRequestPayload, Vec<QuestionAnswer>>;
#[must_use]
pub fn channel() -> (AskUserBroker, AskUserQueue) {
tool_request_channel()
}
#[derive(Debug, Clone)]
pub struct AskUserTool {
broker: AskUserBroker,
session_id: String,
hooks: Option<ExternalHooks>,
}
impl AskUserTool {
#[must_use]
pub fn new(session_id: impl Into<String>, broker: AskUserBroker) -> Self {
Self {
broker,
session_id: session_id.into(),
hooks: None,
}
}
#[must_use]
pub fn with_hooks(mut self, hooks: ExternalHooks) -> Self {
self.hooks = Some(hooks);
self
}
}
impl Tool for AskUserTool {
fn name(&self) -> Cow<'static, str> {
"ask_user".into()
}
type Arguments = AskUserArgs;
type Res = ToolResult;
async fn call(
&self,
args: Self::Arguments,
_cx: ToolContext,
) -> aither_core::Result<Self::Res> {
let questions = if self.hooks.is_some() {
args.clone().into_questions()
} else {
Vec::new()
};
let response = self
.broker
.request(AskUserRequestPayload {
session_id: self.session_id.clone(),
request: args,
})
.await?;
if let Some(hooks) = &self.hooks {
hooks
.fire(&external_hook::AskUser {
questions,
answers: response.clone(),
})
.await;
}
Ok(ToolResult::text(
AskUserResultTemplate { answers: &response }
.render()
.expect("ask_user result template must render"),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_deser_option_array() {
let json = serde_json::json!({
"question": "请选择你喜欢的水果?",
"option": ["苹果", "香蕉", "橘子", "梨"]
});
let args: AskUserArgs = serde_json::from_value(json).unwrap();
assert_eq!(args.option.len(), 4);
assert_eq!(args.option, vec!["苹果", "香蕉", "橘子", "梨"]);
let questions = args.into_questions();
assert_eq!(questions.len(), 1);
assert_eq!(questions[0].option.len(), 4);
}
#[test]
fn test_schema_option_is_array() {
let schema = schemars::schema_for!(AskUserArgs);
let val = serde_json::to_value(schema).unwrap();
tracing::debug!(
"AskUserArgs schema:\n{}",
serde_json::to_string_pretty(&val).unwrap()
);
let props = val.get("properties").unwrap().as_object().unwrap();
let opt = props.get("option").unwrap();
tracing::debug!(
"option field schema: {}",
serde_json::to_string_pretty(opt).unwrap()
);
let opt_type = opt.get("type").and_then(|t| t.as_str());
assert_eq!(
opt_type,
Some("array"),
"option must be array type in schema"
);
}
#[test]
fn test_cli_to_json_with_real_schema() {
let schema = schemars::schema_for!(AskUserArgs);
let schema_val = serde_json::to_value(schema).unwrap();
let result = aither_sandbox::cli_to_json(
&schema_val,
&[
"--question".into(),
"请选择你喜欢的水果?".into(),
"--option".into(),
"苹果".into(),
"--option".into(),
"香蕉".into(),
"--option".into(),
"橘子".into(),
"--option".into(),
"梨".into(),
],
)
.unwrap();
tracing::debug!(
"cli_to_json result: {}",
serde_json::to_string_pretty(&result).unwrap()
);
let args: AskUserArgs = serde_json::from_value(result).unwrap();
assert_eq!(
args.option.len(),
4,
"expected 4 options, got: {:?}",
args.option
);
assert_eq!(args.option, vec!["苹果", "香蕉", "橘子", "梨"]);
}
}