验证基础¶
验证可确保 LLMs 提取的数据符合您的要求。本指南介绍了使用 Instructor 进行验证的基础知识。
为什么验证很重要¶
验证有助于确保
- 数据完整性:所有必需字段都存在且格式正确
- 一致性:数据遵循您的业务规则
- 质量:输出符合您应用的特定标准
┌─────────────┐ ┌──────────────┐ ┌─────────────┐
│ LLM │ -> │ Instructor │ -> │ Validated │
│ Generates │ │ Validates │ │ Structured │
│ Response │ │ Structure │ │ Data │
└─────────────┘ └──────────────┘ └─────────────┘
│
│ If validation fails
▼
┌─────────────┐
│ Retry with │
│ Feedback │
└─────────────┘
简单示例¶
这是一个带验证的基本示例
from pydantic import BaseModel, Field
import instructor
from openai import OpenAI
# Define a model with validation
class UserProfile(BaseModel):
name: str
age: int = Field(ge=13, description="User's age in years")
# Extract validated data
client = instructor.from_openai(OpenAI())
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "My name is Jane Smith and I'm 25 years old."}
],
response_model=UserProfile
)
print(f"User: {response.name}, Age: {response.age}")
在此示例中: - `age` 字段有一个验证约束(ge=13
),确保用户年龄至少为 13 岁 - 如果验证失败,Instructor 将自动重试并提供反馈
常见验证类型¶
以下是您可以使用的最常见验证类型
验证类型 | 示例 | 作用 |
---|---|---|
类型检查 | age: int | 确保值为整数 |
必需字段 | name: str | 字段必须存在 |
可选字段 | middle_name: Optional[str] = None | 字段可以缺失 |
最小值 | age: int = Field(ge=18) | 值必须 ≥ 18 |
最大值 | rating: float = Field(le=5.0) | 值必须 ≤ 5.0 |
字符串长度 | username: str = Field(min_length=3) | 字符串长度至少为 3 个字符 |
验证工作原理¶
在使用 Instructor 进行验证时
- LLM 根据您的 Prompt 生成响应
- Instructor 尝试将响应适配到您的模型中
- 如果验证失败,Instructor 会捕获错误
- 错误信息会返回给 LLM 进行重试
- 这个过程会持续到验证通过或达到最大重试次数为止
添加自定义错误消息¶
为了更清晰的反馈,您可以添加自定义错误消息
from pydantic import BaseModel, Field
class Product(BaseModel):
name: str
price: float = Field(
gt=0,
description="Product price in USD",
json_schema_extra={"error_msg": "Price must be greater than zero"}
)