I built rstructor, a Rust library for structured LLM outputs. It’s like Python’s Instructor/Pydantic, but with the power and type-safety of Rust.
You define your data models as Rust structs/enums, and rstructor handles the rest: JSON Schema generation, LLM communication (OpenAI, Anthropic, etc.), parsing, and validation.
Example – triaging a bug report from messy text:
use rstructor::{Instructor, LLMClient, OpenAIClient, OpenAIModel};
use serde::{Serialize, Deserialize};
// Define enums for classification
#[derive(Instructor, Serialize, Deserialize, Debug)]
enum Severity { Low, Medium, High, Critical }
#[derive(Instructor, Serialize, Deserialize, Debug)]
enum IssueType {
Bug { severity: Severity },
FeatureRequest,
Performance { ms_impact: u32 },
}
// Define the main structured output
#[derive(Instructor, Serialize, Deserialize, Debug)]
struct TriagedIssue {
title: String,
issue_type: IssueType,
}
let client = OpenAIClient::new(env::var("OPENAI_API_KEY")?)?
.model(OpenAIModel::Gpt4OMini);
// Go from messy text to a type-safe Rust struct in one call
let issue: TriagedIssue = client.materialize(
"The login page is super slow, takes like 500ms to load, and it crashes if I type my email wrong."
).await?;
// Leverage Rust's powerful pattern matching
match issue.issue_type {
IssueType::Performance { ms_impact } => {
println!("High-priority performance issue: {}ms impact", ms_impact);
}
IssueType::Bug { severity } => {
println!("Bug of severity {:?} found", severity);
}
_ => {}
}
Key features:
- Support for OpenAI, Anthropic, Grok (xAI), and Gemini
- Custom validation rules with automatic detection
- Nested structures, arrays, and enums with associated data
- Automatic retry with validation error feedback
Crate: https://crates.io/crates/rstructor
GitHub: https://github.com/clifton/rstructor
Docs: https://docs.rs/rstructor
Would love feedback from anyone building LLM-powered tools in Rust!
Comments URL: https://news.ycombinator.com/item?id=45801441
Points: 1
# Comments: 0
Source: news.ycombinator.com
