azr43l commited on
Commit
3b39b74
·
verified ·
1 Parent(s): f23f80e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -41
app.py CHANGED
@@ -31,6 +31,7 @@ client = httpx.AsyncClient(
31
  async def forward_request(
32
  request: Request,
33
  path: str,
 
34
  stream: bool = False
35
  ):
36
  """Forward request to target endpoint"""
@@ -38,8 +39,9 @@ async def forward_request(
38
  # Build target URL
39
  target_url = f"{TARGET_BASE_URL.rstrip('/')}/{path.lstrip('/')}"
40
 
41
- # Get request body
42
- body = await request.body()
 
43
 
44
  # Prepare headers
45
  headers = dict(request.headers)
@@ -49,26 +51,14 @@ async def forward_request(
49
 
50
  # Forward the request with original headers (including the user's API key)
51
  try:
52
- if stream:
53
- # For streaming, we return a streaming response
54
- response = await client.request(
55
- method=request.method,
56
- url=target_url,
57
- headers=headers,
58
- content=body,
59
- follow_redirects=True,
60
- )
61
- return response
62
- else:
63
- # For non-streaming, just get the response
64
- response = await client.request(
65
- method=request.method,
66
- url=target_url,
67
- headers=headers,
68
- content=body,
69
- follow_redirects=True,
70
- )
71
- return response
72
  except httpx.TimeoutException:
73
  raise HTTPException(status_code=504, detail="Gateway Timeout")
74
  except httpx.RequestError as e:
@@ -86,24 +76,20 @@ async def stream_response(response: httpx.Response):
86
  async def proxy_all(path: str, request: Request):
87
  """Main proxy endpoint - catches all requests"""
88
 
89
- # Special handling for streaming completions
 
 
 
90
  is_streaming = False
91
- if path.endswith("completions") or path.endswith("chat/completions"):
92
- # Check if streaming is requested
93
- if request.method == "POST":
94
- body = await request.body()
95
- try:
96
- data = json.loads(body)
97
- is_streaming = data.get("stream", False)
98
- except:
99
- pass
100
- # Re-create request scope - we need to re-read body
101
- # Create a new request with the same body
102
- new_request = Request(request.scope, receive=request.receive)
103
- # Forward with streaming if needed
104
- response = await forward_request(new_request, path, stream=is_streaming)
105
- else:
106
- response = await forward_request(request, path, stream=False)
107
 
108
  # Handle streaming responses
109
  if is_streaming:
@@ -140,9 +126,9 @@ async def root():
140
  }
141
 
142
  @app.get("/v1/models")
143
- async def list_models():
144
  """Proxy for models list"""
145
- response = await forward_request(Request({"method": "GET", "url": "/v1/models"}), "v1/models")
146
  content = await response.aread()
147
  return Response(
148
  content=content,
 
31
  async def forward_request(
32
  request: Request,
33
  path: str,
34
+ body_bytes: Optional[bytes] = None,
35
  stream: bool = False
36
  ):
37
  """Forward request to target endpoint"""
 
39
  # Build target URL
40
  target_url = f"{TARGET_BASE_URL.rstrip('/')}/{path.lstrip('/')}"
41
 
42
+ # Get request body if not provided
43
+ if body_bytes is None:
44
+ body_bytes = await request.body()
45
 
46
  # Prepare headers
47
  headers = dict(request.headers)
 
51
 
52
  # Forward the request with original headers (including the user's API key)
53
  try:
54
+ response = await client.request(
55
+ method=request.method,
56
+ url=target_url,
57
+ headers=headers,
58
+ content=body_bytes,
59
+ follow_redirects=True,
60
+ )
61
+ return response
 
 
 
 
 
 
 
 
 
 
 
 
62
  except httpx.TimeoutException:
63
  raise HTTPException(status_code=504, detail="Gateway Timeout")
64
  except httpx.RequestError as e:
 
76
  async def proxy_all(path: str, request: Request):
77
  """Main proxy endpoint - catches all requests"""
78
 
79
+ # Read the body once
80
+ body_bytes = await request.body()
81
+
82
+ # Check if streaming is requested (only for POST requests to completion endpoints)
83
  is_streaming = False
84
+ if request.method == "POST" and (path.endswith("completions") or path.endswith("chat/completions")):
85
+ try:
86
+ data = json.loads(body_bytes)
87
+ is_streaming = data.get("stream", False)
88
+ except:
89
+ pass
90
+
91
+ # Forward the request
92
+ response = await forward_request(request, path, body_bytes, stream=is_streaming)
 
 
 
 
 
 
 
93
 
94
  # Handle streaming responses
95
  if is_streaming:
 
126
  }
127
 
128
  @app.get("/v1/models")
129
+ async def list_models(request: Request):
130
  """Proxy for models list"""
131
+ response = await forward_request(request, "v1/models")
132
  content = await response.aread()
133
  return Response(
134
  content=content,