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)

运行后会得到以下结果:

相关推荐
阿杰学AI6 小时前
AI核心知识75——大语言模型之MAS (简洁且通俗易懂版)
人工智能·ai·语言模型·自然语言处理·agent·多智能体协作·mas
laplace01239 小时前
Clawdbot 部署到飞书(飞连)使用教程(完整版)
人工智能·笔记·agent·rag·clawdbot
山顶夕景12 小时前
【LLM】多模态智能体Kimi-K2.5模型
llm·agent·多模态
JTnnnnn12 小时前
【架構優化】拒絕 LLM 幻覺:設計基於 Python 路由的 AntV 智慧圖表生成系統
llm·antv·dify
yuanlulu12 小时前
Agent_Skills_完全教程「AI生成」
人工智能·大语言模型·agent·智能体·skill·claude code·opencode
阿_焦12 小时前
docker部署dify踩坑笔记
docker·ai·dify
玄同76513 小时前
LangChain v1.0 中间件深度解析:从 Callback 到 Middleware 的演进
人工智能·语言模型·自然语言处理·中间件·langchain·agent·智能体
roamingcode13 小时前
Cursor-memory-cli 自动化记忆提取的完整实现
运维·自动化·agent·memory·cursor·持久化记忆
陈希瑞13 小时前
OpenClaw部署与配置教程:在Mac mini上接入国产大模型与飞书
飞书·agent·openclawd
GJGCY1 天前
技术解析|中国智能体4类路径深度拆解,这类底座架构优势凸显
人工智能·经验分享·ai·agent·智能体·数字员工