进阶 python.useinstructor.com 2026-11-15 16:34:59 · 11 阅读

第15章 常见问题(FAQ)

Frequently Asked Questions

本页解答关于使用 Instructor 配合各类 LLM 提供商的常见问题。

General Questions

What is Instructor?

Instructor 是一个让开发者能轻松从大型语言模型(LLM)中获取结构化数据的库。它利用 Pydantic 定义输出模式,并为不同的 LLM 提供商提供一致的接口。

How does Instructor work?

Instructor 通过“补丁”LLM 客户端来添加一个 response_model 参数,该参数接受 Pydantic 模型。当你发起请求时,Instructor 会:

  • 将你的 Pydantic 模型转换为 LLM 能理解的 Schema
  • 为提供商格式化合适的提示词(Prompt)
  • 验证 LLM 的响应是否符合你的模型定义
  • 如果验证失败,自动重试
  • 返回一个类型正确的 Pydantic 对象

Which LLM providers does Instructor support?

Instructor 支持众多提供商,包括:

  • OpenAI (GPT 模型)
  • Anthropic (Claude 模型)
  • Google (Gemini 模型)
  • Cohere
  • Mistral AI
  • Groq
  • LiteLLM (元提供商)
  • TrueFoundry AI Gateway
  • 通过 Ollama、llama.cpp 等访问的各种开源模型

完整列表请参见“集成”部分。

What's the difference between various modes?

Instructor 支持跨提供商的通用模式:

  • Mode.TOOLS - 在支持的情况下使用工具/函数调用
  • Mode.JSON - 在支持的情况下生成 JSON (GenAI)
  • Mode.JSON_SCHEMA - 执行 JSON Schema 验证 (OpenAI, Mistral, Cohere)
  • Mode.MD_JSON - 嵌入在 Markdown 中的 JSON
  • Mode.PARALLEL_TOOLS - 在支持的情况下进行并行工具调用

最佳模式取决于你的提供商和使用场景。详情请参见“补丁”章节。

Installation and Setup

How do I install Instructor?

基础安装:

pip install instructor

针对特定提供商:

pip install "instructor[anthropic]" # For Anthropic
pip install "instructor[google-generativeai]" # For Google/Gemini

What environment variables do I need?

这取决于你的提供商:

  • OpenAI: OPENAI_API_KEY
  • Anthropic: ANTHROPIC_API_KEY
  • Google: GOOGLE_API_KEY

每个提供商的具体要求都记录在各自的集成指南中。

Common Issues

Why is my model not returning structured data?

常见原因包括:

  • 为你的提供商使用了错误的模式
  • 模式(Schema)过于复杂,导致模型困惑
  • 提示词中缺乏足够的上下文
  • 使用的模型不支持函数/工具调用

尝试简化你的模式,或在提示词中提供更清晰的指令。

How do I handle validation errors?

当验证失败时,Instructor 会自动重试。你可以自定义这一行为:

from tenacity import stop_after_attempt

result = client.create(
response_model=MyModel,
max_retries=stop_after_attempt(5), # 最多重试 5 次
messages=[...]
)

Can I see the raw response from the LLM?

可以,使用 create_with_completion:

result, completion = client.create_with_completion(
response_model=MyModel,
messages=[...]
)

result 是你的 Pydantic 模型,而 completion 是原始响应。

How do I stream large responses?

使用 create_partial 在生成响应时获取部分更新:

stream = client.create_partial(
response_model=MyModel,
messages=[...]
)

for partial in stream:
print(partial) # 随着字段生成而逐步填充的部分模型

Performance and Costs

How can I optimize token usage?

  • 使用简洁的提示词
  • 对简单任务使用较小的模型
  • 对简单模式使用 MD_JSON 或 JSON 模式
  • 为重复查询缓存响应

How do I handle rate limits?

Instructor 使用 tenacity 库进行重试,你可以对其进行配置:

from tenacity import retry_if_exception_type, wait_exponential
from openai.error import RateLimitError

result = client.create(
response_model=MyModel,
max_retries=retry_if_exception_type(RateLimitError),
messages=[...],
)

Advanced Usage

How do I use Instructor with FastAPI?

Instructor 可以与 FastAPI 无缝协作:

from fastapi import FastAPI
from pydantic import BaseModel
import instructor

app = FastAPI()
client = instructor.from_provider("openai/gpt-5-nano")

class UserInfo(BaseModel):
name: str
age: int

@app.post("/extract")
async def extract_user_info(text: str) -> UserInfo:
return client.create(
model="gpt-5.4-mini",
response_model=UserInfo,
messages=[{"role": "user", "content": text}]
)

How do I use Instructor with async code?

使用异步客户端:

import instructor
import asyncio

client = instructor.from_provider("openai/gpt-5-nano", async_client=True)

async def extract_data():
result = await client.create(
response_model=MyModel,
messages=[...]
)
return result

asyncio.run(extract_data())

Where can I get more help?

  • Discord 社区
  • GitHub Issues
  • Twitter @jxnl

评论 (0)