Langchain结构化输出 一、返回 Pydantic 对象我们可以设置执⾏ Runnable 后的输出结果指定为Pydantic类这将返回⼀个 Pydantic 对象。当收到模型的响应后LangChain 会提取出代表Pydantic参数的 JSON 对象并⽤ Pydantic 模型对其进⾏解析和验证将这个验证后的 JSON 转换为⼀个可⽤的 Pydantic 对象实例返回。#结构化输出 from langchain_community.chat_models import ChatTongyi from pydantic import BaseModel, Field model ChatTongyi(modelqwen-plus) class Joke(BaseModel): 讲一个笑话 setup: str Field(description 这个笑话的开头) punchline: str Field(description 这个笑话的妙语) reating: str Field(description 这个笑话的评分) # with_structured_output 可以定义输出schema structured_model model.with_structured_output(Joke) result structured_model.invoke(给我讲一个笑话) print(result)嵌套输出#结构化输出 from typing import List from langchain_community.chat_models import ChatTongyi from pydantic import BaseModel, Field model ChatTongyi(modelqwen-plus) class Joke(BaseModel): 讲一个笑话 setup: str Field(description 这个笑话的开头) punchline: str Field(description 这个笑话的妙语) reating: str Field(description 这个笑话的评分) #嵌套输出 class Data(BaseModel): 一些笑话 jokes: List[Joke] # with_structured_output 可以定义输出schema structured_model model.with_structured_output(Data) result structured_model.invoke(给我分别将一个唱歌和跳舞的笑话) print(result)二、返回 TypedDictTypedDict它⽤于为字典对象提供精确的、结构化的类型提⽰。它允许我们指定⼀个字典中应该有哪些键以及每个键对应的值的类型。from typing import TypedDict, Annotated from langchain_community.chat_models import ChatTongyi class Joke(TypedDict): 讲一个笑话 setup: Annotated[str, ..., 这个笑话的开头] punchline: Annotated[str, ..., 这个笑话的妙语] reating: Annotated[str, ..., 这个笑话的评分] model ChatTongyi(modelqwen-plus) structured_model model.with_structured_output(Joke) print(structured_model.invoke(给我讲一个笑话))三、返回JSON为了声明 JSON我们需要定义 JSON Schemafrom langchain_community.chat_models import ChatTongyi model ChatTongyi(modelqwen-plus) json_schema { title: joke, description: 给⽤⼾讲⼀个笑话。, type: object, properties: { setup: { type: string, description: 这个笑话的开头, }, punchline: { type: string, description: 这个笑话的妙语, }, rating: { type: integer, description: 从1到10分给这个笑话评分, default: None, }, }, required: [setup, punchline], } model_with_structred model.with_structured_output(json_schema) print(model_with_structred.invoke(给我将一个唱歌的笑话))四、可选择的输出格式创建具有联合类型属性的⽗模式以使⽤ Pydantic 为例其他同理from typing import Union from langchain_community.chat_models import ChatTongyi from pydantic import Field, BaseModel class Joke(BaseModel): 讲一个笑话 setup: str Field(description 这个笑话的开头) punchline: str Field(description 这个笑话的妙语) reating: str Field(description 这个笑话的评分) class Chat(BaseModel): 以对话的方式回复用户的问题 message: str Field(description聊天对话的回答) model ChatTongyi(modelqwen-plus) class FinalResponse(BaseModel): finalMessage: Union[Joke, Chat] model_with_structured model.with_structured_output(FinalResponse); print(model_with_structured.invoke(你是谁)) print(model_with_structured.invoke(给我将一个唱歌的笑话))五、实用场景1.作为信息提取器from typing import Optional from langchain_community.chat_models import ChatTongyi from langchain_core.messages import SystemMessage, HumanMessage from pydantic import BaseModel, Field class Person(BaseModel): name: Optional[str] Field(defaultNone, description 这个人的名字) age: Optional[int] Field(defaultNone, description这个人的年纪) skin: Optional[str] Field(defaultNone, description 这个人的肤色) height: Optional[str] Field(defaultNone, description 这个人的身高以米为单位) action: Optional[str] Field(defaultNone, description这个人的动作) model ChatTongyi(model qwen-plus) model_with_structured model.with_structured_output(Person) message [ SystemMessage(content你是⼀个提取信息的专家只从⽂本中提取相关信息。如果您不知道要提取的属性的值属性值返回null), HumanMessage(content一个黑色的小男孩身高1m8, 18岁正在操场上踢足球他的名字叫做小明) ] print(model_with_structured.invoke(message))2.使⽤少样本提⽰来增强信息提取能⼒3.与工具结合使用from langchain_community.chat_models import ChatTongyi from langchain_core.messages import HumanMessage, ToolMessage from langchain_core.tools import tool from pydantic import BaseModel, Field model ChatTongyi(modelqwen-plus) class SearchResult(BaseModel): 结构化搜索结果。 query: str Field(description搜索查询) findings: str Field(description调查结果摘要) tool def web_search(query: str) - str: 在网上搜索信息。 Args: query: 搜索查询 return 西安今天多云转小雨气温18-23度东南风2级空气质量良好 # ChatTongyi.with_structured_output 只支持 schema 和 include_raw # 不支持 OpenAI 专有的 tools / strict 参数。 # 需要工具时先 bind_tools 调用工具再 with_structured_output 整理结果。 query 搜索当前最新的西安的天气 # 1. 让模型决定是否调用 web_search model_with_search model.bind_tools([web_search]) ai_msg model_with_search.invoke(query) if ai_msg.tool_calls: tool_msg web_search.invoke(ai_msg.tool_calls[0]) messages [ HumanMessage(contentquery), ai_msg, tool_msg, HumanMessage(content请根据上面的搜索结果提取结构化信息。), ] else: messages [HumanMessage(contentquery)] # 2. 将结果解析为 SearchResult structured_search_model model.with_structured_output( SearchResult, include_rawTrue, ) result structured_search_model.invoke(messages) print(result)