Build a Local AI Operations Analyst

Build a local AI analyst with governed SQL, RAG, and SVG charts.

Introduction

30 Second Summary

Operations teams often need a revenue answer before the next meeting begins. The answer must be traceable while sensitive regional figures stay contained.

In this project, you will build ops-insight-agent, a fully local AI agent that answers operational questions from stored evidence. You will enforce regional data boundaries before turning a grounded answer into a charted analyst report.

What You'll Build

east-report.html opens as an East-only operations brief with a grounded explanation above a revenue chart.

By the end of this project, you'll have:

  • Tool-selected business answers that use SQLite for KPI totals. Definitions come from vector retrieval over the persistent ops_glossary collection in Chroma.
  • A region-scoped API that returns different results for East and West callers through FastAPI. Unauthorized regions receive an HTTP 403 response.
  • A browser-ready analyst report in east-report.html with a grounded explanation above an inline SVG revenue chart.
  • Secret Mission: A protected audit trail that records every tool call. Only the auditor role can reveal its history.

What do I need before starting?

You need a Mac running macOS Sonoma 14 or newer with at least 5 GB of free disk space.

Administrator access is required for the application installers. Internet access is only needed for the initial downloads.

Before We Start

Before the hands-on work begins, lock in the operational question that gives every tool a clear purpose. You are committing to a local AI analyst that answers regional revenue and KPI-definition questions while keeping unauthorized East or West rows hidden.

Set Up the Local AI Workstation

Your operational question needs a workstation that can run the analyst locally. A consistent environment keeps every tool focused on the same regional revenue problem.

You will install Python for the agent code. You will also prepare Ollama with a tool-capable local model.

In this step, get ready to:
  • Install Python 3.12.10 with Visual Studio Code.
  • Run qwen3:4b locally through Ollama.
  • Create an isolated environment with the pinned Python dependencies.
Install Python and Visual Studio Code

The analyst depends on one exact Python release. Checking your current installation first identifies the setup path that matches your Mac.

  • Open Finder from the Dock.
  • Select Applications in Finder.
  • Double-click Terminal.
  • Check your current Python version by running this command:
python3 --version

What does this command do?

  • The python3 executable starts the Python 3 installation available to Terminal.
  • The --version flag prints its installed release.

✔️ I see Python 3.12.10

That is the exact Python release this project uses. Your first workstation dependency is ready.

ⓧ I see another version

Your current Python installation does not match the project pin. Install the required release alongside it so the remaining commands use the intended package set.

  • Open the official Python 3.12.10 release page.
  • Download the macOS 64-bit universal2 installer.
  • Open the downloaded installer package.
  • Complete the installer using its default options.
  • Enter your Mac administrator password if the installer requests approval.
  • Quit the current Terminal window.
  • Open a fresh Terminal window from Applications in Finder.
  • Verify the installed release by running this command:
python3 --version

What does this command do?

A fresh Terminal reloads the executable paths available on your Mac. The command then prints the Python release that Terminal resolves.

You should see Python 3.12.10.

ⓧ Command not found

Python is unavailable to your current Terminal session. The official universal installer adds the required release to your Mac.

  • Open the official Python 3.12.10 release page.
  • Download the macOS 64-bit universal2 installer.
  • Open the downloaded installer package.
  • Complete the installer using its default options.
  • Enter your Mac administrator password if the installer requests approval.
  • Quit the current Terminal window.
  • Open a fresh Terminal window from Applications in Finder.
  • Verify the installation by running this command:
python3 --version

What does this command do?

The command asks your new Python installation to identify its release. This confirms that the installer made Python available to Terminal.

You should see Python 3.12.10.

Visual Studio Code gives the project folder one workspace for files and terminal commands. Keeping that workspace on your Desktop also makes the local databases easy to find later.

  • Open the official Visual Studio Code macOS setup page.
  • Download the macOS disk image.
  • Open the downloaded disk image.
  • Drag Visual Studio Code.app into Applications.
  • Click your Desktop to make Finder active.
  • Open the File menu.
  • Choose New Folder.
  • Enter ops-insight-agent as the folder name.
  • Press Return to finish creating the folder.

You should see the ops-insight-agent folder on your Desktop. This is the named workspace for every artifact in the project.

  • Return to Applications in Finder.
  • Double-click Visual Studio Code.app.
  • Open the File menu in Visual Studio Code.
  • Choose Open Folder....
  • Select the ops-insight-agent folder on your Desktop.
  • Select Yes, I trust the authors if Visual Studio Code displays the Workspace Trust dialog after opening the folder.
  • Click Open.

You should see ops-insight-agent in the Explorer view. Visual Studio Code is now anchored to the correct project folder.

Project Folder Missing in Visual Studio Code?

Confirm that you selected the folder on your Desktop. Selecting the Desktop itself opens the wrong workspace level.

Use Open Folder... again if the Explorer does not show ops-insight-agent. Help me open the correct project folder in Visual Studio Code.

Install Ollama and verify the model

Ollama runs the local LLM that chooses tools later in the project. The first model run downloads 2.5 GB of model data, so a pause during this command is expected.

  • Open the official Ollama macOS installation page.
  • Download the Ollama disk image.
  • Open ollama.dmg.
  • Drag the Ollama application into Applications.
  • Return to Applications in Finder.
  • Double-click Ollama.
  • Approve the command-line link request if Ollama displays one.

Ollama now runs locally on your Mac. Terminal can use its command-line interface to download and start the model.

  • Return to the fresh macOS Terminal window from earlier.
  • Download and start the local model by running this command:
ollama run qwen3:4b

What does this command do?

  • The ollama run command downloads the selected model when it is missing.
  • The qwen3:4b identifier selects the local tool-capable model for this project.
  • The command opens an interactive local chat after the model is ready.
  • Test the running model by sending this prompt:
Reply with READY only.

What does this prompt check?

The prompt asks for one deterministic reply. A READY response proves the model can accept a local request through Ollama.

You should see READY in Terminal. Your local model is now taking requests.

  • Leave the interactive model chat by entering this command:
/bye

What does this command do?

The /bye command ends the interactive chat. Ollama stays available for the agent code you build later.

Model Not Replying?

Confirm that the Ollama application is still running. The command-line client needs the local Ollama service.

Keep the download running until the full model finishes. Help me troubleshoot why qwen3:4b is not replying through Ollama.

Create the pinned Python environment

A virtual environment keeps this project's packages inside .venv. The pinned requirements make your workstation reproducible.

  • Return to Visual Studio Code with ops-insight-agent open.
  • Select the Explorer view in the left sidebar.
  • Select the new-file control at the top of the Explorer view.
  • Enter requirements.txt as the file name.
  • Add the pinned dependencies to requirements.txt by pasting this content:
fastapi[standard]==0.165.0
pydantic==2.14.4
chromadb==1.5.9
onnxruntime==1.23.2

What do these dependencies provide?

  • FastAPI 0.165.0 provides the local API framework with its development command.
  • Pydantic 2.14.4 provides request-data models.
  • Chroma 1.5.9 provides persistent vector retrieval for the glossary.
  • ONNX Runtime 1.23.2 supports Chroma's local dependency path on this Mac.
  • Save requirements.txt.
  • Confirm requirements.txt appears directly inside ops-insight-agent in the Explorer view.

You should see the four pinned dependency lines in the saved file. The project now has a repeatable package specification.

Requirements File in the Wrong Place?

Confirm that requirements.txt appears directly beneath ops-insight-agent in the Explorer view. Move it out of any nested folder before continuing.

Check that the file name ends with .txt. Help me verify my requirements file location and contents.

✔️ Awesome, I've got everything!

Great. Double-check that you saved requirements.txt.

ⓧ I'd like to double check the full code

fastapi[standard]==0.165.0
pydantic==2.14.4
chromadb==1.5.9
onnxruntime==1.23.2
  • Open the integrated terminal from the Terminal menu in Visual Studio Code.
  • Choose New Terminal.
  • Create the project virtual environment by running this command:
python3 -m venv .venv

What does this command do?

  • The venv module creates an isolated Python environment.
  • The .venv argument stores that environment inside the project folder.
  • The environment receives its own Python executable with its own package directory.
  • Confirm .venv appears inside ops-insight-agent in the Explorer view.

You should see the new .venv folder. This proves Python created the isolated environment on disk.

Virtual Environment Missing?

Confirm that the integrated terminal starts inside the ops-insight-agent workspace. The environment appears wherever the command runs.

Check that Terminal still resolves Python 3.12.10. Help me troubleshoot why .venv was not created.

  • Activate the new virtual environment by running this command:
source .venv/bin/activate

What does this command do?

The source command updates the current shell session. Python and its package installer now resolve from .venv.

The terminal prompt gains the virtual-environment name at its start. This shows the isolated environment is active.

Environment Name Missing From the Prompt?

Confirm that .venv exists in the Explorer view. Run the activation command from the ops-insight-agent folder.

Keep the same terminal open after activation. Help me activate the .venv environment on macOS.

Why Keep These Versions Pinned?

Chroma 1.5.9 is paired with ONNX Runtime 1.23.2 because ONNX Runtime 1.24.1 removed Intel macOS binaries.

This package set supports a local learning environment. Stop if the four versions do not install together instead of silently changing a pin.

  • Install the pinned dependencies into the active environment by running this command:
python -m pip install -r requirements.txt

What does this command do?

  • The active environment's Python launches its package installer.
  • The -r requirements.txt argument installs every dependency from the saved file.
  • Each exact version stays inside .venv.

The terminal should complete the installation without replacing any version pin. The environment now contains the four required packages.

Pinned Installation Not Completing?

Confirm that the terminal still uses the activated .venv environment. Check that requirements.txt contains the exact four lines from the double-check tab.

Stop if the package installer cannot resolve the pinned combination. Help me diagnose the pinned dependency installation.

Before you run the final check, which four version numbers do you expect Terminal to print?

  • Verify every installed package version by running this command:
python -c "from importlib.metadata import version; print(version('chromadb'), version('fastapi'), version('pydantic'), version('onnxruntime'))"

What does this command do?

Python reads the installed metadata for each package. Printing all four values in one line exposes any version drift immediately.

You should see 1.5.9 0.165.0 2.14.4 1.23.2 in Terminal. Your pinned local environment is ready.

Your local workstation can now run the model with an isolated Python package set. Next, you will give the analyst its SQL and glossary tools.

Give the Agent SQL and RAG Tools

Your local model can respond to a prompt. However, it cannot answer operational questions from your business data yet.

This step connects SQLite for KPI values with Chroma for glossary retrieval. A four-round Ollama tool loop then gives qwen3:4b grounded context before it answers.

In this step, get ready to:
  • Seed operational KPI rows in a local database.
  • Store glossary definitions as persistent custom embeddings.
  • Run a tool-calling agent against both data sources.
Create the local data foundation

The glossary seeder imports paths plus the embedding helper from agent.py. Creating those foundations first gives both files one definition of where their local data belongs.

  • Create agent.py inside the open ops-insight-agent folder using the new-file control in the Visual Studio Code file sidebar.
  • Add the imports plus shared local paths to agent.py by pasting this code:
from __future__ import annotations

import hashlib
import json
import math
import re
import sqlite3
import sys
from pathlib import Path
from urllib.request import Request, urlopen

import chromadb

BASE_DIR = Path(__file__).resolve().parent
DB_PATH = BASE_DIR / "ops_data.db"
CHROMA_PATH = str(BASE_DIR / "chroma_data")
COLLECTION_NAME = "ops_glossary"
OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "qwen3:4b"
ALLOWED_METRICS = {"revenue", "orders", "target"}

What Does This Foundation Define?

  • The Path values keep ops_data.db plus chroma_data beside the Python files.
  • The OLLAMA_URL value points the agent at Ollama's local chat API.
  • The ALLOWED_METRICS set limits dynamic SQL column names to the three seeded metrics.
  • Add the deterministic embedding helper below ALLOWED_METRICS in agent.py by pasting this code:
def embed_text(text: str, dimensions: int = 32) -> list[float]:
    vector = [0.0] * dimensions
    for token in re.findall(r"[a-z0-9]+", text.lower()):
        digest = hashlib.sha256(token.encode("utf-8")).digest()
        index = int.from_bytes(digest[:2], "big") % dimensions
        sign = 1.0 if digest[2] % 2 == 0 else -1.0
        vector[index] += sign
    magnitude = math.sqrt(sum(value * value for value in vector)) or 1.0
    return [value / magnitude for value in vector]

How Does the Embedding Work?

An embedding represents text as a numeric vector. Similar token patterns influence the same positions in this 32-dimensional vector.

The final calculation normalizes the vector length. This creates repeatable embeddings without a second model or an external API.

  • Save agent.py.
  • Confirm agent.py appears in the file sidebar beside requirements.txt.

You now have one shared source for the database path plus the glossary path. The seeder can use the same embedding logic as every later search.

  • Create seed.py inside the open ops-insight-agent folder using the new-file control in the file sidebar.
  • Add the imports plus six monthly KPI rows to seed.py by pasting this code:
import sqlite3

import chromadb

from agent import CHROMA_PATH, COLLECTION_NAME, DB_PATH, embed_text

KPI_ROWS = [
    ("East", "2026-07", 120000.0, 900, 125000.0),
    ("East", "2026-08", 132000.0, 960, 130000.0),
    ("East", "2026-09", 128000.0, 940, 135000.0),
    ("West", "2026-07", 98000.0, 760, 100000.0),
    ("West", "2026-08", 104000.0, 800, 105000.0),
    ("West", "2026-09", 111000.0, 850, 108000.0),
]

What Do These Rows Represent?

  • Each tuple contains a region plus one reporting month.
  • The final three values hold revenue plus orders plus the revenue target.
  • Three East rows plus three West rows create a small operational dataset with a visible regional boundary.
  • Add the three glossary records below KPI_ROWS in seed.py by pasting this code:
GLOSSARY = [
    (
        "revenue",
        "Revenue is the sum of recognized sales for the selected region and reporting period.",
        {"metric": "revenue"},
    ),
    (
        "orders",
        "Orders counts completed customer orders for the selected region and reporting period.",
        {"metric": "orders"},
    ),
    (
        "target",
        "Target is the planned revenue benchmark used to compare actual regional performance.",
        {"metric": "target"},
    ),
]

Why Keep Definitions Separate?

The KPI rows hold measurable facts. The glossary holds business meaning for those facts.

This separation creates a small retrieval-augmented generation pattern. Numeric questions use SQL while definition questions use vector retrieval.

  • Add the database seeding function below GLOSSARY in seed.py by pasting this code:
def seed_sqlite() -> int:
    with sqlite3.connect(DB_PATH) as connection:
        connection.execute("DROP TABLE IF EXISTS kpis")
        connection.execute(
            """
            CREATE TABLE kpis (
                region TEXT NOT NULL,
                month TEXT NOT NULL,
                revenue REAL NOT NULL,
                orders INTEGER NOT NULL,
                target REAL NOT NULL,
                PRIMARY KEY (region, month)
            )
            """
        )
        connection.executemany(
            "INSERT INTO kpis(region, month, revenue, orders, target) VALUES (?, ?, ?, ?, ?)",
            KPI_ROWS,
        )
    return len(KPI_ROWS)

What Does the Database Seeder Do?

  • The function recreates the kpis table so every seed run starts from the same six rows.
  • The composite primary key prevents duplicate region-month records.
  • The placeholders in the insert statement keep row values separate from the SQL instruction.
  • Add the glossary seeder plus the runnable entry point below seed_sqlite() in seed.py by pasting this code:
def seed_chroma() -> int:
    client = chromadb.PersistentClient(path=CHROMA_PATH)
    collection = client.get_or_create_collection(
        name=COLLECTION_NAME,
        embedding_function=None,
    )
    collection.upsert(
        ids=[item[0] for item in GLOSSARY],
        documents=[item[1] for item in GLOSSARY],
        metadatas=[item[2] for item in GLOSSARY],
        embeddings=[embed_text(item[1]) for item in GLOSSARY],
    )
    return collection.count()


if __name__ == "__main__":
    sql_count = seed_sqlite()
    glossary_count = seed_chroma()
    print(f"Seeded {sql_count} KPI rows and {glossary_count} glossary entries.")

What Does the Glossary Seeder Do?

  • The persistent client stores the ops_glossary collection inside chroma_data.
  • Setting embedding_function=None tells Chroma that this project supplies its own vectors.
  • The upsert keeps each glossary ID reusable across repeated seed runs.
  • Save seed.py.
  • Seed both local data stores from the activated .venv terminal by running this command:
python seed.py

What Does This Command Do?

Python runs both seeding functions through the file's entry point. The final message reports the number of records stored in each data source.

You should see Seeded 6 KPI rows and 3 glossary entries. You should also see ops_data.db plus chroma_data in the file sidebar.

Seeder Not Reaching Both Counts?

Confirm that the terminal still shows the activated .venv environment. Check that seed.py imports the four names defined in agent.py.

A typo in KPI_ROWS can stop the database insert before Chroma runs. Help me diagnose why seed.py does not report six KPI rows and three glossary entries.

✔️ Awesome, I've got everything!

Your six KPI rows plus three glossary records are now stored locally. Double-check that you saved seed.py.

ⓧ I'd like to double check the full code

import sqlite3

import chromadb

from agent import CHROMA_PATH, COLLECTION_NAME, DB_PATH, embed_text

KPI_ROWS = [
    ("East", "2026-07", 120000.0, 900, 125000.0),
    ("East", "2026-08", 132000.0, 960, 130000.0),
    ("East", "2026-09", 128000.0, 940, 135000.0),
    ("West", "2026-07", 98000.0, 760, 100000.0),
    ("West", "2026-08", 104000.0, 800, 105000.0),
    ("West", "2026-09", 111000.0, 850, 108000.0),
]

GLOSSARY = [
    (
        "revenue",
        "Revenue is the sum of recognized sales for the selected region and reporting period.",
        {"metric": "revenue"},
    ),
    (
        "orders",
        "Orders counts completed customer orders for the selected region and reporting period.",
        {"metric": "orders"},
    ),
    (
        "target",
        "Target is the planned revenue benchmark used to compare actual regional performance.",
        {"metric": "target"},
    ),
]


def seed_sqlite() -> int:
    with sqlite3.connect(DB_PATH) as connection:
        connection.execute("DROP TABLE IF EXISTS kpis")
        connection.execute(
            """
            CREATE TABLE kpis (
                region TEXT NOT NULL,
                month TEXT NOT NULL,
                revenue REAL NOT NULL,
                orders INTEGER NOT NULL,
                target REAL NOT NULL,
                PRIMARY KEY (region, month)
            )
            """
        )
        connection.executemany(
            "INSERT INTO kpis(region, month, revenue, orders, target) VALUES (?, ?, ?, ?, ?)",
            KPI_ROWS,
        )
    return len(KPI_ROWS)


def seed_chroma() -> int:
    client = chromadb.PersistentClient(path=CHROMA_PATH)
    collection = client.get_or_create_collection(
        name=COLLECTION_NAME,
        embedding_function=None,
    )
    collection.upsert(
        ids=[item[0] for item in GLOSSARY],
        documents=[item[1] for item in GLOSSARY],
        metadatas=[item[2] for item in GLOSSARY],
        embeddings=[embed_text(item[1]) for item in GLOSSARY],
    )
    return collection.count()


if __name__ == "__main__":
    sql_count = seed_sqlite()
    glossary_count = seed_chroma()
    print(f"Seeded {sql_count} KPI rows and {glossary_count} glossary entries.")
Add the SQL and retrieval tools

The agent needs one tool for structured facts plus one tool for business definitions. Both tools return plain dictionaries that Ollama can place back into its conversation.

  • Switch back to agent.py in the editor.
  • Add the KPI query tool below embed_text() by pasting this code:
def query_kpis(metric: str, region: str) -> dict:
    if metric not in ALLOWED_METRICS:
        raise ValueError(f"Unsupported metric: {metric}")
    if region == "All":
        sql = f"SELECT month, {metric} FROM kpis ORDER BY month"
        parameters = ()
    else:
        sql = f"SELECT month, {metric} FROM kpis WHERE region = ? ORDER BY month"
        parameters = (region,)
    with sqlite3.connect(DB_PATH) as connection:
        records = connection.execute(sql, parameters).fetchall()
    rows = [{"month": month, metric: value} for month, value in records]
    return {
        "region": region,
        "metric": metric,
        "rows": rows,
        "total": round(sum(float(row[metric]) for row in rows), 2),
    }

How Does the SQL Tool Work?

  • The metric allowlist protects the dynamic column name before the query is built.
  • A named region becomes a parameter supplied separately from the SQL text.
  • The temporary All path reads every matching row so you can test the first end-to-end agent.
  • Add the glossary search tool below query_kpis() in agent.py by pasting this code:
def search_glossary(query: str) -> dict:
    client = chromadb.PersistentClient(path=CHROMA_PATH)
    collection = client.get_collection(
        name=COLLECTION_NAME,
        embedding_function=None,
    )
    results = collection.query(
        query_embeddings=[embed_text(query)],
        n_results=2,
        include=["documents", "metadatas", "distances"],
    )
    documents = (results.get("documents") or [[]])[0]
    metadatas = (results.get("metadatas") or [[]])[0]
    distances = (results.get("distances") or [[]])[0]
    hits = []
    for index, document in enumerate(documents):
        hits.append(
            {
                "document": document,
                "metadata": metadatas[index] if index < len(metadatas) else None,
                "distance": distances[index] if index < len(distances) else None,
            }
        )
    return {"query": query, "hits": hits}

How Does Retrieval Work?

  • The function reloads the persisted ops_glossary collection from disk.
  • The question receives an embedding from the same helper used during seeding.
  • The result combines each matching document with its metadata plus vector distance.
  • Save agent.py.
  • Check that the new functions import successfully by running the seeder again:
python seed.py

Why Run the Seeder Again?

The seeder imports agent.py before it writes either data source. Reaching the final count confirms that Python parsed both new tool functions.

You should see Seeded 6 KPI rows and 3 glossary entries. again. The repeatable counts show that both seed operations can be rerun safely.

Seeder Stopped After the Tool Edits?

Check the indentation inside query_kpis() plus search_glossary(). Each function body must remain indented beneath its definition.

Compare the closing brackets around the hits.append() dictionary. Help me find the syntax problem in my new agent.py tool functions.

Ollama also needs machine-readable descriptions of the functions it may request. These schemas tell the model which tool names exist plus which arguments each tool accepts.

  • Add the tool schemas below search_glossary() in agent.py by pasting this code:
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "query_kpis",
            "description": "Read monthly KPI values from SQLite. Use for every numeric KPI question.",
            "parameters": {
                "type": "object",
                "required": ["metric"],
                "properties": {
                    "metric": {"type": "string", "enum": ["revenue", "orders", "target"]}
                },
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "search_glossary",
            "description": "Retrieve KPI definitions and business context from Chroma.",
            "parameters": {
                "type": "object",
                "required": ["query"],
                "properties": {"query": {"type": "string"}},
            },
        },
    },
]

What Do the Tool Schemas Control?

  • Each function name must match the Python function that the loop can execute.
  • The required arrays tell the model which arguments every call must include.
  • The metric enum restricts model-selected KPI names to the same allowlist used by Python.
  • Add the local chat request function below TOOLS in agent.py by pasting this code:
def ollama_chat(messages: list[dict]) -> dict:
    payload = json.dumps(
        {
            "model": MODEL,
            "messages": messages,
            "tools": TOOLS,
            "stream": False,
            "think": False,
        }
    ).encode("utf-8")
    request = Request(
        OLLAMA_URL,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    with urlopen(request, timeout=180) as response:
        return json.loads(response.read().decode("utf-8"))

What Does the Chat Request Send?

  • The payload supplies the local model with conversation messages plus both function schemas.
  • The disabled stream returns one complete response for each tool-loop round.
  • The response body is decoded from JSON into a Python dictionary.
  • Save agent.py.
  • Confirm the schemas plus request function parse successfully by running the seeder again:
python seed.py

What Does This Check Prove?

A successful import means Python can parse the schemas plus ollama_chat(). The familiar seed counts also confirm that the shared paths still work.

You should see the same six-row plus three-entry confirmation. Your existing local data remains ready for the agent loop.

Import Failing After the Schemas?

Check that TOOLS starts with one opening square bracket. Confirm that it ends with one matching closing square bracket.

Make sure ollama_chat() starts after the complete schema list. Help me compare the brackets in my TOOLS schema.

A single tool call may supply only part of the answer. The loop gives the model up to four rounds to request data plus read each tool result before producing its final response.

  • Add the four-round agent loop below ollama_chat() in agent.py by pasting this code:
def run_agent(question: str, region: str) -> dict:
    messages = [
        {"role": "system", "content": ("You are Ops Insight Agent in a multi-turn tool loop. " "Use query_kpis for every numeric KPI claim and search_glossary for definitions. " "Never invent business data. " f"The caller requested {region} data.")},
        {"role": "user", "content": question},
    ]
    tools_used: list[str] = []

    for _ in range(4):
        response = ollama_chat(messages)
        message = response["message"]
        messages.append(message)
        tool_calls = message.get("tool_calls") or []
        if not tool_calls:
            return {"answer": message.get("content") or "The agent completed the requested tools.", "region": region, "tools_used": tools_used}
        for call in tool_calls:
            function = call["function"]
            name = function["name"]
            arguments = function.get("arguments", {})
            tools_used.append(name)
            try:
                if name == "query_kpis":
                    result = query_kpis(arguments["metric"], region)
                elif name == "search_glossary":
                    result = search_glossary(arguments["query"])
                else:
                    result = {"error": f"Unknown tool: {name}"}
            except Exception as error:
                result = {"error": str(error)}
            messages.append({"role": "tool", "tool_name": name, "content": json.dumps(result)})
    return {"answer": "The agent stopped after four tool rounds.", "region": region, "tools_used": tools_used}

How Does the Agent Loop Work?

  • The system message tells the model to ground numeric claims plus definitions in tools.
  • Each requested function runs in Python with the caller's selected region.
  • Every tool result returns to the conversation with the tool role.
  • The loop returns once the model sends an answer without another tool call.
  • Add the command-line entry point below run_agent() in agent.py by pasting this code:
if __name__ == "__main__":
    selected_region = sys.argv[1] if len(sys.argv) > 1 else "East"
    selected_question = " ".join(sys.argv[2:]) or "What is total revenue and how is it defined?"
    print(json.dumps(run_agent(selected_question, selected_region), indent=2))

What Does the Entry Point Accept?

The first command-line value becomes the requested region. Every remaining value becomes one natural-language question.

The final dictionary is printed as formatted JSON. This exposes the answer plus the exact tool names used.

  • Save agent.py.

✔️ Awesome, I've got everything!

Your agent now has two callable tools plus a four-round local model loop. Double-check that you saved agent.py.

ⓧ I'd like to double check the full code

from __future__ import annotations

import hashlib
import json
import math
import re
import sqlite3
import sys
from pathlib import Path
from urllib.request import Request, urlopen

import chromadb

BASE_DIR = Path(__file__).resolve().parent
DB_PATH = BASE_DIR / "ops_data.db"
CHROMA_PATH = str(BASE_DIR / "chroma_data")
COLLECTION_NAME = "ops_glossary"
OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "qwen3:4b"
ALLOWED_METRICS = {"revenue", "orders", "target"}


def embed_text(text: str, dimensions: int = 32) -> list[float]:
    vector = [0.0] * dimensions
    for token in re.findall(r"[a-z0-9]+", text.lower()):
        digest = hashlib.sha256(token.encode("utf-8")).digest()
        index = int.from_bytes(digest[:2], "big") % dimensions
        sign = 1.0 if digest[2] % 2 == 0 else -1.0
        vector[index] += sign
    magnitude = math.sqrt(sum(value * value for value in vector)) or 1.0
    return [value / magnitude for value in vector]


def query_kpis(metric: str, region: str) -> dict:
    if metric not in ALLOWED_METRICS:
        raise ValueError(f"Unsupported metric: {metric}")
    if region == "All":
        sql = f"SELECT month, {metric} FROM kpis ORDER BY month"
        parameters = ()
    else:
        sql = f"SELECT month, {metric} FROM kpis WHERE region = ? ORDER BY month"
        parameters = (region,)
    with sqlite3.connect(DB_PATH) as connection:
        records = connection.execute(sql, parameters).fetchall()
    rows = [{"month": month, metric: value} for month, value in records]
    return {
        "region": region,
        "metric": metric,
        "rows": rows,
        "total": round(sum(float(row[metric]) for row in rows), 2),
    }


def search_glossary(query: str) -> dict:
    client = chromadb.PersistentClient(path=CHROMA_PATH)
    collection = client.get_collection(
        name=COLLECTION_NAME,
        embedding_function=None,
    )
    results = collection.query(
        query_embeddings=[embed_text(query)],
        n_results=2,
        include=["documents", "metadatas", "distances"],
    )
    documents = (results.get("documents") or [[]])[0]
    metadatas = (results.get("metadatas") or [[]])[0]
    distances = (results.get("distances") or [[]])[0]
    hits = []
    for index, document in enumerate(documents):
        hits.append(
            {
                "document": document,
                "metadata": metadatas[index] if index < len(metadatas) else None,
                "distance": distances[index] if index < len(distances) else None,
            }
        )
    return {"query": query, "hits": hits}


TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "query_kpis",
            "description": "Read monthly KPI values from SQLite. Use for every numeric KPI question.",
            "parameters": {
                "type": "object",
                "required": ["metric"],
                "properties": {
                    "metric": {"type": "string", "enum": ["revenue", "orders", "target"]}
                },
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "search_glossary",
            "description": "Retrieve KPI definitions and business context from Chroma.",
            "parameters": {
                "type": "object",
                "required": ["query"],
                "properties": {"query": {"type": "string"}},
            },
        },
    },
]


def ollama_chat(messages: list[dict]) -> dict:
    payload = json.dumps(
        {
            "model": MODEL,
            "messages": messages,
            "tools": TOOLS,
            "stream": False,
            "think": False,
        }
    ).encode("utf-8")
    request = Request(
        OLLAMA_URL,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    with urlopen(request, timeout=180) as response:
        return json.loads(response.read().decode("utf-8"))


def run_agent(question: str, region: str) -> dict:
    messages = [
        {"role": "system", "content": ("You are Ops Insight Agent in a multi-turn tool loop. " "Use query_kpis for every numeric KPI claim and search_glossary for definitions. " "Never invent business data. " f"The caller requested {region} data.")},
        {"role": "user", "content": question},
    ]
    tools_used: list[str] = []

    for _ in range(4):
        response = ollama_chat(messages)
        message = response["message"]
        messages.append(message)
        tool_calls = message.get("tool_calls") or []
        if not tool_calls:
            return {"answer": message.get("content") or "The agent completed the requested tools.", "region": region, "tools_used": tools_used}
        for call in tool_calls:
            function = call["function"]
            name = function["name"]
            arguments = function.get("arguments", {})
            tools_used.append(name)
            try:
                if name == "query_kpis":
                    result = query_kpis(arguments["metric"], region)
                elif name == "search_glossary":
                    result = search_glossary(arguments["query"])
                else:
                    result = {"error": f"Unknown tool: {name}"}
            except Exception as error:
                result = {"error": str(error)}
            messages.append({"role": "tool", "tool_name": name, "content": json.dumps(result)})
    return {"answer": "The agent stopped after four tool rounds.", "region": region, "tools_used": tools_used}


if __name__ == "__main__":
    selected_region = sys.argv[1] if len(sys.argv) > 1 else "East"
    selected_question = " ".join(sys.argv[2:]) or "What is total revenue and how is it defined?"
    print(json.dumps(run_agent(selected_question, selected_region), indent=2))
Run the grounded agent

The first end-to-end request asks for a numeric total plus a business definition. That combination gives the model a reason to call both tools in one conversation.

Before you run it, which regional rows do you think the temporary All scope lets the SQL tool read?

  • Run the combined KPI plus definition question from the activated .venv terminal with this command:
python agent.py All "What is total revenue and how is it defined?"

What Does This Command Test?

  • The first argument selects the temporary All scope.
  • The question requires query_kpis for the revenue total.
  • The definition request requires search_glossary for supporting context.

The first local inference can take longer while Ollama loads qwen3:4b into memory. The terminal prints formatted output when the tool loop completes.

You should see query_kpis plus search_glossary in tools_used. The answer should ground the revenue explanation in the seeded data plus glossary.

The Visible Win Exposes a Data Leak

The tools worked, but the temporary All branch combined the three East rows with the three West rows. The revenue total covers both regions.

This shortfall is intentional. The next step moves the region boundary ahead of tool execution so an authorized caller receives only its own rows.

Agent Not Using Both Tools?

Confirm Ollama is still running with the downloaded qwen3:4b model. Check that TOOLS contains both function names exactly.

Make sure ops_data.db plus chroma_data remain beside agent.py. Help me diagnose why my local agent did not call both tools.

Your local agent can now choose between structured KPI analysis plus glossary retrieval. Next, you will close the exposed regional data gap before any tool result reaches the model.

Stop the Region Data Leak

Your local agent now grounds KPI numbers in SQLite data. It also retrieves definitions from the glossary.

The company-wide result exposed the next problem. Authorization must restrict the rows before any tool result reaches the model.

In this step, get ready to:
  • Restrict the agent to East or West data.
  • Expose the governed agent through a guarded local API.
  • Prove that authorized regions work while North receives HTTP 403.
Enforce the region inside the agent

A region check at the model layer would only be a suggestion. The Python tool needs to validate the region before a parameterized SQL query reads protected rows.

  • Select agent.py in the Visual Studio Code Explorer sidebar.
  • Find the existing MODEL declaration.
  • Replace that declaration with the model and allow-list constants below:
MODEL = "qwen3:4b"
ALLOWED_REGIONS = {"East", "West"}
ALLOWED_METRICS = {"revenue", "orders", "target"}

What do these constants control?

  • The MODEL value keeps the agent connected to the local qwen3:4b model.
  • The region allow list limits callers to the two regions stored in ops_data.db.
  • The metric allow list prevents a requested metric from becoming an unchecked SQL identifier.
  • Add the region validator below embed_text() by pasting this function:
def validate_region(region: str) -> str:
    normalized = region.title()
    if normalized not in ALLOWED_REGIONS:
        raise ValueError("Region must be East or West.")
    return normalized

What does this function do?

  • The title() call normalizes common capitalization differences.
  • The membership check rejects every region outside the allow list.
  • The function returns the approved spelling that the SQL query uses.
  • Find the existing query_kpis() function.
  • Replace the complete function with this region-scoped version:
def query_kpis(metric: str, region: str) -> dict:
    if metric not in ALLOWED_METRICS:
        raise ValueError(f"Unsupported metric: {metric}")
    region = validate_region(region)
    sql = f"SELECT month, {metric} FROM kpis WHERE region = ? ORDER BY month"
    with sqlite3.connect(DB_PATH) as connection:
        records = connection.execute(sql, (region,)).fetchall()
    rows = [{"month": month, metric: value} for month, value in records]
    return {
        "region": region,
        "metric": metric,
        "rows": rows,
        "total": round(sum(float(row[metric]) for row in rows), 2),
    }

How does the query protect the rows?

  • The function validates the metric before placing its name in the query.
  • The WHERE region = ? clause makes the region a required filter.
  • The tuple (region,) sends the authorized value to SQLite as a parameter.
  • The returned total can only include rows from the validated region.
  • Find the first line inside run_agent().
  • Add this validation line directly below the function signature:
    region = validate_region(region)

Why validate here too?

This check rejects an unauthorized caller before the agent contacts the model. The SQL tool repeats the check as a second boundary around the protected data.

  • Find the system message inside run_agent().
  • Add this region-specific sentence at the end of its existing content tuple:
                f"The caller is authorized only for {region}. Do not request or disclose another region."

Why tell the model about the boundary?

The system message gives the model the context it needs to answer clearly. Python still enforces the boundary even if the model requests something outside it.

  • Find the query_kpis branch inside the tool-call loop.
  • Replace its existing call with this region-aware line:
                    result = query_kpis(arguments["metric"], region)

What changes in the tool loop?

The model supplies only the metric. The agent injects the already validated region into every KPI query.

  • Save agent.py.

Before you rerun the old company-wide request, predict whether All can still reach the tool loop.

  • Repeat the earlier all-region request in the activated Visual Studio Code terminal by running:
python agent.py All "What is total revenue and how is it defined?"

What does this check prove?

This repeats the request that previously combined East and West values. A rejection now proves authorization runs before the model or SQL tool can return company-wide data.

You should see the request stop with Region must be East or West. The former All path is closed.

Still getting a company-wide answer?

Confirm that run_agent() calls validate_region() before it builds the message list. Check that you saved agent.py before rerunning the command.

Verify that the temporary All branch has been removed from query_kpis(). Help me find why agent.py still accepts the All region.

✔️ The All request is rejected

Good. Your agent now closes the company-wide path before protected rows reach the model.

ⓧ I'd like to double check the full code

from __future__ import annotations

import hashlib
import json
import math
import re
import sqlite3
import sys
from pathlib import Path
from urllib.request import Request, urlopen

import chromadb

BASE_DIR = Path(__file__).resolve().parent
DB_PATH = BASE_DIR / "ops_data.db"
CHROMA_PATH = str(BASE_DIR / "chroma_data")
COLLECTION_NAME = "ops_glossary"
OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "qwen3:4b"
ALLOWED_REGIONS = {"East", "West"}
ALLOWED_METRICS = {"revenue", "orders", "target"}


def embed_text(text: str, dimensions: int = 32) -> list[float]:
    vector = [0.0] * dimensions
    for token in re.findall(r"[a-z0-9]+", text.lower()):
        digest = hashlib.sha256(token.encode("utf-8")).digest()
        index = int.from_bytes(digest[:2], "big") % dimensions
        sign = 1.0 if digest[2] % 2 == 0 else -1.0
        vector[index] += sign
    magnitude = math.sqrt(sum(value * value for value in vector)) or 1.0
    return [value / magnitude for value in vector]


def validate_region(region: str) -> str:
    normalized = region.title()
    if normalized not in ALLOWED_REGIONS:
        raise ValueError("Region must be East or West.")
    return normalized


def query_kpis(metric: str, region: str) -> dict:
    if metric not in ALLOWED_METRICS:
        raise ValueError(f"Unsupported metric: {metric}")
    region = validate_region(region)
    sql = f"SELECT month, {metric} FROM kpis WHERE region = ? ORDER BY month"
    with sqlite3.connect(DB_PATH) as connection:
        records = connection.execute(sql, (region,)).fetchall()
    rows = [{"month": month, metric: value} for month, value in records]
    return {
        "region": region,
        "metric": metric,
        "rows": rows,
        "total": round(sum(float(row[metric]) for row in rows), 2),
    }


def search_glossary(query: str) -> dict:
    client = chromadb.PersistentClient(path=CHROMA_PATH)
    collection = client.get_collection(
        name=COLLECTION_NAME,
        embedding_function=None,
    )
    results = collection.query(
        query_embeddings=[embed_text(query)],
        n_results=2,
        include=["documents", "metadatas", "distances"],
    )
    documents = (results.get("documents") or [[]])[0]
    metadatas = (results.get("metadatas") or [[]])[0]
    distances = (results.get("distances") or [[]])[0]
    hits = []
    for index, document in enumerate(documents):
        hits.append(
            {
                "document": document,
                "metadata": metadatas[index] if index < len(metadatas) else None,
                "distance": distances[index] if index < len(distances) else None,
            }
        )
    return {"query": query, "hits": hits}


TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "query_kpis",
            "description": "Read authorized monthly KPI values from SQLite. Use for every numeric KPI question.",
            "parameters": {
                "type": "object",
                "required": ["metric"],
                "properties": {
                    "metric": {
                        "type": "string",
                        "enum": ["revenue", "orders", "target"],
                    }
                },
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "search_glossary",
            "description": "Retrieve KPI definitions and business context from Chroma.",
            "parameters": {
                "type": "object",
                "required": ["query"],
                "properties": {"query": {"type": "string"}},
            },
        },
    },
]


def ollama_chat(messages: list[dict]) -> dict:
    payload = json.dumps(
        {
            "model": MODEL,
            "messages": messages,
            "tools": TOOLS,
            "stream": False,
            "think": False,
        }
    ).encode("utf-8")
    request = Request(
        OLLAMA_URL,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    with urlopen(request, timeout=180) as response:
        return json.loads(response.read().decode("utf-8"))


def run_agent(question: str, region: str) -> dict:
    region = validate_region(region)
    messages = [
        {
            "role": "system",
            "content": (
                "You are Ops Insight Agent in a multi-turn tool loop. "
                "Use query_kpis for every numeric KPI claim, search_glossary for definitions, "
                "Never invent business data. "
                f"The caller is authorized only for {region}. Do not request or disclose another region."
            ),
        },
        {"role": "user", "content": question},
    ]
    tools_used: list[str] = []

    for _ in range(4):
        response = ollama_chat(messages)
        message = response["message"]
        messages.append(message)
        tool_calls = message.get("tool_calls") or []
        if not tool_calls:
            return {
                "answer": message.get("content") or "The agent completed the requested tools.",
                "region": region,
                "tools_used": tools_used,
            }

        for call in tool_calls:
            function = call["function"]
            name = function["name"]
            arguments = function.get("arguments", {})
            tools_used.append(name)
            try:
                if name == "query_kpis":
                    result = query_kpis(arguments["metric"], region)
                elif name == "search_glossary":
                    result = search_glossary(arguments["query"])
                else:
                    result = {"error": f"Unknown tool: {name}"}
            except Exception as error:
                result = {"error": str(error)}
            messages.append(
                {
                    "role": "tool",
                    "tool_name": name,
                    "content": json.dumps(result),
                }
            )

    return {
        "answer": "The agent stopped after four tool rounds.",
        "region": region,
        "tools_used": tools_used,
    }


if __name__ == "__main__":
    selected_region = sys.argv[1] if len(sys.argv) > 1 else "East"
    selected_question = " ".join(sys.argv[2:]) or "What is total revenue and how is it defined?"
    print(json.dumps(run_agent(selected_question, selected_region), indent=2))
Create the guarded API

The agent now protects its data tool. A FastAPI endpoint adds the same decision at the request boundary before it calls run_agent().

  • Click the New File icon in the Visual Studio Code Explorer toolbar.
  • Enter main.py as the file name.
  • Add the imports, application, request model, and authorization function by pasting this code into main.py:
from typing import Annotated

from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel

from agent import run_agent

app = FastAPI(title="Ops Insight Agent")


class AskRequest(BaseModel):
    question: str


def authorized_region(x_region: str) -> str:
    region = x_region.title()
    if region not in {"East", "West"}:
        raise HTTPException(status_code=403, detail="Region is not authorized")
    return region

What does this API foundation do?

  • The AskRequest model requires a question in the JSON request body.
  • The Header() declaration lets FastAPI read a request header.
  • The authorized_region() function permits East or West.
  • An unauthorized value raises an HTTP 403 response before the agent runs.
  • Add the POST /ask path below authorized_region() by pasting this code:
@app.post("/ask")
def ask(
    payload: AskRequest,
    x_region: Annotated[str, Header()],
) -> dict:
    return run_agent(payload.question, authorized_region(x_region))

How does the path apply the guard?

  • FastAPI maps the Python name x_region to the HTTP header x-region.
  • The endpoint validates that header before passing the region to run_agent().
  • The request reaches the agent only after the region passes both API and agent checks.
  • Save main.py.
  • Confirm main.py appears beside agent.py in the Explorer sidebar.

Seeing import or syntax warnings?

Confirm that the integrated terminal still shows the activated .venv environment. Check that main.py sits in the same ops-insight-agent folder as agent.py.

Compare the indentation inside authorized_region() with the code above. Help me diagnose the warnings in my guarded FastAPI main.py file.

✔️ The guarded API file is ready

Great. Double-check that both agent.py and main.py are saved.

ⓧ I'd like to double check the full code

from typing import Annotated

from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel

from agent import run_agent

app = FastAPI(title="Ops Insight Agent")


class AskRequest(BaseModel):
    question: str


def authorized_region(x_region: str) -> str:
    region = x_region.title()
    if region not in {"East", "West"}:
        raise HTTPException(status_code=403, detail="Region is not authorized")
    return region


@app.post("/ask")
def ask(
    payload: AskRequest,
    x_region: Annotated[str, Header()],
) -> dict:
    return run_agent(payload.question, authorized_region(x_region))
Test authorized and denied requests

The interactive API documentation can send the same question with different headers. This makes the authorization boundary visible without building a separate client.

  • Start the FastAPI development server from the activated Visual Studio Code terminal by running:
fastapi dev main.py

What does this command do?

The command loads main.py in development mode. It serves the API locally at http://127.0.0.1:8000.

The same process provides interactive documentation at http://127.0.0.1:8000/docs.

You should see the development server start successfully. Keep this terminal process running while you test the endpoint.

Development server not starting?

Confirm that main.py is saved inside ops-insight-agent. Confirm that the terminal still shows the activated .venv environment.

Check the first reported file and line for an indentation mistake. Help me troubleshoot why fastapi dev main.py is not starting.

  • Press Cmd+Space to open macOS search.
  • Type Safari.
  • Press Enter to open Safari.
  • Enter http://127.0.0.1:8000/docs in the address bar.
  • Select the POST /ask path.
  • Click Try it out.
  • Paste this question into the request body editor:
{
  "question": "What is total revenue and how is it defined?"
}

What does this request ask for?

The numeric part should trigger query_kpis. The definition part should trigger search_glossary.

The x-region header determines which KPI rows the SQL tool can read.

Before you send the first request, predict whether the East total will include any West values.

  • Enter East in the x-region field.
  • Click Execute.

You should receive an East response with a total revenue of 380000. The tools_used list should name query_kpis and search_glossary.

  • Change the x-region value to West.
  • Click Execute again.

You should receive a West response with a total revenue of 313000. The different total proves the SQL query reads only the authorized regional rows.

Before the final request, predict whether North reaches the agent or stops at the API guard.

  • Change the x-region value to North.
  • Click Execute.

You should receive HTTP 403 with Region is not authorized. The request stops before Ollama or SQLite receives it.

Where is the security boundary?

The x-region header is a teaching guard for this local project. Production authorization should derive region claims from a verified identity token or server-side session.

The parameterized SQL filter remains essential because it protects the rows at the data access point.

Getting the wrong regional result?

Confirm that query_kpis() contains WHERE region = ?. Confirm that run_agent() passes its validated region value into the tool.

If North succeeds, verify that authorized_region() raises HTTPException for values outside East and West. Help me diagnose why my regional API guard is returning the wrong result.

That is the data leak closed. Next, you will turn the governed answer into an analyst report with a visible regional chart.

Return an Analyst Report with a Chart

Your governed FastAPI endpoint now keeps each caller inside the authorized regional boundary. East callers receive East rows while West callers receive West rows.

A JSON response helps developers inspect the result. An operational stakeholder needs a readable explanation with a visible SVG trend.

In this step, get ready to:
  • Add a chart tool that reads authorized KPI rows.
  • Render the agent result as an analyst report.
  • Generate an East-only report with an inline revenue chart.
Add the governed chart tool

The chart tool must reuse the guarded data path. Calling query_kpis() keeps the parameterized SQL boundary in charge of every chart row.

  • Add the chart calculations below search_glossary() in agent.py by pasting this code:
def build_chart(metric: str, region: str) -> dict:
    data = query_kpis(metric, region)
    values = [float(row[metric]) for row in data["rows"]]
    maximum = max(values) if values else 1.0
    width = 600
    height = 300
    baseline = 230
    plot_height = 180
    bars = []
    for index, row in enumerate(data["rows"]):
        value = float(row[metric])
        bar_height = (value / maximum) * plot_height
        x = 85 + index * 155
        y = baseline - bar_height
        bars.append(
            f'<rect x="{x}" y="{y:.1f}" width="90" height="{bar_height:.1f}" fill="#2563eb" rx="6" />'
        )
        bars.append(
            f'<text x="{x + 45}" y="{baseline + 22}" text-anchor="middle" font-size="14">{row["month"]}</text>'
        )
        bars.append(
            f'<text x="{x + 45}" y="{max(20, y - 8):.1f}" text-anchor="middle" font-size="13">{value:,.0f}</text>'
        )

How does the chart stay governed?

  • The call to query_kpis() retrieves rows through the existing authorized-region filter.
  • The height calculation scales every bar against the largest authorized monthly value.
  • The loop creates each bar with its month label and numeric value.
  • Complete build_chart() by adding this code directly below the previous chunk:
    svg = (
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img" '
        f'aria-label="{region} {metric} chart">'
        f'<rect width="100%" height="100%" fill="#f8fafc" rx="12" />'
        f'<text x="30" y="32" font-size="20" font-weight="700">{region} {metric.title()}</text>'
        f'<line x1="55" y1="{baseline}" x2="555" y2="{baseline}" stroke="#475569" />'
        + "".join(bars)
        + "</svg>"
    )
    return {
        "region": region,
        "metric": metric,
        "message": "Chart created from authorized KPI rows.",
        "svg": svg,
    }

What does the completed function return?

  • The svg string combines the trusted chart elements into one inline graphic.
  • The returned region records which authorization boundary produced the chart.
  • The returned metric identifies the KPI shown in the bars.
  • Save agent.py.
  • Switch back to the FastAPI development server terminal from earlier.

You should see reload activity without a syntax error. This proves the running service can import the new chart function.

Server not reloading?

Confirm that agent.py is saved inside ops-insight-agent. Check that every line after def build_chart uses consistent indentation.

Check that the FastAPI development server is still running in its earlier terminal. Help me diagnose why FastAPI cannot reload after I added build_chart to agent.py.

The local Ollama model can request a function only when its tool schema describes that function. The system message also needs to tell the model when a chart is appropriate.

  • Insert the build_chart schema before the closing bracket of TOOLS in agent.py by pasting this code:
    {
        "type": "function",
        "function": {
            "name": "build_chart",
            "description": "Create an SVG chart from authorized monthly KPI values when the user asks for a chart or visualization.",
            "parameters": {
                "type": "object",
                "required": ["metric"],
                "properties": {
                    "metric": {
                        "type": "string",
                        "enum": ["revenue", "orders", "target"],
                    }
                },
            },
        },
    },

What does this tool schema do?

  • The schema exposes build_chart as a callable function.
  • The description connects chart requests to the new tool.
  • The metric enumeration limits requests to supported KPI names.
  • Replace the system message content inside run_agent() with this updated content:
            "content": (
                "You are Ops Insight Agent in a multi-turn tool loop. "
                "Use query_kpis for every numeric KPI claim, search_glossary for definitions, "
                "and build_chart when the user requests a chart. Never invent business data. "
                f"The caller is authorized only for {region}. Do not request or disclose another region."
            ),

Why update the system message?

The message directs chart requests toward build_chart. The existing authorization sentence keeps the selected region visible throughout the tool loop.

  • Save agent.py.
  • Return to the FastAPI development server terminal.

You should see another clean reload. This confirms that the new schema and system message have valid Python syntax.

The agent loop needs to retain the generated SVG after the chart tool finishes. Every completion path must include that stored chart in its result.

  • Replace the section from tools_used through the first completed return inside run_agent() with this code:
    tools_used: list[str] = []
    chart_svg: str | None = None

    for _ in range(4):
        response = ollama_chat(messages)
        message = response["message"]
        messages.append(message)
        tool_calls = message.get("tool_calls") or []
        if not tool_calls:
            return {
                "answer": message.get("content") or "The agent completed the requested tools.",
                "region": region,
                "tools_used": tools_used,
                "chart_svg": chart_svg,
            }

How is the chart carried through the loop?

  • The chart_svg variable starts empty because some questions do not request a chart.
  • The completed result returns the stored chart with the answer and tool history.
  • Save agent.py.
  • Return to the FastAPI development server terminal.

The development server should reload without a syntax error. This confirms that every normal completion now includes chart_svg.

  • Replace the tool dispatch section inside run_agent() with this code:
            try:
                if name == "query_kpis":
                    result = query_kpis(arguments["metric"], region)
                elif name == "search_glossary":
                    result = search_glossary(arguments["query"])
                elif name == "build_chart":
                    result = build_chart(arguments["metric"], region)
                    chart_svg = result["svg"]
                    result = {key: value for key, value in result.items() if key != "svg"}
                else:
                    result = {"error": f"Unknown tool: {name}"}
            except Exception as error:
                result = {"error": str(error)}

How does the agent execute the chart tool?

  • The new branch passes the validated region into build_chart().
  • The generated SVG is stored for the final report.
  • The tool result sent back to the model omits the long SVG string.
  • Replace the final return block in run_agent() with this code:
    return {
        "answer": "The agent stopped after four tool rounds.",
        "region": region,
        "tools_used": tools_used,
        "chart_svg": chart_svg,
    }

Why update the final return?

The fallback now preserves a chart created before the four-round limit. Every exit from run_agent() returns the same result shape.

  • Save agent.py.
  • Return to the FastAPI development server terminal.

The server should reload without a syntax error. This confirms that the running agent recognizes the chart tool.

Chart tool causing a reload error?

Check that the schema name and dispatch name are both build_chart. Confirm that chart_svg is declared before the tool loop.

Check that the final return remains inside run_agent(). Help me compare my chart-tool changes with the final agent.py structure.

✔️ Awesome, I've got everything!

Great. Double-check that you saved agent.py before moving to the report renderer.

ⓧ I'd like to double check the full code

from __future__ import annotations

import hashlib
import json
import math
import re
import sqlite3
import sys
from pathlib import Path
from urllib.request import Request, urlopen

import chromadb

BASE_DIR = Path(__file__).resolve().parent
DB_PATH = BASE_DIR / "ops_data.db"
CHROMA_PATH = str(BASE_DIR / "chroma_data")
COLLECTION_NAME = "ops_glossary"
OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "qwen3:4b"
ALLOWED_REGIONS = {"East", "West"}
ALLOWED_METRICS = {"revenue", "orders", "target"}


def embed_text(text: str, dimensions: int = 32) -> list[float]:
    vector = [0.0] * dimensions
    for token in re.findall(r"[a-z0-9]+", text.lower()):
        digest = hashlib.sha256(token.encode("utf-8")).digest()
        index = int.from_bytes(digest[:2], "big") % dimensions
        sign = 1.0 if digest[2] % 2 == 0 else -1.0
        vector[index] += sign
    magnitude = math.sqrt(sum(value * value for value in vector)) or 1.0
    return [value / magnitude for value in vector]


def validate_region(region: str) -> str:
    normalized = region.title()
    if normalized not in ALLOWED_REGIONS:
        raise ValueError("Region must be East or West.")
    return normalized


def query_kpis(metric: str, region: str) -> dict:
    if metric not in ALLOWED_METRICS:
        raise ValueError(f"Unsupported metric: {metric}")
    region = validate_region(region)
    sql = f"SELECT month, {metric} FROM kpis WHERE region = ? ORDER BY month"
    with sqlite3.connect(DB_PATH) as connection:
        records = connection.execute(sql, (region,)).fetchall()
    rows = [{"month": month, metric: value} for month, value in records]
    return {
        "region": region,
        "metric": metric,
        "rows": rows,
        "total": round(sum(float(row[metric]) for row in rows), 2),
    }


def search_glossary(query: str) -> dict:
    client = chromadb.PersistentClient(path=CHROMA_PATH)
    collection = client.get_collection(
        name=COLLECTION_NAME,
        embedding_function=None,
    )
    results = collection.query(
        query_embeddings=[embed_text(query)],
        n_results=2,
        include=["documents", "metadatas", "distances"],
    )
    documents = (results.get("documents") or [[]])[0]
    metadatas = (results.get("metadatas") or [[]])[0]
    distances = (results.get("distances") or [[]])[0]
    hits = []
    for index, document in enumerate(documents):
        hits.append(
            {
                "document": document,
                "metadata": metadatas[index] if index < len(metadatas) else None,
                "distance": distances[index] if index < len(distances) else None,
            }
        )
    return {"query": query, "hits": hits}


def build_chart(metric: str, region: str) -> dict:
    data = query_kpis(metric, region)
    values = [float(row[metric]) for row in data["rows"]]
    maximum = max(values) if values else 1.0
    width = 600
    height = 300
    baseline = 230
    plot_height = 180
    bars = []
    for index, row in enumerate(data["rows"]):
        value = float(row[metric])
        bar_height = (value / maximum) * plot_height
        x = 85 + index * 155
        y = baseline - bar_height
        bars.append(
            f'<rect x="{x}" y="{y:.1f}" width="90" height="{bar_height:.1f}" fill="#2563eb" rx="6" />'
        )
        bars.append(
            f'<text x="{x + 45}" y="{baseline + 22}" text-anchor="middle" font-size="14">{row["month"]}</text>'
        )
        bars.append(
            f'<text x="{x + 45}" y="{max(20, y - 8):.1f}" text-anchor="middle" font-size="13">{value:,.0f}</text>'
        )
    svg = (
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img" '
        f'aria-label="{region} {metric} chart">'
        f'<rect width="100%" height="100%" fill="#f8fafc" rx="12" />'
        f'<text x="30" y="32" font-size="20" font-weight="700">{region} {metric.title()}</text>'
        f'<line x1="55" y1="{baseline}" x2="555" y2="{baseline}" stroke="#475569" />'
        + "".join(bars)
        + "</svg>"
    )
    return {
        "region": region,
        "metric": metric,
        "message": "Chart created from authorized KPI rows.",
        "svg": svg,
    }


TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "query_kpis",
            "description": "Read authorized monthly KPI values from SQLite. Use for every numeric KPI question.",
            "parameters": {
                "type": "object",
                "required": ["metric"],
                "properties": {
                    "metric": {
                        "type": "string",
                        "enum": ["revenue", "orders", "target"],
                    }
                },
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "search_glossary",
            "description": "Retrieve KPI definitions and business context from Chroma.",
            "parameters": {
                "type": "object",
                "required": ["query"],
                "properties": {"query": {"type": "string"}},
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "build_chart",
            "description": "Create an SVG chart from authorized monthly KPI values when the user asks for a chart or visualization.",
            "parameters": {
                "type": "object",
                "required": ["metric"],
                "properties": {
                    "metric": {
                        "type": "string",
                        "enum": ["revenue", "orders", "target"],
                    }
                },
            },
        },
    },
]


def ollama_chat(messages: list[dict]) -> dict:
    payload = json.dumps(
        {
            "model": MODEL,
            "messages": messages,
            "tools": TOOLS,
            "stream": False,
            "think": False,
        }
    ).encode("utf-8")
    request = Request(
        OLLAMA_URL,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    with urlopen(request, timeout=180) as response:
        return json.loads(response.read().decode("utf-8"))


def run_agent(question: str, region: str) -> dict:
    region = validate_region(region)
    messages = [
        {
            "role": "system",
            "content": (
                "You are Ops Insight Agent in a multi-turn tool loop. "
                "Use query_kpis for every numeric KPI claim, search_glossary for definitions, "
                "and build_chart when the user requests a chart. Never invent business data. "
                f"The caller is authorized only for {region}. Do not request or disclose another region."
            ),
        },
        {"role": "user", "content": question},
    ]
    tools_used: list[str] = []
    chart_svg: str | None = None

    for _ in range(4):
        response = ollama_chat(messages)
        message = response["message"]
        messages.append(message)
        tool_calls = message.get("tool_calls") or []
        if not tool_calls:
            return {
                "answer": message.get("content") or "The agent completed the requested tools.",
                "region": region,
                "tools_used": tools_used,
                "chart_svg": chart_svg,
            }

        for call in tool_calls:
            function = call["function"]
            name = function["name"]
            arguments = function.get("arguments", {})
            tools_used.append(name)
            try:
                if name == "query_kpis":
                    result = query_kpis(arguments["metric"], region)
                elif name == "search_glossary":
                    result = search_glossary(arguments["query"])
                elif name == "build_chart":
                    result = build_chart(arguments["metric"], region)
                    chart_svg = result["svg"]
                    result = {key: value for key, value in result.items() if key != "svg"}
                else:
                    result = {"error": f"Unknown tool: {name}"}
            except Exception as error:
                result = {"error": str(error)}
            messages.append(
                {
                    "role": "tool",
                    "tool_name": name,
                    "content": json.dumps(result),
                }
            )

    return {
        "answer": "The agent stopped after four tool rounds.",
        "region": region,
        "tools_used": tools_used,
        "chart_svg": chart_svg,
    }


if __name__ == "__main__":
    selected_region = sys.argv[1] if len(sys.argv) > 1 else "East"
    selected_question = " ".join(sys.argv[2:]) or "What is total revenue and how is it defined?"
    print(json.dumps(run_agent(selected_question, selected_region), indent=2))

Compare this reference with your saved file. It contains the complete governed chart tool and updated agent loop.

Render the analyst report

The report places model-generated text inside HTML. Escaping that text keeps it separate from the trusted SVG generated by project code.

  • Replace the import section in main.py with this code:
from html import escape
from typing import Annotated

from fastapi import FastAPI, Header, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel

from agent import run_agent

What do the new imports provide?

  • The escape function converts model output into safe HTML text.
  • The HTMLResponse class identifies the report as HTML content.
  • Add render_report() directly below authorized_region() by pasting this code:
def render_report(result: dict) -> str:
    answer = escape(result["answer"])
    tools = escape(", ".join(result["tools_used"]) or "none")
    chart = result["chart_svg"] or "<p>No chart was requested.</p>"
    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Ops Insight Report</title>
  <style>
    body {{ font-family: -apple-system, BlinkMacSystemFont, sans-serif; max-width: 760px; margin: 40px auto; padding: 0 20px; color: #0f172a; }}
    .card {{ background: #ffffff; border: 1px solid #cbd5e1; border-radius: 14px; padding: 24px; box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08); }}
    .answer {{ white-space: pre-wrap; line-height: 1.6; }}
    .meta {{ color: #475569; font-size: 14px; }}
  </style>
</head>
<body>
  <div class="card">
    <h1>{escape(result['region'])} Operations Insight</h1>
    <p class="answer">{answer}</p>
    {chart}
    <p class="meta">Tools used: {tools}</p>
  </div>
</body>
</html>"""

How is the report assembled?

  • The answer passes through escape() before entering the document.
  • The tool list also passes through escape().
  • The authorized region becomes the report heading.
  • The report embeds chart_svg because trusted project code generated it.
  • Save main.py.
  • Return to the FastAPI development server terminal.

You should see a clean reload after the report renderer is added. This proves the running application can import render_report().

Renderer causing a syntax error?

Check that the opening and closing triple quotes surround the entire HTML document. Confirm that the doubled braces remain intact inside the style rules.

Check that escape and HTMLResponse appear in the import section. Help me diagnose the syntax error in my render_report function.

  • Add the report endpoint directly below the existing POST /ask endpoint by pasting this code:
@app.post("/report", response_class=HTMLResponse)
def report(
    payload: AskRequest,
    x_region: Annotated[str, Header()],
) -> str:
    result = run_agent(payload.question, authorized_region(x_region))
    return render_report(result)

How does the report endpoint stay protected?

  • The endpoint passes x_region through the existing authorized_region() guard.
  • The validated region reaches run_agent() before any chart rows are retrieved.
  • The final agent result passes into render_report().

You should see POST /report beside the existing POST /ask path. This proves the running application registered the report endpoint.

Report route not appearing?

Confirm that the report decorator begins at the left edge of main.py. Check that the function sits below the completed ask() endpoint.

Refresh the documentation after the development server finishes reloading. Help me diagnose why POST /report is missing from my FastAPI documentation.

✔️ Awesome, I've got everything!

Great. Double-check that main.py is saved before creating the report demo.

ⓧ I'd like to double check the full code

from html import escape
from typing import Annotated

from fastapi import FastAPI, Header, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel

from agent import run_agent

app = FastAPI(title="Ops Insight Agent")


class AskRequest(BaseModel):
    question: str


def authorized_region(x_region: str) -> str:
    region = x_region.title()
    if region not in {"East", "West"}:
        raise HTTPException(status_code=403, detail="Region is not authorized")
    return region


def render_report(result: dict) -> str:
    answer = escape(result["answer"])
    tools = escape(", ".join(result["tools_used"]) or "none")
    chart = result["chart_svg"] or "<p>No chart was requested.</p>"
    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Ops Insight Report</title>
  <style>
    body {{ font-family: -apple-system, BlinkMacSystemFont, sans-serif; max-width: 760px; margin: 40px auto; padding: 0 20px; color: #0f172a; }}
    .card {{ background: #ffffff; border: 1px solid #cbd5e1; border-radius: 14px; padding: 24px; box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08); }}
    .answer {{ white-space: pre-wrap; line-height: 1.6; }}
    .meta {{ color: #475569; font-size: 14px; }}
  </style>
</head>
<body>
  <div class="card">
    <h1>{escape(result['region'])} Operations Insight</h1>
    <p class="answer">{answer}</p>
    {chart}
    <p class="meta">Tools used: {tools}</p>
  </div>
</body>
</html>"""


@app.post("/ask")
def ask(
    payload: AskRequest,
    x_region: Annotated[str, Header()],
) -> dict:
    return run_agent(payload.question, authorized_region(x_region))


@app.post("/report", response_class=HTMLResponse)
def report(
    payload: AskRequest,
    x_region: Annotated[str, Header()],
) -> str:
    result = run_agent(payload.question, authorized_region(x_region))
    return render_report(result)

Compare this reference with your saved file. It contains both governed endpoints and the complete report renderer.

Generate the East analyst report

The demo turns one governed agent request into a permanent report file. Its question asks for a chart plus a total plus a glossary explanation.

  • Select the ops-insight-agent folder in the Visual Studio Code file sidebar.
  • Click the new-file icon in the file sidebar toolbar.
  • Enter demo.py as the file name.
  • Create the report demo by pasting this code into demo.py.
from pathlib import Path

from agent import run_agent
from main import render_report

question = "Create a revenue chart, tell me total revenue, and explain revenue."
result = run_agent(question, "East")
output_path = Path("east-report.html")
output_path.write_text(render_report(result), encoding="utf-8")

print(f"Tools used: {', '.join(result['tools_used'])}")
print(f"Created {output_path.resolve()}")

What does the demo do?

  • The demo submits the combined analyst question with East as the authorized region.
  • The result passes through render_report() before being written to disk.
  • The generated document is saved as east-report.html.
  • The terminal output lists the tools used and the report path.
  • Save demo.py.

✔️ Awesome, I've got everything!

Great. Double-check that demo.py is saved inside ops-insight-agent.

ⓧ I'd like to double check the full code

from pathlib import Path

from agent import run_agent
from main import render_report

question = "Create a revenue chart, tell me total revenue, and explain revenue."
result = run_agent(question, "East")
output_path = Path("east-report.html")
output_path.write_text(render_report(result), encoding="utf-8")

print(f"Tools used: {', '.join(result['tools_used'])}")
print(f"Created {output_path.resolve()}")

Compare this reference with your saved file. It contains the complete East report demo.

Before you run the demo, which three tool names do you expect Terminal to show?

  • Generate the East analyst report from the activated .venv terminal by running this command:
python demo.py

What does this command do?

The command lets the local agent complete up to four tool-call rounds. It writes the rendered result to east-report.html.

The local model may pause while it selects and executes its tools. Terminal prints the final tool history when the report is ready.

Terminal should include query_kpis and search_glossary in the tool history. These entries prove the answer used structured KPI data plus glossary context.

Terminal should also include build_chart. The next line should show the path to east-report.html.

Report not created?

Confirm that the terminal still shows the activated .venv. Check that Ollama is still running before retrying the demo.

Confirm that agent.py and main.py are saved beside demo.py. Help me diagnose why demo.py did not create east-report.html.

  • Click the Finder icon in the Dock.
  • Search for east-report.html in Finder.
  • Double-click east-report.html in the search results.

You should see a grounded explanation above three East revenue bars covering July through September 2026. The tool history appears below the chart.

That completes the reporting layer. Your governed local agent now turns authorized KPI rows into a report that an operational stakeholder can read and verify.

Secret mission

Add a Protected Audit Trail

Record the tools behind every successful agent request in a durable audit trail. You will protect the newest audit events so only an auditor request can retrieve them.

Clean Up Your Resources

Clean Up Your Resources

Choose whether your local analyst stays ready, pauses for later, or leaves your Mac. Every resource runs locally, so there are no ongoing cloud or paid API costs.

Resources you used:

  • The ops_data.db SQLite operational database with KPI rows plus durable audit_events records.
  • The chroma_data folder with the persistent ops_glossary Chroma collection.
  • The .venv virtual environment containing the pinned Python dependencies.
  • The local qwen3:4b model managed by Ollama.
  • The east-report.html analyst report containing the explanation plus the East revenue chart.

Keep everything running

No action is needed while you are actively building. Your local API remains ready for more questions or reports.

  • Leave the ops-insight-agent folder in its current Finder location.
  • Keep qwen3:4b downloaded in Ollama.
  • Leave the FastAPI development server running in the Visual Studio Code terminal.
  • Continue using the interactive documentation at http://127.0.0.1:8000/docs.

Pause - I'll come back to this later

Shut down the running processes to free memory while preserving every local file. The downloaded model remains ready for your return.

  • Switch back to the terminal panel in Visual Studio Code that is running FastAPI.
  • Stop the development server by pressing Control-C.
  • Quit Ollama.

The FastAPI documentation stops responding after the server closes. Your database, audit history, glossary, report, virtual environment, source files, and model remain on disk.

Delete - I don't want to use this again

This is the destructive option. Use it only when you no longer need the local database, audit history, glossary, report, source files, virtual environment, or downloaded model.

  • Switch back to the terminal panel in Visual Studio Code that is running FastAPI.
  • Stop the development server by pressing Control-C.
  • Remove the downloaded qwen3:4b model by running this command:
ollama rm qwen3:4b

What does this command do?

The ollama rm command deletes the downloaded data for qwen3:4b.

Ollama remains installed on your Mac.

The terminal confirms the model removal, which means its local files no longer occupy disk space.

Model removal failed?

  • Keep Ollama running until the model removal command completes.
  • Get help diagnosing the failed removal.
  • Quit Ollama.
  • Return to the Finder location where you created ops-insight-agent earlier.
  • Move the ops-insight-agent folder to Trash.

You should no longer see ops-insight-agent in its original Finder location. The project database, Chroma index, virtual environment, report, and source files are now in Trash.

Nice Work!

Nice Work!

You did it! Your governed local operations analyst now runs through Ollama with the local qwen3:4b model. FastAPI exposes its region-scoped answers through a local API.

You've learned how to:

  • Orchestrate multi-turn tool calls that select SQL analytics, Chroma retrieval, or chart generation from a plain-English request.
  • Enforce region-scoped KPI access with parameterized SQLite queries before protected rows reach the model.
  • Generate an analyst report with a grounded explanation, an East-only SVG revenue chart, and a visible tool list.
  • Secret Mission: Record a durable tool-call audit trail for successful requests. Restrict the newest 20 audit events to the auditor role.

Ready to quiz yourself?