systemprompt_models/ai/
response_format.rs1use 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 schema: JsonValue,
22 name: Option<String>,
23 strict: Option<bool>,
24 },
25}
26
27impl ResponseFormat {
28 pub const fn json_object() -> Self {
29 Self::JsonObject
30 }
31
32 pub const fn json_schema(schema: JsonValue) -> Self {
33 Self::JsonSchema {
34 schema,
35 name: None,
36 strict: Some(true),
37 }
38 }
39
40 pub const fn json_schema_named(schema: JsonValue, name: String) -> Self {
41 Self::JsonSchema {
42 schema,
43 name: Some(name),
44 strict: Some(true),
45 }
46 }
47
48 pub const fn is_json(&self) -> bool {
49 !matches!(self, Self::Text)
50 }
51
52 pub const fn schema(&self) -> Option<&JsonValue> {
53 match self {
54 Self::JsonSchema { schema, .. } => Some(schema),
55 Self::Text | Self::JsonObject => None,
56 }
57 }
58}
59
60#[derive(Debug, Clone, Default, Serialize, Deserialize)]
61pub struct StructuredOutputOptions {
62 pub response_format: Option<ResponseFormat>,
63 pub max_retries: Option<u8>,
64 pub inject_json_prompt: Option<bool>,
65 pub extraction_pattern: Option<String>,
66 pub validate_schema: Option<bool>,
67}
68
69impl StructuredOutputOptions {
70 pub fn new() -> Self {
71 Self::default()
72 }
73
74 pub fn with_json_object() -> Self {
75 Self {
76 response_format: Some(ResponseFormat::JsonObject),
77 inject_json_prompt: Some(true),
78 validate_schema: Some(false),
79 ..Default::default()
80 }
81 }
82
83 pub fn with_schema(schema: JsonValue) -> Self {
84 Self {
85 response_format: Some(ResponseFormat::JsonSchema {
86 schema,
87 name: None,
88 strict: Some(true),
89 }),
90 inject_json_prompt: Some(true),
91 validate_schema: Some(true),
92 max_retries: Some(3),
93 ..Default::default()
94 }
95 }
96}