从这里开始:Instructor 新手指南¶
欢迎!本指南将帮助您理解 Instructor 的作用以及如何在您的项目中开始使用它,即使您是初次接触语言模型。
什么是 Instructor?¶
Instructor 是一个 Python 库,它可以帮助您从 GPT-4 和 Claude 等语言模型中获取结构化、可预测的数据。这就像给 LLM 提供一份表格让它填写,而不是让它随意回应。
Instructor 的定位¶
以下是 Instructor 如何融入您的应用
flowchart LR
A[Your Application] --> B[Instructor]
B --> C[LLM Provider]
C --> B
B --> A
style B fill:#e2f0fb,stroke:#b8daff,color:#004085
Instructor 解决的问题¶
没有 Instructor,从 LLM 获取结构化数据可能会很困难
- 输出不可预测:LLMs 每次格式化响应可能不同
- 格式错误:获取 JSON 或特定数据结构容易出错
- 验证难题:检查响应是否符合您的需求
Instructor 通过以下方式解决这些问题
- 使用 Python 类精确定义您想要的数据
- 确保 LLM 返回该结构的数据
- 验证输出并自动修复问题
一个简单示例¶
让我们通过一个基本示例来看看 Instructor 的实际应用
# Import the necessary libraries
import instructor
from openai import OpenAI
from pydantic import BaseModel
# Define the structure you want
class Person:
name: str
age: int
city: str
# Connect to the LLM with Instructor
client = instructor.from_openai(OpenAI())
# Extract structured data
person = client.chat.completions.create(
model="gpt-3.5-turbo",
response_model=Person,
messages=[
{"role": "user", "content": "Extract a person from: John is 30 years old and lives in New York."}
]
)
# Now you have a structured object
print(f"Name: {person.name}") # Name: John
print(f"Age: {person.age}") # Age: 30
print(f"City: {person.city}") # City: New York
就是这样!Instructor 处理了让 LLM 正确格式化数据的全部复杂性。
关键概念¶
以下是您需要了解的主要概念
1. 响应模型¶
响应模型定义了您希望 LLM 返回的数据结构。它们是使用 Pydantic 构建的,Pydantic 是一个数据验证库。
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(description="The user's full name")
age: int = Field(description="The user's age in years")
# The descriptions help the LLM understand what to extract
2. 修补 (Patching)¶
修补 (Patching) 将 Instructor 连接到您的 LLM 提供商(如 OpenAI 或 Anthropic)。
# For OpenAI
client = instructor.from_openai(OpenAI())
# For Anthropic
client = instructor.from_anthropic(Anthropic())
3. 模式¶
模式控制 Instructor 如何从 LLM 获取结构化数据。不同的提供商支持不同的模式。
# Using OpenAI's function calling
client = instructor.from_openai(OpenAI(), mode=instructor.Mode.TOOLS)
# Using JSON output directly
client = instructor.from_openai(OpenAI(), mode=instructor.Mode.JSON)
常见用例¶
以下是人们使用 Instructor 的一些常见方式
- 数据提取:从文本文档中提取结构化信息
- 表单填写:将自由文本转换为表单字段
- 分类:将内容分类到预定义的类别中
- 内容生成:创建结构化内容,如文章或产品描述
- API 集成:格式化 LLM 输出以匹配 API 要求
后续步骤¶
现在您已经了解了基础知识,以下是一些建议的后续步骤
常见问题¶
我需要了解 Pydantic 吗?¶
虽然了解 Pydantic 有帮助,但您不需要成为专家。上面展示的基本模式足以让您入门。您可以根据需要学习更高级的功能。
我应该使用哪个 LLM 提供商?¶
OpenAI 是新手最受欢迎的选择,因为它可靠且支持广泛。随着您越来越熟练,您可以探索其他提供商,如 Anthropic Claude、Gemini 或开源模型。
Instructor 难学吗?¶
不难!如果您熟悉 Python 类和使用 API,您会发现 Instructor 非常直观。核心概念很简单,您可以逐步探索高级功能。
Instructor 与其他库相比如何?¶
Instructor 专注于结构化输出,并提供简洁明快的 API。与试图包罗万象的大型框架不同,Instructor 在一件事上做得非常出色:从 LLM 获取结构化数据。
获取帮助¶
如果您遇到困难
- 查看常见问题解答 (FAQ)以获取常见问题解答
- 浏览示例以查看类似用例
- 加入我们的 Discord 社区以获得实时帮助
- 在概念部分查找相关主题
欢迎加入,祝您提取愉快!