SmartInc-API / main.py
yoursdvniel's picture
Create main.py
0b10b26 verified
raw
history blame
1.54 kB
from flask import Flask, request, jsonify
from firestore_client import get_firestore_client
from openai_client import ask_gpt
from role_access import get_allowed_collections
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # Allow access from your React app
db = get_firestore_client()
@app.route('/chat', methods=['POST'])
def chat():
data = request.json
role = data.get('role')
user_input = data.get('message')
if not role or not user_input:
return jsonify({"error": "Missing role or message"}), 400
# Optional: handle 'show [collection]' request directly
if user_input.lower().startswith("show "):
col = user_input.lower().replace("show ", "").strip()
allowed = get_allowed_collections(role)
if col in allowed:
docs = db.collection(col).limit(5).stream()
results = [doc.to_dict() for doc in docs]
return jsonify({"reply": f"Showing data from {col}", "data": results})
else:
return jsonify({"reply": f"Access to {col} is denied for role {role}."})
# Otherwise, use GPT to answer
system_msg = {
"role": "system",
"content": f"You are a smart assistant helping a user with role '{role}'. You can access {', '.join(get_allowed_collections(role))}"
}
user_msg = {
"role": "user",
"content": user_input
}
answer = ask_gpt([system_msg, user_msg])
return jsonify({"reply": answer})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860)