DEV Community

shashank ms
shashank ms

Posted on

Natural Language Generation with LLM Models

We are going to build a batch report generator that turns structured JSON analytics data into human-readable executive summaries. This helps teams automate weekly status reports without writing boilerplate by hand.

What you'll need

Python 3.10 or newer, the OpenAI SDK, and an Oxlo.ai API key from https://portal.oxlo.ai. Install the SDK with pip.

pip install openai

Step 1: Configure the client

Instantiate the OpenAI client pointing at Oxlo.ai. I keep my key in an environment variable, but you can paste it directly for local testing.

from openai import OpenAI

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

Step 2: Define the input schema

The generator expects a JSON object with metrics. I use Pydantic to keep the shape explicit and to validate inputs before burning requests.

from pydantic import BaseModel
import json

class WeeklyMetrics(BaseModel):
    week: str
    total_visitors: int
    bounce_rate: float
    top_channel: str
    conversion_rate: float
    issues_flagged: list[str]

sample_data = WeeklyMetrics(
    week="2025-01-13",
    total_visitors=124500,
    bounce_rate=0.42,
    top_channel="organic_search",
    conversion_rate=0.031,
    issues_flagged=["checkout latency", "mobile CTA below fold"]
)

print(json.dumps(sample_data.model_dump(), indent=2))

Step 3: Design the generation prompt

The system prompt controls tone, length, and what the model must infer versus quote directly. I treat this as config and keep it outside the function so editors can tweak it without touching code.

SYSTEM_PROMPT = """You are a senior data analyst writing weekly executive summaries.
Rules:
- Write one fluent paragraph of 60 to 80 words.
- Mention the week, total visitors, and top channel naturally.
- Flag any issues using cautious language.
- Do not use bullet points or headers.
- Output plain text only, no markdown."""

Step 4: Build the generation function

This helper serializes the metrics, sends them to Llama 3.3 70B on Oxlo.ai, and returns the generated paragraph. I use the standard chat completions endpoint.

def generate_summary(metrics: WeeklyMetrics) -> str:
    user_message = json.dumps(metrics.model_dump(), indent=2)
    
    response = client.chat.completions.create(
        model="llama-3.3-70b",
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": user_message},
        ],
    )
    
    return response.choices[0].message.content.strip()

summary = generate_summary(sample_data)
print(summary)

Step 5: Batch process multiple weeks

Real pipelines handle more than one record. Here is a loop that generates summaries for three weeks and collects them into a list.

batch = [
    WeeklyMetrics(week="2025-01-06", total_visitors=118000, bounce_rate=0.45, top_channel="paid_social", conversion_rate=0.028, issues_flagged=[]),
    WeeklyMetrics(week="2025-01-13", total_visitors=124500, bounce_rate=0.42, top_channel="organic_search", conversion_rate=0.031, issues_flagged=["checkout latency"]),
    WeeklyMetrics(week="2025-01-20", total_visitors=131200, bounce_rate=0.40, top_channel="organic_search", conversion_rate=0.034, issues_flagged=["mobile CTA below fold", "email deliverability"]),
]

reports = []
for record in batch:
    text = generate_summary(record)
    reports.append({"week": record.week, "summary": text})
    print(f"Generated summary for {record.week}")

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

Run it

Save the script as report_generator.py, set your OXLO_API_KEY, and run it. You should see output similar to this.

$ python report_generator.py

Generated summary for 2025-01-06
Generated summary for 2025-01-13
Generated summary for 2025-01-20

[
  {
    "week": "2025-01-06",
    "summary": "During the week of January 6, the site saw 118,000 visitors, with paid social driving the largest share of traffic. The bounce rate held at 45 percent, and the conversion rate reached 2.8 percent. No critical issues were flagged this period."
  },
  {
    "week": "2025-01-13",
    "summary": "The week of January 13 brought 124,500 visitors, a noticeable lift led by organic search. The bounce rate improved to 42 percent while conversions climbed to 3.1 percent. Teams should monitor checkout latency, which was flagged as a potential concern."
  },
  {
    "week": "2025-01-20",
    "summary": "For the week of January 20, traffic rose to 131,200 visitors, again led by organic search. The bounce rate dropped to 40 percent and conversions hit 3.4 percent. Note that mobile CTA placement and email deliverability were flagged for review."
  }
]

Because Oxlo.ai uses request-based pricing, the cost for this batch is the same whether your JSON payloads are fifty tokens or five thousand tokens. That makes it practical to feed the model full weekly exports without worrying about input length.

Next steps

Wire the generator into a scheduled GitHub Action or cron job so reports land in Slack every Monday morning. If you need deeper reasoning over the numbers, swap the model to deepseek-v3.2 or kimi-k2.6 on Oxlo.ai and ask the model to surface trends across weeks in a single call.

Top comments (0)