使用流式模式进行输出

在 python 中使用 stream模式时,除了 payload 中的 stream 需要设置外,request 请求的参数也需要设置 stream=True, 才能正常按照 stream 模式进行返回。

import requests
   
url = "https://api.siliconflow.cn/v1/chat/completions"
   
payload = {
        "model": "deepseek-ai/DeepSeek-V2-Chat", # 替换成你的模型
        "messages": [
            {
                "role": "user",
                "content": "SiliconCloud公测上线,每用户送3亿token 解锁开源大模型创新能力。对于整个大模型应用领域带来哪些改变?"
            }
        ],
        "stream": True # 此处需要设置为stream模式
}

headers = {
        "accept": "application/json",
        "content-type": "application/json",
        "authorization": "Bearer sk-tokens"
    }
   
response = requests.post(url, json=payload, headers=headers, stream=True) # 此处request需要指定stream模式

# 打印流式返回信息
if response.status_code == 200: 
    for chunk in response.iter_content(chunk_size=8192): 
        if chunk:
            decoded_chunk = chunk.decode('utf-8')
            print(decoded_chunk, end='')
else:
    print('Request failed with status code:', response.status_code)