rstructor 0.4.0

Get structured, validated data out of LLMs as native Rust structs and enums. Derive a type and rstructor generates the JSON Schema, prompts the model, parses the reply, and retries on validation errors — across OpenAI, Anthropic Claude, Google Gemini, and xAI Grok. The Rust answer to Python's Pydantic + Instructor.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use serde::Serialize;

use crate::backend::ChatMessage;
use crate::error::{ApiErrorKind, RStructorError, Result};

#[derive(Debug, Serialize)]
#[serde(untagged)]
pub(crate) enum OpenAICompatibleMessageContent {
    Text(String),
    Parts(Vec<OpenAICompatibleMessagePart>),
}

#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(crate) enum OpenAICompatibleMessagePart {
    Text { text: String },
    ImageUrl { image_url: OpenAICompatibleImageUrl },
    File { file: OpenAICompatibleFile },
}

#[derive(Debug, Serialize)]
pub(crate) struct OpenAICompatibleImageUrl {
    pub(crate) url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) detail: Option<String>,
}

/// A file content part for OpenAI chat completions (PDF input).
///
/// See <https://platform.openai.com/docs/guides/pdf-files>: the part is
/// `{"type": "file", "file": {"filename": ..., "file_data": "data:application/pdf;base64,..."}}`.
#[derive(Debug, Serialize)]
pub(crate) struct OpenAICompatibleFile {
    pub(crate) filename: String,
    pub(crate) file_data: String,
}

#[derive(Debug, Serialize)]
#[serde(untagged)]
pub(crate) enum AnthropicMessageContent {
    Text(String),
    Blocks(Vec<AnthropicContentBlock>),
}

#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(crate) enum AnthropicContentBlock {
    Text {
        text: String,
    },
    Image {
        source: AnthropicMediaSource,
    },
    /// A PDF document block, see
    /// <https://docs.anthropic.com/en/docs/build-with-claude/pdf-support>:
    /// `{"type": "document", "source": {"type": "base64", "media_type": "application/pdf", "data": ...}}`
    /// or `{"type": "document", "source": {"type": "url", "url": ...}}`.
    Document {
        source: AnthropicMediaSource,
    },
}

/// Source of an Anthropic `image` or `document` block (both share this shape).
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(crate) enum AnthropicMediaSource {
    Base64 { media_type: String, data: String },
    Url { url: String },
}

pub(crate) fn build_openai_compatible_message_content(
    msg: &ChatMessage,
    provider_name: &str,
) -> Result<OpenAICompatibleMessageContent> {
    if msg.media.is_empty() {
        return Ok(OpenAICompatibleMessageContent::Text(msg.content.clone()));
    }

    let mut parts = Vec::new();
    if !msg.content.is_empty() {
        parts.push(OpenAICompatibleMessagePart::Text {
            text: msg.content.clone(),
        });
    }

    for media in &msg.media {
        if media.mime_type.starts_with("image/") {
            let url = media_to_url(media, provider_name)?;
            parts.push(OpenAICompatibleMessagePart::ImageUrl {
                image_url: OpenAICompatibleImageUrl {
                    url,
                    detail: Some("auto".to_string()),
                },
            });
        } else if media.mime_type == "application/pdf" {
            parts.push(openai_compatible_pdf_part(media, provider_name)?);
        } else {
            return Err(unsupported_media_type(media, provider_name));
        }
    }

    Ok(OpenAICompatibleMessageContent::Parts(parts))
}

/// Build the PDF content part for an OpenAI-compatible chat completions request,
/// or a clear error for providers/sources without a documented PDF pathway.
fn openai_compatible_pdf_part(
    media: &crate::backend::client::MediaFile,
    provider_name: &str,
) -> Result<OpenAICompatibleMessagePart> {
    // xAI's chat completions API only documents text and image content parts
    // (https://docs.x.ai/docs/guides/image-understanding); there is no file or
    // document part, so sending a PDF would be silently mislabeled or rejected.
    if provider_name == "Grok" {
        return Err(RStructorError::api_error(
            provider_name,
            ApiErrorKind::BadRequest {
                details: "PDF attachments are not supported for Grok: the xAI chat \
                          completions API only accepts text and image content parts. \
                          Extract the PDF's text or render its pages to images and \
                          attach those instead"
                    .to_string(),
            },
        ));
    }

    if let Some(data) = media.data.as_ref() {
        if data.is_empty() {
            return Err(RStructorError::api_error(
                provider_name,
                ApiErrorKind::BadRequest {
                    details: "MediaFile inline data cannot be empty".to_string(),
                },
            ));
        }
        // Chat completions accept PDFs as a `file` part with base64 `file_data`
        // (https://platform.openai.com/docs/guides/pdf-files).
        Ok(OpenAICompatibleMessagePart::File {
            file: OpenAICompatibleFile {
                filename: "document.pdf".to_string(),
                file_data: format!("data:{};base64,{}", media.mime_type, data),
            },
        })
    } else if !media.uri.is_empty() {
        // Chat completions do not accept remote file URLs (only `file_data` or an
        // uploaded `file_id`); see https://platform.openai.com/docs/guides/pdf-files.
        Err(RStructorError::api_error(
            provider_name,
            ApiErrorKind::BadRequest {
                details: format!(
                    "{provider_name} chat completions does not support URL-based PDF \
                     attachments; download the file and attach the bytes inline with \
                     MediaFile::from_bytes(bytes, \"application/pdf\") instead"
                ),
            },
        ))
    } else {
        Err(RStructorError::api_error(
            provider_name,
            ApiErrorKind::BadRequest {
                details: "MediaFile must include either inline data or uri".to_string(),
            },
        ))
    }
}

/// Error for MIME types with no documented attachment pathway on this provider.
fn unsupported_media_type(
    media: &crate::backend::client::MediaFile,
    provider_name: &str,
) -> RStructorError {
    let supported = if provider_name == "Grok" {
        "image/*"
    } else {
        "image/* and application/pdf"
    };
    RStructorError::api_error(
        provider_name,
        ApiErrorKind::BadRequest {
            details: format!(
                "unsupported media type {:?} for {provider_name}: only {supported} \
                 attachments are supported on this provider",
                media.mime_type,
            ),
        },
    )
}

pub(crate) fn build_anthropic_message_content(
    msg: &ChatMessage,
) -> Result<AnthropicMessageContent> {
    if msg.media.is_empty() {
        return Ok(AnthropicMessageContent::Text(msg.content.clone()));
    }

    let mut blocks = Vec::new();
    if !msg.content.is_empty() {
        blocks.push(AnthropicContentBlock::Text {
            text: msg.content.clone(),
        });
    }

    for media in &msg.media {
        let is_image = media.mime_type.starts_with("image/");
        let is_pdf = media.mime_type == "application/pdf";

        let source = if let Some(data) = media.data.as_ref() {
            if data.is_empty() {
                return Err(RStructorError::api_error(
                    "Anthropic",
                    ApiErrorKind::BadRequest {
                        details: "MediaFile inline data cannot be empty".to_string(),
                    },
                ));
            }
            if media.mime_type.is_empty() {
                return Err(RStructorError::api_error(
                    "Anthropic",
                    ApiErrorKind::BadRequest {
                        details: "MediaFile mime_type cannot be empty".to_string(),
                    },
                ));
            }
            AnthropicMediaSource::Base64 {
                media_type: media.mime_type.clone(),
                data: data.clone(),
            }
        } else if !media.uri.is_empty() {
            AnthropicMediaSource::Url {
                url: media.uri.clone(),
            }
        } else {
            return Err(RStructorError::api_error(
                "Anthropic",
                ApiErrorKind::BadRequest {
                    details: "MediaFile must include either inline data or uri".to_string(),
                },
            ));
        };

        if is_image {
            blocks.push(AnthropicContentBlock::Image { source });
        } else if is_pdf {
            // PDFs go in a `document` block, never an `image` block; see
            // https://docs.anthropic.com/en/docs/build-with-claude/pdf-support.
            blocks.push(AnthropicContentBlock::Document { source });
        } else {
            return Err(unsupported_media_type(media, "Anthropic"));
        }
    }

    Ok(AnthropicMessageContent::Blocks(blocks))
}

fn media_to_url(media: &crate::backend::client::MediaFile, provider_name: &str) -> Result<String> {
    if let Some(data) = media.data.as_ref() {
        if data.is_empty() {
            return Err(RStructorError::api_error(
                provider_name,
                ApiErrorKind::BadRequest {
                    details: "MediaFile inline data cannot be empty".to_string(),
                },
            ));
        }
        if media.mime_type.is_empty() {
            return Err(RStructorError::api_error(
                provider_name,
                ApiErrorKind::BadRequest {
                    details: "MediaFile mime_type cannot be empty".to_string(),
                },
            ));
        }
        Ok(format!("data:{};base64,{}", media.mime_type, data))
    } else if !media.uri.is_empty() {
        Ok(media.uri.clone())
    } else {
        Err(RStructorError::api_error(
            provider_name,
            ApiErrorKind::BadRequest {
                details: "MediaFile must include either inline data or uri".to_string(),
            },
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::MediaFile;

    #[test]
    fn test_openai_compatible_content_text_only() {
        let msg = ChatMessage::user("hello");
        let content =
            build_openai_compatible_message_content(&msg, "OpenAI").expect("content should build");
        let json = serde_json::to_value(&content).expect("content should serialize");
        assert_eq!(json, serde_json::json!("hello"));
    }

    #[test]
    fn test_openai_compatible_content_with_media() {
        let msg = ChatMessage::user_with_media(
            "describe image",
            vec![MediaFile::from_bytes(b"abc", "image/png")],
        );
        let content =
            build_openai_compatible_message_content(&msg, "OpenAI").expect("content should build");
        let json = serde_json::to_value(&content).expect("content should serialize");
        assert_eq!(json[0]["type"], "text");
        assert_eq!(json[1]["type"], "image_url");
        assert_eq!(json[1]["image_url"]["url"], "data:image/png;base64,YWJj");
    }

    #[test]
    fn test_anthropic_content_text_only() {
        let msg = ChatMessage::user("hello");
        let content = build_anthropic_message_content(&msg).expect("content should build");
        let json = serde_json::to_value(&content).expect("content should serialize");
        assert_eq!(json, serde_json::json!("hello"));
    }

    #[test]
    fn test_anthropic_content_with_inline_media() {
        let msg = ChatMessage::user_with_media(
            "describe image",
            vec![MediaFile::from_bytes(b"abc", "image/png")],
        );
        let content = build_anthropic_message_content(&msg).expect("content should build");
        let json = serde_json::to_value(&content).expect("content should serialize");
        assert_eq!(json[0]["type"], "text");
        assert_eq!(json[1]["type"], "image");
        assert_eq!(json[1]["source"]["type"], "base64");
        assert_eq!(json[1]["source"]["media_type"], "image/png");
        assert_eq!(json[1]["source"]["data"], "YWJj");
    }

    #[test]
    fn test_anthropic_content_with_url_image() {
        let msg = ChatMessage::user_with_media(
            "describe image",
            vec![MediaFile::new("https://example.com/cat.png", "image/png")],
        );
        let content = build_anthropic_message_content(&msg).expect("content should build");
        let json = serde_json::to_value(&content).expect("content should serialize");
        assert_eq!(json[1]["type"], "image");
        assert_eq!(
            json[1]["source"],
            serde_json::json!({"type": "url", "url": "https://example.com/cat.png"})
        );
    }

    // ---- PDF routing: OpenAI ----

    #[test]
    fn test_openai_inline_pdf_becomes_file_part() {
        let msg = ChatMessage::user_with_media(
            "summarize",
            vec![MediaFile::from_bytes(b"%PDF", "application/pdf")],
        );
        let content =
            build_openai_compatible_message_content(&msg, "OpenAI").expect("content should build");
        let json = serde_json::to_value(&content).expect("content should serialize");
        assert_eq!(json[0]["type"], "text");
        assert_eq!(
            json[1],
            serde_json::json!({
                "type": "file",
                "file": {
                    "filename": "document.pdf",
                    "file_data": "data:application/pdf;base64,JVBERg==",
                }
            })
        );
    }

    #[test]
    fn test_openai_url_pdf_is_a_clear_error() {
        let msg = ChatMessage::user_with_media(
            "summarize",
            vec![MediaFile::new(
                "https://example.com/report.pdf",
                "application/pdf",
            )],
        );
        let err = build_openai_compatible_message_content(&msg, "OpenAI")
            .expect_err("URL-based PDFs are not supported by chat completions");
        let text = err.to_string();
        assert!(
            text.contains("URL-based PDF") && text.contains("MediaFile::from_bytes"),
            "error should explain the fix, got: {text}"
        );
    }

    #[test]
    fn test_openai_non_image_non_pdf_is_a_clear_error() {
        let msg = ChatMessage::user_with_media(
            "transcribe",
            vec![MediaFile::from_bytes(b"abc", "audio/mpeg")],
        );
        let err = build_openai_compatible_message_content(&msg, "OpenAI")
            .expect_err("audio attachments have no chat-completions pathway");
        let text = err.to_string();
        assert!(
            text.contains("unsupported media type") && text.contains("audio/mpeg"),
            "error should name the offending MIME type, got: {text}"
        );
    }

    // ---- PDF routing: Grok ----

    #[test]
    fn test_grok_inline_pdf_is_a_clear_error_not_an_image_url() {
        let msg = ChatMessage::user_with_media(
            "summarize",
            vec![MediaFile::from_bytes(b"%PDF", "application/pdf")],
        );
        let err = build_openai_compatible_message_content(&msg, "Grok")
            .expect_err("Grok has no documented PDF pathway");
        let text = err.to_string();
        assert!(
            text.contains("PDF attachments are not supported for Grok"),
            "error should say PDFs are unsupported on Grok, got: {text}"
        );
    }

    #[test]
    fn test_grok_url_pdf_is_a_clear_error() {
        let msg = ChatMessage::user_with_media(
            "summarize",
            vec![MediaFile::new(
                "https://example.com/report.pdf",
                "application/pdf",
            )],
        );
        let err = build_openai_compatible_message_content(&msg, "Grok")
            .expect_err("Grok has no documented PDF pathway");
        assert!(
            err.to_string()
                .contains("PDF attachments are not supported for Grok")
        );
    }

    #[test]
    fn test_grok_images_still_use_image_url() {
        let msg = ChatMessage::user_with_media(
            "describe image",
            vec![MediaFile::from_bytes(b"abc", "image/jpeg")],
        );
        let content =
            build_openai_compatible_message_content(&msg, "Grok").expect("content should build");
        let json = serde_json::to_value(&content).expect("content should serialize");
        assert_eq!(json[1]["type"], "image_url");
        assert_eq!(json[1]["image_url"]["url"], "data:image/jpeg;base64,YWJj");
    }

    // ---- PDF routing: Anthropic ----

    #[test]
    fn test_anthropic_inline_pdf_becomes_document_block() {
        let msg = ChatMessage::user_with_media(
            "summarize",
            vec![MediaFile::from_bytes(b"%PDF", "application/pdf")],
        );
        let content = build_anthropic_message_content(&msg).expect("content should build");
        let json = serde_json::to_value(&content).expect("content should serialize");
        assert_eq!(json[0]["type"], "text");
        assert_eq!(
            json[1],
            serde_json::json!({
                "type": "document",
                "source": {
                    "type": "base64",
                    "media_type": "application/pdf",
                    "data": "JVBERg==",
                }
            })
        );
    }

    #[test]
    fn test_anthropic_url_pdf_becomes_url_document_block() {
        let msg = ChatMessage::user_with_media(
            "summarize",
            vec![MediaFile::new(
                "https://example.com/report.pdf",
                "application/pdf",
            )],
        );
        let content = build_anthropic_message_content(&msg).expect("content should build");
        let json = serde_json::to_value(&content).expect("content should serialize");
        assert_eq!(
            json[1],
            serde_json::json!({
                "type": "document",
                "source": {
                    "type": "url",
                    "url": "https://example.com/report.pdf",
                }
            })
        );
    }

    #[test]
    fn test_anthropic_non_image_non_pdf_is_a_clear_error() {
        let msg = ChatMessage::user_with_media(
            "transcribe",
            vec![MediaFile::from_bytes(b"abc", "audio/mpeg")],
        );
        let err = build_anthropic_message_content(&msg)
            .expect_err("audio attachments have no Messages API pathway");
        let text = err.to_string();
        assert!(
            text.contains("unsupported media type") && text.contains("audio/mpeg"),
            "error should name the offending MIME type, got: {text}"
        );
    }
}