You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用LangChain输出解析器提取流式ConversationChain的response字段?

提取ConversationChain输出中"response"字段的解决方案

LangChain没有直接适配这种需求的现成解析器,但可以通过两种简单方案实现:

1. 自定义输出解析器

继承BaseOutputParser实现一个只提取"response"字段的解析器,兼容流式输出场景:

from langchain.schema import BaseOutputParser
import json

class ResponseOnlyParser(BaseOutputParser):
    def parse(self, text: str) -> str:
        try:
            return json.loads(text).get("response", "")
        except json.JSONDecodeError:
            return text

# 集成到ConversationChain
parser = ResponseOnlyParser()
chain = ConversationChain(llm=your_llm_instance, output_parser=parser)

2. 用JsonOutputParser配合字段提取

先用JsonOutputParser将输出转为字典,再直接提取"response"字段。如果是流式场景,需注意缓存流片段直到拿到完整JSON再解析:

from langchain.output_parsers import JsonOutputParser
from langchain.schema import SystemMessage

# 初始化解析器
parser = JsonOutputParser()
# 可添加系统提示确保LLM输出标准JSON
chain = ConversationChain(
    llm=your_llm_instance,
    output_parser=parser,
    messages=[
        SystemMessage(content="请严格以包含input、history、response字段的JSON格式返回结果")
    ]
)

# 调用后提取response
result = chain.invoke({"input": "你的查询内容"})
target_response = result.get("response", "")

流式场景下,如果LLM是分块输出JSON内容,建议先缓存所有流片段,拼接成完整JSON字符串后再解析提取,避免因部分JSON导致的解析错误。

内容的提问来源于stack exchange,提问作者MartinL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 04:59:54