流式输出
启用流式
bash
curl https://api.osp.io/v1/chat/completions \
-H "Authorization: Bearer $OSP_A... \
-d '{"model": "gpt-4o", "messages": [{"role": "user", "content": "用三句话解释量子计算"}], "stream": true}'响应为 SSE 流(text/event-stream)。
Python 示例
python
import requests, json
resp = requests.post("https://api.osp.io/v1/chat/completions",
headers={"Authorization": f"Bearer {api_key}"},
json={"model": "gpt-4o", "messages": [{"role": "user", "content": "hello"}], "stream": True},
stream=True)
for line in resp.iter_lines():
if line.startswith("data: "):
data = line[6:]
if data.strip() == "[DONE]": break
content = json.loads(data)["choices"][0]["delta"].get("content", "")
if content: print(content, end="", flush=True)注意事项
- 流式无法与
response_format: json_schema兼用 - Gemini/Claude 流式格式兼容 OpenAI SSE