Update main.py
Browse files
main.py
CHANGED
|
@@ -2,11 +2,11 @@ import httpx
|
|
| 2 |
from fastapi import FastAPI, Request, HTTPException
|
| 3 |
from fastapi.responses import StreamingResponse
|
| 4 |
import json
|
| 5 |
-
import
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
-
# List of API URLs
|
| 10 |
API_URLS = [
|
| 11 |
"https://api.deepinfra.com/v1/openai/chat/completions",
|
| 12 |
"https://stage.api.deepinfra.com/v1/openai/chat/completions",
|
|
@@ -15,15 +15,14 @@ API_URLS = [
|
|
| 15 |
@app.post("/v1/openai/chat/completions")
|
| 16 |
async def proxy_deepinfra(request: Request):
|
| 17 |
"""
|
| 18 |
-
Proxies chat completion requests to the DeepInfra API
|
|
|
|
| 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,24 +34,29 @@ async def proxy_deepinfra(request: Request):
|
|
| 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
|
|
|
|
| 41 |
try:
|
| 42 |
async with httpx.AsyncClient() as client:
|
| 43 |
-
|
| 44 |
-
|
| 45 |
response.raise_for_status()
|
|
|
|
|
|
|
| 46 |
async for chunk in response.aiter_bytes():
|
| 47 |
yield chunk
|
| 48 |
-
#
|
| 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"
|
| 54 |
continue
|
| 55 |
-
|
|
|
|
| 56 |
if last_error:
|
| 57 |
raise HTTPException(status_code=502, detail=f"All API endpoints failed. Last error: {last_error}")
|
| 58 |
|
|
|
|
| 2 |
from fastapi import FastAPI, Request, HTTPException
|
| 3 |
from fastapi.responses import StreamingResponse
|
| 4 |
import json
|
| 5 |
+
import random # Import the random library
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
+
# List of API URLs to be randomized
|
| 10 |
API_URLS = [
|
| 11 |
"https://api.deepinfra.com/v1/openai/chat/completions",
|
| 12 |
"https://stage.api.deepinfra.com/v1/openai/chat/completions",
|
|
|
|
| 15 |
@app.post("/v1/openai/chat/completions")
|
| 16 |
async def proxy_deepinfra(request: Request):
|
| 17 |
"""
|
| 18 |
+
Proxies chat completion requests to the DeepInfra API.
|
| 19 |
+
It randomizes the order of API URLs and uses the next as a fallback.
|
| 20 |
"""
|
| 21 |
try:
|
| 22 |
body = await request.json()
|
| 23 |
except json.JSONDecodeError:
|
| 24 |
raise HTTPException(status_code=400, detail="Invalid JSON in request body")
|
| 25 |
|
|
|
|
|
|
|
| 26 |
headers = {
|
| 27 |
'sec-ch-ua-platform': request.headers.get('sec-ch-ua-platform', '"Windows"'),
|
| 28 |
'Referer': request.headers.get('Referer', 'https://deepinfra.com/'),
|
|
|
|
| 34 |
'Content-Type': request.headers.get('Content-Type', 'application/json'),
|
| 35 |
}
|
| 36 |
|
| 37 |
+
# Create a randomized list of URLs for this specific request
|
| 38 |
+
shuffled_urls = random.sample(API_URLS, len(API_URLS))
|
| 39 |
+
|
| 40 |
async def stream_generator():
|
| 41 |
last_error = None
|
| 42 |
+
for url in shuffled_urls:
|
| 43 |
+
print(f"Attempting to connect to: {url}")
|
| 44 |
try:
|
| 45 |
async with httpx.AsyncClient() as client:
|
| 46 |
+
# Setting timeout=None disables client-side timeouts
|
| 47 |
+
async with client.stream("POST", url, headers=headers, json=body, timeout=None) as response:
|
| 48 |
response.raise_for_status()
|
| 49 |
+
# If successful, print the URL being used
|
| 50 |
+
print(f"Successfully connected. Streaming from: {url}")
|
| 51 |
async for chunk in response.aiter_bytes():
|
| 52 |
yield chunk
|
| 53 |
+
return # Exit after successful stream
|
|
|
|
| 54 |
except (httpx.RequestError, httpx.HTTPStatusError) as e:
|
|
|
|
| 55 |
last_error = e
|
| 56 |
+
print(f"Failed to connect to {url}: {e}. Trying next URL.")
|
| 57 |
continue
|
| 58 |
+
|
| 59 |
+
# This part is reached only if all URLs in the shuffled list failed
|
| 60 |
if last_error:
|
| 61 |
raise HTTPException(status_code=502, detail=f"All API endpoints failed. Last error: {last_error}")
|
| 62 |
|