SuperAPI AI 工具集

instructor

数据与分析

查看项目

更新于 10-15 13:10

技能介绍

概述

Instructor 是一个用于从大语言模型(LLM)响应中提取结构化数据的 Python 工具。它通过 Pydantic 模型定义期望的输出结构,自动对 LLM 返回内容进行校验,并在校验失败时自动重试。资料显示其在 GitHub 上拥有 15,000+ 星标,被 100,000+ 开发者使用。

主要能力

  • 结构化提取:使用 Pydantic 模型定义输出结构,从 LLM 响应中可靠提取结构化数据。
  • 自动校验:基于 Pydantic 对输出自动校验,支持内置验证器(如 Field 约束、EmailStr、HttpUrl)、自定义字段验证器(field_validator)和模型级验证器(model_validator)。
  • 自动重试:校验失败时自动把错误信息反馈给 LLM 并重试,默认最多 3 次(可通过 max_retries 设置)。
  • 流式处理:支持流式返回部分结果(create_partial)以及流式迭代列表项(create_iterable),便于实时处理。
  • 多提供商支持:提供 Anthropic、OpenAI 以及本地模型(如 Ollama)等提供商的统一 API。
  • 复杂 JSON 与类型安全:通过 Pydantic 类型提示实现类型安全解析,支持嵌套模型、Optional 字段、Enum 约束、Union 类型、动态模型等。

安装方式

基础安装:

pip install instructor

按提供商安装:

pip install "instructor[anthropic]"  # Anthropic Claude
pip install "instructor[openai]"     # OpenAI
pip install "instructor[all]"        # 所有提供商

使用方式

以 Anthropic 为例,定义输出结构并创建客户端:

import instructor
from pydantic import BaseModel
from anthropic import Anthropic

class User(BaseModel):
    name: str
    age: int
    email: str

client = instructor.from_anthropic(Anthropic())

user = client.messages.create(
    model="claude-sonnet-4-5-20250929",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": "John Doe is 30 years old. His email is john@example.com"
    }],
    response_model=User
)

OpenAI 通过 instructor.from_openai(OpenAI()) 使用 client.chat.completions.create,本地模型(Ollama)则指向 http://localhost:11434/v1 并设置 mode=instructor.Mode.JSON。提供商配置支持 Mode.ANTHROPIC_TOOLS、Mode.JSON、Mode.TOOLS 等模式。

常见使用模式

资料列举了以下模式:从文本中提取数据(如公司信息)、分类(如文章分类)、多实体抽取(人物、组织、地点)、结构化分析(如情感分析)、批量处理等。

适用场景

  • 需要结构化、经过校验的 LLM 输出
  • 希望获得类型安全与 IDE 支持
  • 需要自动重试机制
  • 构建数据提取系统

限制与替代方案

资料对比指出,若需要提示优化可考虑 DSPy;若构建复杂链可考虑 LangChain;若只是一次性简单提取可手动处理。Instructor 的学习曲线为低,而 DSPy 为高。

资源

  • 文档:https://python.useinstructor.com
  • GitHub:https://github.com/jxnl/instructor
  • Cookbook:https://python.useinstructor.com/examples
  • Discord:提供社区支持

(注:本次资料未提供 Instructor 的收费、价格等信息,相关事实暂未提供。)