Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import httpx
|
| 4 |
+
from sanic import Request, Sanic
|
| 5 |
+
from sanic.response import ResponseStream, HTTPResponse
|
| 6 |
+
|
| 7 |
+
HOST = os.getenv("HOST", "::")
|
| 8 |
+
PORT = int(os.getenv("PORT", 8000))
|
| 9 |
+
PROXY_URL = os.getenv("PROXY_URL", None)
|
| 10 |
+
URL = os.getenv("TARGET_URL", "https://api.groq.com/openai/v1/chat/completions")
|
| 11 |
+
TIMEOUT = int(os.getenv("TIMEOUT", 60))
|
| 12 |
+
|
| 13 |
+
app = Sanic("GroqProxy")
|
| 14 |
+
client = httpx.AsyncClient(proxy=PROXY_URL, timeout=TIMEOUT)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@app.post("v1/chat/completions")
|
| 18 |
+
async def completions(request: Request):
|
| 19 |
+
headers = {"Content-Type": "application/json"}
|
| 20 |
+
if auth := request.headers.get("Authorization"):
|
| 21 |
+
headers["Authorization"] = auth
|
| 22 |
+
|
| 23 |
+
if request.json.get("stream", False):
|
| 24 |
+
|
| 25 |
+
async def _streaming_fn(response):
|
| 26 |
+
async with client.stream("POST", URL, headers=headers, data=request.body) as resp:
|
| 27 |
+
async for chunk in resp.aiter_bytes():
|
| 28 |
+
await response.write(chunk)
|
| 29 |
+
|
| 30 |
+
return ResponseStream(streaming_fn=_streaming_fn, content_type="text/event-stream")
|
| 31 |
+
|
| 32 |
+
return HTTPResponse(
|
| 33 |
+
body=(await client.post(URL, headers=headers, data=request.body)).content,
|
| 34 |
+
content_type="application/json",
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if __name__ == "__main__":
|
| 39 |
+
app.run(host=HOST, port=PORT, single_process=True, debug=True)
|