A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
feat: add Personal Finance Agent using LangChain, SQLite and Orq.ai
Tiioluwani52c5df4c57cc
diff --git a/ai_agents/personal_finance_agent/.env.example b/ai_agents/personal_finance_agent/.env.examplenew file mode 100644index 0000000..64f189f--- /dev/null+++ b/ai_agents/personal_finance_agent/.env.example@@ -0,0 +1,5 @@+# Orq.ai API key — https://orq.ai/+ORQ_API_KEY=your-orq-api-key-here++# Optional: override the routed model (default: deepseek-v4-flash)+# ORQ_MODEL=deepseek-v4-flashdiff --git a/ai_agents/personal_finance_agent/README.md b/ai_agents/personal_finance_agent/README.mdnew file mode 100644index 0000000..17ba925--- /dev/null+++ b/ai_agents/personal_finance_agent/README.md@@ -0,0 +1,154 @@+# Personal Finance Agent++> Upload a bank statement or transaction CSV, categorize your spending, and ask natural language questions about your finances.++## Overview++Personal Finance Agent is a Streamlit application that ingests transaction CSVs, classifies each row into spending categories with pandas, and stores the results in SQLite. Users ask questions in plain English and receive answers from a LangChain tool-calling agent backed by Orq.ai. The agent can summarize spending by category, surface large discretionary purchases, and suggest a weekly budget plan based on historical patterns.++## Demo++++## Features++- CSV upload for bank exports with flexible column names (date, description, amount, or debit/credit)+- Automatic categorization into Food, Transport, Entertainment, Utilities, Shopping, Health, and Other+- SQLite persistence for fast queries and agent tool access+- Natural language Q&A via a LangChain agent with pandas summaries and read-only SQL tools+- Weekly budget suggestions derived from your spending patterns+- Bundled sample data (`transactions.csv`) so you can try the app without uploading a bank statement+- Orq.ai model routing through the OpenAI SDK with `deepseek-v4-flash` by default++## Tech Stack++Frameworks & Libraries:++- [LangChain](https://www.langchain.com/) for agent orchestration and tools+- [LangGraph](https://langchain-ai.github.io/langgraph/) for the agent execution graph+- [LangChain OpenAI](https://python.langchain.com/docs/integrations/chat/openai/) for chat models via Orq.ai+- [OpenAI Python SDK](https://github.com/openai/openai-python) (Orq.ai-compatible client)+- [python-dotenv](https://github.com/theskumar/python-dotenv) for environment configuration++Additional Tools:++- Database: SQLite+- Data Processing: pandas+- Web Framework: Streamlit++## Prerequisites++- Python 3.10 or higher+- API keys for:+ - Orq.ai (`ORQ_API_KEY`)++## Installation++### 1. Clone the Repository++```bash+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/personal_finance_agent+```++### 2. Create Virtual Environment (Recommended)++```bash+python -m venv venv+```++**Windows:**++```bash+venv\Scripts\activate+```++**macOS/Linux:**++```bash+source venv/bin/activate+```++### 3. Install Dependencies++```bash+pip install -r requirements.txt+```++### 4. Set Up Environment Variables++```bash+cp .env.example .env+```++Edit `.env` and set your Orq.ai API key:++```env+ORQ_API_KEY=your-orq-api-key-here+```++On Windows Command Prompt, use `copy .env.example .env` instead of `cp`.++## Usage++### Running the Application++```bash+streamlit run app.py+```++Open the local URL shown in the terminal (typically `http://localhost:8501`). In the sidebar, click **Load sample transactions.csv** or upload your own CSV, then ask questions in the chat or use the sample prompt buttons.++### Example Usage++| Question | What the agent returns |+| --- | --- |+| How much did I spend on food last month? | Total Food spending for the prior calendar month with a formatted dollar amount |+| What's my biggest unnecessary expense? | The largest discretionary charges across Entertainment, Shopping, and non-essential Food |+| Break down my spending by category. | Per-category totals and percentage share of overall spending |+| Suggest a weekly budget plan based on my habits. | Proportional weekly budget caps by category with a trim on discretionary spending |+| How much did I spend on transport in the last 7 days? | Transport total for the most recent seven days in the loaded data |++## Project Structure++```+personal_finance_agent/+├── app.py # Streamlit UI with CSV upload and chat interface+├── agent.py # LangChain agent, categorization logic, and SQLite tools+├── transactions.csv # Sample transaction data for immediate testing+├── requirements.txt # Python dependencies+├── .env.example # Environment variable template+├── .gitignore+├── README.md+└── assets/+ └── demo.gif # Demo recording for the README+```++## How It Works++1. **CSV upload**+ The user uploads a bank export or loads the bundled `transactions.csv` from the sidebar in `app.py`.++2. **Parse and normalize**+ `ingest_csv()` in `agent.py` reads the file with pandas, normalizes column names, and parses amounts. The importer supports a single `amount` column or separate `debit` and `credit` columns.++3. **Categorize**+ Each transaction description is matched against keyword rules and assigned to Food, Transport, Entertainment, Utilities, Shopping, Health, or Other. Income rows (positive amounts with salary or deposit keywords) are stored but excluded from spending summaries.++4. **SQLite storage**+ Categorized rows are written to `finance.db` in a `transactions` table. Each new import replaces the previous dataset.++5. **Natural language Q&A**+ The user asks a question in the Streamlit chat. `ask_finance_agent()` runs a LangChain agent with an OpenAI-compatible client pointed at `https://api.orq.ai/v3/router` using the `deepseek-v4-flash` model.++6. **Tool use**+ The agent selects tools to answer with real numbers from the database: read-only SQL (`query_transactions_sql`), pandas summaries (`summarize_spending`, `get_category_spending`), discretionary analysis (`find_largest_discretionary_expenses`), and budget planning (`suggest_weekly_budget`).++7. **Response**+ The agent formats tool results into a plain-English reply in the chat. Prior conversation turns are passed on follow-up questions for context.++**Data flow:**++```+CSV upload -> pandas parse and categorize -> SQLite -> LangChain agent and tools -> chat answer+```diff --git a/ai_agents/personal_finance_agent/agent.py b/ai_agents/personal_finance_agent/agent.pynew file mode 100644index 0000000..3e0ccf4--- /dev/null+++ b/ai_agents/personal_finance_agent/agent.py@@ -0,0 +1,431 @@+"""LangChain finance agent with pandas and SQLite tools."""++from __future__ import annotations++import os+import re+import sqlite3+from datetime import datetime, timedelta+from pathlib import Path+from typing import Any++import pandas as pd+from dotenv import load_dotenv+from langchain_core.tools import tool+from openai import OpenAI++load_dotenv()++PROJECT_ROOT = Path(__file__).resolve().parent+DB_PATH = PROJECT_ROOT / "finance.db"+SAMPLE_CSV = PROJECT_ROOT / "transactions.csv"++CATEGORIES = (+ "Food",+ "Transport",+ "Entertainment",+ "Utilities",+ "Shopping",+ "Health",+ "Other",+)++CATEGORY_KEYWORDS: dict[str, tuple[str, ...]] = {+ "Food": (+ "restaurant", "grocery", "starbucks", "mcdonald", "chipotle", "pizza",+ "subway", "taco", "burger", "sushi", "thai", "indian", "olive garden",+ "panera", "domino", "dunkin", "whole foods", "trader joe", "safeway",+ "kroger", "costco", "walmart", "uber eats", "doordash",+ ),+ "Transport": (+ "uber", "lyft", "shell", "chevron", "gas station", "gas ", "metro transit",+ "bus pass", "train ticket", "parking", "transit",+ ),+ "Entertainment": (+ "netflix", "spotify", "hulu", "apple music", "steam", "playstation",+ "video game", "amc", "regal cinema", "concert", "bowling", "festival",+ "theater",+ ),+ "Utilities": (+ "electric", "water utility", "internet provider", "phone bill",+ "gas & electric",+ ),+ "Shopping": (+ "amazon", "target", "best buy", "ikea", "home depot", "nike", "zara",+ "h&m", "old navy", "fashion", "clothing", "electronics", "furniture",+ ),+ "Health": (+ "pharmacy", "cvs", "walgreens", "dentist", "doctor", "planet fitness",+ "gym", "yoga", "optometrist", "copay",+ ),+}++INCOME_KEYWORDS = ("salary", "deposit", "payroll", "income", "refund")+++def _normalize_columns(df: pd.DataFrame) -> pd.DataFrame:+ df = df.copy()+ df.columns = [str(c).strip().lower().replace(" ", "_") for c in df.columns]+ rename_map = {+ "transaction_date": "date",+ "posted_date": "date",+ "memo": "description",+ "narrative": "description",+ "details": "description",+ "merchant": "description",+ "debit": "amount",+ "credit": "amount",+ "transaction_amount": "amount",+ "value": "amount",+ }+ df = df.rename(columns={k: v for k, v in rename_map.items() if k in df.columns})+ return df+++def _parse_amount(row: pd.Series) -> float:+ if "amount" in row and pd.notna(row["amount"]):+ return float(row["amount"])+ debit = row.get("debit")+ credit = row.get("credit")+ if pd.notna(debit) and float(debit) != 0:+ return -abs(float(debit))+ if pd.notna(credit) and float(credit) != 0:+ return abs(float(credit))+ raise ValueError("Could not determine transaction amount")+++def categorize_transaction(description: str, amount: float) -> str:+ text = (description or "").lower()+ if amount > 0 and any(k in text for k in INCOME_KEYWORDS):+ return "Other"+ for category, keywords in CATEGORY_KEYWORDS.items():+ if any(k in text for k in keywords):+ return category+ return "Other"+++def _init_db(conn: sqlite3.Connection) -> None:+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS transactions (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ date TEXT NOT NULL,+ description TEXT NOT NULL,+ amount REAL NOT NULL,+ category TEXT NOT NULL,+ is_income INTEGER NOT NULL DEFAULT 0+ )+ """+ )+ conn.commit()+++def ingest_csv(file_path: str | Path, replace: bool = True) -> dict[str, Any]:+ """Parse CSV, categorize transactions, and persist to SQLite."""+ path = Path(file_path)+ raw = pd.read_csv(path)+ df = _normalize_columns(raw)++ if "date" not in df.columns or "description" not in df.columns:+ raise ValueError(+ "CSV must include date and description columns "+ "(or common aliases like transaction_date, memo)."+ )++ amounts = []+ categories = []+ for _, row in df.iterrows():+ amount = _parse_amount(row)+ desc = str(row["description"])+ amounts.append(amount)+ categories.append(categorize_transaction(desc, amount))++ df["amount"] = amounts+ df["category"] = categories+ df["date"] = pd.to_datetime(df["date"], errors="coerce").dt.strftime("%Y-%m-%d")+ df["is_income"] = (df["amount"] > 0).astype(int)+ df = df.dropna(subset=["date"])++ with sqlite3.connect(DB_PATH) as conn:+ _init_db(conn)+ if replace:+ conn.execute("DELETE FROM transactions")+ records = df[["date", "description", "amount", "category", "is_income"]].to_dict(+ "records"+ )+ conn.executemany(+ """+ INSERT INTO transactions (date, description, amount, category, is_income)+ VALUES (:date, :description, :amount, :category, :is_income)+ """,+ records,+ )+ conn.commit()+ count = conn.execute("SELECT COUNT(*) FROM transactions").fetchone()[0]++ spending = df[df["amount"] < 0]["amount"].sum()+ by_category = (+ df[df["amount"] < 0]+ .groupby("category")["amount"]+ .sum()+ .abs()+ .sort_values(ascending=False)+ )+ return {+ "rows_imported": int(count),+ "total_spending": float(abs(spending)),+ "category_breakdown": {k: float(v) for k, v in by_category.items()},+ "date_range": f"{df['date'].min()} to {df['date'].max()}",+ }+++def load_transactions_df() -> pd.DataFrame:+ if not DB_PATH.exists():+ return pd.DataFrame(+ columns=["id", "date", "description", "amount", "category", "is_income"]+ )+ with sqlite3.connect(DB_PATH) as conn:+ return pd.read_sql_query("SELECT * FROM transactions ORDER BY date", conn)+++def _spending_df() -> pd.DataFrame:+ df = load_transactions_df()+ if df.empty:+ return df+ out = df[df["is_income"] == 0].copy()+ out["spend"] = out["amount"].abs()+ out["date"] = pd.to_datetime(out["date"])+ return out+++def _format_weekly_budget() -> str:+ df = _spending_df()+ if df.empty:+ return "No transaction data loaded. Upload a CSV first."++ weeks = max(1, (df["date"].max() - df["date"].min()).days // 7 + 1)+ total_spend = df["spend"].sum()+ weekly_avg = total_spend / weeks++ by_cat = df.groupby("category")["spend"].sum().sort_values(ascending=False)+ lines = [+ f"Based on {weeks} week(s) of data, average weekly spending: ${weekly_avg:,.2f}",+ "",+ "Suggested weekly budget by category (proportional to past spending, 10% trim on discretionary):",+ ]+ discretionary = {"Entertainment", "Shopping", "Food"}+ for cat, total in by_cat.items():+ share = total / total_spend if total_spend else 0+ weekly = weekly_avg * share+ if cat in discretionary:+ weekly *= 0.9+ lines.append(f"- {cat}: ${weekly:,.2f}/week")++ top = by_cat.index[0] if len(by_cat) else "N/A"+ lines.extend(+ [+ "",+ f"Largest category: {top} (${by_cat.iloc[0]:,.2f} total).",+ "Tip: cap Entertainment and Shopping first if you want quick savings.",+ ]+ )+ return "\n".join(lines)+++def get_llm():+ from langchain_openai import ChatOpenAI++ api_key = os.getenv("ORQ_API_KEY")+ if not api_key:+ raise ValueError("ORQ_API_KEY is not set. Copy .env.example to .env and add your key.")+ return ChatOpenAI(+ model=os.getenv("ORQ_MODEL", "deepseek-v4-flash"),+ openai_api_key=api_key,+ openai_api_base="https://api.orq.ai/v3/router",+ temperature=0.2,+ )+++def verify_orq_connection() -> str:+ api_key = os.getenv("ORQ_API_KEY")+ if not api_key:+ return "ORQ_API_KEY missing"+ client = OpenAI(base_url="https://api.orq.ai/v3/router", api_key=api_key)+ model = os.getenv("ORQ_MODEL", "deepseek-v4-flash")+ response = client.chat.completions.create(+ model=model,+ messages=[{"role": "user", "content": "Reply with OK only."}],+ max_tokens=10,+ )+ return response.choices[0].message.content or "OK"+++@tool+def query_transactions_sql(sql: str) -> str:+ """Run a read-only SQL SELECT against the transactions table in SQLite.+ Table schema: transactions(id, date, description, amount, category, is_income).+ amount is negative for expenses and positive for income. Only SELECT queries allowed."""+ cleaned = sql.strip().rstrip(";")+ if not re.match(r"^\s*select\b", cleaned, re.IGNORECASE):+ return "Error: only SELECT queries are allowed."+ forbidden = re.search(r"\b(insert|update|delete|drop|alter|create|attach)\b", cleaned, re.I)+ if forbidden:+ return "Error: mutating SQL statements are not allowed."+ try:+ with sqlite3.connect(DB_PATH) as conn:+ result = pd.read_sql_query(cleaned, conn)+ if result.empty:+ return "Query returned no rows."+ return result.to_string(index=False)+ except Exception as exc:+ return f"SQL error: {exc}"+++@tool+def summarize_spending(period: str = "all") -> str:+ """Summarize spending with pandas. period: 'all', 'last_month', 'last_7_days', or 'this_month'."""+ df = _spending_df()+ if df.empty:+ return "No spending data in the database. Upload a CSV first."++ subset, label = _filter_by_period(df, period)+ if subset.empty:+ return f"No transactions for {label}."++ total = subset["spend"].sum()+ by_cat = subset.groupby("category")["spend"].sum().sort_values(ascending=False)+ lines = [f"Spending summary ({label}): ${total:,.2f} total", ""]+ for cat, val in by_cat.items():+ pct = 100 * val / total if total else 0+ lines.append(f"- {cat}: ${val:,.2f} ({pct:.1f}%)")+ top_merchants = (+ subset.groupby("description")["spend"]+ .sum()+ .sort_values(ascending=False)+ .head(5)+ )+ lines.append("\nTop merchants:")+ for desc, val in top_merchants.items():+ lines.append(f"- {desc}: ${val:,.2f}")+ return "\n".join(lines)+++def _filter_by_period(df: pd.DataFrame, period: str) -> tuple[pd.DataFrame, str]:+ now = df["date"].max()+ if period == "last_month":+ start = (now.replace(day=1) - timedelta(days=1)).replace(day=1)+ end = now.replace(day=1) - timedelta(days=1)+ mask = (df["date"] >= start) & (df["date"] <= end)+ label = f"last month ({start.date()} to {end.date()})"+ elif period == "this_month":+ start = now.replace(day=1)+ mask = df["date"] >= start+ label = f"this month (from {start.date()})"+ elif period == "last_7_days":+ start = now - timedelta(days=7)+ mask = df["date"] >= start+ label = "last 7 days"+ else:+ mask = pd.Series([True] * len(df), index=df.index)+ label = "all time"+ return df.loc[mask], label+++@tool+def get_category_spending(category: str, period: str = "all") -> str:+ """Get total spending for one category (Food, Transport, etc.). period same as summarize_spending."""+ category = category.strip().title()+ if category not in CATEGORIES:+ return f"Unknown category. Use one of: {', '.join(CATEGORIES)}"+ df = _spending_df()+ if df.empty:+ return "No spending data in the database. Upload a CSV first."+ subset, label = _filter_by_period(df, period)+ cat_total = subset.loc[subset["category"] == category, "spend"].sum()+ return f"{category} spending ({label}): ${cat_total:,.2f}"+++@tool+def suggest_weekly_budget() -> str:+ """Generate a suggested weekly budget plan from historical spending patterns."""+ return _format_weekly_budget()+++@tool+def find_largest_discretionary_expenses(limit: int = 5) -> str:+ """Find the largest individual discretionary expenses (Entertainment, Shopping, Food)."""+ df = _spending_df()+ if df.empty:+ return "No data loaded."+ disc = df[df["category"].isin(["Entertainment", "Shopping", "Food"])]+ top = disc.nlargest(limit, "spend")[["date", "description", "category", "spend"]]+ if top.empty:+ return "No discretionary expenses found."+ lines = ["Largest discretionary expenses:"]+ for _, row in top.iterrows():+ lines.append(+ f"- {row['date'].date()} | {row['description']} | "+ f"{row['category']} | ${row['spend']:,.2f}"+ )+ return "\n".join(lines)+++TOOLS = [+ query_transactions_sql,+ summarize_spending,+ get_category_spending,+ suggest_weekly_budget,+ find_largest_discretionary_expenses,+]++SYSTEM_PROMPT = """You are a Personal Finance Agent helping users understand their bank transactions.++You have access to categorized transaction data in SQLite (categories: Food, Transport, Entertainment, Utilities, Shopping, Health, Other).+Expenses have negative amounts; income is positive.++Use the provided tools to answer questions with real numbers from the data. When users ask about budgets, call suggest_weekly_budget.+For vague questions like "unnecessary expenses", use find_largest_discretionary_expenses and highlight Entertainment, Shopping, and non-essential Food.++Be concise, use USD formatting, and cite figures from tool results. If no data is loaded, tell the user to upload a CSV.+Today's reference date for relative periods is {today}.+"""+++def build_agent_graph():+ from langchain.agents import create_agent++ llm = get_llm()+ today = datetime.now().strftime("%Y-%m-%d")+ return create_agent(+ llm,+ tools=TOOLS,+ system_prompt=SYSTEM_PROMPT.format(today=today),+ )+++def _extract_reply(messages: list) -> str:+ from langchain_core.messages import AIMessage++ for msg in reversed(messages):+ if isinstance(msg, AIMessage) and msg.content:+ text = msg.content+ return text if isinstance(text, str) else str(text)+ return "I could not generate a response."+++def ask_finance_agent(+ question: str,+ chat_history: list[tuple[str, str]] | None = None,+) -> str:+ from langchain_core.messages import AIMessage, HumanMessage++ graph = build_agent_graph()+ messages: list = []+ if chat_history:+ for human, ai in chat_history:+ messages.append(HumanMessage(content=human))+ messages.append(AIMessage(content=ai))+ messages.append(HumanMessage(content=question))++ result = graph.invoke({"messages": messages})+ return _extract_reply(result.get("messages", []))diff --git a/ai_agents/personal_finance_agent/app.py b/ai_agents/personal_finance_agent/app.pynew file mode 100644index 0000000..16d028b--- /dev/null+++ b/ai_agents/personal_finance_agent/app.py@@ -0,0 +1,153 @@+"""Streamlit UI for the Personal Finance Agent."""++from __future__ import annotations++import tempfile++import streamlit as st+from dotenv import load_dotenv++from agent import (+ SAMPLE_CSV,+ ask_finance_agent,+ ingest_csv,+ load_transactions_df,+)++load_dotenv()++st.set_page_config(+ page_title="Personal Finance Agent",+ page_icon="💰",+ layout="wide",+)++SAMPLE_QUESTIONS = [+ "How much did I spend on food last month?",+ "What's my biggest unnecessary expense?",+ "Break down my spending by category.",+ "Suggest a weekly budget plan based on my habits.",+ "How much did I spend on transport in the last 7 days?",+]+++def _init_session() -> None:+ if "messages" not in st.session_state:+ st.session_state.messages = []+ if "data_loaded" not in st.session_state:+ st.session_state.data_loaded = False+++def _render_sidebar() -> None:+ with st.sidebar:+ st.header("Data")+ uploaded = st.file_uploader(+ "Upload bank statement or transaction CSV",+ type=["csv"],+ help="CSV should include date, description, and amount (or debit/credit columns).",+ )++ if st.button("Load sample transactions.csv", use_container_width=True):+ summary = ingest_csv(SAMPLE_CSV, replace=True)+ st.session_state.data_loaded = True+ st.session_state.import_summary = summary+ st.success(f"Loaded {summary['rows_imported']} sample transactions.")++ if uploaded is not None:+ with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as tmp:+ tmp.write(uploaded.getvalue())+ temp_path = tmp.name+ try:+ summary = ingest_csv(temp_path, replace=True)+ st.session_state.data_loaded = True+ st.session_state.import_summary = summary+ st.success(+ f"Imported {summary['rows_imported']} transactions "+ f"({summary['date_range']})."+ )+ except Exception as exc:+ st.error(f"Could not parse CSV: {exc}")++ if st.session_state.get("data_loaded"):+ summary = st.session_state.get("import_summary", {})+ if summary:+ st.metric("Total spending", f"${summary.get('total_spending', 0):,.2f}")+ breakdown = summary.get("category_breakdown", {})+ if breakdown:+ st.caption("Category totals")+ for cat, val in breakdown.items():+ st.write(f"**{cat}:** ${val:,.2f}")+++def _render_transactions_preview() -> None:+ df = load_transactions_df()+ if df.empty:+ return+ with st.expander("Transaction preview", expanded=False):+ display = df.copy()+ display["amount"] = display["amount"].map(lambda x: f"${x:,.2f}")+ st.dataframe(display, use_container_width=True, hide_index=True)+++def main() -> None:+ _init_session()+ _render_sidebar()++ st.title("Personal Finance Agent")+ st.markdown(+ "Upload a transaction CSV, then ask natural language questions about your spending. "+ "The agent categorizes transactions and answers using your SQLite-backed history."+ )++ _render_transactions_preview()++ if not st.session_state.data_loaded and load_transactions_df().empty:+ st.info(+ "No transactions loaded yet. Upload a CSV in the sidebar or click "+ "**Load sample transactions.csv** to try the demo."+ )++ for message in st.session_state.messages:+ with st.chat_message(message["role"]):+ st.markdown(message["content"])++ for q in SAMPLE_QUESTIONS:+ if st.button(q, key=f"sample_{q}"):+ st.session_state.pending_question = q++ prompt = st.chat_input("Ask about your finances...")+ if st.session_state.get("pending_question"):+ prompt = st.session_state.pop("pending_question")++ if prompt:+ st.session_state.messages.append({"role": "user", "content": prompt})+ with st.chat_message("user"):+ st.markdown(prompt)++ with st.chat_message("assistant"):+ with st.spinner("Analyzing your transactions..."):+ history: list[tuple[str, str]] = []+ prior = st.session_state.messages[:-1]+ idx = 0+ while idx < len(prior) - 1:+ if prior[idx]["role"] == "user" and prior[idx + 1]["role"] == "assistant":+ history.append((prior[idx]["content"], prior[idx + 1]["content"]))+ idx += 2+ else:+ idx += 1+ try:+ answer = ask_finance_agent(prompt, chat_history=history)+ except ValueError as exc:+ answer = f"Configuration error: {exc}"+ except Exception as exc:+ answer = (+ f"I ran into an error: {exc}\n\n"+ "Check that `ORQ_API_KEY` is set and your Orq.ai router has "+ "`deepseek-v4-flash` available."+ )+ st.markdown(answer)+ st.session_state.messages.append({"role": "assistant", "content": answer})+++if __name__ == "__main__":+ main()diff --git a/ai_agents/personal_finance_agent/assets/demo.gif b/ai_agents/personal_finance_agent/assets/demo.gifnew file mode 100644index 0000000..a5bf3a9Binary files /dev/null and b/ai_agents/personal_finance_agent/assets/demo.gif differdiff --git a/ai_agents/personal_finance_agent/requirements.txt b/ai_agents/personal_finance_agent/requirements.txtnew file mode 100644index 0000000..0487b55--- /dev/null+++ b/ai_agents/personal_finance_agent/requirements.txt@@ -0,0 +1,8 @@+streamlit>=1.32.0+pandas>=2.2.0+langchain>=1.0.0+langchain-openai>=0.3.0+langchain-core>=0.3.0+langgraph>=0.2.0+openai>=1.40.0+python-dotenv>=1.0.0diff --git a/ai_agents/personal_finance_agent/transactions.csv b/ai_agents/personal_finance_agent/transactions.csvnew file mode 100644index 0000000..a07586e--- /dev/null+++ b/ai_agents/personal_finance_agent/transactions.csv@@ -0,0 +1,89 @@+date,description,amount+2026-01-02,Whole Foods Market,-87.42+2026-01-03,Shell Gas Station,-45.20+2026-01-04,Netflix Subscription,-15.99+2026-01-05,Starbucks Coffee,-6.75+2026-01-06,Amazon Purchase,-34.99+2026-01-07,CVS Pharmacy,-22.50+2026-01-08,Chipotle Mexican Grill,-14.25+2026-01-09,Uber Ride,-18.60+2026-01-10,Electric Company Bill,-112.34+2026-01-11,Target Shopping,-67.88+2026-01-12,AMC Theaters,-28.50+2026-01-13,Trader Joe's,-54.30+2026-01-14,Spotify Premium,-10.99+2026-01-15,Shell Gas Station,-42.15+2026-01-16,Salary Deposit,3200.00+2026-01-17,Planet Fitness,-24.99+2026-01-18,Domino's Pizza,-22.40+2026-01-19,Water Utility,-48.20+2026-01-20,Best Buy Electronics,-189.99+2026-01-21,McDonald's,-11.89+2026-01-22,Lyft Ride,-14.75+2026-01-23,Internet Provider,-79.99+2026-01-24,Walmart Grocery,-93.15+2026-01-25,Steam Games,-59.99+2026-01-26,Dentist Office,-150.00+2026-01-27,Subway Restaurant,-9.50+2026-01-28,Metro Transit Pass,-45.00+2026-01-29,H&M Clothing,-78.40+2026-01-30,Concert Tickets,-95.00+2026-02-01,Whole Foods Market,-72.18+2026-02-02,Shell Gas Station,-48.90+2026-02-03,Netflix Subscription,-15.99+2026-02-04,Starbucks Coffee,-7.25+2026-02-05,Amazon Purchase,-129.00+2026-02-06,Walgreens,-18.75+2026-02-07,Olive Garden,-52.30+2026-02-08,Uber Ride,-22.40+2026-02-09,Electric Company Bill,-98.76+2026-02-10,IKEA Furniture,-245.00+2026-02-11,Regal Cinemas,-32.00+2026-02-12,Costco Wholesale,-156.42+2026-02-13,Apple Music,-10.99+2026-02-14,Shell Gas Station,-39.80+2026-02-15,Salary Deposit,3200.00+2026-02-16,Yoga Studio,-35.00+2026-02-17,Panera Bread,-16.80+2026-02-18,Gas & Electric,-134.50+2026-02-19,Home Depot,-87.25+2026-02-20,Taco Bell,-8.99+2026-02-21,City Bus Pass,-30.00+2026-02-22,Phone Bill,-65.00+2026-02-23,Kroger Supermarket,-68.90+2026-02-24,PlayStation Store,-44.99+2026-02-25,Doctor Visit Copay,-40.00+2026-02-26,Sushi Restaurant,-48.75+2026-02-27,Parking Garage,-12.00+2026-02-28,Zara Fashion,-112.50+2026-03-01,Whole Foods Market,-81.55+2026-03-02,Chevron Gas,-51.30+2026-03-03,Netflix Subscription,-15.99+2026-03-04,Dunkin Donuts,-5.49+2026-03-05,Amazon Prime Purchase,-45.67+2026-03-06,Pharmacy Express,-31.20+2026-03-07,Thai Restaurant,-38.90+2026-03-08,Uber Eats Delivery,-24.50+2026-03-09,Water Utility,-52.10+2026-03-10,Nike Store,-95.00+2026-03-11,Bowling Alley,-42.00+2026-03-12,Safeway Grocery,-77.33+2026-03-13,Hulu Subscription,-17.99+2026-03-14,Shell Gas Station,-44.60+2026-03-15,Salary Deposit,3200.00+2026-03-16,Gym Membership,-29.99+2026-03-17,Pizza Hut,-19.99+2026-03-18,Internet Provider,-79.99+2026-03-19,Best Buy,-299.00+2026-03-20,Burger King,-12.45+2026-03-21,Train Ticket,-28.00+2026-03-22,ATM Withdrawal,-100.00+2026-03-23,Trader Joe's,-61.20+2026-03-24,Video Game Purchase,-69.99+2026-03-25,Optometrist,-85.00+2026-03-26,Indian Restaurant,-35.60+2026-03-27,Lyft Ride,-16.80+2026-03-28,Old Navy,-54.99+2026-03-29,Music Festival,-120.00+2026-03-30,Miscellaneous Fee,-25.00+2026-03-31,Electric Company Bill,-105.88