Skip to main content

rig_core/
structured_output.rs

1//! Model-facing structured-output policy shared by the agent runtimes: the
2//! synthetic output tool's name and description, the instructions and reprompts
3//! the model sees, and the schema check on an answer.
4//!
5//! ```
6//! use rig_core::structured_output::{output_tool_augmentation, output_tool_name};
7//! let name = output_tool_name(|taken| taken == "final_result");
8//! assert_eq!(name, "final_result_1");
9//! assert!(output_tool_augmentation(&name).contains("`final_result_1`"));
10//! ```
11
12use crate::message::ToolChoice;
13
14/// The output tool's default name.
15pub const OUTPUT_TOOL_NAME: &str = "final_result";
16
17/// The output tool's default description.
18pub const OUTPUT_TOOL_DESCRIPTION: &str = "Call this tool exactly once with your final answer when you are done. Its arguments are the structured result and must satisfy the output schema.";
19
20/// The separator between the preamble and an augmentation.
21pub const AUGMENTATION_SEPARATOR: &str = "\n\n";
22
23/// Appended to the preamble when the answer is asked for through the output
24/// tool named `name`.
25pub fn output_tool_augmentation(name: &str) -> String {
26    format!(
27        "When you have gathered enough information to answer, call the `{name}` tool exactly once with your final answer. Its arguments are the structured result and must satisfy the required schema. Do not return the final answer as plain text."
28    )
29}
30
31/// Appended to the preamble when the answer is asked for as prompted JSON;
32/// `schema` is the schema's canonical rendering.
33pub fn prompted_augmentation(schema: &str) -> String {
34    format!(
35        "Respond with ONLY a single JSON object that conforms to this JSON Schema. Do not include any prose, explanation, or markdown code fences.\n{schema}"
36    )
37}
38
39/// The reprompt when the model answered as text instead of calling the output
40/// tool named `name`.
41pub fn reprompt_text_answer(name: &str) -> String {
42    format!(
43        "Provide your final answer by calling the `{name}` tool with the structured result as its arguments, not as plain text."
44    )
45}
46
47/// The reprompt when the output tool named `name` was called without the
48/// `missing` required fields.
49pub fn reprompt_missing_fields(name: &str, missing: &[String]) -> String {
50    format!(
51        "The `{name}` arguments were missing required field(s): {}. Call `{name}` again with every required field.",
52        missing.join(", ")
53    )
54}
55
56/// The reprompt when the output tool named `name` was called with arguments
57/// that do not fit the output schema, `problems` saying where.
58pub fn reprompt_schema_problems(name: &str, problems: &str) -> String {
59    format!(
60        "The `{name}` arguments do not satisfy the output schema: {problems}. Call `{name}` again with arguments that do."
61    )
62}
63
64/// The output tool's name for a run: the default, numbered from 1 while
65/// `is_taken` reports a collision (`final_result`, `final_result_1`, ...).
66pub fn output_tool_name(is_taken: impl Fn(&str) -> bool) -> String {
67    let mut name = OUTPUT_TOOL_NAME.to_owned();
68    let mut suffix = 1u32;
69    while is_taken(&name) {
70        name = format!("{OUTPUT_TOOL_NAME}_{suffix}");
71        suffix += 1;
72    }
73    name
74}
75
76/// Whether the tool choice permits calling the output tool named `name`.
77/// No choice, `Auto`, `Required`, and a `Specific` set naming it permit it.
78pub fn output_tool_callable(choice: Option<&ToolChoice>, name: &str) -> bool {
79    match choice {
80        None | Some(ToolChoice::Auto | ToolChoice::Required) => true,
81        Some(ToolChoice::None) => false,
82        Some(ToolChoice::Specific { function_names }) => {
83            function_names.iter().any(|named| named == name)
84        }
85    }
86}
87
88/// The top-level required fields of an object schema that `arguments` lacks,
89/// in the schema's order. A non-object argument lacks every one.
90pub fn missing_required_fields(
91    schema: &serde_json::Value,
92    arguments: &serde_json::Value,
93) -> Vec<String> {
94    let object = arguments.as_object();
95    schema
96        .get("required")
97        .and_then(serde_json::Value::as_array)
98        .into_iter()
99        .flatten()
100        .filter_map(serde_json::Value::as_str)
101        .filter(|name| object.is_none_or(|object| !object.contains_key(*name)))
102        .map(str::to_owned)
103        .collect()
104}
105
106/// Checks that `text` carries JSON that fits `schema`, as
107/// [`validate`](crate::tool::validate::validate) checks it: the whole text,
108/// else one value starting at its first `{` or `[` (JSON wrapped in prose or
109/// a markdown fence), as typed prompts read it. Without a schema any JSON
110/// passes. `Err` holds every problem; text with no JSON is one problem for
111/// the whole value.
112pub fn validate_text(
113    schema: Option<&serde_json::Value>,
114    text: &str,
115) -> Result<(), Vec<crate::tool::validate::Problem>> {
116    let value = json_in_text::<serde_json::Value>(text).map_err(|_| {
117        vec![crate::tool::validate::Problem {
118            at: String::new(),
119            what: "no JSON value".to_owned(),
120        }]
121    })?;
122    schema.map_or(Ok(()), |schema| {
123        crate::tool::validate::validate(schema, &value)
124    })
125}
126
127/// Reads `T` from `text` as typed prompts read it: the whole trimmed text,
128/// else one value starting at its first `{` or `[` (JSON wrapped in prose or
129/// a markdown fence).
130///
131/// # Errors
132///
133/// The error of parsing the whole text when it has no `{` or `[`, else the
134/// error of parsing the value that starts there.
135pub fn json_in_text<T: serde::de::DeserializeOwned>(text: &str) -> Result<T, serde_json::Error> {
136    let text = text.trim();
137    serde_json::from_str(text).or_else(|direct| {
138        let Some(rest) = text.find(['{', '[']).and_then(|start| text.get(start..)) else {
139            return Err(direct);
140        };
141        serde_json::Deserializer::from_str(rest)
142            .into_iter()
143            .next()
144            .unwrap_or(Err(direct))
145    })
146}
147
148#[cfg(test)]
149mod tests;