代码示例 / Python

python request 请求 流式输出demo


import requests

import json



url = "https://www.cokeapi.com/v1/chat/completions"



payload = json.dumps({

   "model": "o1-preview",

   "messages": [

      {

         "role": "user",

         "content": "写一个小情书"

      }

   ],

   "stream": True

})

headers = {

   'Accept': 'text/event-stream',

   'Authorization': 'Bearer 你的key',

   'Content-Type': 'application/json'

}



response = requests.request("POST", url, headers=headers, data=payload, stream=True)



for line in response.iter_lines():

    if line:

        # 跳过空行

        line = line.decode('utf-8')

        if line.startswith('data: '):

            if line == 'data: [DONE]':

                break

            # 解析JSON数据

            data = json.loads(line[6:])  # 去掉 "data: " 前缀

            if 'choices' in data and len(data['choices']) > 0:

                delta = data['choices'][0].get('delta', {})

                if 'content' in delta:

                    print(delta['content'], end='', flush=True)