rkihacker commited on
Commit
500ef17
·
verified ·
1 Parent(s): 4d54556

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +34 -15
main.py CHANGED
@@ -1,26 +1,29 @@
1
  import httpx
2
- from fastapi import FastAPI, Request
3
  from fastapi.responses import StreamingResponse
4
  import json
 
5
 
6
  app = FastAPI()
7
 
 
 
 
 
 
 
8
  @app.post("/v1/openai/chat/completions")
9
  async def proxy_deepinfra(request: Request):
10
  """
11
- Proxies chat completion requests to the DeepInfra API.
12
  """
13
- client = httpx.AsyncClient()
14
- url = "https://api.deepinfra.com/v1/openai/chat/completions"
15
-
16
- # Extract the raw body from the request
17
- body = await request.body()
18
- # Decode the body to a string and then load it as JSON
19
  try:
20
- data = json.loads(body.decode('utf-8'))
21
  except json.JSONDecodeError:
22
- return {"error": "Invalid JSON in request body"}, 400
23
 
 
 
24
  headers = {
25
  'sec-ch-ua-platform': request.headers.get('sec-ch-ua-platform', '"Windows"'),
26
  'Referer': request.headers.get('Referer', 'https://deepinfra.com/'),
@@ -32,12 +35,28 @@ async def proxy_deepinfra(request: Request):
32
  'Content-Type': request.headers.get('Content-Type', 'application/json'),
33
  }
34
 
35
- async def stream_response():
36
- async with client.stream("POST", url, headers=headers, json=data, timeout=None) as response:
37
- async for chunk in response.aiter_bytes():
38
- yield chunk
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- return StreamingResponse(stream_response(), media_type="text/event-stream")
41
 
42
  if __name__ == "__main__":
43
  import uvicorn
 
1
  import httpx
2
+ from fastapi import FastAPI, Request, HTTPException
3
  from fastapi.responses import StreamingResponse
4
  import json
5
+ import asyncio
6
 
7
  app = FastAPI()
8
 
9
+ # List of API URLs, with the primary first and fallbacks after
10
+ API_URLS = [
11
+ "https://api.deepinfra.com/v1/openai/chat/completions",
12
+ "https://stage.api.deepinfra.com/v1/openai/chat/completions",
13
+ ]
14
+
15
  @app.post("/v1/openai/chat/completions")
16
  async def proxy_deepinfra(request: Request):
17
  """
18
+ Proxies chat completion requests to the DeepInfra API with fallback support.
19
  """
 
 
 
 
 
 
20
  try:
21
+ body = await request.json()
22
  except json.JSONDecodeError:
23
+ raise HTTPException(status_code=400, detail="Invalid JSON in request body")
24
 
25
+ # The original curl command headers can be used as a base
26
+ # and overridden by headers from the incoming request if needed.
27
  headers = {
28
  'sec-ch-ua-platform': request.headers.get('sec-ch-ua-platform', '"Windows"'),
29
  'Referer': request.headers.get('Referer', 'https://deepinfra.com/'),
 
35
  'Content-Type': request.headers.get('Content-Type', 'application/json'),
36
  }
37
 
38
+ async def stream_generator():
39
+ last_error = None
40
+ for url in API_URLS:
41
+ try:
42
+ async with httpx.AsyncClient() as client:
43
+ async with client.stream("POST", url, headers=headers, json=body, timeout=30.0) as response:
44
+ # Raise an exception for bad status codes to trigger the fallback
45
+ response.raise_for_status()
46
+ async for chunk in response.aiter_bytes():
47
+ yield chunk
48
+ # If we successfully stream the response, we're done.
49
+ return
50
+ except (httpx.RequestError, httpx.HTTPStatusError) as e:
51
+ # Store the last error and try the next URL
52
+ last_error = e
53
+ print(f"Error with URL {url}: {e}. Trying next fallback.")
54
+ continue
55
+ # If all URLs failed, raise an exception based on the last error.
56
+ if last_error:
57
+ raise HTTPException(status_code=502, detail=f"All API endpoints failed. Last error: {last_error}")
58
 
59
+ return StreamingResponse(stream_generator(), media_type="text/event-stream")
60
 
61
  if __name__ == "__main__":
62
  import uvicorn