Spaces:
Runtime error
Runtime error
File size: 3,769 Bytes
0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 18e8000 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 18e8000 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 18e8000 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 18e8000 0ff5961 931b5d1 0ff5961 18e8000 931b5d1 18e8000 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 0ff5961 931b5d1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | import asyncio
import json
from concurrent.futures import ThreadPoolExecutor
from typing import List
import g4f
from fastapi import FastAPI, HTTPException, Header
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
# =====================================
# CONFIG
# =====================================
API_KEY = "sk-your-secret-key"
executor = ThreadPoolExecutor(max_workers=5)
# =====================================
# APP
# =====================================
app = FastAPI(
title="AI Gateway"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# =====================================
# MODELS
# =====================================
class Message(BaseModel):
role: str
content: str
class ChatRequest(BaseModel):
model: str = "gpt-4o-mini"
messages: List[Message]
stream: bool = False
# =====================================
# AUTH
# =====================================
def verify_api_key(auth: str):
if not auth:
raise HTTPException(
status_code=401,
detail="Missing Authorization Header"
)
if not auth.startswith("Bearer "):
raise HTTPException(
status_code=401,
detail="Invalid Authorization"
)
token = auth.replace("Bearer ", "")
if token != API_KEY:
raise HTTPException(
status_code=403,
detail="Invalid API Key"
)
# =====================================
# GENERATE
# =====================================
def generate(model, messages):
response = g4f.ChatCompletion.create(
model=model,
messages=messages
)
return response
# =====================================
# STREAM
# =====================================
async def stream_generate(model, messages):
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(
executor,
lambda: g4f.ChatCompletion.create(
model=model,
messages=messages,
stream=True
)
)
for chunk in response:
if chunk:
payload = {
"choices": [
{
"delta": {
"content": chunk
}
}
]
}
yield f"data: {json.dumps(payload)}\\n\\n"
yield "data: [DONE]\\n\\n"
# =====================================
# HOME
# =====================================
@app.get("/")
async def home():
return {
"status": "online"
}
# =====================================
# CHAT
# =====================================
@app.post("/v1/chat/completions")
async def chat(
req: ChatRequest,
authorization: str = Header(None)
):
verify_api_key(authorization)
messages = [
m.model_dump()
for m in req.messages
]
# =========================
# STREAM
# =========================
if req.stream:
return StreamingResponse(
stream_generate(
req.model,
messages
),
media_type="text/event-stream"
)
# =========================
# NORMAL
# =========================
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(
executor,
lambda: generate(
req.model,
messages
)
)
return {
"choices": [
{
"message": {
"role": "assistant",
"content": response
}
}
]
} |