rig_core/
structured_output.rs1use crate::message::ToolChoice;
13
14pub const OUTPUT_TOOL_NAME: &str = "final_result";
16
17pub 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
20pub const AUGMENTATION_SEPARATOR: &str = "\n\n";
22
23pub 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
31pub 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
39pub 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
47pub 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
56pub 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
64pub 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
76pub 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
88pub 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
106pub 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
127pub 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;