StructuredOutputParser 小于 1.0 版本,推荐使用 PydanticOutputParser 大于 1.0
StructuredOutputParser "结构化输出解析器"是一款非常有用的工具,它能够将大型语言模型(LLM)的响应格式化为字典结构,从而能够以键/值对的形式返回多个字段。
虽然 Pydantic 和 JSON 解析器具备强大的功能,但StructuredOutputParser"结构化输出解析器"对于功能较弱的模型(例如参数较少的本地模型)尤其有效。对于与像 GPT 或 Claude 这样的高级模型相比智能程度较低的模型而言,它尤其有益。
通过使用结构化输出解析器,开发人员可以在各种 LLM 应用程序中保持数据的完整性和一致性,即使是在使用参数数量较少的模型时也是如此。
使用 ResponseSchema 和 StructuredOutputParser (0.3版本以前的写法,1.0版本已经弃用,改为更加现代化的方式)
-
使用
ResponseSchema类定义响应模式,以包含用户问题的答案和所使用的来源(网站)的description。 -
使用
response_schemas初始化StructuredOutputParser,以根据定义的响应模式构建输出结构。
[注意] 在使用本地模型时,Pydantic 解析器可能经常无法正常工作。在这种情况下,使用 StructuredOutputParser 可以作为一个很好的替代解决方案。
所以对于这个情况后,在1.0版本中,推荐使用更加现代化的方式来实现结构化输出解析器。PydanticOutputParser 是一个基于 Pydantic 模型的解析器,它可以将 LLM 的响应解析为符合定义的 Pydantic 模型的实例。
现代化的结构化输出解析器 (1.0版本及以后)
方式1:使用 Pydantic 模型(推荐)
最灵活且功能最强大的方式,支持字段验证和嵌套结构:
python
from pydantic import BaseModel, Field
class ResponseSchema(BaseModel):
answer: str = Field(description="用户问题的答案")
source: str = Field(description="所使用的来源(网站)的描述")
方式2:使用 TypedDict(简洁)
当你不需要运行时验证时的轻量级方式:
python
from typing_extensions import TypedDict, Annotated
class ResponseSchema(TypedDict):
answer: Annotated[str, Field(description="用户问题的答案")]
source: Annotated[str, Field(description="所使用的来源(网站)的描述")]
使用方式1:使用 ResponseSchema
python
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
Qwen2_5_7B_Instruct_llm = ChatOpenAI(
temperature=0.1, # 控制输出的随机性和创造性,值越低输出越稳定可预测,值越高输出越有创意但可能偏离预期 (范围: 0.0 ~ 2.0)
model_name="Qwen/Qwen2.5-7B-Instruct", # 硅基流动支持的模型名称
openai_api_key=os.getenv("SILICONFLOW_API_KEY"), # 从环境变量获取API密钥
openai_api_base="https://api.siliconflow.cn/v1" # 硅基流动API的基础URL
)
template="尽可能好地回答用户的问题。\n{format_instructions}\n{question}"
agent = create_agent(
model=Qwen2_5_7B_Instruct_llm,
response_format=ResponseSchema, # Agent 最终返回结构化格式
system_prompt=system_prompt
)
agent.invoke({"question": "世界上最大的沙漠是什么?"})
使用方式2:使用 PydanticOutputParser
python
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import PydanticOutputParser
Qwen2_5_7B_Instruct_llm = ChatOpenAI(
temperature=0.1, # 控制输出的随机性和创造性,值越低输出越稳定可预测,值越高输出越有创意但可能偏离预期 (范围: 0.0 ~ 2.0)
model_name="Qwen/Qwen2.5-7B-Instruct", # 硅基流动支持的模型名称
openai_api_key=os.getenv("SILICONFLOW_API_KEY"), # 从环境变量获取API密钥
openai_api_base="https://api.siliconflow.cn/v1" # 硅基流动API的基础URL
)
template="尽可能好地回答用户的问题。\n{format_instructions}\n{question}"
parser = PydanticOutputParser(pydantic_object=ResponseSchema)
prompt = template.format(format_instructions=parser.get_format_instructions())
chain = prompt | Qwen2_5_7B_Instruct_llm | output_parser # 连接提示词、模型和输出解析器
# 提问:"世界上最大的沙漠是什么?"
chain.invoke({"question": "世界上最大的沙漠是什么?"})
使用流式输出
使用 chain.stream 方法来接收对 question 的流式响应:"一支足球队有多少名球员?"
python
for chunk in chain.stream({"question": "一支足球队有多少名球员?"}):
print(chunk)