外观
python request 请求 流式输出demo
python
import requests
import json
url = "https://www.aipro2.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)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
