Django实现SSE流

文章目录

一、代码示例

python 复制代码
def llm_stream_generator(agent_url: str, headers: dict, request_data: dict):
    # 调用大模型SSE接口
    response = requests.post(
        url=agent_url,
        headers=headers,
        json=request_data,
        stream=True,
        timeout=10
    )
    response.raise_for_status()

    # 流式读取响应数据
    for line in response.iter_lines():
        if line:
            # 解析大模型返回的SSE数据(根据实际返回格式调整)
            line_data = line.decode('utf-8').strip()
            if line_data.startswith('data:'):
                yield line_data + "\n\n"
python 复制代码
from django.http import StreamingHttpResponse
from django.views.decorators.http import require_GET
from rest_framework.exceptions import APIException

from .utils import llm_stream_generator

# 存储所有连接的客户端
clients = []

@require_GET
def sse_endpoint(request):
    try:
        llm_gen = llm_stream_generator(agent_url="http://127.0.0.1:27080/v1/chat-messages",
                                       headers={"authorization": "Bearer app-xxxxxxxxx"})
        # 3. 返回流式响应
        stream_response = StreamingHttpResponse(
            llm_gen,
            content_type="text/event-stream; charset=utf-8",
        )
        return stream_response
    except Exception as e:
        raise APIException(f"服务器内部错误: {str(e)}")
相关推荐
龙腾AI白云12 小时前
多模大模型应用实战:智能问答系统开发
python·机器学习·数据分析·django·tornado
程序媛徐师姐14 小时前
Python基于OpenCV的马赛克画的设计与实现【附源码、文档说明】
python·opencv·django·马赛克绘画·python马赛克绘画系统·马赛克画·python马赛克画
斯班奇的好朋友阿法法16 小时前
Django 项目打包部署完整指南(适配你的项目,零报错)
python·django·sqlite
斯班奇的好朋友阿法法17 小时前
Django 3.2 项目:从 Hello World 开始(完整功能版)
python·django
tzy2332 天前
AI 对话的流式输出详解——不止于SSE
javascript·ai·llm·sse·readablestream
源码之屋2 天前
计算机毕业设计:Python天气数据采集与可视化分析平台 Django框架 线性回归 数据分析 大数据 机器学习 大模型 气象数据(建议收藏)✅
人工智能·python·深度学习·算法·django·线性回归·课程设计
架构师老Y2 天前
003、Python Web框架深度对比:Django vs Flask vs FastAPI
前端·python·django
预立科技2 天前
SSE、WebSocket 和 HTTP
websocket·网络协议·http·sse
暴力袋鼠哥2 天前
基于 Django 与 Vue 的汽车数据分析系统设计与实现
vue.js·django·汽车
360智汇云2 天前
PostgreSQL 全文检索深度指南:内置 FTS、zhparser 与 pg_search 全解
postgresql·django·全文检索