DeepSeek的API调用 | 结合DeepSeek API文档 | 流式输出效果实现(五)

1、基本情况介绍

  流式输出中,API 规定 stream = True

  震惊!!!官方文档也出错啦!!!

  官方:API 指南 ==> 推理模型 ==> 流式输出代码如下:

from openai import OpenAI
client = OpenAI(api_key="sk-123456", base_url="https://api.deepseek.com")

# Round 1
messages = [{"role": "user", "content": "9.11 and 9.8, which is greater?"}]
response = client.chat.completions.create(
    model="deepseek-reasoner",
    messages=messages,
    stream=True
)

reasoning_content = ""
content = ""

for chunk in response:
    if chunk.choices[0].delta.reasoning_content:
        reasoning_content += chunk.choices[0].delta.reasoning_content
    else:
        content += chunk.choices[0].delta.content

# Round 2
messages.append({"role": "assistant", "content": content})
messages.append({'role': 'user', 'content': "How many Rs are there in the word 'strawberry'?"})
response = client.chat.completions.create(
    model="deepseek-reasoner",
    messages=messages,
    stream=True
)
# ...

  如果运行,结果是报错的,输出结果如下:
2025-4-1-Snipaste_2025-04-01_10-42-17.jpg

说明:多轮对话流式输出与非流式输出的不同在于上一轮对话的结果需要拼接在一起,作为下一轮对话的messages。

1.1 官方文档出错内容介绍和改正

1.1.1 出错内容和原因

for chunk in response:
    if chunk.choices[0].delta.reasoning_content:
        reasoning_content += chunk.choices[0].delta.reasoning_content
    else:
        content += chunk.choices[0].delta.content

以上为出错代码,上面错误原因指出:str只能与str相连。为什么呢?
因为chunk不仅仅只有 reasoning_contentcontent 还存在空值,所以不能只是单单的else

1.1.2 官方文档改正

for chunk in response:
    if chunk.choices[0].delta.reasoning_content:
        reasoning_content += chunk.choices[0].delta.reasoning_content
    elif chunk.choices[0].delta.content:
        content += chunk.choices[0].delta.content

已经运行完毕,结果没有出错

2、 下面流式输出使用 DeepSeek-R1 模型,V3模型也可以使用,但是V3模型没有思维链,太简单了

3、流式输出实现

3.1 只输出思维链

  代码如下:

from openai import OpenAI
import time
client = OpenAI(api_key="sk-123456", base_url="https://api.deepseek.com")

messages = [{"role": "user", "content": "在llm中,什么是rag技术?"}]
response = client.chat.completions.create(
    model="deepseek-reasoner",
    messages=messages,
    stream=True)

for chunk in response:
    if chunk.choices[0].delta.reasoning_content:
        print(chunk.choices[0].delta.reasoning_content, end='', flush=True)
        time.sleep(0.1)  

  代码解释:

  1. 引入了 time 库
  2. 从 response 获取 chunk ,判断是不是 reasoning_content。代码:if chunk.choices[0].delta.reasoning_content:
  3. print() 中,设置 end='' 。不让程序输出一个字就换一行。默认end=‘/n’
  4. flush = True,默认为False。强制将缓冲区的内容立即输出,确保实时显示。
  5. time.sleep(0.1):控制输出速度:每个响应块(chunk)打印后暂停 0.1 秒,模拟逐字输出的效果,避免内容一次性显示过快,提升用户体验。

  结果:
2025-4-1-Snipaste_2025-04-01_11-10-31.jpg

3.2 只流式输出结果

  同理,代码如下:

from openai import OpenAI
import time
client = OpenAI(api_key="sk-123456", base_url="https://api.deepseek.com")
messages = [{"role": "user", "content": "在llm中,什么是rag技术?"}]
response = client.chat.completions.create(
    model="deepseek-reasoner",
    messages=messages,
    stream=True)
for chunk in response:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end='', flush=True)
        time.sleep(0.1)  

只是将 reasoning_content 替换为 content

3.3 流式输出思维链和文本内容

  代码如下:

from openai import OpenAI
import time
client = OpenAI(api_key="sk-123456", base_url="https://api.deepseek.com")
answer_started = False

messages = [{"role": "user", "content": "在llm中,什么是rag技术?"}]
response = client.chat.completions.create(
    model="deepseek-reasoner",
    messages=messages,
    stream=True
)

for chunk in response:
    if chunk.choices[0].delta.reasoning_content:
        print(chunk.choices[0].delta.reasoning_content, end='', flush=True)
        time.sleep(0.1) 
    else:
        if not answer_started and chunk.choices[0].delta.content:
            print("\n\n—————————————【最终答案】———————————————————————————\n", end='')
            answer_started = True
        print(chunk.choices[0].delta.content, end='', flush=True)
        time.sleep(0.1)  

设置一个开关:answer_started ,初始值为负值,代表输出思维链的状态。当开始输出文本内容时,就结束了思维链的输出,所以 answer_started 的值变为正值。输出:————【最终答案】————。然后再输出文本答案。
但是出现一个问题,就是输出思维链的前面输出了一个字符:None ,分析原因可知:chunk在获得思维链之前为空值,使用了print(chunk.choices[0].delta.content, end=‘’, flush=True)为其将 None 输出出来。

3.4 解决思维链中出现None的问题,为最后完整的代码,实现流式输出

from openai import OpenAI
import time
client = OpenAI(api_key="sk-123456", base_url="https://api.deepseek.com")
answer_started = False

messages = [{"role": "user", "content": "在llm中,什么是rag技术?"}]
response = client.chat.completions.create(
    model="deepseek-reasoner",
    messages=messages,
    stream=True
)

for chunk in response:
    if chunk.choices[0].delta.reasoning_content:
        print(chunk.choices[0].delta.reasoning_content, end='', flush=True)
        time.sleep(0.1) 
    elif chunk.choices[0].delta.content:
        if not answer_started:
            print("\n\n—————————————【最终答案】—————————————————————\n", end='')
            answer_started = True
        print(chunk.choices[0].delta.content, end='', flush=True)
        time.sleep(0.1)  
    else:
        continue

2025-4-1-Snipaste_2025-04-01_11-25-53.jpg

4、 总结

  本文解决了官方文档的出错,同时实现了思维链和文本结果的流式输出。

最终代码为:

from openai import OpenAI
import time
client = OpenAI(api_key="sk-123456", base_url="https://api.deepseek.com")
answer_started = False

messages = [{"role": "user", "content": "在llm中,什么是rag技术?"}]
response = client.chat.completions.create(
    model="deepseek-reasoner",
    messages=messages,
    stream=True
)

reasoning_content = ""
content = ""

for chunk in response:
    if chunk.choices[0].delta.reasoning_content:
        reasoning_content += chunk.choices[0].delta.reasoning_content
        print(chunk.choices[0].delta.reasoning_content, end='', flush=True)
        time.sleep(0.1) 
    elif chunk.choices[0].delta.content:
        if not answer_started:
            print("\n\n—————————————【最终答案】———————————————————————————\n", end='')
            answer_started = True
        content += chunk.choices[0].delta.content
        print(chunk.choices[0].delta.content, end='', flush=True)
        time.sleep(0.1)  
    else:
        continue
print(reasoning_content)
print(content)

2025-4-1-Snipaste_2025-04-01_11-36-32.jpg
2025-4-1-Snipaste_2025-04-01_11-37-05.jpg

### 使用Python调用DeepSeek API实现流式输出 为了通过Python调用DeepSeek API并处理流式数据,通常需要遵循API文档中的指导来设置请求参数以及解析响应。虽然具体细节依赖于DeepSeek API的设计,一般流程涉及创建HTTP会话、发送带有适当头部信息和查询字符串的GET或POST请求,并实时读取返回的数据。 假设DeepSeek支持WebSocket协议用于流传输,则可以利用`websockets`库建立连接: ```python import asyncio import websockets async def deepseek_stream(uri): async with websockets.connect(uri) as websocket: while True: message = await websocket.recv() process_message(message) def start_streaming(): uri = "wss://api.deepseek.example/stream" loop = asyncio.get_event_loop() try: loop.run_until_complete(deepseek_stream(uri)) finally: loop.close() start_streaming() ``` 如果采用RESTful风格接口进行分批获取更新,则可能更倾向于使用`requests`库发起持续轮询或是监听长轮询(long polling): ```python import requests def fetch_updates(last_id=None): url = 'https://api.deepseek.example/updates' params = {'last_id': last_id} if last_id else {} response = requests.get(url, stream=True, params=params) for line in response.iter_lines(): if line: decoded_line = line.decode('utf-8') handle_update(decoded_line) fetch_updates() ``` 上述方法适用于不同类型的流服务架构;对于特定于DeepSeek的功能特性,建议查阅官方提供的最新版API手册以获得最准确的操作指南[^1]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

在下_诸葛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值