请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

requests模块的SSE请求

老师,这里的request的请求,如果需要流式返回的话,我测试的时候,发现需要显示的加上这个stream=True的参数才能实现

https://img1.sycdn.imooc.com/szimg/c1facd69090475a307470567.jpg

正在回答

2回答

with requests.request(
        "POST",
        "https://api.deepseek.com/chat/completions",
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": f"Bearer {os.getenv('DEEPSEEK_API_KEY')}"
        },
        # 推理模型:"model": "deepseek-reasoner",
        # 聊天模型:"model": "deepseek-chat",
        json={
            "model": "deepseek-reasoner",
            "messages": [
                {"role": "user", "content": "你好,介绍一下你自己"}
            ],
            "stream": True
        },
        stream=True,
) as resp:

测试了一下,确实需要增加两个

"stream": True

json中的那个stream:true是为了让模型的返回能支持流式分片返回,但是课程中的方式没有开启http库的流式返回,因此最终的结果是一次性全部打印出来了,但是内容是分片的。

需要在requests网络库里也单独再启stream:true,才能真正在控制台响应那里实现流式打印的效果。

0 回复 有任何疑惑可以回复我~
泽辉呀 2025-11-12 08:35:19

能看下在外部不加stream=True的时候,resp的响应内容么?

0 回复 有任何疑惑可以回复我~
  • 补充:
    在外部不加stream=True的内容是直接返回过来的是一次性是全部的,但会按照流失效果 分开的内容
    1.{"id":"710999f4-d93f-4bba-bddc-a9141de1fbe4","object":"chat.completion.chunk","created":1774319317,"model":"deepseek-reasoner","system_fingerprint":"fp_eaab8d114b_prod0820_fp8_kvcache_new_kvcache","choices":[{"index":0,"delta":{"content":null,"reasoning_content":","},"logprobs":null,"finish_reason":null}]}
    
    
    2.{"id":"710999f4-d93f-4bba-bddc-a9141de1fbe4","object":"chat.completion.chunk","created":1774319317,"model":"deepseek-reasoner","system_fingerprint":"fp_eaab8d114b_prod0820_fp8_kvcache_new_kvcache","choices":[{"index":0,"delta":{"content":null,"reasoning_content":"保持"},"logprobs":null,"finish_reason":null}]}
    
    3.{"id":"710999f4-d93f-4bba-bddc-a9141de1fbe4","object":"chat.completion.chunk","created":1774319317,"model":"deepseek-reasoner","system_fingerprint":"fp_eaab8d114b_prod0820_fp8_kvcache_new_kvcache","choices":[{"index":0,"delta":{"content":null,"reasoning_content":"友好"},"logprobs":null,"finish_reason":null}]}
    
    
      就是保持友好
    回复 有任何疑惑可以回复我~ 1天前
  • 测试了的确是,我优化下,感谢反馈
    回复 有任何疑惑可以回复我~ 1天前
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号