Spaces:
Runtime error
Runtime error
Update src/streamlit_app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072081234567891011121314151617181920212223242526272829303132332102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652663435363738394041424344454647484950# app.py"""Personal Finance Chatbot (Streamlit + IBM watsonx + Watson Assistant)- Single-file demo app- Requirements: streamlit, pandas, python-dotenv, ibm-watsonx-ai, ibm-watson- Set env vars before running (see README block below)"""
import osimport jsonimport pandas as pdimport streamlit as stfrom dotenv import load_dotenvfrom datetime import datetimefrom typing import Dict, Any, List
# IBM SDK importstry: from ibm_watsonx_ai import APIClient, Credentialsexcept Exception: APIClient = Nonetry: from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticatorexcept Exception: AssistantV2 = None
# Load env vars from .env if presentload_dotenv()
# -------------------------# Configuration / ENV VARS# -------------------------WATSONX_API_KEY = os.getenv("WATSONX_API_KEY") # watsonx IAM apikeyWATSONX_URL = os.getenv("WATSONX_URL") # watsonx url/endpoint (e.g. https://us-south.ml.cloud.ibm.com)WATSONX_MODEL_ID = os.getenv("WATSONX_MODEL_ID", "ibm/granite-13b-instruct-v2") # default example model
ASSISTANT_APIKEY = os.getenv("ASSISTANT_APIKEY") # Watson Assistant api key (optional)ASSISTANT_URL = os.getenv("ASSISTANT_URL") # Watson Assistant url (optional)ASSISTANT_ID = os.getenv("ASSISTANT_ID") # Assistant ID (if using dialog)
# Minimal checksif APIClient is None: st.warning("ibm-watsonx-ai not installed. Install with: pip install ibm-watsonx-ai")if AssistantV2 is None: st.info("ibm-watson (Assistant) client not installed or optional. Install: pip install ibm-watson")
# -------------------------# Helper: WatsonX client# -------------------------def make_watsonx_client() -> Any: """Create and return a watsonx APIClient or None if not configured""" if not (WATSONX_API_KEY and WATSONX_URL): return None credentials = Credentials(url=WATSONX_URL, api_key=WATSONX_API_KEY) client = APIClient(credentials=credentials) return client
def watsonx_generate(client: Any, prompt: str, model_id: str = None, max_tokens: int = 512) -> str: """ Generate text using watsonx foundation model via ibm_watsonx_ai client. This function uses ModelInference utilities available on the client. """ if client is None: return "Watsonx client is not configured. Please set WATSONX_API_KEY and WATSONX_URL."
model_id = model_id or WATSONX_MODEL_ID # Use the client's models or model inference helper: # many SDK variations exist; below uses a common pattern (generate_text). try: model_inference = client.model_inference(model_id=model_id) # simple call; more params (temperature, top_k, max_output_tokens) can be passed via params generated = model_inference.generate_text(prompt=prompt, max_output_tokens=max_tokens) # returned type can be dict/json or string depending on sdk version if isinstance(generated, (dict, list)): # attempt to extract textual content text = json.dumps(generated) # fallback representation else: text = str(generated) return text except Exception as e: return f"Error calling watsonx generate: {e}"
# -------------------------# Optional: Watson Assistant helper (for intents / dialog)# -------------------------def make_assistant_client(): if not (ASSISTANT_APIKEY and ASSISTANT_URL): return None auth = IAMAuthenticator(ASSISTANT_APIKEY) assistant = AssistantV2(version="2024-01-01", authenticator=auth) assistant.set_service_url(ASSISTANT_URL) return assistant
# -------------------------# Budget parsing & analytics# -------------------------def parse_transactions_csv(uploaded_file) -> pd.DataFrame: """ Expect CSV with columns: date, description, amount, category (category optional). Returns dataframe with normalized date and numeric amount. """ df = pd.read_csv(uploaded_file) # basic normalization if "date" in df.columns: df["date"] = pd.to_datetime(df["date"], errors="coerce") if "amount" in df.columns: df["amount"] = pd.to_numeric(df["amount"], errors="coerce") # create category if missing (simple rule-based) if "category" not in df.columns: df["category"] = df["description"].fillna("").str.lower().apply(guess_category_from_desc) df = df.dropna(subset=["amount"]) return df
def guess_category_from_desc(desc: str) -> str: desc = (desc or "").lower() if any(k in desc for k in ["uber", "ola", "cab", "taxi"]): return "transport" if any(k in desc for k in ["grocery", "walmart", "bigbasket", "grocer"]): return "groceries" if any(k in desc for k in ["rent", "apartment", "house"]): return "rent" if any(k in desc for k in ["netflix", "spotify", "prime", "hulu"]): return "entertainment" if any(k in desc for k in ["salary", "pay", "deposit"]): return "income" return "other"
def budget_summary(df: pd.DataFrame) -> Dict[str, Any]: """ Generate a simple summary: total income, total expenses, top categories. """ income = df[df["amount"] > 0]["amount"].sum() expenses = -df[df["amount"] < 0]["amount"].sum() # amounts might be negative for expenses by_cat = df.groupby("category")["amount"].sum().sort_values() top_exp = by_cat[by_cat < 0].sort_values().head(5) * -1 return { "total_income": float(income), "total_expenses": float(expenses), "net_savings": float(income - expenses), "top_expense_categories": top_exp.to_dict() }
# -------------------------# Prompt engineering helpers# -------------------------def build_prompt(user_question: str, demographic: str, budget_summary_text: str = "") -> str: """ Build a watsonx prompt which adjusts tone and complexity based on demographic. demographic: "student" or "professional" """ tone = "friendly, simple, and educational" if demographic.lower() == "student" else "concise, professional, actionable" complexity = "use short, clear sentences and examples" if demographic.lower() == "student" else "use precise financial language; include bullet recommendations" prompt = ( f"You are a helpful personal finance assistant. Adopt a {tone} tone and {complexity}.\n\n" f"Context (if any):\n{budget_summary_text}\n\n" f"User question: {user_question}\n\n" f"Provide:\n1) Short answer to the user's question.\n2) A 3-point actionable plan or suggestion.\n3) If the question is budget-related, give 1 quick saving tip.\n\nAnswer:" ) return prompt
# -------------------------# Streamlit UI# -------------------------st.set_page_config(page_title="Personal Finance Chatbot", layout="wide")st.title("💬 Personal Finance Chatbot — Savings, Taxes, Investments (IBM watsonx)")
# Sidebar: upload transactions and settingsst.sidebar.header("Data & Settings")uploaded = st.sidebar.file_uploader("Upload transactions CSV (date,description,amount,category optional)", type=["csv"])demographic = st.sidebar.selectbox("User type (affects tone & complexity)", ["student", "professional"])model_choice = st.sidebar.text_input("watsonx model id", value=WATSONX_MODEL_ID)
st.sidebar.markdown("**API status**")watsonx_client = make_watsonx_client()assistant_client = make_assistant_client()st.sidebar.write("watsonx configured:", bool(watsonx_client))st.sidebar.write("Assistant configured:", bool(assistant_client))
# Load transactions if providedtx_df = Nonebudget_text = ""if uploaded: try: tx_df = parse_transactions_csv(uploaded) st.sidebar.success(f"Loaded {len(tx_df)} transactions") summary = budget_summary(tx_df) # create a short textual budget summary for context to the model budget_text = ( f"Total income: {summary['total_income']:.2f}. " f"Total expenses: {summary['total_expenses']:.2f}. " f"Net savings: {summary['net_savings']:.2f}. " f"Top expense categories: {', '.join([f'{k}: {v:.2f}' for k,v in summary['top_expense_categories'].items()])}." ) except Exception as e: st.sidebar.error(f"Failed to parse CSV: {e}")
# Main: chat areaif "chat_messages" not in st.session_state: st.session_state.chat_messages = []
chat_col, info_col = st.columns([3,1])with chat_col: st.subheader("Chat") # display history for msg in st.session_state.chat_messages: if msg["role"] == "user": st.chat_message("user").write(msg["content"])# Add a FINANCE_KEYWORDS list at the topFINANCE_KEYWORDS = [ "finance", "money", "budget", "spend", "expense", "investment", "invest", "mutual fund", "savings", "loan", "credit", "debit", "stock", "tax", "insurance", "emi", "pay", "salary", "income", "expense", "roi", "interest", "dividend", "bond", "rate", "portfolio", "wealth", "goal", "sip", "fd", "rd", "fixed deposit", "asset", "liability", "capital"]
def is_finance_related(text): text_l = text.lower() # Keywords if any(word in text_l for word in FINANCE_KEYWORDS): return True # Numbers (strip commas, dots, %) if any(char.isdigit() for char in text): return True return False
# In your chat input section, filter before sending to the AIwith col_chat: st.subheader("🗣️ Ask about finance or numbers only") for turn in st.session_state.chat_history: with st.chat_message(turn["role"]): st.markdown(turn["content"]) user_msg = st.chat_input("Type your finance/numbers-related question…") if user_msg: if not is_finance_related(user_msg): assistant_message = "Sorry, I can only answer questions related to finance or numbers. Please rephrase your query." st.session_state.chat_history.append({"role": "assistant", "content": assistant_message}) with st.chat_message("assistant"): st.markdown(assistant_message) else: st.chat_message("assistant").write(msg["content"])
user_input = st.chat_input("Ask about savings, taxes, budgets, or investments...") if user_input: # show the user's message immediately st.session_state.chat_messages.append({"role":"user", "content": user_input}) # Build prompt for watsonx prompt = build_prompt(user_input, demographic, budget_summary_text=budget_text) with st.spinner("Generating response from watsonx..."): if watsonx_client: response_text = watsonx_generate(watsonx_client, prompt=prompt, model_id=model_choice, max_tokens=512) else: # fallback heuristic answer if watsonx not configured response_text = ( "Watsonx not configured. (Set WATSONX_API_KEY and WATSONX_URL.)\n\n" "Quick tips: 1) Track monthly expenses; 2) Build 3-6 months emergency fund; 3) Automate savings." ) # Append assistant response st.session_state.chat_messages.append({"role":"assistant", "content": response_text}) st.experimental_rerun()
with info_col: st.subheader("Quick Tools") if tx_df is not None: st.markdown("**Budget snapshot**") st.write(budget_text) if st.button("Show top expenses table"): top = tx_df.groupby("category")["amount"].sum().abs().sort_values(ascending=False).reset_index() top.columns = ["category","total_spent"] st.table(top.head(10)) else: st.info("Upload transactions to enable budget summaries & insights")
# Footer: example prompts & environment instructionsst.markdown("---")st.markdown("**Example prompts**")st.markdown("- `How much should I save monthly given my income is ₹50,000?`")st.markdown("- `Suggest tax-saving instruments suitable for a young professional in India.`")st.markdown("- `I spent too much on food. How can I cut dining expenses by 20%?`")
st.markdown("---")st.markdown("**Setup / Requirements**")st.code("""pip install streamlit pandas python-dotenv ibm-watsonx-ai ibm-watson# Environment variables (example)export WATSONX_API_KEY='your_watsonx_api_key'export WATSONX_URL='https://<region>.ml.cloud.ibm.com'export WATSONX_MODEL_ID='ibm/granite-13b-instruct-v2'# Optional (Assistant)export ASSISTANT_APIKEY='your_assistant_apikey'export ASSISTANT_URL='https://api.<region>.assistant.watson.cloud.ibm.com'export ASSISTANT_ID='your_assistant_id'# Runstreamlit run app.py""", language="bash")
st.caption("This is a prototype demo — for production, add secure secret handling, input validation, rate-limiting, logging, and robust error handling.") st.session_state.chat_history.append({"role": "user", "content": user_msg}) intent = detect_intent(user_msg) sys_prompt = ( "You are a finance and numbers-only AI assistant. " "If asked anything outside of finance or numbers, politely refuse to answer." "\n\n" + build_system_prompt(profile) ) usr_prompt = craft_user_prompt(user_msg, intent, summary) final_prompt = sys_prompt + "\n\n" + usr_prompt with st.chat_message("assistant"): with st.spinner(f"Thinking with {provider.name}…"): try: ai = provider.generate(final_prompt, max_tokens=768) except Exception as e: ai = f"Provider error: {e}\nFalling back to heuristic guidance.\n" + usr_prompt st.markdown(ai) st.session_state.chat_history.append({"role": "assistant", "content": ai})src/streamlit_app.py+49-265