javaeeduke commited on
Commit
4faa385
·
verified ·
1 Parent(s): 1da5973

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +16 -12
main.py CHANGED
@@ -277,18 +277,22 @@ async def chat_completions(
277
  logger.info(f"转发请求 → {provider_name} | 模型: {model} | 流式: {stream}")
278
 
279
  # 流式响应中增加状态码检查
280
- if stream:
281
- async def event_stream():
282
- async with httpx.AsyncClient(timeout=120) as client:
283
- async with client.stream("POST", url, headers=headers, json=body) as resp:
284
- if resp.status_code != 200:
285
- err = await resp.aread()
286
- logger.error(f"上游流式错误 {resp.status_code}: {err[:300]}")
287
- yield json.dumps({"error": err.decode(errors='ignore')})
288
- return
289
- async for chunk in resp.aiter_text():
290
- yield chunk
291
- return StreamingResponse(event_stream(), media_type="text/event-stream")
 
 
 
 
292
 
293
  # ── 普通响应 ──
294
  async with httpx.AsyncClient(timeout=120) as client:
 
277
  logger.info(f"转发请求 → {provider_name} | 模型: {model} | 流式: {stream}")
278
 
279
  # 流式响应中增加状态码检查
280
+ # ── 流式响应 ──(注意:if 在函数体内,缩进 4 空格)
281
+ if stream:
282
+ async def event_stream():
283
+ async with httpx.AsyncClient(timeout=120) as client:
284
+ async with client.stream("POST", url, headers=headers, json=body) as resp:
285
+ if resp.status_code != 200:
286
+ err = await resp.aread()
287
+ logger.error(f"上游流式错误 {resp.status_code}")
288
+ yield json.dumps({"error": err.decode(errors="ignore")})
289
+ return
290
+ async for chunk in resp.aiter_text():
291
+ yield chunk
292
+
293
+ # 这个 return 必须缩进 8 空格(在 if stream: 内部)
294
+ return StreamingResponse(event_stream(), media_type="text/event-stream")
295
+
296
 
297
  # ── 普通响应 ──
298
  async with httpx.AsyncClient(timeout=120) as client: