File size: 1,804 Bytes
ba99ec5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

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)

@app.route("/ask", methods=["POST"])
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)}"})