langchain核心组件 Model I/O(3)-OutputParser

2.5.1 输出解析器介绍

在应用开发中,大模型的输出可能是下一步逻辑处理的关键输入。因此,在这种情况下,规范化输出是必须要做的任务,以确保应用能够顺利进行后续的逻辑处理。

语言模型返回的内容通常都是文本字符串,而实际AI应用开发过程中有时希望模型可以返回更直观、更格式化的内容,LangChain提供了输出解析器(Output Parser)将模型输出解析为结构化数据。

有多种类型的输出解析器,常用的有 StrOutputParser(字符串解析器)与 JsonOutputParser(JSON 解析器)。

2.5.2 StrOutputParser

StrOutputParser 是一个简单的解析器,从结果中提取 content 字段。

举例:将模型输出结果解析为字符串

ini 复制代码
import os   
from langchain.chat_models import init_Chat_model   
from langchain_core.output_parser import StrOutputParser   
llm = init_chatting_model( 
    model="openai/gpt-oss-20b:free", 
    modelprovider="openai",
    base_url="https://openrouter.ai/api/v1", 
    api_key = os.getenv("OPENROUTER_API_KEY"),   
)  
messages=[ {"role": "system", "content": "你是一个机器人"}, {"role": "user", "content": "你好"}]   
resp = llm.invoke(messages)
print(resp)# content'你好!有什么我可以帮忙的吗?'  
str_resp = StrOutputParser().invoke(resp)   
print(str_resp)# 你好!有什么我可以帮忙的吗?

2.5.3 JsonOutputParser

JSON解析器用于将大模型的自由文本输出转换为结构化JSON数据的工具。特别适用于需要严格结构化输出的场景,比如API调用、数据存储或下游任务处理。

JsonOutputParser 能够结合 Pydantic 模型进行数据验证,自动验证字段类型和内容(如字符串、数字、嵌套对象等)

使用get_formatInstructions()获取JSON解析的格式化指令:

ini 复制代码
from pydantic import BaseModel, Field   
from langchain_core.output_parser import JsonOutputParser   
class Prime(BaseModel): 
    prime: list[int]=Field(description="素数") 
    count: list[int] = Field(description = "小于该素数的素数个数")   
json_parser = JsonOutputParser(pydantic_object=Prime) 
print (json_parser.get_format Instructions()) 
# The output should be formatted as a JSON instance that conforms to the JSON schema below.

举例:

ini 复制代码
import os  
from pydantic import BaseModel, Field  
from langchain.chat_models import init_chatting_model
from langchain_core.output_parser import JsonOutputParser   
llm = init_chatting_model(
    model = "openai/gpt-oss-20b:free",
    modelprovider = "openai", 
    base_url = "https://openrouter.ai/api/v1", 
    api_key =os.getenv("OPENROUTER_API_KEY"),   
class Prime(BaseModel): 
    prime: list[int]=Field(description="素数") 
    count: list[int]=Field(description="小于该素数的素数个数")   
json_parser = JsonOutputParser(pydantic_object=Prime) messages={"role": "system", "content": json_parser.get_formatInstructions}}, { "role": "user", "content": "任意生成5个1000-100000之间素数,并标出小于该素数的 素数个数", },   
]   
resp = llm.invoke(messages) 
jsonResp=json_parser.invoke (resp) 
print(jsonResp) 
#{'prime':[1009,2003,3001,4001,5003], 'count':[168,303, 430,584,669]}

2.6 Structured Outputs

可以要求模型按照给定的模式格式提供其响应,这有助于确保输出可以被轻松解析并在后续处理中使用。LangChain支持多种模式类型和强制结构化输出的方法。

2.6.1TypedDict

TypedDict 提供了一个使用 Python 内置类型的简单方案,但是没有验证功能。

kotlin 复制代码
import os  
from typing import Dict, Annotated  
from langchain.chat_models import init chatting_model

llm = init chatting_model(
    model="openai/gpt-oss-20b:free",
    modelprovider="openai",
    base_url="https://openrouter.ai/api/v1",
    api_key=os.getenv("OPENROUTER_API_KEY"),
) 
class Animal(TypedDict):
    animal: Annotated[str, "动物"]
    emoji: Annotated[str, "表情"]
class AnimalList(TypedDict):
    animals: Annotated[list[Animal], "动物与表情列表"]
messages = ["role": "user", "content": "任意生成三种动物,以及他们的emoji表情"]
llm_with_structured_output = llm.with_structured_output(AnimalList)
resp = llm_with_structured_output.invoke(messages)
print(resp)
#{'animals': ['animal': '猫', 'emoji': '鸟'}, {'animal': '老虎', 'emoji': '□'}, {'animal': '企鹅', 'emoji': '□'}]}

2.6.2 Pydantic

Pydantic 模型提供了丰富的功能集,包括字段验证、描述和嵌套结构。

ini 复制代码
import os   
from pydantic import BaseModel,Field   
from langchain.chat_models import init_chat_model   
llm = init_chatting_model( 
    model = "openai/gpt-oss-20b:free", 
    modelprovider = "openai", 
    base_url = "https://openrouter.ai/api/v1", 
    api_key = os.getenv("OPENROUTER_API_KEY"),   
class Animal(BaseModel):
    animal: str=Field(description="动物")  
    emoji: str=Field(description="表情")  
class AnimalList(BaseModel):  
    animals: list[Animal] = Field(description="动物与表情列表")  
    messages = ["role": "user", "content": "任意生成三种动物,以及他们的emoji表情"]  
llm_with_structured_output = llm.with_structured_output(AnimalList)  
resp = llm_with_structured_output.invoke(messages)  
print(resp)  

2.6.3 JSON Schema

若需最大程度的控制或互操作性,可以提供一个原始的JSON Schema。详情可参考platform.openai.com/docs/guides...

可以将原始响应与解析后的表示一起返回,可在调用 with_structured_output 时设置 include_raw=True 来实现。

python 复制代码
import os   
from langchain.chat_models import init_chat_model   
llm=init_chatting_model( 
    model="openai/gpt-oss-20b:free", 
    modelprovider="openai", 
    base_url= "https://openrouter.ai/api/v1", 
    api_key=os.getenv("OPENROUTER_API_KEY")   
)   
schema = {
    "name": "animal_list",
    "schema": {
        "type": "array",
        "items": {
            "type": "object",
            "properties": {
                "animal": {"type": "string", "description": "动物名称"},
                "emoji": {"type": "string", "description": "动物的emoji表情"},
            },
            "required": ["animal", "emoji"],
        },
    },
}  
messages = ["role": "user", "content": "任意生成三种动物,以及他们的emoji表情"]}  
llm_with_structured_output = llm.with_structured_output(schema, method="json_schema", include_raw=True)  
resp = llm_with_structured_output.invoke(messages)  
print(resp)  
print(resp["raw")]  
print(resp[" parsed")]  
相关推荐
沐雪架构师6 小时前
LangChain 1.0 内置的Agent中间件详解
中间件·langchain
Bruk.Liu8 小时前
(LangChain实战5):LangChain消息模版ChatPromptTemplate
人工智能·python·langchain·agent
爱敲代码的TOM8 小时前
大模型应用开发-LangChain框架基础
python·langchain·大模型应用
Bruk.Liu8 小时前
(LangChain实战3):LangChain阻塞式invoke与流式stream的调用
人工智能·python·langchain
Bruk.Liu8 小时前
(LangChain实战4):LangChain消息模版PromptTemplate
人工智能·python·langchain
共享家95279 小时前
LangChain初识
人工智能·langchain
Wang201220139 小时前
langchai自带的搜索功能国内tool有哪些(langchain+deepseek+百度AI搜索 打造带搜索功能的agent)
langchain
玄同7651 天前
Llama.cpp 全实战指南:跨平台部署本地大模型的零门槛方案
人工智能·语言模型·自然语言处理·langchain·交互·llama·ollama
玄同7651 天前
LangChain v1.0+ Prompt 模板完全指南:构建精准可控的大模型交互
人工智能·语言模型·自然语言处理·langchain·nlp·交互·知识图谱
一只理智恩1 天前
筹备计划·江湖邀请令!!!
python·langchain