rstructor: Structured LLM Outputs for Rust
rstructor is a Rust library for extracting structured data from Large Language Models (LLMs) with built-in validation. Define your schemas as Rust structs/enums, and rstructor will handle the restβgenerating JSON Schemas, communicating with LLMs, parsing responses, and validating the results.
Think of it as the Rust equivalent of Instructor + Pydantic for Python, bringing the same structured output capabilities to the Rust ecosystem.
β¨ Features
- π Type-Safe Definitions: Define data models as standard Rust structs/enums with attributes
- π JSON Schema Generation: Auto-generates JSON Schema from your Rust types
- β Built-in Validation: Type checking plus custom business rule validation
- π Multiple LLM Providers: Support for OpenAI, Anthropic, Grok (xAI), and Gemini (Google), with an extensible backend system
- π§© Complex Data Structures: Support for nested objects, arrays, optional fields, and deeply nested enums
- π§ Schema Fidelity: Heuristic-free JSON Schema generation that preserves nested struct and enum detail
- π Custom Validation Rules: Add domain-specific validation with automatically detected
validatemethods - π Async API: Fully asynchronous API for efficient operations
- βοΈ Builder Pattern: Fluent API for configuring LLM clients (temperature retries, timeouts, etc)
- π Feature Flags: Optional backends via feature flags
π¦ Installation
Add rstructor to your Cargo.toml:
[]
= "0.1.0"
= { = "1.0", = ["derive"] }
= { = "1.0", = ["rt-multi-thread", "macros"] }
π Quick Start
Here's a simple example of extracting structured information about a movie from an LLM:
use ;
use ;
use env;
use Duration;
// Define your data model
async
π Detailed Examples
Production Example with Automatic Retry
For production use, prefer generate_struct_with_retry which automatically retries on validation errors:
use ;
use Duration;
use ;
// Generate with automatic retry (recommended for production)
let movie: Movie = client
.
.await?;
Basic Example with Validation
Add custom validation rules to enforce business logic beyond type checking:
use ;
use ;
// Add custom validation
// The derive macro automatically wires this method into the generated implementation,
// so you won't see `dead_code` warnings even if the method is only called by rstructor.
Complex Nested Structures
rstructor supports complex nested data structures:
use ;
use Duration;
use ;
// Define a nested data model for a recipe
// Usage:
// let recipe: Recipe = client.generate_struct("Give me a recipe for chocolate chip cookies").await?;
Working with Enums
rstructor supports both simple enums and enums with associated data.
Simple Enums
Use enums for categorical data:
use ;
use ;
// Define an enum for sentiment analysis
// Usage:
// let analysis: SentimentAnalysis = client.generate_struct("Analyze the sentiment of: I love this product!").await?;
Enums with Associated Data (Tagged Unions)
rstructor also supports more complex enums with associated data:
use ;
use ;
// Enum with different types of associated data
// Using struct variants for more complex associated data
// Usage:
// let user_status: UserStatus = client.generate_struct("What's the user's status?").await?;
Nested Enums Across Structs
Enums can be freely nested inside other enums and structsβ#[derive(Instructor)] now
generates the correct schema without requiring manual SchemaType implementations:
// Works automatically β TaskState::schema() includes the nested enum structure.
See examples/nested_enum_example.rs for a complete runnable walkthrough that
also exercises deserialization of nested enum variants.
When serialized to JSON, these enum variants with data become tagged unions:
// UserStatus::Away("Back in 10 minutes")
// PaymentMethod::Card { number: "4111...", expiry: "12/25" }
Working with Custom Types (Dates, UUIDs, etc.)
rstructor provides the CustomTypeSchema trait to handle types that don't have direct JSON representations but need specific schema formats. This is particularly useful for:
- Date/time types (e.g.,
chrono::DateTime) - UUIDs (e.g.,
uuid::Uuid) - Email addresses
- URLs
- Custom domain-specific types
Basic Implementation
use ;
use ;
use ;
use json;
use Uuid;
// Implement CustomTypeSchema for chrono::DateTime<Utc>
// Implement CustomTypeSchema for UUID
Usage in Structs
Once implemented, these custom types can be used directly in your structs:
Advanced Customization
You can add additional schema properties for more complex validation:
The macro automatically detects these custom types and generates appropriate JSON Schema with format specifications that guide LLMs to produce correctly formatted values. The library includes built-in recognition of common date and UUID types, but you can implement the trait for any custom type.
Configuring Different LLM Providers
Choose between different providers:
// Using OpenAI
let openai_client = new?
.model
.temperature
.max_tokens
.with_timeout // Optional: set 60 second timeout
.build;
// Using Anthropic
let anthropic_client = new?
.model
.temperature
.max_tokens
.with_timeout // Optional: set 60 second timeout
.build;
// Using Grok (xAI) - reads from XAI_API_KEY environment variable
let grok_client = from_env? // Reads from XAI_API_KEY env var
.model
.temperature
.max_tokens
.with_timeout // Optional: set 60 second timeout
.build;
// Using Gemini (Google) - reads from GEMINI_API_KEY environment variable
let gemini_client = from_env? // Reads from GEMINI_API_KEY env var
.model
.temperature
.max_tokens
.with_timeout // Optional: set 60 second timeout
.build;
Configuring Request Timeouts
All clients (OpenAIClient, AnthropicClient, GrokClient, and GeminiClient) support configurable timeouts for HTTP requests using the builder pattern:
use Duration;
let client = new?
.model
.temperature
.with_timeout // Set 30 second timeout
.build;
Timeout Behavior:
- The timeout applies to each HTTP request made by the client
- If a request exceeds the timeout, it will return
RStructorError::Timeout - If no timeout is specified, the client uses reqwest's default timeout behavior
- Timeout values are specified as
std::time::Duration(e.g.,Duration::from_secs(30)orDuration::from_millis(2500))
Example with timeout error handling:
use ;
use Duration;
match client..await
Handling Container-Level Attributes
Add metadata and examples at the container level:
)]
π API Reference
Instructor Trait
The Instructor trait is the core of rstructor. It's implemented automatically via the derive macro and provides schema generation and validation:
Override the validate method to add custom validation logic.
CustomTypeSchema Trait
The CustomTypeSchema trait allows you to define JSON Schema representations for types that don't have direct JSON equivalents, like dates and UUIDs:
Implement this trait for custom types like DateTime<Utc> or Uuid to control their JSON Schema representation. Most implementations only need to specify schema_type() and schema_format(), with the remaining methods providing additional schema customization when needed.
LLMClient Trait
The LLMClient trait defines the interface for all LLM providers:
Note: For production applications, prefer generate_struct_with_retry over generate_struct as it automatically handles validation errors by retrying with error feedback. This significantly improves success rates with complex schemas.
Supported Attributes
Field Attributes
description: Text description of the fieldexample: A single example valueexamples: Multiple example values
Container Attributes
description: Text description of the struct or enumtitle: Custom title for the JSON Schemaexamples: Example instances as JSON objects
π§ Feature Flags
Configure rstructor with feature flags:
[]
= { = "0.1.0", = ["openai", "anthropic", "grok", "gemini"] }
Available features:
openai: Include the OpenAI clientanthropic: Include the Anthropic clientgrok: Include the Grok (xAI) clientgemini: Include the Gemini (Google) clientderive: Include the derive macro (enabled by default)logging: Enable tracing integration with default subscriber
π Logging and Tracing
rstructor includes structured logging via the tracing crate:
use ;
// Initialize with desired level
init_logging;
// Or use filter strings for granular control
// init_logging_with_filter("rstructor=info,rstructor::backend=trace");
Override with environment variables:
RSTRUCTOR_LOG=debug
Validation errors, retries, and API interactions are thoroughly logged at appropriate levels.
π Examples
See the examples/ directory for complete, working examples:
structured_movie_info.rs: Basic example of getting movie information with validationnested_objects_example.rs: Working with complex nested structures for recipe datanews_article_categorizer.rs: Using enums for categorizationenum_with_data_example.rs: Working with enums that have associated data (tagged unions)event_planner.rs: Interactive event planning with user inputweather_example.rs: Simple model with validation demonstrationvalidation_example.rs: Demonstrates custom validation without dead code warningscustom_type_example.rs: Using custom types like dates and UUIDs with JSON Schema format supportlogging_example.rs: Demonstrates tracing integration with custom log levelsnested_enum_example.rs: Shows automatic schema generation for nested enums inside structs
βΆοΈ Running the Examples
# Set environment variables
# or
# or
# or
# Run examples
β οΈ Current Limitations
rstructor currently focuses on single-turn, synchronous structured output generation. The following features are planned but not yet implemented:
- Streaming Responses: Real-time streaming of partial results as they're generated
- Conversation History: Multi-turn conversations with message history (currently only single prompts supported)
- System Messages: Explicit system prompts for role-based interactions
- Response Modes: Different validation strategies (strict, partial, etc.)
- Rate Limiting: Built-in rate limit handling and backoff strategies
π£οΈ Roadmap
- Core traits and interfaces
- OpenAI backend implementation
- Anthropic backend implementation
- Procedural macro for deriving
Instructor - Schema generation functionality
- Custom validation capabilities
- Support for nested structures
- Rich validation API with custom domain rules
- Support for enums with associated data (tagged unions)
- Support for custom types (dates, UUIDs, etc.)
- Structured logging and tracing
- Automatic retry with validation error feedback
- Streaming responses
- Conversation history / multi-turn support
- System messages and role-based prompts
- Response modes (strict, partial, retry)
- Rate limiting and backoff strategies
- Support for additional LLM providers
- Integration with web frameworks (Axum, Actix)
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π₯ Contributing
Contributions are welcome! Please feel free to submit a Pull Request.