rstructor 0.5.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
//! Offline tests for [`MockClient`]. None of these touch the network or need an
//! API key. The core suite runs in any build with the `mock` feature (including
//! schema-only); the streaming/tools/builder sections gate on their features.

#![cfg(feature = "mock")]

use rstructor::{Instructor, LLMClient, MockClient, MockResponse, RStructorError, RequestKind};
use serde::{Deserialize, Serialize};

#[derive(Instructor, Serialize, Deserialize, Debug, PartialEq)]
#[llm(validate = "validate_movie")]
struct Movie {
    title: String,
    year: u16,
}

#[derive(Instructor, Serialize, Deserialize, Debug, PartialEq)]
struct Portfolio {
    portfolio_id: String,
    positions: Vec<Position>,
}

#[derive(Instructor, Serialize, Deserialize, Debug, PartialEq)]
struct Position {
    symbol: String,
    quantity: i64,
}

fn validate_movie(m: &Movie) -> rstructor::Result<()> {
    if m.year < 1888 {
        return Err(RStructorError::ValidationError(format!(
            "year {} predates cinema",
            m.year
        )));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Core: materialize / generate / metadata / list_models / recording
// ---------------------------------------------------------------------------

#[tokio::test]
async fn generate_returns_scripted_text() {
    let client = MockClient::new().with_response("a haiku");
    assert_eq!(client.generate("write a haiku").await.unwrap(), "a haiku");
    assert_eq!(client.last_request().unwrap().kind, RequestKind::Generate);
}

#[tokio::test]
async fn generate_with_metadata_usage_is_none_by_default() {
    let client = MockClient::new().with_response("hello");
    let result = client.generate_with_metadata("p").await.unwrap();
    assert_eq!(result.text, "hello");
    assert!(result.usage.is_none());
}

#[tokio::test]
async fn metadata_usage_can_be_configured() {
    use rstructor::TokenUsage;
    let client = MockClient::new()
        .with_response(r#"{"title":"A","year":2000}"#)
        .with_usage(TokenUsage::new("mock-model", 11, 22));
    let result = client
        .materialize_with_metadata::<Movie>("p")
        .await
        .unwrap();
    assert_eq!(result.data.year, 2000);
    let usage = result.usage.unwrap();
    assert_eq!(usage.input_tokens, 11);
    assert_eq!(usage.total_tokens(), 33);
}

#[tokio::test]
async fn attempt_report_uses_per_response_usage_for_realistic_reask_fixture() {
    use rstructor::{AttemptKind, AttemptOutcome, TokenUsage};

    let client = MockClient::new()
        .with_response_and_usage(
            include_str!("fixtures/structured/portfolio_invalid_quantity.json"),
            TokenUsage::new("mock-risk-router-v1", 90, 15),
        )
        .with_response_and_usage(
            include_str!("fixtures/structured/portfolio_valid.json"),
            TokenUsage::new("mock-risk-router-v2", 120, 18),
        )
        .with_retries(1);

    let report = client
        .materialize_with_attempts::<Portfolio>("reconcile positions")
        .await
        .unwrap();

    assert_eq!(report.data.positions[1].quantity, -240);
    assert_eq!(report.attempts.len(), 2);
    assert_eq!(report.attempts[0].kind, AttemptKind::Semantic);
    assert!(matches!(
        report.attempts[0].outcome,
        AttemptOutcome::Failed {
            disposition: rstructor::RetryDisposition::Retried,
            ..
        }
    ));
    assert_eq!(report.attempts[1].outcome, AttemptOutcome::Succeeded);
    assert_eq!(
        report.cumulative_usage.as_ref().unwrap().total_tokens(),
        243
    );
    assert_eq!(
        report.final_usage.as_ref().unwrap().model,
        "mock-risk-router-v2"
    );
    assert_eq!(
        client.last_request().unwrap().kind,
        RequestKind::MaterializeWithAttempts
    );
    assert_eq!(client.request_count(), 1);
}

#[tokio::test]
async fn attempt_exhaustion_keeps_usage_and_final_decode_error() {
    use rstructor::{AttemptOutcome, TokenUsage};

    let invalid = include_str!("fixtures/structured/portfolio_invalid_quantity.json");
    let client = MockClient::new()
        .with_response_and_usage(invalid, TokenUsage::new("mock-risk-router", 80, 10))
        .with_response_and_usage(invalid, TokenUsage::new("mock-risk-router", 100, 12))
        .with_retries(1);

    let failure = client
        .materialize_with_attempts::<Portfolio>("reconcile positions")
        .await
        .unwrap_err();

    assert!(matches!(
        failure.error(),
        RStructorError::OutputDecodeError { path, .. }
            if path == "$.positions[1].quantity"
    ));
    assert_eq!(failure.attempts.len(), 2);
    assert!(matches!(
        failure.attempts[1].outcome,
        AttemptOutcome::Failed {
            disposition: rstructor::RetryDisposition::BudgetExhausted,
            ..
        }
    ));
    assert_eq!(
        failure.cumulative_usage.as_ref().unwrap().total_tokens(),
        202
    );
}

#[tokio::test]
async fn scripted_transport_error_retains_usage_without_retrying() {
    use rstructor::{ApiErrorKind, AttemptKind, AttemptOutcome, RetryDisposition, TokenUsage};

    let client = MockClient::new()
        .with_response_and_usage(
            MockResponse::Error(RStructorError::api_error(
                "MockProvider",
                ApiErrorKind::AuthenticationFailed,
            )),
            TokenUsage::new("mock-risk-router", 22, 3),
        )
        .with_retries(3);

    let failure = client
        .materialize_with_attempts::<Portfolio>("reconcile positions")
        .await
        .unwrap_err();

    assert!(failure.attempts_complete);
    assert_eq!(failure.attempts.len(), 1);
    assert_eq!(failure.attempts[0].kind, AttemptKind::Transport);
    assert!(matches!(
        failure.attempts[0].outcome,
        AttemptOutcome::Failed {
            disposition: RetryDisposition::NonRetryable,
            ..
        }
    ));
    assert_eq!(
        failure.attempts[0].usage.as_ref().unwrap().total_tokens(),
        25
    );
    assert_eq!(
        failure.cumulative_usage.as_ref().unwrap().total_tokens(),
        25
    );
}

#[tokio::test]
async fn queue_is_fifo() {
    let client = MockClient::new()
        .with_response(r#"{"title":"First","year":2001}"#)
        .with_response(r#"{"title":"Second","year":2002}"#);
    let a: Movie = client.materialize("p").await.unwrap();
    let b: Movie = client.materialize("p").await.unwrap();
    assert_eq!(a.title, "First");
    assert_eq!(b.title, "Second");
    assert!(client.responses_exhausted());
}

#[tokio::test]
async fn with_responses_bulk_and_json_helper() {
    let client = MockClient::new()
        .with_json(&Movie {
            title: "Dune".into(),
            year: 2021,
        })
        .unwrap()
        .with_responses(vec![MockResponse::text(
            r#"{"title":"Arrival","year":2016}"#,
        )]);
    let a: Movie = client.materialize("p").await.unwrap();
    let b: Movie = client.materialize("p").await.unwrap();
    assert_eq!(a.title, "Dune");
    assert_eq!(b.title, "Arrival");
}

#[tokio::test]
async fn list_models_default_and_custom() {
    use rstructor::ModelInfo;
    let client = MockClient::new();
    assert_eq!(client.list_models().await.unwrap().len(), 1);
    assert_eq!(client.last_request().unwrap().kind, RequestKind::ListModels);

    let client = MockClient::new().with_models(vec![ModelInfo {
        id: "gpt-test".into(),
        name: None,
        description: None,
    }]);
    let models = client.list_models().await.unwrap();
    assert_eq!(models[0].id, "gpt-test");
}

#[tokio::test]
async fn materialize_with_media_records_media() {
    use rstructor::MediaFile;
    let client = MockClient::new().with_response(r#"{"title":"Poster","year":1999}"#);
    let media = [MediaFile::new(
        "https://example.com/poster.png",
        "image/png",
    )];
    let movie: Movie = client
        .materialize_with_media("describe", &media)
        .await
        .unwrap();
    assert_eq!(movie.title, "Poster");
    let req = client.last_request().unwrap();
    assert_eq!(req.kind, RequestKind::MaterializeWithMedia);
    assert_eq!(req.media.len(), 1);
    assert_eq!(req.media[0].mime_type, "image/png");
}

#[tokio::test]
async fn custom_default_response_used_after_exhaustion() {
    let client =
        MockClient::new().with_default_response(MockResponse::error(RStructorError::Timeout));
    assert_eq!(
        client.materialize::<Movie>("p").await.unwrap_err(),
        RStructorError::Timeout
    );
}

#[tokio::test]
async fn clear_requests_resets_log_only() {
    let client = MockClient::new()
        .with_response(r#"{"title":"A","year":2000}"#)
        .with_response(r#"{"title":"B","year":2001}"#);
    let _: Movie = client.materialize("p").await.unwrap();
    assert_eq!(client.request_count(), 1);
    client.clear_requests();
    assert_eq!(client.request_count(), 0);
    // Queue is untouched: the second response is still available.
    let m: Movie = client.materialize("p").await.unwrap();
    assert_eq!(m.title, "B");
}

#[tokio::test]
async fn nested_validation_recurses_through_the_mock() {
    #[derive(Instructor, Serialize, Deserialize, Debug)]
    struct Festival {
        name: String,
        films: Vec<Movie>, // each Movie is validated recursively
    }
    // Inner film has an invalid year → the whole materialize must fail.
    let client = MockClient::new().with_response(
        r#"{"name":"Cannes","films":[{"title":"OK","year":2000},{"title":"Bad","year":1000}]}"#,
    );
    let err = client.materialize::<Festival>("p").await.unwrap_err();
    assert!(matches!(err, RStructorError::ValidationError(_)));
}

#[tokio::test]
async fn nested_decode_error_reports_fixture_path_without_echoing_payload() {
    let raw = include_str!("fixtures/structured/portfolio_invalid_quantity.json");
    let client = MockClient::new().with_response(raw);

    let error = client
        .materialize::<Portfolio>("reconcile positions")
        .await
        .unwrap_err();
    match error {
        RStructorError::OutputDecodeError { path, message } => {
            assert_eq!(path, "$.positions[1].quantity");
            assert!(message.contains("invalid type"));
            assert!(!message.contains("HF-ALPHA-001"));
        }
        other => panic!("expected OutputDecodeError, got {other:?}"),
    }
}

// ---------------------------------------------------------------------------
// Streaming (requires `streaming`, which implies `_client`)
// ---------------------------------------------------------------------------

#[cfg(feature = "streaming")]
mod streaming {
    use super::*;
    use futures_util::StreamExt;
    use rstructor::StreamedObject;

    #[tokio::test]
    async fn generate_stream_emits_text() {
        let client = MockClient::new().with_response("streamed text");
        let mut stream = client.generate_stream("p");
        let mut out = String::new();
        while let Some(chunk) = stream.next().await {
            out.push_str(&chunk.unwrap());
        }
        assert_eq!(out, "streamed text");
    }

    #[tokio::test]
    async fn materialize_stream_yields_partial_then_complete() {
        let client = MockClient::new().with_response(r#"{"title":"Heat","year":1995}"#);
        let mut stream = client.materialize_stream::<Movie>("p");
        let mut saw_partial = false;
        let mut complete: Option<Movie> = None;
        while let Some(item) = stream.next().await {
            match item.unwrap() {
                StreamedObject::Partial(_) => saw_partial = true,
                StreamedObject::Complete(m) => complete = Some(m),
            }
        }
        assert!(saw_partial, "expected at least one Partial snapshot");
        assert_eq!(complete.unwrap().title, "Heat");
    }

    #[tokio::test]
    async fn materialize_stream_validation_failure_ends_with_err() {
        let client = MockClient::new().with_response(r#"{"title":"Old","year":1000}"#);
        let mut stream = client.materialize_stream::<Movie>("p");
        let mut last_err = None;
        while let Some(item) = stream.next().await {
            if let Err(e) = item {
                last_err = Some(e);
            }
        }
        assert!(matches!(last_err, Some(RStructorError::ValidationError(_))));
    }

    #[tokio::test]
    async fn materialize_stream_decode_failure_reports_the_nested_path() {
        let client = MockClient::new().with_response(include_str!(
            "fixtures/structured/portfolio_invalid_quantity.json"
        ));
        let mut stream = client.materialize_stream::<Portfolio>("p");
        let mut last_error = None;

        while let Some(item) = stream.next().await {
            if let Err(error) = item {
                last_error = Some(error);
            }
        }

        assert!(matches!(
            last_error,
            Some(RStructorError::OutputDecodeError { path, .. })
                if path == "$.positions[1].quantity"
        ));
    }

    #[tokio::test]
    async fn materialize_iter_items_wrapper() {
        let client = MockClient::new()
            .with_response(r#"{"items":[{"title":"A","year":2001},{"title":"B","year":2002}]}"#);
        let mut stream = client.materialize_iter::<Movie>("p");
        let mut titles = Vec::new();
        while let Some(item) = stream.next().await {
            titles.push(item.unwrap().title);
        }
        assert_eq!(titles, vec!["A", "B"]);
    }

    #[tokio::test]
    async fn materialize_iter_bare_array() {
        let client = MockClient::new()
            .with_response(r#"[{"title":"X","year":2003},{"title":"Y","year":2004}]"#);
        let stream = client.materialize_iter::<Movie>("p");
        let count = stream.count().await;
        assert_eq!(count, 2);
    }
}

// ---------------------------------------------------------------------------
// Tools (requires `tools`, which implies `_client`)
// ---------------------------------------------------------------------------

#[cfg(feature = "tools")]
mod tools {
    use super::*;
    use rstructor::{FnTool, RequestExt, Toolbox};
    use serde_json::json;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};

    #[derive(Instructor, Serialize, Deserialize)]
    struct PingArgs {
        #[allow(dead_code)]
        value: u32,
    }

    #[tokio::test]
    async fn run_tool_loop_records_names_and_returns_final_text() {
        let tb = Toolbox::new().with(FnTool::new(
            "ping",
            "a ping tool",
            |_a: PingArgs| async move { Ok(json!({ "pong": true })) },
        ));
        let client = MockClient::new().with_response("final answer");
        let out = client.with_tools(&tb).run("do it").await.unwrap();
        assert_eq!(out, "final answer");
        let req = client.last_request().unwrap();
        assert_eq!(req.kind, RequestKind::RunToolLoop);
        assert_eq!(req.tool_names, vec!["ping".to_string()]);
    }

    #[tokio::test]
    async fn scripted_tool_loop_actually_invokes_the_tool() {
        let calls = Arc::new(AtomicUsize::new(0));
        let calls_in_tool = calls.clone();
        let tb = Toolbox::new().with(FnTool::new("ping", "a ping tool", move |a: PingArgs| {
            let c = calls_in_tool.clone();
            async move {
                c.fetch_add(1, SeqCst);
                Ok(json!({ "echo": a.value }))
            }
        }));
        let client = MockClient::new()
            .with_tool_script(vec![("ping".to_string(), json!({ "value": 7 }))])
            .with_response("done");
        let out = client.with_tools(&tb).run("call the tool").await.unwrap();
        assert_eq!(out, "done");
        assert_eq!(calls.load(SeqCst), 1, "the tool's invoke should have run");
    }

    #[tokio::test]
    async fn scripted_tool_loop_unknown_tool_errors() {
        let tb = Toolbox::new();
        let client = MockClient::new().with_tool_script(vec![("nope".to_string(), json!({}))]);
        let err = client.with_tools(&tb).run("p").await.unwrap_err();
        assert!(matches!(err, RStructorError::Unsupported(_)));
    }
}

// ---------------------------------------------------------------------------
// Fluent builder integration (requires `_client`, brought in by any provider)
// ---------------------------------------------------------------------------

#[cfg(feature = "_client")]
mod builder {
    use super::*;
    use rstructor::RequestExt;

    #[tokio::test]
    async fn with_system_is_prepended_into_recorded_prompt() {
        let client = MockClient::new().with_response(r#"{"title":"Sys","year":2005}"#);
        let _: Movie = client
            .with_system("Always answer in USD.")
            .materialize("Describe a film")
            .await
            .unwrap();
        let req = client.last_request().unwrap();
        // The builder prepends the system text before dispatch.
        assert!(req.prompt.contains("Always answer in USD."));
        assert!(req.prompt.contains("Describe a film"));
    }
}