Spaces:
Sleeping
Sleeping
Initial commit
Browse files- .DS_Store +0 -0
- .idea/.gitignore +8 -0
- .idea/FinnAI.iml +10 -0
- .idea/inspectionProfiles/profiles_settings.xml +6 -0
- .idea/misc.xml +7 -0
- .idea/modules.xml +8 -0
- .idea/vcs.xml +6 -0
- .streamlit/secrets.toml +2 -0
- __pycache__/instLLM.cpython-313.pyc +0 -0
- agent/__pycache__/agent.cpython-313.pyc +0 -0
- agent/__pycache__/utils.cpython-313.pyc +0 -0
- agent/agent.py +122 -0
- agent/data.xlsx +0 -0
- agent/utils.py +199 -0
- app.py +85 -0
- chart.png +0 -0
- data.xlsx +0 -0
- fixtures/data.xlsx +0 -0
- opex_month_wise.png +0 -0
- requirements.txt +14 -0
- tests/__init__.py +0 -0
- tests/__pycache__/__init__.cpython-313.pyc +0 -0
- tests/__pycache__/test1.cpython-313-pytest-8.4.2.pyc +0 -0
- tests/__pycache__/test_1.cpython-313-pytest-8.4.2.pyc +0 -0
- tests/__pycache__/test_2.cpython-313-pytest-8.4.2.pyc +0 -0
- tests/__pycache__/test_3.cpython-313-pytest-8.4.2.pyc +0 -0
- tests/__pycache__/test_agent_logic.cpython-313-pytest-8.4.2.pyc +0 -0
- tests/test_1.py +106 -0
- tests/test_2.py +27 -0
- tests/test_3.py +25 -0
.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
.idea/.gitignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Default ignored files
|
| 2 |
+
/shelf/
|
| 3 |
+
/workspace.xml
|
| 4 |
+
# Editor-based HTTP Client requests
|
| 5 |
+
/httpRequests/
|
| 6 |
+
# Datasource local storage ignored files
|
| 7 |
+
/dataSources/
|
| 8 |
+
/dataSources.local.xml
|
.idea/FinnAI.iml
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<module type="PYTHON_MODULE" version="4">
|
| 3 |
+
<component name="NewModuleRootManager">
|
| 4 |
+
<content url="file://$MODULE_DIR$">
|
| 5 |
+
<excludeFolder url="file://$MODULE_DIR$/.venv" />
|
| 6 |
+
</content>
|
| 7 |
+
<orderEntry type="jdk" jdkName="Python 3.13 (FinnAI)" jdkType="Python SDK" />
|
| 8 |
+
<orderEntry type="sourceFolder" forTests="false" />
|
| 9 |
+
</component>
|
| 10 |
+
</module>
|
.idea/inspectionProfiles/profiles_settings.xml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<component name="InspectionProjectProfileManager">
|
| 2 |
+
<settings>
|
| 3 |
+
<option name="USE_PROJECT_PROFILE" value="false" />
|
| 4 |
+
<version value="1.0" />
|
| 5 |
+
</settings>
|
| 6 |
+
</component>
|
.idea/misc.xml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<project version="4">
|
| 3 |
+
<component name="Black">
|
| 4 |
+
<option name="sdkName" value="Python 3.13 (PyCharmMiscProject)" />
|
| 5 |
+
</component>
|
| 6 |
+
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.13 (FinnAI)" project-jdk-type="Python SDK" />
|
| 7 |
+
</project>
|
.idea/modules.xml
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<project version="4">
|
| 3 |
+
<component name="ProjectModuleManager">
|
| 4 |
+
<modules>
|
| 5 |
+
<module fileurl="file://$PROJECT_DIR$/.idea/FinnAI.iml" filepath="$PROJECT_DIR$/.idea/FinnAI.iml" />
|
| 6 |
+
</modules>
|
| 7 |
+
</component>
|
| 8 |
+
</project>
|
.idea/vcs.xml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<project version="4">
|
| 3 |
+
<component name="VcsDirectoryMappings">
|
| 4 |
+
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
| 5 |
+
</component>
|
| 6 |
+
</project>
|
.streamlit/secrets.toml
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# .streamlit/secrets.toml
|
| 2 |
+
GOOGLE_API_KEY = "AIzaSyBxrJAxe69t02jMZKtOGXY3gCIgVm8RAMY"
|
__pycache__/instLLM.cpython-313.pyc
ADDED
|
Binary file (4.85 kB). View file
|
|
|
agent/__pycache__/agent.cpython-313.pyc
ADDED
|
Binary file (6.85 kB). View file
|
|
|
agent/__pycache__/utils.cpython-313.pyc
ADDED
|
Binary file (10.7 kB). View file
|
|
|
agent/agent.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import sys
|
| 3 |
+
from langchain_openai import ChatOpenAI
|
| 4 |
+
from langchain.agents import create_openai_tools_agent, AgentExecutor
|
| 5 |
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 6 |
+
from langchain_core.tools import tool
|
| 7 |
+
from langchain_experimental.tools.python.tool import PythonREPLTool
|
| 8 |
+
from . import utils
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
python_repl = PythonREPLTool(python_path=sys.executable)
|
| 12 |
+
|
| 13 |
+
@tool
|
| 14 |
+
def code_analysis(code: str) -> str:
|
| 15 |
+
"""Takes python code and gives back the output."""
|
| 16 |
+
return python_repl.run(code)
|
| 17 |
+
|
| 18 |
+
@tool
|
| 19 |
+
def get_revenue_variance(start_month: str, end_month: str) -> float:
|
| 20 |
+
"""Calculate revenue variance (revenue vs budget) in USD over a date range."""
|
| 21 |
+
return utils.revenue_variance(start_month, end_month)
|
| 22 |
+
|
| 23 |
+
@tool
|
| 24 |
+
def get_gross_margin_pct(start_month: str, end_month: str) -> float:
|
| 25 |
+
"""Calculate month on month gross margin percentage over a date range."""
|
| 26 |
+
return utils.gross_margin_pct(start_month, end_month)
|
| 27 |
+
|
| 28 |
+
@tool
|
| 29 |
+
def get_opex_breakdown(start_month: str, end_month: str) -> dict:
|
| 30 |
+
"""Break down operating expenses by category in USD over a date range."""
|
| 31 |
+
return utils.opex_breakdown(start_month, end_month)
|
| 32 |
+
|
| 33 |
+
@tool
|
| 34 |
+
def get_ebitda_proxy(start_month: str, end_month: str) -> float:
|
| 35 |
+
"""Calculate proxy EBITDA over a date range."""
|
| 36 |
+
return utils.ebitda_proxy(start_month, end_month)
|
| 37 |
+
|
| 38 |
+
@tool
|
| 39 |
+
def get_cash_runway(as_of_month: str = None, last_n_months: int = 3) -> float:
|
| 40 |
+
"""Calculate cash runway in months based on historical or current burn rate."""
|
| 41 |
+
return utils.cash_runway(as_of_month, last_n_months)
|
| 42 |
+
|
| 43 |
+
@tool
|
| 44 |
+
def plot_chart(chart_type: str, x: list, y: list, title: str, x_label: str, y_label: str, output_path: str = "chart.png", legends: list[str] | None = None) -> str:
|
| 45 |
+
"""Generate and save a graph/chart with the specified data and formatting."""
|
| 46 |
+
return utils.plot_chart(chart_type, x, y, title, x_label, y_label, output_path, legends)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@st.cache_resource
|
| 50 |
+
def initialize_agent():
|
| 51 |
+
"""
|
| 52 |
+
Initializes and returns the LangChain agent executor.
|
| 53 |
+
This function is now self-contained and handles all agent logic.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
gemini_client = ChatOpenAI(
|
| 58 |
+
api_key=st.secrets["GOOGLE_API_KEY"],
|
| 59 |
+
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
|
| 60 |
+
model="gemini-2.0-flash",
|
| 61 |
+
temperature=0.2
|
| 62 |
+
)
|
| 63 |
+
except (KeyError, FileNotFoundError):
|
| 64 |
+
st.error("GOOGLE_API_KEY not found. Please add it to your .streamlit/secrets.toml file.")
|
| 65 |
+
st.stop()
|
| 66 |
+
|
| 67 |
+
# --- Tool Definitions ---
|
| 68 |
+
|
| 69 |
+
# --- System Prompt ---
|
| 70 |
+
ma_prompt = ChatPromptTemplate.from_messages([
|
| 71 |
+
("system", """
|
| 72 |
+
You are the Smart Financial Analytics Agent.
|
| 73 |
+
|
| 74 |
+
You have access to data from an Excel file with these sheets:
|
| 75 |
+
- actuals: (month, entity, account_category, amount, currency)
|
| 76 |
+
- budget: (month, entity, account_category, amount, currency)
|
| 77 |
+
- cash: (month, entity, cash_usd)
|
| 78 |
+
- fx: (month, currency, rate_to_usd)
|
| 79 |
+
|
| 80 |
+
Key points:
|
| 81 |
+
- Always verify currencies. Default to USD; if EUR, convert using the fx sheet.
|
| 82 |
+
- Months may appear as “YYYY-MM”, “June 2025”, “Jun’25”, etc. Treat them as equivalent.
|
| 83 |
+
- account_category has values: Revenuem, COGS, Opex:Marketing, Opex:Sales, Opex:R&D, Opex:Admin
|
| 84 |
+
|
| 85 |
+
Metric definitions:
|
| 86 |
+
-Revenue (USD): actual vs budget.
|
| 87 |
+
-Gross Margin %: (Revenue – COGS) / Revenue.
|
| 88 |
+
-Opex total (USD): grouped by Opex:* categories.
|
| 89 |
+
-EBITDA (proxy): Revenue – COGS – Opex.
|
| 90 |
+
-Cash runway: cash ÷ avg monthly net burn (last 3 months).
|
| 91 |
+
|
| 92 |
+
Dates:
|
| 93 |
+
- Range 2023-01 to 2025-12
|
| 94 |
+
- Normalize month formats into the same period.
|
| 95 |
+
- If the user says "current year" or "this year", map it to the latest year in the dataset (2025).
|
| 96 |
+
- If the user specifies a month without a year, default to the latest year available (2025).
|
| 97 |
+
- If the request refers to a year outside the dataset range (2023–2025) or no matching data exists, ask the user for clarification.
|
| 98 |
+
|
| 99 |
+
ONLY and ONLY,
|
| 100 |
+
If user asked something which cannot be fulfilled by a tool (where the params not allow, or tool is not capabale etc.). Make your own code and pass it to the code_analysis tool use the 'data.xlsx' file.
|
| 101 |
+
Do retry if code throws error.
|
| 102 |
+
|
| 103 |
+
Instructions:
|
| 104 |
+
1. If the user’s request matches a tool, call it. You can call multiple tools multiple times if needed.
|
| 105 |
+
2. Only call the 'code_analysis' tool as a last resort if no other tool is suitable.
|
| 106 |
+
3. After a tool call:
|
| 107 |
+
- Lead with the direct answer/figures.
|
| 108 |
+
- Give a short interpretation (context, implications).
|
| 109 |
+
- If a chart is generated, confirm that the chart is now displayed.
|
| 110 |
+
4. Keep answers concise, actionable, and financially relevant, remember you are answer directly to the CFO of the company.
|
| 111 |
+
"""),
|
| 112 |
+
MessagesPlaceholder("chat_history", optional=True),
|
| 113 |
+
("human", "{input}"),
|
| 114 |
+
MessagesPlaceholder("agent_scratchpad")
|
| 115 |
+
])
|
| 116 |
+
|
| 117 |
+
# --- Agent and Executor Creation ---
|
| 118 |
+
tools = [code_analysis, get_cash_runway, get_ebitda_proxy, get_opex_breakdown, get_revenue_variance, get_gross_margin_pct, plot_chart]
|
| 119 |
+
main_agent = create_openai_tools_agent(llm=gemini_client, tools=tools, prompt=ma_prompt)
|
| 120 |
+
agent_executor = AgentExecutor(agent=main_agent, tools=tools, verbose=True, return_intermediate_steps=True)
|
| 121 |
+
|
| 122 |
+
return agent_executor
|
agent/data.xlsx
ADDED
|
Binary file (45.8 kB). View file
|
|
|
agent/utils.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
|
| 5 |
+
# Load and prepare data
|
| 6 |
+
dfs = pd.read_excel("data.xlsx", sheet_name=None)
|
| 7 |
+
actuals = dfs["actuals"].copy()
|
| 8 |
+
budget = dfs["budget"].copy()
|
| 9 |
+
cash = dfs["cash"].copy()
|
| 10 |
+
fx = dfs["fx"].copy()
|
| 11 |
+
|
| 12 |
+
# Normalize month columns
|
| 13 |
+
for df in (actuals, budget, cash, fx):
|
| 14 |
+
df["month"] = pd.to_datetime(df["month"]).dt.to_period("M")
|
| 15 |
+
|
| 16 |
+
# Helper: convert any DataFrame with `amount` & `currency` to USD
|
| 17 |
+
def convert_to_usd(df: pd.DataFrame, fx: pd.DataFrame) -> pd.DataFrame:
|
| 18 |
+
merged = df.merge(
|
| 19 |
+
fx,
|
| 20 |
+
on=["month", "currency"],
|
| 21 |
+
how="left",
|
| 22 |
+
suffixes=("", "_fx"),
|
| 23 |
+
)
|
| 24 |
+
merged["rate_to_usd"] = merged["rate_to_usd"].fillna(1.0)
|
| 25 |
+
merged["amount_usd"] = merged["amount"] * merged["rate_to_usd"]
|
| 26 |
+
return merged
|
| 27 |
+
|
| 28 |
+
# 1. Revenue variance
|
| 29 |
+
def revenue_variance(start_month: str, end_month: str) -> float:
|
| 30 |
+
a = convert_to_usd(actuals, fx)
|
| 31 |
+
b = convert_to_usd(budget, fx)
|
| 32 |
+
mask = lambda df: (df["month"] >= pd.Period(start_month)) & (df["month"] <= pd.Period(end_month))
|
| 33 |
+
actual_rev = a[mask(a) & (a["account_category"] == "Revenue")]["amount_usd"].sum()
|
| 34 |
+
budget_rev = b[mask(b) & (b["account_category"] == "Revenue")]["amount_usd"].sum()
|
| 35 |
+
return actual_rev - budget_rev, actual_rev, budget_rev
|
| 36 |
+
|
| 37 |
+
# 2. Gross Margin %
|
| 38 |
+
def gross_margin_pct(start_month: str, end_month: str) -> float:
|
| 39 |
+
a = convert_to_usd(actuals, fx)
|
| 40 |
+
mask = (a["month"] >= pd.Period(start_month)) & (a["month"] <= pd.Period(end_month))
|
| 41 |
+
|
| 42 |
+
result = {}
|
| 43 |
+
for m in sorted(a[mask]["month"].unique()):
|
| 44 |
+
sub = a[a["month"] == m]
|
| 45 |
+
rev = sub[sub["account_category"] == "Revenue"]["amount_usd"].sum()
|
| 46 |
+
cogs = sub[sub["account_category"] == "COGS"]["amount_usd"].sum()
|
| 47 |
+
result[str(m)] = round((rev - cogs) / rev * 100, 2) if rev != 0 else 0.0
|
| 48 |
+
|
| 49 |
+
return result
|
| 50 |
+
|
| 51 |
+
# 3. Opex breakdown
|
| 52 |
+
def opex_breakdown(start_month: str, end_month: str) -> dict:
|
| 53 |
+
a = convert_to_usd(actuals, fx)
|
| 54 |
+
mask = (a["month"] >= pd.Period(start_month)) & (a["month"] <= pd.Period(end_month))
|
| 55 |
+
opex = a[mask & a["account_category"].str.startswith("Opex")]
|
| 56 |
+
return opex.groupby("account_category")["amount_usd"].sum().to_dict()
|
| 57 |
+
|
| 58 |
+
# 4. EBITDA proxy
|
| 59 |
+
def ebitda_proxy(start_month: str, end_month: str) -> float:
|
| 60 |
+
a = convert_to_usd(actuals, fx)
|
| 61 |
+
mask = (a["month"] >= pd.Period(start_month)) & (a["month"] <= pd.Period(end_month))
|
| 62 |
+
rev = a[mask & (a["account_category"] == "Revenue")]["amount_usd"].sum()
|
| 63 |
+
cogs = a[mask & (a["account_category"] == "COGS")]["amount_usd"].sum()
|
| 64 |
+
opex = a[mask & a["account_category"].str.startswith("Opex")]["amount_usd"].sum()
|
| 65 |
+
return rev - cogs - opex
|
| 66 |
+
|
| 67 |
+
# 5. Cash runway
|
| 68 |
+
def cash_runway(as_of_month: str = None, last_n_months: int = 3) -> float:
|
| 69 |
+
# If no as_of_month specified, use most recent
|
| 70 |
+
if as_of_month is None:
|
| 71 |
+
most_recent = cash["month"].max()
|
| 72 |
+
else:
|
| 73 |
+
most_recent = pd.Period(as_of_month)
|
| 74 |
+
|
| 75 |
+
# Get cash balance as of the specified/most recent month
|
| 76 |
+
cash_usd = cash[cash["month"] == most_recent]["cash_usd"].sum()
|
| 77 |
+
|
| 78 |
+
# Calculate net burn for each of the last N months before as_of_month
|
| 79 |
+
a = convert_to_usd(actuals, fx)
|
| 80 |
+
|
| 81 |
+
# Get months ending before as_of_month
|
| 82 |
+
available_months = sorted([m for m in a["month"].unique() if m < most_recent])
|
| 83 |
+
months = available_months[-last_n_months:] if len(available_months) >= last_n_months else available_months
|
| 84 |
+
|
| 85 |
+
burns = []
|
| 86 |
+
for m in months:
|
| 87 |
+
dfm = a[a["month"] == m]
|
| 88 |
+
rev = dfm[dfm["account_category"] == "Revenue"]["amount_usd"].sum()
|
| 89 |
+
cogs = dfm[dfm["account_category"] == "COGS"]["amount_usd"].sum()
|
| 90 |
+
opex = dfm[dfm["account_category"].str.startswith("Opex")]["amount_usd"].sum()
|
| 91 |
+
burns.append(cogs + opex - rev)
|
| 92 |
+
|
| 93 |
+
avg_burn = sum(burns) / len(burns) if burns else 0
|
| 94 |
+
return cash_usd / avg_burn if avg_burn > 0 else float('inf'), avg_burn
|
| 95 |
+
|
| 96 |
+
def plot_chart(
|
| 97 |
+
chart_type: str,
|
| 98 |
+
x,
|
| 99 |
+
y,
|
| 100 |
+
title: str,
|
| 101 |
+
x_label: str,
|
| 102 |
+
y_label: str,
|
| 103 |
+
output_path: str,
|
| 104 |
+
legends: list[str] | None = None, # ← NEW
|
| 105 |
+
) -> str:
|
| 106 |
+
"""
|
| 107 |
+
Plot helper that supports single-series and multi-series
|
| 108 |
+
bar, line, scatter and pie charts.
|
| 109 |
+
|
| 110 |
+
Parameters
|
| 111 |
+
----------
|
| 112 |
+
chart_type : {"bar", "line", "scatter", "pie"}
|
| 113 |
+
x, y : list-like objects. For multi-series data,
|
| 114 |
+
use y = [[series1], [series2], …] and
|
| 115 |
+
x = [[categories]].
|
| 116 |
+
legends : Optional list of legend labels, one per series.
|
| 117 |
+
"""
|
| 118 |
+
try:
|
| 119 |
+
|
| 120 |
+
plt.figure(figsize=(7, 4))
|
| 121 |
+
|
| 122 |
+
# ── MULTI-SERIES ────────────────────────────────────────────────
|
| 123 |
+
if isinstance(y[0], list) and len(y) > 1:
|
| 124 |
+
categories = x[0] # shared x-axis
|
| 125 |
+
n_groups = len(categories)
|
| 126 |
+
n_series = len(y)
|
| 127 |
+
|
| 128 |
+
if chart_type == "bar":
|
| 129 |
+
bar_width = 0.8 / n_series
|
| 130 |
+
x_pos = np.arange(n_groups)
|
| 131 |
+
colors = ['#1f77b4', '#ff7f0e', '#2ca02c',
|
| 132 |
+
'#d62728', '#9467bd']
|
| 133 |
+
|
| 134 |
+
for i, series in enumerate(y):
|
| 135 |
+
offset = (i - n_series / 2 + 0.5) * bar_width
|
| 136 |
+
plt.bar(
|
| 137 |
+
x_pos + offset,
|
| 138 |
+
series,
|
| 139 |
+
bar_width,
|
| 140 |
+
color=colors[i % len(colors)],
|
| 141 |
+
label=(legends[i] if legends and i < len(legends)
|
| 142 |
+
else f"Series {i + 1}")
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
plt.xticks(x_pos, categories, rotation=45)
|
| 146 |
+
plt.legend()
|
| 147 |
+
|
| 148 |
+
elif chart_type == "line":
|
| 149 |
+
for i, series in enumerate(y):
|
| 150 |
+
plt.plot(
|
| 151 |
+
categories,
|
| 152 |
+
series,
|
| 153 |
+
marker="o",
|
| 154 |
+
label=(legends[i] if legends and i < len(legends)
|
| 155 |
+
else f"Series {i + 1}")
|
| 156 |
+
)
|
| 157 |
+
plt.legend()
|
| 158 |
+
plt.xticks(rotation=45)
|
| 159 |
+
|
| 160 |
+
# ── SINGLE-SERIES ───────────────────────────────────────────────
|
| 161 |
+
else:
|
| 162 |
+
# flatten if wrapped
|
| 163 |
+
if isinstance(y[0], list): y = y[0]
|
| 164 |
+
if isinstance(x[0], list): x = x[0]
|
| 165 |
+
|
| 166 |
+
if chart_type == "line":
|
| 167 |
+
plt.plot(x, y, marker="o", linewidth=2, markersize=6,
|
| 168 |
+
label=legends[0] if legends else None)
|
| 169 |
+
elif chart_type == "bar":
|
| 170 |
+
plt.bar(x, y, color="skyblue", edgecolor="navy", alpha=0.7,
|
| 171 |
+
label=legends[0] if legends else None)
|
| 172 |
+
plt.xticks(rotation=45)
|
| 173 |
+
plt.ylim(bottom=0)
|
| 174 |
+
elif chart_type == "scatter":
|
| 175 |
+
plt.scatter(x, y, s=60, alpha=0.7,
|
| 176 |
+
label=legends[0] if legends else None)
|
| 177 |
+
elif chart_type == "pie":
|
| 178 |
+
plt.pie(y, labels=x, autopct="%1.1f%%", startangle=90)
|
| 179 |
+
plt.axis("equal")
|
| 180 |
+
|
| 181 |
+
if legends and chart_type != "pie":
|
| 182 |
+
plt.legend()
|
| 183 |
+
|
| 184 |
+
# ── COMMON FORMATTING ──────────────────────────────────────────
|
| 185 |
+
plt.title(title, fontsize=14, fontweight="bold")
|
| 186 |
+
|
| 187 |
+
if chart_type != "pie":
|
| 188 |
+
plt.xlabel(x_label, fontsize=12)
|
| 189 |
+
plt.ylabel(y_label, fontsize=12)
|
| 190 |
+
plt.grid(True, alpha=0.3)
|
| 191 |
+
|
| 192 |
+
plt.tight_layout()
|
| 193 |
+
plt.savefig(output_path, dpi=100, bbox_inches="tight")
|
| 194 |
+
plt.close()
|
| 195 |
+
return output_path
|
| 196 |
+
|
| 197 |
+
except Exception as e:
|
| 198 |
+
return f'There is some problem with the data you send, I am using matplotlib to plot. Can you send a full code to other tool which could run on PythonREPLTool (should save the graph and return the filename). Here is the error: {e}'
|
| 199 |
+
# return f'There is some problem with the data you send, I am using matplotlib to plot. Can you recheck the data and send it again. May be just include the most important field to plot. Here is the error: {e}'
|
app.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
import streamlit as st
|
| 5 |
+
from langchain_core.messages import AIMessage, HumanMessage
|
| 6 |
+
|
| 7 |
+
# Import the agent initializer from its new location
|
| 8 |
+
from agent.agent import initialize_agent
|
| 9 |
+
|
| 10 |
+
def extract_image_paths(text: str) -> list[str]:
|
| 11 |
+
"""
|
| 12 |
+
Finds all image filenames (png/jpeg) in a block of text,
|
| 13 |
+
whether in quotes or bare.
|
| 14 |
+
"""
|
| 15 |
+
return re.findall(r"['\"]?([A-Za-z0-9_\-]+\.(?:png|jpg|jpeg))['\"]?", text)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
st.set_page_config(page_title="🤖 Smart Financial Analytics Agent", layout="wide")
|
| 19 |
+
st.title("🤖 CFO Copilot")
|
| 20 |
+
|
| 21 |
+
# Initialize the agent
|
| 22 |
+
agent_executor = initialize_agent()
|
| 23 |
+
|
| 24 |
+
# Initialize chat history in session state
|
| 25 |
+
if "messages" not in st.session_state:
|
| 26 |
+
st.session_state.messages = []
|
| 27 |
+
|
| 28 |
+
# Display past messages
|
| 29 |
+
for message in st.session_state.messages:
|
| 30 |
+
with st.chat_message(message["role"]):
|
| 31 |
+
|
| 32 |
+
st.text(message["content"])
|
| 33 |
+
if "image_path" in message and message["image_path"]:
|
| 34 |
+
st.image(message["image_path"])
|
| 35 |
+
|
| 36 |
+
# Get user input
|
| 37 |
+
if prompt := st.chat_input("Ask a question about your financial data..."):
|
| 38 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 39 |
+
with st.chat_message("user"):
|
| 40 |
+
st.markdown(prompt)
|
| 41 |
+
|
| 42 |
+
# Generate and display assistant response
|
| 43 |
+
with st.chat_message("assistant"):
|
| 44 |
+
with st.spinner("Thinking..."):
|
| 45 |
+
chat_history = [
|
| 46 |
+
HumanMessage(content=msg["content"]) if msg["role"] == "user" else AIMessage(content=msg["content"])
|
| 47 |
+
for msg in st.session_state.messages[:-1]
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
response = agent_executor.invoke({
|
| 51 |
+
"input": prompt,
|
| 52 |
+
"chat_history": chat_history
|
| 53 |
+
})
|
| 54 |
+
|
| 55 |
+
output_text = response["output"]
|
| 56 |
+
st.text(output_text)
|
| 57 |
+
|
| 58 |
+
# Collect any image paths from intermediate steps & output
|
| 59 |
+
image_paths = []
|
| 60 |
+
|
| 61 |
+
# 1. From intermediate_steps (even if action.tool != 'plot_chart')
|
| 62 |
+
for step in response.get("intermediate_steps", []):
|
| 63 |
+
_, observation = step
|
| 64 |
+
# observation might be a filename or a descriptive text
|
| 65 |
+
if isinstance(observation, str):
|
| 66 |
+
image_paths += extract_image_paths(observation)
|
| 67 |
+
|
| 68 |
+
# 2. From the assistant’s final output text
|
| 69 |
+
image_paths += extract_image_paths(output_text)
|
| 70 |
+
|
| 71 |
+
# 3. De-duplicate and display
|
| 72 |
+
for path in dict.fromkeys(image_paths): # preserves order, removes dups
|
| 73 |
+
try:
|
| 74 |
+
st.image(path)
|
| 75 |
+
# also record for session state
|
| 76 |
+
image_path = path
|
| 77 |
+
except Exception as e:
|
| 78 |
+
st.error(f"Failed to load image {path}: {e}")
|
| 79 |
+
|
| 80 |
+
# Save session state
|
| 81 |
+
st.session_state.messages.append({
|
| 82 |
+
"role": "assistant",
|
| 83 |
+
"content": output_text,
|
| 84 |
+
"image_path": image_path if image_paths else None
|
| 85 |
+
})
|
chart.png
ADDED
|
data.xlsx
ADDED
|
Binary file (45.8 kB). View file
|
|
|
fixtures/data.xlsx
ADDED
|
Binary file (45.8 kB). View file
|
|
|
opex_month_wise.png
ADDED
|
requirements.txt
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
langchain==0.3.27
|
| 2 |
+
langchain-community==0.3.30
|
| 3 |
+
langchain-core==0.3.76
|
| 4 |
+
langchain-experimental==0.3.4
|
| 5 |
+
langchain-google-genai==2.1.12
|
| 6 |
+
langchain-openai==0.3.33
|
| 7 |
+
langchain-text-splitters==0.3.11
|
| 8 |
+
matplotlib==3.10.6
|
| 9 |
+
matplotlib-inline==0.1.7
|
| 10 |
+
numpy==2.3.3
|
| 11 |
+
pandas==2.3.2
|
| 12 |
+
pytest==8.4.2
|
| 13 |
+
pytest-mock==3.15.1
|
| 14 |
+
streamlit==1.50.0
|
tests/__init__.py
ADDED
|
File without changes
|
tests/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (144 Bytes). View file
|
|
|
tests/__pycache__/test1.cpython-313-pytest-8.4.2.pyc
ADDED
|
Binary file (2.1 kB). View file
|
|
|
tests/__pycache__/test_1.cpython-313-pytest-8.4.2.pyc
ADDED
|
Binary file (13.5 kB). View file
|
|
|
tests/__pycache__/test_2.cpython-313-pytest-8.4.2.pyc
ADDED
|
Binary file (2.73 kB). View file
|
|
|
tests/__pycache__/test_3.cpython-313-pytest-8.4.2.pyc
ADDED
|
Binary file (2.53 kB). View file
|
|
|
tests/__pycache__/test_agent_logic.cpython-313-pytest-8.4.2.pyc
ADDED
|
Binary file (13.5 kB). View file
|
|
|
tests/test_1.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# test_module_level_tools.py
|
| 2 |
+
import pytest
|
| 3 |
+
from unittest.mock import patch, Mock
|
| 4 |
+
from agent import agent
|
| 5 |
+
from agent.agent import (
|
| 6 |
+
code_analysis,
|
| 7 |
+
get_revenue_variance,
|
| 8 |
+
get_gross_margin_pct,
|
| 9 |
+
get_opex_breakdown,
|
| 10 |
+
get_ebitda_proxy,
|
| 11 |
+
get_cash_runway,
|
| 12 |
+
plot_chart
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestModuleLevelTools:
|
| 17 |
+
"""Test the module-level tool definitions"""
|
| 18 |
+
|
| 19 |
+
def test_tools_have_correct_decorators(self):
|
| 20 |
+
"""Test that all tools are properly decorated"""
|
| 21 |
+
tools = [
|
| 22 |
+
code_analysis,
|
| 23 |
+
get_revenue_variance,
|
| 24 |
+
get_gross_margin_pct,
|
| 25 |
+
get_opex_breakdown,
|
| 26 |
+
get_ebitda_proxy,
|
| 27 |
+
get_cash_runway,
|
| 28 |
+
plot_chart
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
for tool in tools:
|
| 32 |
+
# Check that tool has required attributes from @tool decorator
|
| 33 |
+
assert hasattr(tool, 'name'), f"Tool {tool} missing 'name' attribute"
|
| 34 |
+
assert hasattr(tool, 'description'), f"Tool {tool} missing 'description' attribute"
|
| 35 |
+
assert hasattr(tool, 'args_schema'), f"Tool {tool} missing 'args_schema' attribute"
|
| 36 |
+
|
| 37 |
+
def test_tool_names_are_correct(self):
|
| 38 |
+
"""Test that tool names match function names"""
|
| 39 |
+
expected_names = {
|
| 40 |
+
'code_analysis': code_analysis.name,
|
| 41 |
+
'get_revenue_variance': get_revenue_variance.name,
|
| 42 |
+
'get_gross_margin_pct': get_gross_margin_pct.name,
|
| 43 |
+
'get_opex_breakdown': get_opex_breakdown.name,
|
| 44 |
+
'get_ebitda_proxy': get_ebitda_proxy.name,
|
| 45 |
+
'get_cash_runway': get_cash_runway.name,
|
| 46 |
+
'plot_chart': plot_chart.name,
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
for expected_name, actual_name in expected_names.items():
|
| 50 |
+
assert expected_name == actual_name
|
| 51 |
+
|
| 52 |
+
def test_tool_descriptions_exist(self):
|
| 53 |
+
"""Test that all tools have non-empty descriptions"""
|
| 54 |
+
tools = [code_analysis, get_revenue_variance, get_gross_margin_pct,
|
| 55 |
+
get_opex_breakdown, get_ebitda_proxy, get_cash_runway, plot_chart]
|
| 56 |
+
|
| 57 |
+
for tool in tools:
|
| 58 |
+
assert tool.description is not None
|
| 59 |
+
assert len(tool.description.strip()) > 0
|
| 60 |
+
|
| 61 |
+
@patch('agent.utils.revenue_variance')
|
| 62 |
+
def test_get_revenue_variance_tool_execution(self, mock_utils_func):
|
| 63 |
+
"""Test revenue variance tool execution"""
|
| 64 |
+
mock_utils_func.return_value = 5000.0
|
| 65 |
+
|
| 66 |
+
result = get_revenue_variance.invoke({
|
| 67 |
+
'start_month': '2025-01',
|
| 68 |
+
'end_month': '2025-01'
|
| 69 |
+
})
|
| 70 |
+
|
| 71 |
+
assert result == 5000.0
|
| 72 |
+
mock_utils_func.assert_called_once_with('2025-01', '2025-01')
|
| 73 |
+
|
| 74 |
+
@patch('agent.utils.cash_runway')
|
| 75 |
+
def test_get_cash_runway_tool_execution(self, mock_utils_func):
|
| 76 |
+
"""Test cash runway tool with optional parameters"""
|
| 77 |
+
mock_utils_func.return_value = 12.5
|
| 78 |
+
|
| 79 |
+
# Test with default parameters
|
| 80 |
+
result = get_cash_runway.invoke({})
|
| 81 |
+
assert result == 12.5
|
| 82 |
+
mock_utils_func.assert_called_once_with(None, 3)
|
| 83 |
+
|
| 84 |
+
# Test with custom parameters
|
| 85 |
+
mock_utils_func.reset_mock()
|
| 86 |
+
result = get_cash_runway.invoke({
|
| 87 |
+
'as_of_month': '2025-01',
|
| 88 |
+
'last_n_months': 6
|
| 89 |
+
})
|
| 90 |
+
assert result == 12.5
|
| 91 |
+
mock_utils_func.assert_called_once_with('2025-01', 6)
|
| 92 |
+
|
| 93 |
+
def test_python_repl_tool_instance(self):
|
| 94 |
+
"""Test that python_repl is properly initialized"""
|
| 95 |
+
assert agent.python_repl is not None
|
| 96 |
+
assert hasattr(agent.python_repl, 'run')
|
| 97 |
+
|
| 98 |
+
@patch('agent.agent.python_repl')
|
| 99 |
+
def test_code_analysis_tool_execution(self, mock_python_repl):
|
| 100 |
+
"""Test code analysis tool execution"""
|
| 101 |
+
mock_python_repl.run.return_value = "Output: 42"
|
| 102 |
+
|
| 103 |
+
result = code_analysis.invoke({'code': 'print(21 * 2)'})
|
| 104 |
+
|
| 105 |
+
assert result == "Output: 42"
|
| 106 |
+
mock_python_repl.run.assert_called_once_with('print(21 * 2)')
|
tests/test_2.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# tests/test_agent_tool_selection_updated.py
|
| 2 |
+
import pytest
|
| 3 |
+
from unittest.mock import patch, Mock
|
| 4 |
+
from agent.agent import initialize_agent
|
| 5 |
+
from langchain.agents.agent import AgentExecutor
|
| 6 |
+
|
| 7 |
+
class TestAgentToolSelectionUpdated:
|
| 8 |
+
|
| 9 |
+
@pytest.fixture(autouse=True)
|
| 10 |
+
def setup_agent(self):
|
| 11 |
+
with patch("streamlit.secrets", {"GOOGLE_API_KEY": "AIzaSyBxrJAxe69t02jMZKtOGXY3gCIgVm8RAMY"}):
|
| 12 |
+
with patch("langchain_openai.ChatOpenAI") as mock_llm:
|
| 13 |
+
mock_llm.return_value = Mock()
|
| 14 |
+
self.agent = initialize_agent()
|
| 15 |
+
|
| 16 |
+
def test_agent_has_all_tools_registered(self):
|
| 17 |
+
expected = {
|
| 18 |
+
"code_analysis",
|
| 19 |
+
"get_revenue_variance",
|
| 20 |
+
"get_gross_margin_pct",
|
| 21 |
+
"get_opex_breakdown",
|
| 22 |
+
"get_ebitda_proxy",
|
| 23 |
+
"get_cash_runway",
|
| 24 |
+
"plot_chart"
|
| 25 |
+
}
|
| 26 |
+
actual = {tool.name for tool in self.agent.tools}
|
| 27 |
+
assert expected == actual
|
tests/test_3.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# tests/test_agent_tool_selection_by_log.py
|
| 2 |
+
import pytest
|
| 3 |
+
from agent.agent import initialize_agent
|
| 4 |
+
from unittest.mock import patch, Mock
|
| 5 |
+
|
| 6 |
+
@pytest.fixture(autouse=True)
|
| 7 |
+
def agent_executor():
|
| 8 |
+
# Create an agent with a dummy LLM but real logging of tool calls
|
| 9 |
+
with patch("streamlit.secrets", {"GOOGLE_API_KEY": "AIzaSyBxrJAxe69t02jMZKtOGXY3gCIgVm8RAMY"}):
|
| 10 |
+
with patch("langchain_openai.ChatOpenAI") as mock_llm:
|
| 11 |
+
mock_llm.return_value = Mock()
|
| 12 |
+
yield initialize_agent()
|
| 13 |
+
|
| 14 |
+
@pytest.mark.parametrize("query,tool_name", [
|
| 15 |
+
("What is revenue variance for January 2025?", "get_revenue_variance"),
|
| 16 |
+
("What is our cash runway for 2025?", "get_cash_runway"),
|
| 17 |
+
("Show me gross margin percentage for July 2025", "get_gross_margin_pct"),
|
| 18 |
+
("Break down opex by category for 2025", "get_opex_breakdown"),
|
| 19 |
+
("What's our EBITDA right now for last 3 months?", "get_ebitda_proxy"),
|
| 20 |
+
])
|
| 21 |
+
def test_tool_selected_in_logs(agent_executor, capsys, query, tool_name):
|
| 22 |
+
# Run the agent; it will print "Invoking: `tool_name` with ..."
|
| 23 |
+
agent_executor({"input": query})
|
| 24 |
+
captured = capsys.readouterr().out
|
| 25 |
+
assert f"Invoking: `{tool_name}`" in captured
|