Dify chat模型streaming转为文字解决方案

问题

我们搭建了一个Agent的知识库问题,希望调用接口进行返回,但是Agent模型只支持streaming格式,不支持blocking模式。

而流式输出是字节码,我们是不能直接看懂它的意思,因此需要通过下面代码去实现转换。

python 复制代码
import requests
import json


def stream_to_text(url, headers, data):
    """
    将流式API响应转换为完整的文字输出

    参数:
        url: API端点URL
        headers: 请求头
        data: 请求数据(字典格式)

    返回:
        完整的响应文本
    """
    full_response = ""

    try:
        # 发送POST请求,设置stream=True来接收流式响应
        response = requests.post(url, headers=headers, json=data, stream=True)
        response.raise_for_status()

        # 逐行读取流式响应
        for line in response.iter_lines():
            if line:
                # 解码字节为字符串
                line_str = line.decode('utf-8')

                # 流式响应通常以"data: "开头
                if line_str.startswith('data: '):
                    json_str = line_str[6:]  # 移除"data: "前缀

                    try:
                        # 解析JSON数据
                        data_obj = json.loads(json_str)

                        # 根据实际API响应结构提取文本
                        # 这里可能需要根据你的API实际返回格式调整
                        if 'answer' in data_obj:
                            full_response += data_obj['answer']
                        elif 'message' in data_obj:
                            full_response += data_obj['message']
                        elif 'text' in data_obj:
                            full_response += data_obj['text']

                    except json.JSONDecodeError:
                        # 如果不是JSON格式,直接添加文本
                        if json_str != '[DONE]':  # 忽略结束标记
                            full_response += json_str

        return full_response

    except requests.exceptions.RequestException as e:
        return f"请求错误: {str(e)}"


# 使用示例
if __name__ == "__main__":
    url = "http://xxx/v1/chat-messages"

    headers = {
        "Authorization": "Bearer your-api-key",
        "Content-Type": "application/json"
    }

    data = {
        "inputs": {},
        "query": "卷纸属于哪一类的费用报销",
        "response_mode": "streaming",
        "conversation_id": "",
        "user": "abc-123"
    }

    print("正在请求API...")
    result = stream_to_text(url, headers, data)
    print("\n完整响应:")
    print(result)

运行后会得到以下结果:

相关推荐
J船长6 小时前
Agent开发 00|从 ChatGPT 到生产级 AI Agent
agent
Csvn7 小时前
如果明天供应商涨价 3 倍?三层解耦,换模型只改一行配置(C05)
人工智能·aigc·agent
七夜zippoe9 小时前
Agent 告警设计:分级告警、智能降噪与值班排班
开发语言·ai·agent·告警·智能降噪·值班排班
prince_zxill14 小时前
把 17 个散文件装进一个文件夹:拆解 claude-plugins-official 的插件打包术(47,413 Star 实测)
python·github·agent·mcp·claude code
程序员张富华15 小时前
一次发布拦住12个破坏性变更:我们给Agent工作流加了Schema门禁
人工智能·agent
ZhengEnCi17 小时前
Claude 的记忆是怎么设计的:四层记忆栈,和一场叫「做梦」的离线整理
aigc·agent·ai编程
Csvn1 天前
换供应商要改一遍代码?把模型接入收进一层网关(C04)
人工智能·aigc·agent
七夜zippoe1 天前
多 Agent 通信灾难:状态不一致导致雪崩故障的排查与防护
ai·agent·通信灾难·雪崩故障·排查与防护
谙弆悕博士1 天前
多智能体架构详解:层级树状架构(分级主从型)
运维·架构·大模型·agent·多智能体·langgraph·层级树状