instructor

structured outputs for llms

open-sourcevoice-agents
12.6k
Stars
+135
Stars/month
8
Releases (6m)

Star Growth

+49 (0.4%)
12.4k12.6k12.9kMar 27Apr 1

Overview

Instructor是一个Python库,专门用于从大语言模型中获取可靠的结构化JSON输出。基于Pydantic构建,提供验证、类型安全和IDE支持。该工具解决了从LLM提取结构化数据时面临的核心挑战:复杂的JSON schema编写、验证错误处理、失败重试机制以及非结构化响应解析。通过Instructor,开发者只需定义一个Pydantic模型,就能自动获得结构化数据,无需手动处理JSON解析、错误处理或重试逻辑。该库支持多个LLM提供商,包括OpenAI、Anthropic等,通过统一接口简化了不同API的使用。Instructor特别适合需要将自然语言转换为结构化数据的应用场景,如数据提取、API集成、数据库录入等。与全功能的智能体框架相比,Instructor专注于schema驱动的数据提取,保持流程简单且成本效益高。对于需要更丰富智能体功能的用户,可以考虑升级到PydanticAI。

Deep Analysis

Key Differentiator

Simplest path from LLM text to validated Pydantic objects with automatic retries — vs raw JSON mode or Guardrails (heavier, validator-focused)

Capabilities

  • Structured data extraction from LLMs using Pydantic models
  • Automatic validation and retry on extraction failure
  • Streaming partial objects during generation
  • Nested object extraction
  • Universal provider support via from_provider()
  • Type-safe responses with IDE autocomplete

🔗 Integrations

OpenAIAnthropicGoogle GeminiOllamaGroqMistralCohereLiteLLM

Best For

  • Extracting structured JSON data from any LLM reliably
  • Building type-safe LLM integrations with validation
  • Replacing manual JSON parsing and error handling

Not Ideal For

  • Building full agent systems (use PydanticAI or LangGraph)
  • Non-extraction LLM use cases like chat or generation

Languages

PythonTypeScriptRubyGoElixirRust

Deployment

pip/uv/poetry packageIn-process library

Pricing Detail

Free: Open source MIT, fully free
Paid: N/A — completely free

Known Limitations

  • Focused solely on structured extraction, not full agent workflows
  • Relies on Pydantic for validation (Python-centric design)
  • No built-in RAG or tool use beyond extraction
  • Retry mechanism adds latency and token cost

Pros

  • + 极简API设计:只需定义Pydantic模型即可获得结构化输出,相比传统方法大幅减少代码复杂度
  • + 内置Pydantic集成:提供强类型验证、IDE智能提示和自动错误处理,确保数据质量和开发体验
  • + 自动化处理机制:内置JSON解析、验证错误处理和失败重试,无需手动管理复杂的错误场景

Cons

  • - Python生态限制:基于Pydantic构建,仅支持Python环境,无法在其他编程语言中使用
  • - 依赖LLM质量:提取准确性完全依赖于底层语言模型的理解能力,模型局限性会直接影响结果
  • - 功能范围有限:专注于结构化数据提取,不支持复杂的多轮对话、推理链或智能体工作流

Use Cases

  • 从非结构化文本中提取实体信息,如从客户反馈中提取用户资料、产品特征和情感倾向
  • 将自然语言输入转换为API就绪的结构化数据,如将用户查询转换为数据库查询参数
  • 处理文档和消息转换为数据库模式,如将邮件内容解析为CRM系统的标准化记录格式

Getting Started

1. 安装Instructor库:`pip install instructor` 2. 定义Pydantic数据模型:创建描述期望输出结构的BaseModel类,包含字段类型和验证规则 3. 使用instructor.from_provider()连接LLM提供商,调用create()方法并传入response_model参数来提取结构化数据

Compare instructor