risingwave_frontend/binder/expr/function/
ai_decide.rs1use risingwave_common::types::{DataType, Datum, JsonbVal, ScalarImpl, ScalarRefImpl};
16use risingwave_expr::scalar::ai_decide::QuestionSchema;
17use serde_json::{Map, Value, json};
18use thiserror_ext::AsReport;
19
20use crate::error::{ErrorCode, Result};
21use crate::expr::{ExprImpl, ExprType, FunctionCall, Literal};
22
23fn invalid(reason: impl Into<String>) -> crate::error::RwError {
24 ErrorCode::InvalidInputSyntax(reason.into()).into()
25}
26
27fn constant(expr: &ExprImpl, argument: &str) -> Result<Datum> {
28 expr.try_fold_const()
29 .ok_or_else(|| invalid(format!("{argument} must be constant")))?
30}
31
32fn json_constant(expr: &ExprImpl, argument: &str) -> Result<JsonbVal> {
33 match constant(expr, argument)? {
34 Some(ScalarImpl::Jsonb(value)) => Ok(value),
35 _ => Err(invalid(format!("{argument} must be non-null JSONB"))),
36 }
37}
38
39fn text_constant(expr: &ExprImpl, argument: &str) -> Result<String> {
40 match constant(expr, argument)? {
41 Some(ScalarImpl::Utf8(value)) if !value.trim().is_empty() => Ok(value.into()),
42 _ => Err(invalid(format!("{argument} must be a nonempty string"))),
43 }
44}
45
46fn literal(value: Value) -> ExprImpl {
47 Literal::new(Some(JsonbVal::from(value).into()), DataType::Jsonb).into()
48}
49
50pub(super) fn bind(mut inputs: Vec<ExprImpl>) -> Result<ExprImpl> {
51 if inputs.len() != 5 {
52 return Err(invalid("ai_decide expects exactly five arguments"));
53 }
54 for (index, ty) in [
55 DataType::Jsonb,
56 DataType::Varchar,
57 DataType::Varchar,
58 DataType::Jsonb,
59 DataType::Varchar,
60 ]
61 .into_iter()
62 .enumerate()
63 {
64 inputs[index].cast_implicit_mut(&ty)?;
65 }
66 let questions = json_constant(&inputs[3], "ai_decide questions")?;
67 let schema = QuestionSchema::parse(&questions).map_err(|e| invalid(e.to_report_string()))?;
68 inputs[3] = Literal::new(Some(questions.into()), DataType::Jsonb).into();
70 Ok(FunctionCall::new_unchecked(ExprType::AiDecide, inputs, schema.return_type()).into())
71}
72
73pub(super) fn option(inputs: Vec<ExprImpl>) -> Result<ExprImpl> {
75 let [label, description]: [_; 2] = inputs
76 .try_into()
77 .map_err(|_| invalid("ai_option expects label and description"))?;
78 let label = text_constant(&label, "ai_option label")?;
79 let description = match constant(&description, "ai_option description")? {
80 None => Value::Null,
81 Some(ScalarImpl::Utf8(value)) if !value.trim().is_empty() => Value::String(value.into()),
82 _ => {
83 return Err(invalid(
84 "ai_option description must be a nonempty string or NULL",
85 ));
86 }
87 };
88 Ok(literal(json!({"label": label, "description": description})))
89}
90
91pub(super) fn question(kind: &str, inputs: Vec<ExprImpl>) -> Result<ExprImpl> {
92 let expected = if kind == "noul" { 2 } else { 3 };
93 if inputs.len() != expected {
94 return Err(invalid(format!(
95 "ai question constructor expects {expected} arguments"
96 )));
97 }
98 let id = text_constant(&inputs[0], "question name")?;
99 let instructions = text_constant(&inputs[1], "question instructions")?;
100 let mut definition = json!({"type": kind, "instructions": instructions});
101 if kind != "noul" {
102 let Some(ScalarImpl::List(criteria)) = constant(&inputs[2], "question criteria")? else {
103 return Err(invalid("question criteria must be a non-null array"));
104 };
105 if kind == "choice" {
106 let mut options = Map::new();
107 for item in criteria.iter() {
108 let (label, description) = match item {
109 Some(ScalarRefImpl::Utf8(label)) => (label.to_owned(), Value::Null),
110 Some(ScalarRefImpl::Jsonb(value)) => {
111 let value = JsonbVal::from(value).take();
112 let object =
113 value.as_object().filter(|v| v.len() == 2).ok_or_else(|| {
114 invalid("choice options must be labels or ai_option values")
115 })?;
116 let label = object
117 .get("label")
118 .and_then(Value::as_str)
119 .ok_or_else(|| invalid("choice option requires a string label"))?;
120 let description = object
121 .get("description")
122 .ok_or_else(|| invalid("choice option requires a description"))?;
123 (label.to_owned(), description.clone())
124 }
125 _ => {
126 return Err(invalid(
127 "choice options must be non-null labels or ai_option values",
128 ));
129 }
130 };
131 if options.insert(label, description).is_some() {
132 return Err(invalid(format!("question {id:?}: duplicate choice label")));
133 }
134 }
135 definition["criteria"] = Value::Object(options);
136 } else {
137 let levels = criteria
138 .iter()
139 .map(|item| match item {
140 Some(ScalarRefImpl::Utf8(value)) if !value.trim().is_empty() => {
141 Ok(Value::String(value.to_owned()))
142 }
143 _ => Err(invalid("score levels must be nonempty strings")),
144 })
145 .collect::<Result<Vec<_>>>()?;
146 definition["criteria"] = Value::Array(levels);
147 }
148 }
149 let result = json!({id: definition});
150 QuestionSchema::parse(&JsonbVal::from(result.clone()))
151 .map_err(|e| invalid(e.to_report_string()))?;
152 Ok(literal(result))
153}
154
155pub(super) fn questions(inputs: Vec<ExprImpl>) -> Result<ExprImpl> {
156 let mut questions = Map::new();
157 for input in inputs {
158 let value = json_constant(&input, "ai_questions argument")?.take();
159 let object = value
160 .as_object()
161 .ok_or_else(|| invalid("ai_questions expects question definitions"))?;
162 for (id, question) in object {
163 if questions.insert(id.clone(), question.clone()).is_some() {
164 return Err(invalid(format!(
165 "ai_questions: duplicate question name {id:?}"
166 )));
167 }
168 }
169 }
170 let result = Value::Object(questions);
171 QuestionSchema::parse(&JsonbVal::from(result.clone()))
172 .map_err(|e| invalid(e.to_report_string()))?;
173 Ok(literal(result))
174}