Wimmboo commited on
Commit
22bdc0f
·
1 Parent(s): d94b228

fix httpx streaming: use client.stream() for async SSE

Browse files
Files changed (1) hide show
  1. proxy/client.py +14 -9
proxy/client.py CHANGED
@@ -64,7 +64,20 @@ async def forward_request(provider: Provider, real_key: str, request: Request, b
64
 
65
  async with httpx.AsyncClient(timeout=_TIMEOUT, follow_redirects=True) as client:
66
  try:
67
- upstream = await client.post(target_url, headers=headers, json=body, stream=stream)
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  except httpx.TimeoutException as exc:
69
  logger.warning("Upstream timeout for %s: %s", provider.name, exc)
70
  raise HTTPException(status_code=504, detail="Upstream provider timed out")
@@ -83,14 +96,6 @@ async def forward_request(provider: Provider, real_key: str, request: Request, b
83
  logger.warning("Upstream error from %s: %d %s", provider.name, upstream.status_code, content[:500])
84
  raise HTTPException(status_code=upstream.status_code, detail=content.decode("utf-8", errors="replace"))
85
 
86
- if stream:
87
- return StreamingResponse(
88
- _stream_chunks(upstream),
89
- status_code=upstream.status_code,
90
- media_type=upstream.headers.get("content-type", "text/event-stream"),
91
- headers={k: v for k, v in upstream.headers.items() if k.lower() in ("cache-control", "x-request-id")},
92
- )
93
-
94
  return {
95
  "status_code": upstream.status_code,
96
  "headers": dict(upstream.headers),
 
64
 
65
  async with httpx.AsyncClient(timeout=_TIMEOUT, follow_redirects=True) as client:
66
  try:
67
+ if stream:
68
+ async with client.stream("POST", target_url, headers=headers, json=body) as upstream:
69
+ if upstream.status_code >= 400:
70
+ content = await upstream.aread()
71
+ logger.warning("Upstream error from %s: %d %s", provider.name, upstream.status_code, content[:500])
72
+ raise HTTPException(status_code=upstream.status_code, detail=content.decode("utf-8", errors="replace"))
73
+ return StreamingResponse(
74
+ _stream_chunks(upstream),
75
+ status_code=upstream.status_code,
76
+ media_type=upstream.headers.get("content-type", "text/event-stream"),
77
+ headers={k: v for k, v in upstream.headers.items() if k.lower() in ("cache-control", "x-request-id")},
78
+ )
79
+ else:
80
+ upstream = await client.post(target_url, headers=headers, json=body)
81
  except httpx.TimeoutException as exc:
82
  logger.warning("Upstream timeout for %s: %s", provider.name, exc)
83
  raise HTTPException(status_code=504, detail="Upstream provider timed out")
 
96
  logger.warning("Upstream error from %s: %d %s", provider.name, upstream.status_code, content[:500])
97
  raise HTTPException(status_code=upstream.status_code, detail=content.decode("utf-8", errors="replace"))
98
 
 
 
 
 
 
 
 
 
99
  return {
100
  "status_code": upstream.status_code,
101
  "headers": dict(upstream.headers),