Spaces:
Sleeping
Sleeping
Update assistant.py
Browse files- assistant.py +7 -21
assistant.py
CHANGED
|
@@ -8,65 +8,52 @@ from dotenv import load_dotenv
|
|
| 8 |
load_dotenv()
|
| 9 |
|
| 10 |
assistant_bp = Blueprint("assistant", __name__)
|
| 11 |
-
|
| 12 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
| 13 |
|
| 14 |
-
|
| 15 |
def _build_financial_context(user_id: str) -> str:
|
| 16 |
db = get_db()
|
| 17 |
docs = list(db["transactions"].find({"user_id": user_id}).sort("date", -1).limit(20))
|
| 18 |
-
|
| 19 |
if not docs:
|
| 20 |
return "The user has no transactions recorded yet."
|
| 21 |
-
|
| 22 |
income = sum(d["amount"] for d in docs if d["type"] == "income")
|
| 23 |
expense = sum(d["amount"] for d in docs if d["type"] == "expense")
|
| 24 |
balance = income - expense
|
| 25 |
-
|
| 26 |
lines = [
|
| 27 |
-
f"Total income
|
| 28 |
-
f"Total expenses
|
| 29 |
f"Net balance: ₹{balance:,.2f}",
|
| 30 |
"",
|
| 31 |
-
"Recent transactions
|
| 32 |
]
|
| 33 |
for d in docs[:10]:
|
| 34 |
sign = "+" if d["type"] == "income" else "-"
|
| 35 |
date_str = d["date"].strftime("%d %b %Y") if d.get("date") else "unknown date"
|
| 36 |
lines.append(f" {sign}₹{d['amount']:,.2f} | {d['title']} | {d['category']} | {date_str}")
|
| 37 |
-
|
| 38 |
return "\n".join(lines)
|
| 39 |
|
| 40 |
-
|
| 41 |
-
SYSTEM_PROMPT_TEMPLATE = """You are a smart, friendly personal finance assistant for WealthTracker — a personal finance app.
|
| 42 |
You help users understand their spending, plan budgets, and make better financial decisions.
|
| 43 |
Be concise, practical, and encouraging. Use Indian Rupees (₹) when referencing amounts.
|
| 44 |
|
| 45 |
-
|
| 46 |
{context}
|
| 47 |
|
| 48 |
-
Answer
|
| 49 |
-
|
| 50 |
|
| 51 |
@assistant_bp.route("/chat", methods=["POST"])
|
| 52 |
@require_auth
|
| 53 |
def chat():
|
| 54 |
data = request.get_json(silent=True) or {}
|
| 55 |
user_message = (data.get("message") or "").strip()
|
| 56 |
-
|
| 57 |
if not user_message:
|
| 58 |
return jsonify({"error": "Message is required"}), 400
|
| 59 |
-
|
| 60 |
if not GROQ_API_KEY:
|
| 61 |
return jsonify({"error": "Groq API key not configured"}), 503
|
| 62 |
-
|
| 63 |
try:
|
| 64 |
financial_context = _build_financial_context(g.user_id)
|
| 65 |
except Exception:
|
| 66 |
financial_context = "Could not load transaction data."
|
| 67 |
-
|
| 68 |
-
system_prompt = SYSTEM_PROMPT_TEMPLATE.format(context=financial_context)
|
| 69 |
-
|
| 70 |
try:
|
| 71 |
client = Groq(api_key=GROQ_API_KEY)
|
| 72 |
response = client.chat.completions.create(
|
|
@@ -79,6 +66,5 @@ def chat():
|
|
| 79 |
)
|
| 80 |
reply = response.choices[0].message.content
|
| 81 |
return jsonify({"reply": reply}), 200
|
| 82 |
-
|
| 83 |
except Exception as e:
|
| 84 |
return jsonify({"error": f"AI error: {str(e)}"}), 500
|
|
|
|
| 8 |
load_dotenv()
|
| 9 |
|
| 10 |
assistant_bp = Blueprint("assistant", __name__)
|
|
|
|
| 11 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
| 12 |
|
|
|
|
| 13 |
def _build_financial_context(user_id: str) -> str:
|
| 14 |
db = get_db()
|
| 15 |
docs = list(db["transactions"].find({"user_id": user_id}).sort("date", -1).limit(20))
|
|
|
|
| 16 |
if not docs:
|
| 17 |
return "The user has no transactions recorded yet."
|
|
|
|
| 18 |
income = sum(d["amount"] for d in docs if d["type"] == "income")
|
| 19 |
expense = sum(d["amount"] for d in docs if d["type"] == "expense")
|
| 20 |
balance = income - expense
|
|
|
|
| 21 |
lines = [
|
| 22 |
+
f"Total income: ₹{income:,.2f}",
|
| 23 |
+
f"Total expenses: ₹{expense:,.2f}",
|
| 24 |
f"Net balance: ₹{balance:,.2f}",
|
| 25 |
"",
|
| 26 |
+
"Recent transactions:",
|
| 27 |
]
|
| 28 |
for d in docs[:10]:
|
| 29 |
sign = "+" if d["type"] == "income" else "-"
|
| 30 |
date_str = d["date"].strftime("%d %b %Y") if d.get("date") else "unknown date"
|
| 31 |
lines.append(f" {sign}₹{d['amount']:,.2f} | {d['title']} | {d['category']} | {date_str}")
|
|
|
|
| 32 |
return "\n".join(lines)
|
| 33 |
|
| 34 |
+
SYSTEM_PROMPT = """You are a smart, friendly personal finance assistant for WealthTracker.
|
|
|
|
| 35 |
You help users understand their spending, plan budgets, and make better financial decisions.
|
| 36 |
Be concise, practical, and encouraging. Use Indian Rupees (₹) when referencing amounts.
|
| 37 |
|
| 38 |
+
User's financial snapshot:
|
| 39 |
{context}
|
| 40 |
|
| 41 |
+
Answer based on this data. If not finance-related, gently redirect."""
|
|
|
|
| 42 |
|
| 43 |
@assistant_bp.route("/chat", methods=["POST"])
|
| 44 |
@require_auth
|
| 45 |
def chat():
|
| 46 |
data = request.get_json(silent=True) or {}
|
| 47 |
user_message = (data.get("message") or "").strip()
|
|
|
|
| 48 |
if not user_message:
|
| 49 |
return jsonify({"error": "Message is required"}), 400
|
|
|
|
| 50 |
if not GROQ_API_KEY:
|
| 51 |
return jsonify({"error": "Groq API key not configured"}), 503
|
|
|
|
| 52 |
try:
|
| 53 |
financial_context = _build_financial_context(g.user_id)
|
| 54 |
except Exception:
|
| 55 |
financial_context = "Could not load transaction data."
|
| 56 |
+
system_prompt = SYSTEM_PROMPT.format(context=financial_context)
|
|
|
|
|
|
|
| 57 |
try:
|
| 58 |
client = Groq(api_key=GROQ_API_KEY)
|
| 59 |
response = client.chat.completions.create(
|
|
|
|
| 66 |
)
|
| 67 |
reply = response.choices[0].message.content
|
| 68 |
return jsonify({"reply": reply}), 200
|
|
|
|
| 69 |
except Exception as e:
|
| 70 |
return jsonify({"error": f"AI error: {str(e)}"}), 500
|