DEV Community

shashank ms
shashank ms

Posted on

Practical Applications of LLMs in Business Analytics

We are going to build a lightweight analytics agent that ingests a raw CSV of monthly sales figures, calculates growth and margin metrics with Python, and uses an LLM to generate a structured executive summary. This saves finance and operations teams from manually copying spreadsheet data into slide decks. I run it on Oxlo.ai because the flat per-request pricing keeps costs predictable even when the monthly data payload grows, and you can see the exact rate on the pricing page.

What you'll need

Python 3.10 or newer, the openai and pandas packages, and an Oxlo.ai API key from https://portal.oxlo.ai. Install the dependencies with pip.

pip install openai pandas

Step 1: Prepare sample data

I will start with a hard-coded CSV string representing six months of revenue and expenses. In production you would swap this for a file from S3 or a database export.

import pandas as pd
from io import StringIO

csv_data = """Month,Revenue,Expenses
2024-01,125000,98000
2024-02,132000,101000
2024-03,118000,99000
2024-04,145000,105000
2024-05,138000,110000
2024-06,155000,108000"""

df = pd.read_csv(StringIO(csv_data))
print(df)

Step 2: Compute baseline metrics

Next, calculate month-over-month revenue growth, profit margin, and flag the weakest period. Keeping this in Python guarantees the numbers are reproducible.

import json

df["Profit"] = df["Revenue"] - df["Expenses"]
df["Margin_Pct"] = (df["Profit"] / df["Revenue"] * 100).round(2)
df["Revenue_MoM_Pct"] = df["Revenue"].pct_change() * 100
df["Revenue_MoM_Pct"] = df["Revenue_MoM_Pct"].round(2)

worst_month = df.loc[df["Revenue_MoM_Pct"].idxmin(), "Month"]

metrics_payload = {
    "periods": df.to_dict(orient="records"),
    "average_margin": round(df["Margin_Pct"].mean(), 2),
    "worst_growth_month": worst_month,
    "total_revenue": int(df["Revenue"].sum()),
}

print(json.dumps(metrics_payload, indent=2))

Step 3: Draft the system prompt

The system prompt defines the analyst persona and the exact JSON schema I want back. I keep it separate so non-engineers can tweak the tone without touching code.

SYSTEM_PROMPT = """You are a senior business analyst. You receive structured monthly sales metrics in JSON. Write a concise executive summary with three sections: Overview, Risk Flags, and Recommendations. Return valid JSON with keys: overview, risk_flags (array), recommendations (array), and confidence (string). Be specific and cite numbers."""

Step 4: Send metrics to the LLM

Now I route the JSON payload to Oxlo.ai using the OpenAI SDK. I use llama-3.3-70b and request JSON mode so the response is machine-readable.

from openai import OpenAI
import os

client = OpenAI(
    base_url="https://api.oxlo.ai/v1",
    api_key=os.environ.get("OXLO_API_KEY", "YOUR_OXLO_API_KEY"),
)

user_message = json.dumps(metrics_payload, indent=2)

response = client.chat.completions.create(
    model="llama-3.3-70b",
    messages=[
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": user_message},
    ],
    response_format={"type": "json_object"},
    temperature=0.2,
)

raw_report = response.choices[0].message.content
print(raw_report)

Step 5: Parse the structured report

Finally, load the JSON and print a human-readable summary. This is the block you would drop into a CI report, email helper, or Slack bot.

report = json.loads(raw_report)

print("=== Executive Summary ===")
print(f"Overview: {report['overview']}")
print("\nRisk Flags:")
for flag in report["risk_flags"]:
    print(f"  - {flag}")
print("\nRecommendations:")
for rec in report["recommendations"]:
    print(f"  - {rec}")
print(f"\nConfidence: {report['confidence']}")

Run it

Save the complete script as analytics_agent.py, set your API key, and run it. The output below is typical of what I see on Oxlo.ai.

import os
import json
import pandas as pd
from io import StringIO
from openai import OpenAI

csv_data = """Month,Revenue,Expenses
2024-01,125000,98000
2024-02,132000,101000
2024-03,118000,99000
2024-04,145000,105000
2024-05,138000,110000
2024-06,155000,108000"""

df = pd.read_csv(StringIO(csv_data))

df["Profit"] = df["Revenue"] - df["Expenses"]
df["Margin_Pct"] = (df["Profit"] / df["Revenue"] * 100).round(2)
df["Revenue_MoM_Pct"] = df["Revenue"].pct_change() * 100
df["Revenue_MoM_Pct"] = df["Revenue_MoM_Pct"].round(2)

worst_month = df.loc[df["Revenue_MoM_Pct"].idxmin(), "Month"]

metrics_payload = {
    "periods": df.to_dict(orient="records"),
    "average_margin": round(df["Margin_Pct"].mean(), 2),
    "worst_growth_month": worst_month,
    "total_revenue": int(df["Revenue"].sum()),
}

SYSTEM_PROMPT = """You are a senior business analyst. You receive structured monthly sales metrics in JSON. Write a concise executive summary with three sections: Overview, Risk Flags, and Recommendations. Return valid JSON with keys: overview, risk_flags (array), recommendations (array), and confidence (string). Be specific and cite numbers."""

client = OpenAI(
    base_url="https://api.oxlo.ai/v1",
    api_key=os.environ.get("OXLO_API_KEY", "YOUR_OXLO_API_KEY"),
)

user_message = json.dumps(metrics_payload, indent=2)

response = client.chat.completions.create(
    model="llama-3.3-70b",
    messages=[
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": user_message},
    ],
    response_format={"type": "json_object"},
    temperature=0.2,
)

report = json.loads(response.choices[0].message.content)

print("=== Executive Summary ===")
print(f"Overview: {report['overview']}")
print("\nRisk Flags:")
for flag in report["risk_flags"]:
    print(f"  - {flag}")
print("\nRecommendations:")
for rec in report["recommendations"]:
    print(f"  - {rec}")
print(f"\nConfidence: {report['confidence']}")

Example output:

=== Executive Summary ===
Overview: Total revenue for the six-month period reached $813,000 with an average profit margin of 22.3%. Growth was strongest in April, but March recorded a 10.6% month-over-month revenue decline.

Risk Flags:
  - March revenue dropped sharply to $118,000, breaking the upward trend.
  - Expenses rose to $110,000 in May while revenue contracted, squeezing margin.

Recommendations:
  - Investigate March churn and pipeline coverage to prevent similar drops.
  - Review May cost drivers; $110,000 spend against falling revenue is a warning signal.

Confidence: high

Wrap-up

Swap the CSV string for a live database query or S3 trigger to turn this into a nightly report. If you need the same summary in Mandarin or Spanish for regional stakeholders, pipe the English output through qwen-3-32b on Oxlo.ai in a second pass. It handles multilingual reasoning well and the flat per-request cost means the extra translation step does not balloon your bill.

Top comments (0)