Skip to main content

risingwave_expr/scalar/
ai_decide.rs

1// Copyright 2026 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Fixed question schemas shared by the binder and executor.
16
17use risingwave_common::types::{DataType, JsonbVal, MapType, StructType};
18use serde_json::Value;
19
20use crate::{ExprError, Result};
21
22#[derive(Debug, Clone)]
23pub enum QuestionKind {
24    Noul,
25    Choice(Vec<String>),
26    Score(usize),
27}
28
29#[derive(Debug, Clone)]
30pub struct Question {
31    pub id: String,
32    pub kind: QuestionKind,
33}
34
35#[derive(Debug, Clone)]
36pub struct QuestionSchema(pub Vec<Question>);
37
38impl QuestionSchema {
39    pub fn parse(questions: &JsonbVal) -> Result<Self> {
40        let value = questions.clone().take();
41        let object = value.as_object().filter(|v| !v.is_empty()).ok_or_else(|| {
42            invalid_questions("expected a nonempty object of fixed question definitions")
43        })?;
44        let mut result = Vec::with_capacity(object.len());
45        for (id, definition) in object {
46            let error = |reason: &str| invalid_questions(format!("question {id:?}: {reason}"));
47            if id.trim().is_empty() {
48                return Err(error("name must not be empty"));
49            }
50            let definition = definition
51                .as_object()
52                .ok_or_else(|| error("expected an object"))?;
53            if definition
54                .keys()
55                .any(|k| !matches!(k.as_str(), "type" | "instructions" | "criteria"))
56            {
57                return Err(error(
58                    "unknown field; expected type, instructions or criteria",
59                ));
60            }
61            if definition
62                .get("instructions")
63                .is_some_and(|v| !is_description(v))
64            {
65                return Err(error(
66                    "instructions must be a string, object, array or null",
67                ));
68            }
69            let kind = match definition.get("type").and_then(|v| v.as_str()) {
70                Some("noul") => {
71                    let mut has_description =
72                        definition.get("instructions").is_some_and(|v| !v.is_null());
73                    if let Some(criteria) = definition.get("criteria").filter(|v| !v.is_null()) {
74                        let criteria = criteria.as_object().ok_or_else(|| {
75                            error("probability criteria must be an object or null")
76                        })?;
77                        for (label, description) in criteria {
78                            if !matches!(label.as_str(), "true" | "false") {
79                                return Err(error(
80                                    "probability criteria keys must be true or false",
81                                ));
82                            }
83                            if !is_description(description) {
84                                return Err(error(
85                                    "probability descriptions must be strings, objects, arrays or null",
86                                ));
87                            }
88                            has_description |= !description.is_null();
89                        }
90                    }
91                    if !has_description {
92                        return Err(error(
93                            "probability questions require instructions or at least one non-null outcome description",
94                        ));
95                    }
96                    QuestionKind::Noul
97                }
98                Some("choice") => {
99                    let criteria = definition
100                        .get("criteria")
101                        .and_then(|v| v.as_object())
102                        .filter(|v| (1..=255).contains(&v.len()))
103                        .ok_or_else(|| error("choice requires 1 to 255 named options"))?;
104                    for (label, description) in criteria {
105                        if label.trim().is_empty() || !is_description(description) {
106                            return Err(error(
107                                "option labels must be nonempty; descriptions must be strings, objects, arrays or null",
108                            ));
109                        }
110                    }
111                    QuestionKind::Choice(criteria.keys().cloned().collect())
112                }
113                Some("score") => {
114                    let criteria = definition
115                        .get("criteria")
116                        .and_then(|v| v.as_array())
117                        .filter(|v| (2..=10).contains(&v.len()))
118                        .ok_or_else(|| {
119                            error("score requires 2 to 10 ordered level descriptions")
120                        })?;
121                    let mut seen = std::collections::HashSet::new();
122                    for description in criteria {
123                        if !is_description(description) {
124                            return Err(error(
125                                "score levels must be strings, objects, arrays or null",
126                            ));
127                        }
128                        if !seen.insert(description) {
129                            return Err(error("score levels must be unique"));
130                        }
131                    }
132                    QuestionKind::Score(criteria.len())
133                }
134                _ => return Err(error("type must be noul, choice or score")),
135            };
136            result.push(Question {
137                id: id.clone(),
138                kind,
139            });
140        }
141        Ok(Self(result))
142    }
143
144    pub fn return_type(&self) -> DataType {
145        DataType::Struct(StructType::new(self.0.iter().map(|question| {
146            let ty = match &question.kind {
147                QuestionKind::Noul => DataType::Float64,
148                QuestionKind::Choice(_) => DataType::Struct(StructType::new([
149                    ("choice", DataType::Varchar),
150                    ("confidence", DataType::Float64),
151                    (
152                        "probabilities",
153                        MapType::from_kv(DataType::Varchar, DataType::Float64).into(),
154                    ),
155                ])),
156                QuestionKind::Score(_) => DataType::Struct(StructType::new([
157                    ("score", DataType::Float64),
158                    ("confidence", DataType::Float64),
159                    ("probabilities", DataType::list(DataType::Float64)),
160                ])),
161            };
162            (question.id.clone(), ty)
163        })))
164    }
165}
166
167// EntryType constrains the outer shape, while nested JSON content is passed through.
168fn is_description(value: &Value) -> bool {
169    matches!(
170        value,
171        Value::String(_) | Value::Object(_) | Value::Array(_) | Value::Null
172    )
173}
174
175fn invalid_questions(reason: impl Into<String>) -> ExprError {
176    ExprError::InvalidParam {
177        name: "ai_decide questions",
178        reason: reason.into().into(),
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use serde_json::json;
185
186    use super::*;
187
188    #[test]
189    fn fixed_questions_infer_named_fields_and_reject_invalid_definitions() {
190        let schema = QuestionSchema::parse(&r#"{
191            "refund":{"type":"noul","instructions":"Refund requested?"},
192            "team":{"type":"choice","instructions":"Which team?","criteria":{"billing":"Payments","tech":null}},
193            "urgency":{"type":"score","instructions":"How urgent?","criteria":["Routine","Blocking"]}
194        }"#.parse().unwrap()).unwrap();
195        let ty = schema.return_type();
196        let fields: Vec<_> = ty.as_struct().iter().collect();
197        assert_eq!(fields[0], ("refund", &DataType::Float64));
198        assert_eq!(fields[1].0, "team");
199        assert_eq!(
200            fields[1].1.as_struct().names().collect::<Vec<_>>(),
201            vec!["choice", "confidence", "probabilities"]
202        );
203        assert_eq!(fields[2].0, "urgency");
204        for json in [
205            "null",
206            "[]",
207            "{}",
208            r#"{"":{"type":"noul","instructions":"Question?"}}"#,
209            r#"{"q":{"type":"noul"}}"#,
210            r#"{"q":{"type":"text","instructions":"Question?"}}"#,
211            r#"{"q":{"type":"noul","instructions":"Question?","unknown":true}}"#,
212            r#"{"q":{"type":"choice","instructions":"Question?","criteria":{}}}"#,
213            r#"{"q":{"type":"choice","instructions":"Question?","criteria":{"a":42}}}"#,
214            r#"{"q":{"type":"score","instructions":"Question?","criteria":["same","same"]}}"#,
215            r#"{"q":{"type":"score","instructions":"Question?","criteria":["only"]}}"#,
216        ] {
217            assert!(
218                QuestionSchema::parse(&json.parse().unwrap()).is_err(),
219                "{json}"
220            );
221        }
222    }
223
224    #[test]
225    fn structured_descriptions_preserve_result_types() {
226        for description in [
227            json!("Question?"),
228            json!(""),
229            json!({"question": "Resolved?", "examples": [true, 42, null]}),
230            json!(["Resolved?", {"minimum": 1}, false, null]),
231            json!({}),
232            json!([]),
233            Value::Null,
234        ] {
235            let questions = json!({
236                "probability": {"type": "noul", "instructions": description,
237                    "criteria": {"true": description, "false": "Negative outcome"}},
238                "choice": {"type": "choice", "instructions": description,
239                    "criteria": {"yes": description, "no": description}},
240                "score": {"type": "score", "instructions": description,
241                    "criteria": [description, "Another level"]}
242            });
243            let schema = QuestionSchema::parse(&JsonbVal::from(questions)).unwrap();
244            let plain = QuestionSchema::parse(&JsonbVal::from(json!({
245                "probability": {"type": "noul", "instructions": "Question?"},
246                "choice": {"type": "choice", "instructions": "Question?",
247                    "criteria": {"yes": "Yes", "no": "No"}},
248                "score": {"type": "score", "instructions": "Question?",
249                    "criteria": ["First", "Second"]}
250            })))
251            .unwrap();
252            assert_eq!(schema.return_type(), plain.return_type());
253        }
254    }
255
256    #[test]
257    fn optional_instructions_require_a_noul_description() {
258        for instructions in [None, Some(Value::Null)] {
259            for definition in [
260                json!({"type": "noul", "criteria": {"true": "Yes"}}),
261                json!({"type": "noul", "criteria": {"false": ["No"], "true": null}}),
262                json!({"type": "noul", "criteria": {"true": {}}}),
263                json!({"type": "choice", "criteria": {"yes": null, "no": null}}),
264                json!({"type": "score", "criteria": ["Low", "High"]}),
265            ] {
266                let mut definition = definition;
267                if let Some(instructions) = &instructions {
268                    definition["instructions"] = instructions.clone();
269                }
270                assert!(QuestionSchema::parse(&JsonbVal::from(json!({"q": definition}))).is_ok());
271            }
272            for definition in [
273                json!({"type": "noul"}),
274                json!({"type": "noul", "criteria": null}),
275                json!({"type": "noul", "criteria": {}}),
276                json!({"type": "noul", "criteria": {"true": null, "false": null}}),
277            ] {
278                let mut definition = definition;
279                if let Some(instructions) = &instructions {
280                    definition["instructions"] = instructions.clone();
281                }
282                let error =
283                    QuestionSchema::parse(&JsonbVal::from(json!({"q": definition}))).unwrap_err();
284                assert!(matches!(error, ExprError::InvalidParam { reason, .. }
285                    if reason.contains("at least one non-null outcome description")));
286            }
287        }
288        // Empty containers and strings are descriptions; only null means absent.
289        for instructions in [json!(""), json!({}), json!([])] {
290            QuestionSchema::parse(&JsonbVal::from(json!({
291                "q": {"type": "noul", "instructions": instructions, "criteria": {}}
292            })))
293            .unwrap();
294        }
295    }
296
297    #[test]
298    fn structured_descriptions_still_reject_invalid_shapes() {
299        for definition in [
300            json!({"type": "noul", "instructions": true}),
301            json!({"type": "noul", "instructions": 42}),
302            json!({"type": "noul", "instructions": [], "criteria": []}),
303            json!({"type": "noul", "instructions": {}, "criteria": {"yes": "Yes"}}),
304            json!({"type": "noul", "instructions": null, "criteria": {"true": true}}),
305            json!({"type": "noul", "instructions": null, "criteria": {"false": 0}}),
306            json!({"type": "choice", "instructions": {}, "criteria": {"": {}}}),
307            json!({"type": "choice", "instructions": [], "criteria": {"yes": false}}),
308            json!({"type": "score", "instructions": {}, "criteria": [null, 42]}),
309            json!({"type": "score", "instructions": [], "criteria": [null, false]}),
310            json!({"type": "score", "instructions": null, "criteria": [{"same": 1}, {"same": 1}]}),
311        ] {
312            assert!(
313                QuestionSchema::parse(&JsonbVal::from(json!({"q": definition}))).is_err(),
314                "{definition}"
315            );
316        }
317    }
318}