Structured Output (JSON Mode) Pattern
Demonstrates extracting typed, validated structured data from LLM responses using JSON mode.
Stop parsing free-form LLM text — get typed, validated JSON structs back every time, across every provider.
Edition
Section titled “Edition”Community — runs on the OSS / Community SDK edition.
What this demonstrates
Section titled “What this demonstrates”Difficulty: Starter 🟢 · LLM
- Summary: JSON mode and structured output generation
- Scenario: Request and parse structured JSON responses from an LLM
tech_tagsin manifest:LLM— example idstructured-outputinconformance/examples_manifest.json.
Prerequisites
Section titled “Prerequisites”- SDK: Use an installed SDK tree (
NXUSKIT_SDK_DIR,NXUSKIT_LIB_PATHas needed);test-examples.shresolves Go/Rust/Python deps from that tree only — see README.md,scripts/setup-sdk.sh, andscripts/test-examples.sh. - Languages in this example: go, rust (paths under this directory; Python may live under a sibling
python/or shared reference per Language Implementations). - Models: Set cloud provider API keys and/or run Ollama locally when you execute the Run steps (interactive flags like
--help/--verboseare documented below).
Key nxusKit Features Demonstrated
Section titled “Key nxusKit Features Demonstrated”| Feature | Description |
|---|---|
| JSON Mode Abstraction | nxusKit handles provider-specific JSON mode implementations |
| Type-Safe Responses | Strong typing with serde (Rust) / json (Go) for reliability |
| Provider-Agnostic Schemas | Same schema works across OpenAI, Claude, and Ollama |
Provider Compatibility: Ollama (format parameter), OpenAI (response_format), Claude (via tool use)
Pattern Overview
Section titled “Pattern Overview”LLMs naturally produce unstructured text, but many applications need structured data. This pattern uses JSON mode to ensure valid JSON output, then parses and validates it into typed structures.
Key Features
Section titled “Key Features”- JSON mode ensures valid JSON response
- Type-safe parsing into structs
- Validation of enumerated fields
- Helper functions for testing
Real-World Application
Section titled “Real-World Application”Data extraction, form auto-fill, API response generation.
Technologies
Section titled “Technologies”LLM
Language Implementations
Section titled “Language Implementations”| Language | Path | Status |
|---|---|---|
| Rust | rust/ | Available |
| Go | go/ | Available |
Attach an installed SDK (NXUSKIT_SDK_DIR). See the repository README.md and scripts/test-examples.sh.
# From `/examples/patterns/structured-output`:cd rust && cargo buildcd go && make buildLog Classification Example
Section titled “Log Classification Example”The example classifies log entries into structured categories:
{ "severity": "error", "category": "auth", "summary": "Failed login attempt for admin user", "actionable": true}Valid Values
Section titled “Valid Values”- severity:
info,warning,error,critical - category:
auth,network,system,application
Library usage
Section titled “Library usage”use structured_output::{classify_log, LogClassification};
let classification = classify_log(&provider, "llama3", log_entry).await?;
println!("Severity: {}", classification.severity);println!("Actionable: {}", classification.actionable);classification, err := ClassifyLog(ctx, provider, "llama3", logEntry)
fmt.Println("Severity:", classification.Severity)fmt.Println("Actionable:", classification.Actionable)cd rustcargo runcd gogo run .Interactive Modes
Section titled “Interactive Modes”All examples support debugging flags:
# Verbose mode - show raw HTTP request/response datacargo run -- --verbose # Rustgo run . --verbose # Go
# Step mode - pause at each step with explanationscargo run -- --step # Rustgo run . --step # Go
# Combined modecargo run -- --verbose --stepOr use environment variables:
export NXUSKIT_VERBOSE=1export NXUSKIT_STEP=1Testing
Section titled “Testing”# Rustcd rust && cargo test
# Gocd go && go test -vPrompt Engineering Tips
Section titled “Prompt Engineering Tips”- Be explicit: Specify the exact JSON format in the system prompt
- List valid values: Enumerate allowed values for each field
- Provide examples: Include example JSON in complex cases
- Validate output: Always validate parsed JSON against your schema
Production Considerations
Section titled “Production Considerations”- Retry on validation failure: LLMs may occasionally produce invalid values
- Fallback handling: Have a default category for edge cases
- Schema evolution: Version your schemas for backward compatibility
- Rate limiting: JSON mode may use more tokens due to formatting