File size: 4,734 Bytes
88a6b83 | 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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | 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"
PROVIDERS = [
g4f.Provider.DuckDuckGo,
g4f.Provider.Blackbox,
]
executor = ThreadPoolExecutor(max_workers=5)
# =====================================
# APP
# =====================================
app = FastAPI(
title="HuggingFace 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.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):
last_error = None
for provider in PROVIDERS:
try:
response = g4f.ChatCompletion.create(
model=model,
provider=provider,
messages=messages
)
return response
except Exception as e:
print(f"{provider.__name__}: {e}")
last_error = e
raise Exception(str(last_error))
# =====================================
# STREAM
# =====================================
async def stream_generate(model, messages):
loop = asyncio.get_event_loop()
for provider in PROVIDERS:
try:
response = await loop.run_in_executor(
executor,
lambda: g4f.ChatCompletion.create(
model=model,
provider=provider,
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"
return
except Exception as e:
print(f"Streaming Error: {e}")
continue
yield f"data: {json.dumps({'error':'All providers failed'})}\\n\\n"
# =====================================
# API
# =====================================
@app.get("/")
async def home():
return {
"status": "online"
}
@app.post("/v1/chat/completions")
async def chat(
req: ChatRequest,
authorization: str = Header(None)
):
if not authorization:
raise HTTPException(
status_code=401,
detail="Missing Authorization"
)
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()
try:
response = await loop.run_in_executor(
executor,
lambda: generate(
req.model,
messages
)
)
return {
"choices": [
{
"message": {
"role": "assistant",
"content": response
}
}
]
}
except Exception as e:
raise HTTPException(
status_code=500,
detail=str(e)
) |