Spaces:
Configuration error
Configuration error
import json | |
import os | |
import numpy as np | |
import faiss | |
from sentence_transformers import SentenceTransformer | |
from flask import Flask, request, jsonify | |
from flask_cors import CORS | |
import google.generativeai as genai | |
app = Flask(__name__) | |
CORS(app) | |
# Load Gemini | |
genai.configure(api_key=os.environ["GEMINI_API_KEY"]) | |
gemini_model = genai.GenerativeModel("gemini-1.5-flash") | |
# Lazy load | |
model = None | |
chunks = None | |
index = None | |
# Load profiles once | |
with open("profiles.json", "r") as f: | |
profiles = json.load(f) | |
def ask(): | |
global model, chunks, index | |
data = request.get_json() | |
question = data.get("question") | |
user_id = data.get("userId") | |
profile_name = data.get("profileName", "").lower() | |
if not question or not user_id: | |
return jsonify({"answer": "Missing question or userId"}), 400 | |
# Lazy load embeddings and FAISS | |
if model is None: | |
model = SentenceTransformer("intfloat/e5-small") | |
if chunks is None or index is None: | |
with open("chunks.json", "r") as f: | |
chunks = json.load(f) | |
index = faiss.read_index("faiss.index") | |
# Embed question | |
q_emb = model.encode([question]) | |
D, I = index.search(np.array(q_emb), k=3) | |
context = "\n\n".join([chunks[i] for i in I[0]]) | |
# Load profile | |
bullet_points = profiles.get(profile_name, []) | |
profile_context = "\n".join(bullet_points) | |
# Prompt | |
prompt = f""" | |
You are El_Kapitán_100b, a professional cross-country skiing coach. | |
User profile: | |
{profile_context} | |
Context: | |
{context} | |
Question: | |
{question} | |
""" | |
try: | |
response = gemini_model.generate_content(prompt) | |
return jsonify({"answer": response.text}) | |
except Exception as e: | |
return jsonify({"answer": f"Server error: {str(e)}"}) | |