import json
import time
import requests
from sseclient import SSEClient
from typing import Dict, Any, Callable
def stream_request() -> None:
"""
模拟实现类似JavaScript中基于事件源的请求功能,发送POST请求并处理相关事件回调。
"""
url = "https://api.deepseek.com/chat/completions"
payLoad = {
"messages": [
{
"content": "介绍你自己",
"role": "system"
},
{
"content": "Hi",
"role": "user"
}
],
"model": "deepseek-chat",
"frequency_penalty": 0,
"max_tokens": 2048,
"presence_penalty": 0,
"response_format": {
"type": "text"
},
"stop": None,
"stream": True,
"stream_options": None,
"temperature": 1,
"top_p": 1,
"tools": None,
"tool_choice": "none",
"logprobs": False,
"top_logprobs": None
}
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer xxx'
}
time1=time.time()
try:
with requests.post(url, json=payLoad, headers=headers, stream=True) as response:
if response.status_code!= 200:
print(f"请求失败,状态码: {response.status_code},错误信息: {response.text}")
return
client = SSEClient(response)
for msg in client.events():
print("耗时:",time.time()-time1)
try:
# 尝试解析消息内容里的JSON数据(假设消息里包含JSON数据)
data = json.loads(msg.data)
# print(data)
except json.JSONDecodeError as json_err:
print(f"解析消息数据时出错: {json_err}")
except requests.RequestException as req_err:
print(f"请求过程出现错误: {req_err}")
except Exception as e:
print(f"发生其他未知错误: {e}")
stream_request()
SSEClient
最新推荐文章于 2025-03-23 21:48:29 发布