AI 大模型应用进阶系列(三):大模型流式输出

带思考能力模型的流式输出

返回数据

  • 存在 reasoning_content,说明正在思考
  • 不存在 reasoning_content 说明思考已经结束
  • 返回 [DONE],说明已经完成
json 复制代码
 {
    "choices": [
        {
            "delta": {
                "content": "xxx",
                "reasoning_content": "xxx",
                "role": "assistant"
            },
            "index": 0
        }
    ],
    "created": xxx,
    "id": "xxx",
    "model": "xxx",
    "service_tier": "default",
    "object": "chat.completion.chunk",
    "usage": null
} 

代码逻辑

python 复制代码
import sys
import json
import requests

# 定义模型配置
_ai_config = {
    "model": "deepseek-reasoner",
    "url": "https://api.deepseek.com/chat/completions",
    "key": "you deepseek key",
}

# 开始思考
def _on_think_start():
    print("think start")

# 思考借宿
def _on_think_end():
    print("think end")

# 正在思考
def _on_thinking(chunk_text):
    sys.stdout.write(chunk_text)
    sys.stdout.flush()

# 流式接收
def _on_receiving(full_text, chunk_text):
    sys.stdout.write(chunk_text)
    sys.stdout.flush()

# 输出结束
def _on_finish(full_text):
    print("finish: " + full_text)


# 流式调用
def chat_stream(
    histories,
    ai_config=None,
    on_receiving=None,
    on_finish=None,
    on_thinking=None,
    on_think_start=None,
    on_think_end=None,
    response_format="text",
):

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {ai_config['key']}",
    }

    payload = {
        "model": ai_config["model"],
        "messages": histories,
        "response_format": {"type": response_format},
        "stream": True,
    }

    full_content = ""

    try:
        # 发送POST请求,设置stream=True以启用流式响应
        with requests.post(
            ai_config["url"], headers=headers, json=payload, stream=True, timeout=60
        ) as response:
            # 检查响应状态码
            response.raise_for_status()

            # 明确设置响应编码为UTF-8,解决中文乱码问题
            response.encoding = "utf-8"

            is_thinking = False
            full_content = ""

            # 流式处理响应内容
            for line in response.iter_lines(decode_unicode=True):

                if line:
                    if line.startswith("data: ") and not line.startswith(
                        "data: [DONE]"
                    ):
                        data = json.loads(line[6:])
                        # 提取并处理返回的内容(这里假设返回格式为OpenAI API风格)
                        if "choices" in data and len(data["choices"]) > 0:
                            delta = data["choices"][0].get("delta", {})
                            if "reasoning_content" in delta:
                                # 存在reasoning_content,说明正在思考
                                current_thinking = True
                            else:
                                # 没有reasoning_content,说明已经思考结束
                                current_thinking = False

                            if current_thinking is True and is_thinking is False:
                                is_thinking = current_thinking
                                if on_think_start is not None:
                                    on_think_start()
                                    continue
                            if current_thinking is False and is_thinking is True:
                                is_thinking = current_thinking
                                if on_think_end is not None:
                                    on_think_end()
                                    continue

                            is_thinking = current_thinking

                            if is_thinking is True:
                                if on_thinking is not None:
                                    on_thinking(delta.get("reasoning_content", ""))
                                    continue

                            content = delta.get("content", "")
                            full_content += content
                            if on_receiving is not None:
                                on_receiving(full_content, content)

        if on_finish is not None:
            on_finish(full_content)
    except requests.exceptions.RequestException as e:
        print(f"请求异常: {e}")
    except json.JSONDecodeError as e:
        print(f"JSON解析错误: {e}")
    except Exception as e:
        print(f"发生未知错误: {e}")

    return full_content

# 调用大模型
chat_stream(
    ai_config=_ai_config,
    on_think_start=_on_think_start,
    on_think_end=_on_think_end,
    on_thinking=_on_thinking,
    on_receiving=_on_receiving,
    on_finish=_on_finish,
    histories=[
        {
            "role": "user",
            "content": "你好",
        }
    ],
)
相关推荐
newxtc2 小时前
【昆明市不动产登记中心-注册安全分析报告】
人工智能·安全
techdashen2 小时前
圆桌讨论:Coding Agent or AI IDE 的现状和未来发展
ide·人工智能
CV实验室3 小时前
TIP 2025 | 哈工大&哈佛等提出 TripleMixer:攻克雨雪雾干扰的3D点云去噪网络!
人工智能·计算机视觉·3d·论文
余俊晖4 小时前
一套针对金融领域多模态问答的自适应多层级RAG框架-VeritasFi
人工智能·金融·rag
码农阿树4 小时前
视频解析转换耗时—OpenCV优化摸索路
人工智能·opencv·音视频
伏小白白白5 小时前
【论文精度-2】求解车辆路径问题的神经组合优化算法:综合展望(Yubin Xiao,2025)
人工智能·算法·机器学习
应用市场5 小时前
OpenCV编程入门:从零开始的计算机视觉之旅
人工智能·opencv·计算机视觉
星域智链5 小时前
宠物智能用品:当毛孩子遇上 AI,是便利还是过度?
人工智能·科技·学习·宠物
taxunjishu6 小时前
DeviceNet 转 MODBUS TCP罗克韦尔 ControlLogix PLC 与上位机在汽车零部件涂装生产线漆膜厚度精准控制的通讯配置案例
人工智能·区块链·工业物联网·工业自动化·总线协议
说私域6 小时前
基于多模态AI技术的传统行业智能化升级路径研究——以开源AI大模型、AI智能名片与S2B2C商城小程序为例
人工智能·小程序·开源