Skip to main content

systemprompt_models/ai/
response_format.rs

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