Skip to main content

Crate instructors

Crate instructors 

Source
Expand description

§instructors

Type-safe structured output extraction from LLMs.

Define a Rust struct, and instructors will make the LLM return data that deserializes directly into it — with automatic schema generation, validation, and retry on failure.

§Quick start

use instructors::prelude::*;

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

let client = Client::openai("sk-...");
let result: ExtractResult<Contact> = client
    .extract("Contact John Doe at john@example.com")
    .model("gpt-4o")
    .await?;

println!("{}: {:?}", result.value.name, result.value.email);
println!("tokens: {}, cost: {:?}", result.usage.total_tokens, result.usage.cost);

§Validation

use instructors::prelude::*;

#[derive(Debug, Deserialize, JsonSchema)]
struct User {
    name: String,
    age: u32,
}

let client = Client::openai("sk-...");

// closure-based validation
let user: User = client.extract("...")
    .validate(|u: &User| {
        if u.age > 150 { Err("age unrealistic".into()) } else { Ok(()) }
    })
    .await?.value;

§Features

  • Multi-provider — OpenAI (response_format strict), Anthropic (tool_use), plus any OpenAI/Anthropic-compatible API
  • List extractionextract_many::<T>() returns Vec<T>
  • Batch processingextract_batch::<T>() with configurable concurrency
  • Multi-turn.messages() for conversation history
  • Validation — closure-based .validate() or trait-based .validated()
  • Lifecycle hooks.on_request() / .on_response()
  • Cost tracking — token counting and cost estimation via tiktoken (optional)

Re-exports§

pub use serde;

Modules§

prelude
Common imports for working with instructors.

Structs§

BatchBuilder
Builder for concurrent batch extraction.
Client
LLM client for structured data extraction.
ExtractBuilder
Builder for configuring an extraction request.
ExtractResult
Result of a successful extraction containing the typed value and usage info.
Message
Usage
Token usage and cost information from an extraction request.
ValidationError
Validation error with a human-readable message that gets fed back to the LLM on retry.

Enums§

Error

Traits§

JsonSchema
A type which can be described as a JSON Schema document.
Validate
Trait for types that can validate themselves after extraction.

Type Aliases§

Result

Derive Macros§

JsonSchema
Derive macro for JsonSchema trait.