Spaces:
Running
Running
| # main.py | |
| from fastapi import FastAPI, Query | |
| from fastapi.middleware.cors import CORSMiddleware | |
| import requests | |
| import os | |
| from vector_index import VectorDB | |
| vector_db = VectorDB.load("vector_db.pkl") | |
| # --------------------------- | |
| # FastAPI app | |
| # --------------------------- | |
| app = FastAPI(title="Smart AI Backend") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # --------------------------- | |
| # OpenRouter settings | |
| # --------------------------- | |
| OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY") | |
| API_URL = "https://openrouter.ai/api/v1/chat/completions" | |
| HEADERS = { | |
| "Authorization": f"Bearer {OPENROUTER_API_KEY}", | |
| "Content-Type": "application/json", | |
| "HTTP-Referer": "https://huggingface.co", | |
| "X-Title": "My Free AI App" | |
| } | |
| MODEL = "meta-llama/llama-3.3-70b-instruct:free" # FREE & fast | |
| # --------------------------- | |
| # AI Personality (System Prompt) | |
| # --------------------------- | |
| SYSTEM_PROMPT = """ | |
| You are a Men's Fashion Counsellor and Style Consultant. | |
| Your job is to help men dress better while respecting: | |
| - their personality | |
| - comfort | |
| - body type | |
| - budget | |
| - confidence level | |
| - Indian climate and lifestyle | |
| Tone: | |
| - Warm | |
| - Friendly | |
| - Practical | |
| - Confidence-boosting | |
| - Non-judgmental | |
| Style principles: | |
| - Prefer timeless, clean fashion over short-lived trends | |
| - Explain WHY an outfit works | |
| - Suggest realistic, wearable combinations | |
| - Avoid over-complication | |
| - Help the user feel confident, not pressured | |
| When needed: | |
| - Ask simple clarifying questions | |
| - Give step-by-step guidance | |
| """ | |
| # --------------------------- | |
| # Routes | |
| # --------------------------- | |
| def home(): | |
| return {"message": "Backend is working"} | |
| def chat(prompt: str = Query(...)): | |
| if not OPENROUTER_API_KEY: | |
| return {"error": "OPENROUTER_API_KEY not set in Hugging Face Secrets"} | |
| payload = { | |
| "model": MODEL, | |
| "messages": [ | |
| {"role": "system", "content": SYSTEM_PROMPT}, | |
| {"role": "user", "content": prompt} | |
| ] | |
| } | |
| try: | |
| response = requests.post( | |
| API_URL, | |
| headers=HEADERS, | |
| json=payload, | |
| timeout=30 | |
| ) | |
| if response.status_code != 200: | |
| return { | |
| "error": "OpenRouter API error", | |
| "status_code": response.status_code, | |
| "details": response.text | |
| } | |
| data = response.json() | |
| reply = data["choices"][0]["message"]["content"] | |
| return {"reply": reply} | |
| except Exception as e: | |
| return {"error": str(e)} | |