Spaces:
Paused
Paused
Update app/main.py
Browse files12123456789101110111213141516121819131415161718192021222324252627282627282932303132333536373834354041363738394044454647484950515253414243444546474849505152535455565758import osfrom fastapi import FastAPI, HTTPException# app/main.pyfrom fastapi import FastAPIfrom pydantic import BaseModelimport osimport httpx
app = FastAPI()
# Environment variablesHF_TOKEN = os.environ.get("HF_TOKEN")ACCESS_KEY = os.environ.get("ACCESS_KEY")HF_API_BASE = "https://api-inference.huggingface.co/models"
ALLOWED_MODELS = { "gpt2": "gpt2", "mistral": "mistralai/Mistral-7B", "llama2": "meta-llama/Llama-2-7b-chat-hf"}
if not HF_TOKEN or not ACCESS_KEY: raise RuntimeError("Set both HF_TOKEN and ACCESS_KEY in your environment.")# Allowed models for studentsALLOWED_MODELS = [ "gpt2", "distilgpt2", "google/flan-t5-small", "EleutherAI/gpt-neo-125M"]
class Query(BaseModel): text: str model: str key: str
def headers(): return {"Authorization": f"Bearer {HF_TOKEN}"}
@app.post("/predict")async def predict(query: Query): # Check student access key if query.key != ACCESS_KEY: raise HTTPException(status_code=401, detail="Unauthorized") return {"error": "Unauthorized: invalid access key"}
# Check if the model is allowed if query.model not in ALLOWED_MODELS: raise HTTPException( status_code=400, detail=f"Invalid model. Choose from: {list(ALLOWED_MODELS.keys())}" ) return {"error": f"Model '{query.model}' is not allowed. Choose one of {ALLOWED_MODELS}"}
model_name = ALLOWED_MODELS[query.model] url = f"{HF_API_BASE}/{model_name}" # Prepare Hugging Face API request url = f"https://api-inference.huggingface.co/models/{query.model}" headers = {"Authorization": f"Bearer {HF_TOKEN}"} payload = {"inputs": query.text}
async with httpx.AsyncClient(timeout=60.0) as client: resp = await client.post(url, headers=headers(), json=payload) if resp.status_code >= 400: raise HTTPException(status_code=502, detail=f"HF API error: {resp.text}")
data = resp.json() try: return {"generated_text": data[0]["generated_text"]} except (KeyError, IndexError): raise HTTPException(status_code=500, detail="Unexpected response from HF API") try: async with httpx.AsyncClient(timeout=30.0) as client: response = await client.post(url, headers=headers, json=payload) if response.status_code != 200: return {"error": f"HF API error: {response.json()}"}
# Hugging Face returns a list of dicts for text-generation data = response.json() if isinstance(data, list) and "generated_text" in data[0]: return {"generated_text": data[0]["generated_text"]} else: return {"error": f"Unexpected HF API response: {data}"}
except httpx.RequestError as e: return {"error": f"Network error: {str(e)}"}
@app.get("/")def home():app/main.py+33-31