Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, Request | |
| from fastapi.middleware.cors import CORSMiddleware | |
| import requests | |
| import uvicorn | |
| import os | |
| app = FastAPI() | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| G4F_URL = "https://g4f.space/api/ollama/chat/completions" | |
| async def root(): | |
| return {"status": "running"} | |
| async def chat(request: Request): | |
| data = await request.json() | |
| messages = data.get("messages", []) | |
| model = data.get("model", "gemma3:4b") | |
| clean_messages = [ | |
| {"role": m["role"], "content": str(m["content"])} | |
| for m in messages | |
| if isinstance(m, dict) and m.get("role") and m.get("content") | |
| ] | |
| if not clean_messages: | |
| return {"error": "No valid messages"} | |
| try: | |
| res = requests.post( | |
| G4F_URL, | |
| json={"model": model, "messages": clean_messages}, | |
| headers={"Authorization": "Bearer secret"}, | |
| timeout=120, | |
| ) | |
| res.raise_for_status() | |
| return res.json() | |
| except Exception as e: | |
| return {"error": str(e)} | |
| if __name__ == "__main__": | |
| uvicorn.run( | |
| "app:app", | |
| host="0.0.0.0", | |
| port=int(os.environ.get("PORT", 7860)), | |
| reload=False | |
| ) |