python request 请求 流式输出demo
import requests
import json
url = "https://api.quickrouter.ai/v1/chat/completions"
payload = json.dumps({
"model": "o1-preview",
"messages": [
{
"role": "user",
"content": "写一个小情书"
}
],
"stream": True
})
headers = {
"Accept": "text/event-stream",
"Authorization": "Bearer YOUR_API_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
data = json.loads(line[6:])
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)