Lab – LangChain Agent for KPI Queries#

“Because your boss doesn’t want SQL. They want answers.” 💼🤖


🎯 Goal#

In this lab, you’ll build your own AI-powered business analyst — a LangChain agent that fetches KPIs from data, explains trends, and makes you look like you worked all night when you really didn’t. ☕


🧱 What You’ll Learn#

By the end of this lab, you’ll know how to:

  • ⚙️ Build a LangChain Agent that understands KPI questions

  • 🧠 Connect it with your data (CSV, SQL, Excel, or API)

  • 💬 Query business metrics in plain English

  • 📊 Generate automatic summaries and insights

  • 🎭 Impress your manager in one meeting


🧰 Prerequisites#

Make sure you’ve installed the essentials:

pip install langchain openai pandas python-dotenv sqlalchemy

Optional (if you’re querying a database):

pip install psycopg2-binary  # For PostgreSQL
pip install sqlite3          # Or use built-in SQLite

And don’t forget your OpenAI API key in .env:

OPENAI_API_KEY=your_key_here

🧮 Step 1: Load Some Data#

Let’s simulate your company’s sales data. (Spoiler: it’s slightly fake but totally functional.)

import pandas as pd

data = {
    "Region": ["East", "West", "North", "South"],
    "Sales": [120000, 95000, 102000, 87000],
    "Profit": [24000, 18000, 15000, 11000],
    "Month": ["January", "January", "January", "January"]
}

df = pd.DataFrame(data)
df.to_csv("sales_data.csv", index=False)

Now your AI agent has something to gossip about.


🤖 Step 2: Connect LangChain to Your Data#

from langchain.agents import create_pandas_dataframe_agent
from langchain.chat_models import ChatOpenAI
import pandas as pd
import os
from dotenv import load_dotenv

load_dotenv()

df = pd.read_csv("sales_data.csv")

llm = ChatOpenAI(model="gpt-4o", temperature=0)
agent = create_pandas_dataframe_agent(llm, df, verbose=True)

💬 Step 3: Ask Business Questions#

“Finally, someone who understands your vague requests.”

Try asking things like:

agent.run("What is the total sales and profit by region?")
agent.run("Which region performed best in terms of profit margin?")
agent.run("Generate a quick summary of the performance in one sentence.")

The output might look like:

East had the highest sales and profit, followed by North and West. South needs therapy.

🧠 Step 4: Make It Fancy – Add Natural Language Dashboards#

If you want to visualize KPIs, plug in Plotly:

import plotly.express as px

fig = px.bar(df, x="Region", y="Sales", color="Profit", title="Sales vs Profit by Region")
fig.show()

💡 Combine this with your LangChain responses for an auto-insight dashboard that explains data and plots it — like a data storyteller with caffeine.


🗃️ Step 5: Connect a Database (Optional)#

Your boss loves “real-time dashboards,” right? Let’s make it actually real (ish).

from langchain.sql_database import SQLDatabase
from langchain.agents import create_sql_agent

db = SQLDatabase.from_uri("sqlite:///business_data.db")
sql_agent = create_sql_agent(llm, db=db, verbose=True)

sql_agent.run("Find the top 3 products by revenue last quarter.")

Boom 💥 — instant data insights without a single JOIN (you’re welcome).


💡 Step 6: Automate KPI Reports#

Let’s pretend you’re building an email summary system:

prompt = """
Summarize company performance for the month of January
based on sales_data.csv and include one sentence of motivation.
"""
response = agent.run(prompt)
print(response)

Possible output:

“January sales totaled $404K, with East region leading the charge. Keep the coffee strong and targets stronger!”


⚙️ Step 7: Deploy It as a Slack or Streamlit Bot#

Because your teammates deserve to talk to something smarter than Jira.

pip install streamlit langchain openai
import streamlit as st

query = st.text_input("Ask me anything about KPIs 👇")
if query:
    answer = agent.run(query)
    st.write("📊", answer)

Now everyone in your office can casually chat with your data. (Warning: they will ask “Who’s underperforming?”)


🧠 Extra Credit#

Try adding:

  • 🧩 Memory: So it remembers previous KPI questions

  • 🔗 Tools: Integrate with CRMs or Google Sheets

  • 🗓️ Scheduling: Daily auto-reports emailed via LangChain workflow

Bonus challenge:

Make it say “You’re doing great, champ!” when revenue drops.


🎯 Summary#

Concept

Description

🧠 LangChain Agent

A smart layer between data & humans

🧾 KPI Querying

Natural language → Insight

⚙️ Integration

CSV, SQL, APIs

📊 Visualisation

Optional but makes you look professional

🤣 Humor

Mandatory (as per this course policy)


🏁 What You’ve Built#

✅ An LLM-powered KPI Query Agent ✅ That can analyze, summarize, and visualize business data ✅ Using LangChain + Pandas + OpenAI ✅ While making you laugh instead of cry at your dashboards

# Your code here