File size: 1,614 Bytes
edb14b7 |
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
import httpx
import asyncio
import ssl
import logging
# 设置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
async def make_request():
# SSL 上下文设置
# ssl_context = ssl.create_default_context()
# ssl_context.set_alpn_protocols(["h2", "http/1.1"])
# 创建自定义传输
transport = httpx.AsyncHTTPTransport(
http2=True,
# verify=ssl_context,
verify=False,
retries=1
)
# 设置头部
headers = {
"User-Agent": "curl/8.7.1",
"Accept": "*/*",
"Content-Type": "application/json",
"Authorization": "Bearer sk-xxxxxxx"
}
# 请求数据
data = {
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": "say test"
}
],
"stream": True
}
async with httpx.AsyncClient(transport=transport) as client:
try:
response = await client.post(
"https://api.xxxxxxxxxx.me/v1/chat/completions",
headers=headers,
json=data,
timeout=30.0
)
logger.info(f"Status Code: {response.status_code}")
logger.info(f"Headers: {response.headers}")
# 处理流式响应
async for line in response.aiter_lines():
if line:
print(line)
except httpx.RequestError as e:
logger.error(f"An error occurred while requesting {e.request.url!r}.")
# 运行异步函数
asyncio.run(make_request()) |