Skip to main content

systemprompt_models/ai/
response_format.rs

1//! Structured-output response format options.
2//!
3//! Copyright (c) systemprompt.io — Business Source License 1.1.
4//! See <https://systemprompt.io> for licensing details.
5
6use serde::{Deserialize, Serialize};
7use serde_json::Value as JsonValue;
8
9#[derive(Debug, Clone, Default, Serialize, Deserialize)]
10#[serde(tag = "type")]
11pub enum ResponseFormat {
12    #[serde(rename = "text")]
13    #[default]
14    Text,
15
16    #[serde(rename = "json_object")]
17    JsonObject,
18
19    #[serde(rename = "json_schema")]
20    JsonSchema {
21        // JSON: JSON Schema document for structured output.
22        schema: JsonValue,
23        name: Option<String>,
24        strict: Option<bool>,
25    },
26}
27
28impl ResponseFormat {
29    pub const fn json_object() -> Self {
30        Self::JsonObject
31    }
32
33    // JSON: JSON Schema document for structured output.
34    pub const fn json_schema(schema: JsonValue) -> Self {
35        Self::JsonSchema {
36            schema,
37            name: None,
38            strict: Some(true),
39        }
40    }
41
42    // JSON: JSON Schema document for structured output.
43    pub const fn json_schema_named(schema: JsonValue, name: String) -> Self {
44        Self::JsonSchema {
45            schema,
46            name: Some(name),
47            strict: Some(true),
48        }
49    }
50
51    pub const fn is_json(&self) -> bool {
52        !matches!(self, Self::Text)
53    }
54
55    // JSON: JSON Schema document for structured output.
56    pub const fn schema(&self) -> Option<&JsonValue> {
57        match self {
58            Self::JsonSchema { schema, .. } => Some(schema),
59            Self::Text | Self::JsonObject => None,
60        }
61    }
62}
63
64#[derive(Debug, Clone, Default, Serialize, Deserialize)]
65pub struct StructuredOutputOptions {
66    pub response_format: Option<ResponseFormat>,
67    pub max_retries: Option<u8>,
68    pub inject_json_prompt: Option<bool>,
69    pub extraction_pattern: Option<String>,
70    pub validate_schema: Option<bool>,
71}
72
73impl StructuredOutputOptions {
74    pub fn new() -> Self {
75        Self::default()
76    }
77
78    pub fn with_json_object() -> Self {
79        Self {
80            response_format: Some(ResponseFormat::JsonObject),
81            inject_json_prompt: Some(true),
82            validate_schema: Some(false),
83            ..Default::default()
84        }
85    }
86
87    // JSON: JSON Schema document for structured output.
88    pub fn with_schema(schema: JsonValue) -> Self {
89        Self {
90            response_format: Some(ResponseFormat::JsonSchema {
91                schema,
92                name: None,
93                strict: Some(true),
94            }),
95            inject_json_prompt: Some(true),
96            validate_schema: Some(true),
97            max_retries: Some(3),
98            ..Default::default()
99        }
100    }
101}