instructors 1.3.2

Type-safe structured output extraction from LLMs. The Rust 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
use std::sync::{Arc, Mutex};

use instructors::{Client, Error, ImageInput, Validate, ValidationError};
use schemars::JsonSchema;
use serde::Deserialize;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

#[derive(Debug, Deserialize, JsonSchema)]
struct Contact {
    name: String,
    email: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct StrictContact {
    name: String,
    email: String,
}

impl Validate for StrictContact {
    fn validate(&self) -> Result<(), ValidationError> {
        if !self.email.contains('@') {
            return Err(format!("'{}' is not a valid email", self.email).into());
        }
        Ok(())
    }
}

fn anthropic_response(json_value: serde_json::Value) -> serde_json::Value {
    serde_json::json!({
        "id": "msg_test",
        "type": "message",
        "role": "assistant",
        "content": [{
            "type": "tool_use",
            "id": "toolu_test",
            "name": "extract",
            "input": json_value
        }],
        "usage": {
            "input_tokens": 40,
            "output_tokens": 15
        }
    })
}

#[tokio::test]
async fn extract_contact() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/messages"))
        .and(header("x-api-key", "ant-key"))
        .and(header("anthropic-version", "2023-06-01"))
        .respond_with(ResponseTemplate::new(200).set_body_json(anthropic_response(
            serde_json::json!({"name": "Alice", "email": "alice@test.com"}),
        )))
        .expect(1)
        .mount(&server)
        .await;

    let client = Client::anthropic_compatible("ant-key", &server.uri());
    let result = client.extract::<Contact>("extract contact").await.unwrap();

    assert_eq!(result.value.name, "Alice");
    assert_eq!(result.value.email, Some("alice@test.com".into()));
    assert_eq!(result.usage.input_tokens, 40);
    assert_eq!(result.usage.output_tokens, 15);
    assert_eq!(result.usage.total_tokens, 55);
}

#[tokio::test]
async fn extract_optional_null() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(anthropic_response(
            serde_json::json!({"name": "Bob", "email": null}),
        )))
        .expect(1)
        .mount(&server)
        .await;

    let client = Client::anthropic_compatible("key", &server.uri());
    let result = client.extract::<Contact>("Bob").await.unwrap();

    assert_eq!(result.value.name, "Bob");
    assert_eq!(result.value.email, None);
}

#[tokio::test]
async fn api_error_401() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(ResponseTemplate::new(401).set_body_string(r#"{"error":"invalid api key"}"#))
        .expect(1)
        .mount(&server)
        .await;

    let client = Client::anthropic_compatible("bad-key", &server.uri());
    let err = client.extract::<Contact>("test").await.unwrap_err();

    match err {
        Error::Api { status, message } => {
            assert_eq!(status, 401);
            assert!(message.contains("invalid api key"));
        }
        _ => panic!("expected Api error, got: {err:?}"),
    }
}

#[tokio::test]
async fn api_error_429() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(
            ResponseTemplate::new(429).set_body_string(r#"{"error":"rate_limit_exceeded"}"#),
        )
        .expect(1)
        .mount(&server)
        .await;

    let client = Client::anthropic_compatible("key", &server.uri());
    let err = client.extract::<Contact>("test").await.unwrap_err();

    match err {
        Error::Api { status, .. } => assert_eq!(status, 429),
        _ => panic!("expected Api error"),
    }
}

#[tokio::test]
async fn no_tool_use_block() {
    let server = MockServer::start().await;

    let response_text_only = serde_json::json!({
        "id": "msg_test",
        "type": "message",
        "role": "assistant",
        "content": [{
            "type": "text",
            "text": "I cannot extract that"
        }],
        "usage": {
            "input_tokens": 40,
            "output_tokens": 15
        }
    });

    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(response_text_only))
        .expect(1)
        .mount(&server)
        .await;

    let client = Client::anthropic_compatible("key", &server.uri());
    let err = client.extract::<Contact>("test").await.unwrap_err();

    assert!(matches!(err, Error::Other(_)));
}

#[tokio::test]
async fn no_usage_in_response() {
    let server = MockServer::start().await;

    let response_no_usage = serde_json::json!({
        "id": "msg_test",
        "type": "message",
        "role": "assistant",
        "content": [{
            "type": "tool_use",
            "id": "toolu_test",
            "name": "extract",
            "input": {"name": "Test", "email": null}
        }]
    });

    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(response_no_usage))
        .expect(1)
        .mount(&server)
        .await;

    let client = Client::anthropic_compatible("key", &server.uri());
    let result = client.extract::<Contact>("test").await.unwrap();

    assert_eq!(result.usage.input_tokens, 0);
    assert_eq!(result.usage.output_tokens, 0);
}

#[tokio::test]
async fn retry_on_bad_json_from_tool() {
    let server = MockServer::start().await;

    // first: tool_use with input that doesn't match schema
    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(anthropic_response(serde_json::json!({"wrong_field": 123}))),
        )
        .expect(1)
        .up_to_n_times(1)
        .mount(&server)
        .await;

    // second: correct
    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(anthropic_response(
            serde_json::json!({"name": "Fixed", "email": null}),
        )))
        .expect(1)
        .mount(&server)
        .await;

    let client = Client::anthropic_compatible("key", &server.uri());
    let result = client
        .extract::<Contact>("test")
        .max_retries(2)
        .await
        .unwrap();

    assert_eq!(result.value.name, "Fixed");
    assert_eq!(result.usage.retries, 1);
}

#[tokio::test]
async fn trait_validation_with_anthropic() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(anthropic_response(
            serde_json::json!({"name": "Alice", "email": "alice@example.com"}),
        )))
        .expect(1)
        .mount(&server)
        .await;

    let client = Client::anthropic_compatible("key", &server.uri());
    let result = client
        .extract::<StrictContact>("Alice")
        .validated()
        .await
        .unwrap();

    assert_eq!(result.value.name, "Alice");
    assert!(result.value.email.contains('@'));
}

#[tokio::test]
async fn trait_validation_fails_anthropic() {
    let server = MockServer::start().await;

    // always returns invalid email
    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(anthropic_response(
            serde_json::json!({"name": "Bob", "email": "not-an-email"}),
        )))
        .mount(&server)
        .await;

    let client = Client::anthropic_compatible("key", &server.uri());
    let err = client
        .extract::<StrictContact>("Bob")
        .validated()
        .max_retries(1)
        .await
        .unwrap_err();

    assert!(matches!(err, Error::ValidationFailed { retries: 1, .. }));
}

#[tokio::test]
async fn custom_model_anthropic() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(anthropic_response(
            serde_json::json!({"name": "Test", "email": null}),
        )))
        .expect(1)
        .mount(&server)
        .await;

    let client = Client::anthropic_compatible("key", &server.uri());
    let result = client
        .extract::<Contact>("test")
        .model("claude-opus-4-20250514")
        .await
        .unwrap();

    assert_eq!(result.value.name, "Test");
}

#[tokio::test]
async fn extract_with_image_anthropic() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(anthropic_response(
            serde_json::json!({"name": "Cat", "email": "cat@test.com"}),
        )))
        .expect(1)
        .mount(&server)
        .await;

    let client = Client::anthropic_compatible("key", &server.uri());
    let result = client
        .extract::<Contact>("what animal is this?")
        .image(ImageInput::Base64 {
            media_type: "image/png".into(),
            data: "dGVzdA==".into(),
        })
        .await
        .unwrap();

    assert_eq!(result.value.name, "Cat");
}

fn anthropic_stream_events(json_content: &str) -> String {
    let mut sse = String::new();

    // message_start with usage
    let msg_start = serde_json::json!({
        "type": "message_start",
        "message": {
            "usage": { "input_tokens": 25, "output_tokens": 0 }
        }
    });
    sse.push_str(&format!("event: message_start\ndata: {msg_start}\n\n"));

    // content_block_start
    let block_start = serde_json::json!({
        "type": "content_block_start",
        "index": 0,
        "content_block": { "type": "tool_use", "id": "toolu_test", "name": "extract", "input": {} }
    });
    sse.push_str(&format!(
        "event: content_block_start\ndata: {block_start}\n\n"
    ));

    // stream JSON char-by-char as input_json_delta
    for ch in json_content.chars() {
        let delta = serde_json::json!({
            "type": "content_block_delta",
            "delta": {
                "type": "input_json_delta",
                "partial_json": ch.to_string()
            }
        });
        sse.push_str(&format!("event: content_block_delta\ndata: {delta}\n\n"));
    }

    // message_delta with output usage
    let msg_delta = serde_json::json!({
        "type": "message_delta",
        "usage": { "input_tokens": 0, "output_tokens": 12 }
    });
    sse.push_str(&format!("event: message_delta\ndata: {msg_delta}\n\n"));

    // message_stop
    let msg_stop = serde_json::json!({ "type": "message_stop" });
    sse.push_str(&format!("event: message_stop\ndata: {msg_stop}\n\n"));

    sse
}

#[tokio::test]
async fn extract_with_streaming_anthropic() {
    let server = MockServer::start().await;

    let json_content = r#"{"name":"Stream","email":"s@t.com"}"#;
    let sse_body = anthropic_stream_events(json_content);

    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/event-stream")
                .set_body_string(sse_body),
        )
        .expect(1)
        .mount(&server)
        .await;

    let chunks: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let chunks_clone = chunks.clone();

    let client = Client::anthropic_compatible("key", &server.uri());
    let result = client
        .extract::<Contact>("test")
        .on_stream(move |chunk| {
            chunks_clone.lock().unwrap().push(chunk.to_string());
        })
        .await
        .unwrap();

    assert_eq!(result.value.name, "Stream");
    assert_eq!(result.value.email, Some("s@t.com".into()));
    assert_eq!(result.usage.input_tokens, 25);
    assert_eq!(result.usage.output_tokens, 12);

    let collected = chunks.lock().unwrap();
    assert!(!collected.is_empty());
    let reassembled: String = collected.iter().cloned().collect();
    assert_eq!(reassembled, json_content);
}

#[tokio::test]
async fn streaming_multibyte_utf8_anthropic() {
    let server = MockServer::start().await;

    // stream JSON with multi-byte chars across chunks
    let json_content = r#"{"name":"東京","email":"t@t.com"}"#;
    let sse_body = anthropic_stream_events(json_content);

    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/event-stream")
                .set_body_string(sse_body),
        )
        .expect(1)
        .mount(&server)
        .await;

    let chunks: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let chunks_clone = chunks.clone();

    let client = Client::anthropic_compatible("key", &server.uri());
    let result = client
        .extract::<Contact>("test")
        .on_stream(move |chunk| {
            chunks_clone.lock().unwrap().push(chunk.to_string());
        })
        .await
        .unwrap();

    assert_eq!(result.value.name, "東京");

    let collected = chunks.lock().unwrap();
    let reassembled: String = collected.iter().cloned().collect();
    assert_eq!(reassembled, json_content);
}

#[tokio::test]
async fn cross_provider_fallback_openai_to_anthropic() {
    use wiremock::matchers::path;

    let openai_server = MockServer::start().await;
    let anthropic_server = MockServer::start().await;

    // openai returns 429 (rate limit)
    Mock::given(method("POST"))
        .and(path("/chat/completions"))
        .respond_with(ResponseTemplate::new(429).set_body_string("rate limited"))
        .expect(1)
        .mount(&openai_server)
        .await;

    // anthropic succeeds
    Mock::given(method("POST"))
        .and(path("/messages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(anthropic_response(
            serde_json::json!({"name": "Cross", "email": "cross@test.com"}),
        )))
        .expect(1)
        .mount(&anthropic_server)
        .await;

    let client = Client::openai_compatible("key", &openai_server.uri()).with_fallback(
        Client::anthropic_compatible("ant-key", &anthropic_server.uri()),
    );

    let result = client
        .extract::<Contact>("test")
        .max_retries(0)
        .await
        .unwrap();

    assert_eq!(result.value.name, "Cross");
}