<!--
  canonical-url: https://www.avonture.be/blog/python-ai-helper
  published:     2026-12-03
  This is a static plain-Markdown mirror generated at build time.
  Visit the canonical URL above for the fully rendered page, with images and interactive components.
-->

# Auto-documenting and testing python scripts

> A Dockerized agent that reads a Python file, writes a real docstring for it, generates a pytest file, and runs that test file immediately — all through a local Ollama model, no code leaving the machine.

---
![Auto-documenting and testing python scripts](/img/v2/python-ai-helper.webp)

**TL;DR**

`ai-agent` is a small Python program packaged as a Docker image. Point it at a folder or a single `.py` file: for each script it asks a local Ollama model for a module docstring, writes a pytest file under `tests/`, and runs it straight away. Nothing leaves your machine, files stay owned by you, and the container runs read-only. The generated test is a first draft to review, not a verdict on your code.

I have Python scripts scattered across projects with no docstring and no test — written fast, never revisited, and every time I open one months later I have to re-read the whole thing to remember what it does. Writing the docstring by hand is quick per file; writing it for the fortieth script in a project I inherited is not.

By the end of this article, one `make run` will document and test a whole folder of Python scripts, using the Ollama model already running on your machine.

**Quick Jump:** [See it in action](#what-ai-agent-does-for-you) | [Get the files and build the image](#build-the-image) | [Run it on your project](#run-it-on-your-own-project)

## What ai-agent Does For You

Here, the agent runs on a folder holding one script, `helper.py`: five file utilities, no docstring, no test.

```bash
$ make run PROJECT_PATH=/home/me/dev/demo
2026-12-04 07:54:26,633 | INFO     | AI-Agent | --- Analyzing helper.py ---
2026-12-04 07:54:27,398 | INFO     | AI-Agent | ✓ Docstring updated: helper.py
2026-12-04 07:54:30,241 | INFO     | AI-Agent | ✓ Tests PASSED for helper.py (5 passed in 0.03s)
2026-12-04 07:54:30,241 | INFO     | AI-Agent | ✓ Test generation completed: helper.py
2026-12-04 07:54:30,241 | INFO     | AI-Agent | Done. Total Execution Time: 3.61s
```

Three things happened in under four seconds. A docstring was written at the top of `helper.py` — the first three lines below are new, everything else is the original code:

**helper.py**

```python
"""
This module provides functions for reading, writing, and managing files, including reading and writing text content, getting file information, listing files by extension, and safely deleting files. It includes error handling and logging to provide feedback on operations.
"""

import logging
from pathlib import Path
from typing import Final

logger: Final = logging.getLogger(__name__)


def read_text_content(file_path: Path) -> str:
    try:
        return file_path.read_text(encoding="utf-8")
    except FileNotFoundError:
        logger.error("File not found at %s", file_path)
        raise
    except IOError as e:
        logger.error("Failed to read file %s: %s", file_path, e)
        raise


def write_text_content(file_path: Path, content: str, append: bool = False) -> None:
    try:
        file_path.parent.mkdir(parents=True, exist_ok=True)
        mode: str = "a" if append else "w"
        with file_path.open(mode=mode, encoding="utf-8") as file:
            file.write(content)
    except IOError as e:
        logger.error("Could not write to %s: %s", file_path, e)
        raise


def get_file_info(file_path: Path) -> dict[str, int | float]:
    if not file_path.is_file():
        raise FileNotFoundError(f"No file found at {file_path}")

    stats = file_path.stat()
    return {"size_bytes": stats.st_size, "modified_at": stats.st_mtime}


def list_files_by_extension(directory: Path, extension: str) -> list[Path]:
    if not directory.is_dir():
        return []

    ext: str = extension if extension.startswith(".") else f".{extension}"
    return [path for path in directory.iterdir() if path.is_file() and path.suffix == ext]


def safe_delete(file_path: Path) -> bool:
    try:
        if file_path.exists():
            file_path.unlink()
            return True
        return False
    except OSError as e:
        logger.error("Error deleting file %s: %s", file_path, e)
        return False
```

A `tests/test_helper.py` file was created next to it, one test per function, working on real files in pytest's `tmp_path` folder:

**tests/test\_helper.py**

```python

import pytest
from helper import *


@pytest.fixture
def tmp_file(tmp_path):
    file_path = tmp_path / "test.txt"
    write_text_content(file_path, "test content")
    return file_path


def test_read_text_content(tmp_file):
    content = read_text_content(tmp_file)
    assert content == "test content"


def test_write_text_content(tmp_path):
    file_path = tmp_path / "new_test.txt"
    write_text_content(file_path, "new content")
    assert read_text_content(file_path) == "new content"


def test_get_file_info(tmp_file):
    info = get_file_info(tmp_file)
    assert isinstance(info["size_bytes"], int)
    assert isinstance(info["modified_at"], float)


def test_list_files_by_extension(tmp_path):
    (tmp_path / "test.txt").touch()
    (tmp_path / "test2.txt").touch()
    (tmp_path / "test3.md").touch()
    files = list_files_by_extension(tmp_path, "txt")
    assert len(files) == 2
    assert all(file.suffix == ".txt" for file in files)


def test_safe_delete(tmp_file):
    assert safe_delete(tmp_file)
    assert not tmp_file.exists()
```

And pytest ran it: five tests, all green.

> **Read the generated test before trusting it:**
>
> A failing assertion does not necessarily mean your code is broken — the model can get an expected value wrong. A passing one does not mean much either if the test only checks that a key exists. Treat a generated test the way you'd treat a pull request from a junior colleague: read it before you rely on it.

## Why It Works

* **One container, one model call per task.** No IDE plugin, no API key, no account: the agent talks to the Ollama instance you already run, so your code never leaves the machine.
* **The docstring is inserted, not rewritten.** The source is parsed into a syntax tree and the docstring is added as the first statement — the model never gets to "improve" your functions.
* **Tests are executed, not just written.** A test file that doesn't even import is caught on the spot, while you still have the context in mind.
* **It's safe to run twice.** Files that already have a docstring or a test file are skipped unless you ask to regenerate them, so re-running on a half-processed project only costs the files still missing.
* **It can't make a mess.** The container runs with a read-only filesystem and your own user ID: whatever it writes belongs to you, and it can only write in the folder you hand it.

## Build the Image

The image is not published on Docker Hub: you build it once, locally, from the files below. You need Docker, `make`, and Ollama listening on port `11434` of your machine — I've covered [installing Ollama as a Docker container](/blog/ollama-installation) before.

Pull the model the agent uses by default (about 4.7 GB). The command assumes Ollama runs in a container named `ollama`; with a native install, just drop `docker exec -it ollama`:

```bash
$ docker exec -it ollama ollama pull qwen2.5-coder:7b
```

Then create the project. Use the **Script** button to create every file in one paste, or **ZIP** to download them:

**Project: /tmp/ai-agent**

> **Note:**
>
> Run 'make build' in the ai-agent folder to build the cavo789/ai-agent
>
> :latest
>
> &#x20;image.

**makefile**

```
# Default model
MODEL ?= qwen2.5-coder:7b

# Get current user ID and Group ID
UID := $(shell id -u)
GID := $(shell id -g)

.PHONY: build run help

help:
	@echo "Usage: make run PROJECT_PATH=/path/to/your/project"
	@echo ""
	@echo "make run PROJECT_PATH=/path/to/project       -> Run on folder"
	@echo "make run PROJECT_PATH=/path/to/file.py      -> Run on single file"
	@echo "make compose-run PROJECT_PATH=/path        -> Run using Compose (hot-reload)"

build:
	docker build --build-arg USER_ID=$(UID) --build-arg GROUP_ID=$(GID) -t cavo789/ai-agent:latest .

run:
ifndef PROJECT_PATH
	$(error PROJECT_PATH is undefined. Usage: make run PROJECT_PATH=/absolute/path/to/project)
endif
	@if [ ! -e "$(PROJECT_PATH)" ]; then \
		echo "Error: Target $(PROJECT_PATH) does not exist."; \
		exit 1; \
	fi
	@# Calculate Mount Source and Target Name for single-file support
	$(eval MOUNT_SRC=$(shell [ -f $(PROJECT_PATH) ] && realpath $$(dirname $(PROJECT_PATH)) || realpath $(PROJECT_PATH)))
	$(eval TARGET_NAME=$(shell [ -f $(PROJECT_PATH) ] && basename $(PROJECT_PATH) || echo "."))
	@docker run --rm \
		-v "$(MOUNT_SRC):/app/project" \
		--user $(UID):$(GID) \
		--read-only \
		--tmpfs /tmp:mode=1777 \
		--add-host=host.docker.internal:host-gateway \
		cavo789/ai-agent:latest --path /app/project/$(TARGET_NAME) --docstring --tests --run-tests --model $(MODEL)

compose-run:
ifndef PROJECT_PATH
	$(error PROJECT_PATH is undefined. Usage: make compose-run PROJECT_PATH=/path/to/target)
endif
	@# Calculate Mount Source and Target Name only at runtime
	$(eval MOUNT_SRC=$(shell [ -f $(PROJECT_PATH) ] && realpath $$(dirname $(PROJECT_PATH)) || realpath $(PROJECT_PATH)))
	$(eval TARGET_NAME=$(shell [ -f $(PROJECT_PATH) ] && basename $(PROJECT_PATH) || echo "."))

	UID=$(UID) GID=$(GID) \
	MOUNT_SRC=$(MOUNT_SRC) \
	TARGET_NAME=$(TARGET_NAME) \
	docker compose run --rm ai-agent --path /app/project/$(TARGET_NAME) --docstring --verbose
```

**Dockerfile**

```docker
# syntax=docker/dockerfile:1

FROM python:3.13-slim AS builder

WORKDIR /build

COPY pyproject.toml .

# Create dummy src for pip install .
RUN mkdir src && touch src/__init__.py

RUN --mount=type=cache,target=/root/.cache/pip \
    pip install --prefix=/install .[dev]

FROM python:3.13-slim AS runtime

ARG USER_ID=1000
ARG GROUP_ID=1000

RUN groupadd -g ${GROUP_ID} agentgroup && \
    useradd -l -u ${USER_ID} -g agentgroup agentuser && \
    mkdir -p /app/src /tmp/agent && chown -R agentuser:agentgroup /app

COPY --from=builder /install /usr/local
COPY --chown=agentuser:agentgroup src /app/src
COPY --chown=agentuser:agentgroup pyproject.toml /app/

WORKDIR /app

USER agentuser

ENV HOME=/tmp \
    PYTHONPATH=/app/src \
    PYTHONDONTWRITEBYTECODE=1

ENTRYPOINT ["python", "src/main.py"]
```

**pyproject.toml**

```toml
[project]
name = "ai-maintenance-agent"
version = "0.1.0"
description = "Elite AI-powered Python maintenance agent"
requires-python = ">=3.13"
dependencies = [
    "libcst>=1.5.0",
    "requests>=2.32.0",
    "pyyaml>=6.0.1",
]

[project.optional-dependencies]
dev = [
    "ruff>=0.8.0",
    "mypy>=1.13.0",
    "pytest>=8.3.0",
]

[tool.ruff]
line-length = 100
target-version = "py313"
# Redirect Ruff cache to ephemeral tmpfs
cache-dir = "/tmp/.ruff_cache"

[tool.ruff.lint]
select = ["E", "F", "I", "N", "UP", "B", "C4"]

[tool.mypy]
python_version = "3.13"
strict = true
ignore_missing_imports = true

[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = "test_*.py"
```

**compose.yaml**

```yaml
services:
  ai-agent:
    build:
      context: .
      args:
        USER_ID: ${UID:-1000}
        GROUP_ID: ${GID:-1000}
    image: cavo789/ai-agent:latest
    # Read-only root filesystem for security
    read_only: true
    security_opt:
      - no-new-privileges:true
    # Mount /tmp as tmpfs for logs and volatile files
    tmpfs:
      - /tmp:mode=1777
    volumes:
      # Feature 1: Mount the code and config for live development
      - ./src:/app/src:ro
      - ./agent.yaml:/app/agent.yaml:ro
      # Mount the target project to be analyzed
      - ${MOUNT_SRC}:/app/project
    environment:
      - OLLAMA_URL=http://host.docker.internal:11434
      - PYTHONPATH=/app/src
    extra_hosts:
      - "host.docker.internal:host-gateway"
    # Overridable command for flexibility
    command: ["--path", "/app/project", "--docstring", "--verbose"]
```

**agent.yaml**

```yaml
# =============================================================================
# AI Maintenance Agent - Global Configuration Profile
# =============================================================================

# The specific LLM model to use for all code generation and analysis tasks.
# Ensure this model is already pulled in your local Ollama instance.
model: "qwen2.5-coder:7b"

# Toggles exhaustive logging. When set to true, the agent outputs the exact
# prompts, API responses, generated code sizes, and detailed Pytest outputs.
verbose: true

# Controls idempotency. If false, the agent skips files that already have
# docstrings or existing test files to save time. If true, it overwrites them.
force: false

# =============================================================================
# Task Execution Pipeline
# Enable or disable specific maintenance operations here.
# =============================================================================
tasks:
  # Generates missing module-level docstrings based on the code's behavior.
  docstring: true

  # Automatically generates a dedicated pytest file for the target module.
  tests: true

  # If true, immediately executes the generated test file using pytest
  # to validate that the AI-generated tests actually pass.
  run_tests: true

# =============================================================================
# Local LLM Infrastructure (Ollama)
# =============================================================================
ollama:
  # The endpoint of the Ollama API. 'host.docker.internal' allows the Docker
  # container to securely communicate with the Ollama instance running on your host.
  url: "http://host.docker.internal:11434"

  # Maximum time (in seconds) the agent will wait for the LLM to generate a response.
  # Increase this if running larger models on slower hardware.
  timeout: 300

  # Controls the LLM's creativity. Set to 0.0 for strict, highly deterministic
  # output, which is mandatory for reliable code generation.
  temperature: 0.0
```

**src/main.py**

```python
"""Elite AI Maintenance Agent - Main Orchestrator."""

import argparse
import os
import time
from pathlib import Path
from typing import Any, List

import yaml

from core.docstring import DocstringTask
from core.llm import OllamaClient
from core.logger import AgentLogger
from tasks.unit_test import UnitTestTask


class AgentOrchestrator:
    """Orchestrates the maintenance tasks across targeted Python files."""

    def __init__(self, config: dict[str, Any], args: argparse.Namespace):
        self.config: dict[str, Any] = config
        self.args: argparse.Namespace = args
        self.log = AgentLogger.setup(args.verbose or config.get("verbose", False))

        self.model: str = args.model or config.get("model", "qwen2.5-coder:7b")
        ollama_url: str = os.getenv(
            "OLLAMA_URL", config.get("ollama", {}).get("url", "http://host.docker.internal:11434")
        )

        self.llm = OllamaClient(url=ollama_url, model=self.model)

    def _get_target_files(self, root: Path) -> List[Path]:
        if root.is_file():
            if root.suffix != ".py":
                self.log.warning(f"Processing {root.name} despite missing .py extension.")
            return [root]

        if root.is_dir():
            return [
                f
                for f in root.rglob("*.py")
                if "tests" not in f.parts and f.name != "main.py"
            ]

        self.log.error(f"Path does not exist: {root}")
        return []

    def execute(self) -> None:
        start_time = time.time()

        root_path = Path(self.args.path).resolve()
        files = self._get_target_files(root_path)

        if not files:
            self.log.warning("No valid Python files found to process.")
            return

        force_flag = self.args.force or self.config.get("force", False)

        for py_file in files:
            display_name = py_file.name if root_path.is_file() else py_file.relative_to(root_path)
            self.log.info(f"--- Analyzing {display_name} ---")

            try:
                code = py_file.read_text(encoding="utf-8")

                if self.args.docstring or self.config.get("tasks", {}).get("docstring"):
                    if DocstringTask(self.llm).run(py_file, code, force=force_flag):
                        self.log.info(f"✓ Docstring updated: {py_file.name}")

                if self.args.tests or self.config.get("tasks", {}).get("tests"):
                    run_tests_flag = self.args.run_tests or self.config.get("tasks", {}).get("run_tests", False)
                    if UnitTestTask(self.llm).run(py_file, code, run_tests=run_tests_flag, force=force_flag):
                        self.log.info(f"✓ Test generation completed: {py_file.name}")

            except Exception as e:
                self.log.error(f"Failed to process {py_file.name}: {e}")

        # Calculate and display execution time
        elapsed = time.time() - start_time
        mins, secs = divmod(elapsed, 60)
        time_str = f"{int(mins)}m {secs:.2f}s" if mins > 0 else f"{secs:.2f}s"
        self.log.info(f"Done. Total Execution Time: {time_str}")


def main() -> None:
    """CLI Entrypoint."""
    parser = argparse.ArgumentParser(description="Elite AI Maintenance Agent")
    parser.add_argument("--path", required=True, help="Directory or single file")
    parser.add_argument("--config", default="/app/agent.yaml", help="Path to config file")
    parser.add_argument("--docstring", action="store_true")
    parser.add_argument("--tests", action="store_true")
    parser.add_argument("--run-tests", action="store_true")
    parser.add_argument("--model", type=str)
    parser.add_argument("--verbose", action="store_true")
    parser.add_argument("--force", action="store_true", help="Overwrite existing assets")
    args = parser.parse_args()

    config_path = Path(args.config)
    config: dict[str, Any] = {}

    if config_path.exists():
        with open(config_path, "r", encoding="utf-8") as f:
            config = yaml.safe_load(f) or {}

    AgentOrchestrator(config, args).execute()


if __name__ == "__main__":
    main()
```

**src/core/llm.py**

````python
"""Ollama LLM Client."""

import logging
import re
from typing import Final

import requests


class OllamaClient:
    """Dedicated client for LLM interaction."""

    def __init__(self, url: str, model: str, temperature: float = 0.0):
        self.url: Final[str] = f"{url}/api/generate"
        self.model: Final[str] = model
        self.temperature: Final[float] = temperature
        self.log = logging.getLogger("AI-Agent")

    def call(self, prompt: str, system_msg: str = "") -> str:
        """Sends a prompt to the Ollama API and returns the extracted code/text."""
        payload = {
            "model": self.model,
            "prompt": prompt,
            "stream": False,
            "system": system_msg,
            "options": {"temperature": self.temperature}
        }
        try:
            response = requests.post(self.url, json=payload, timeout=300)
            response.raise_for_status()
            text = response.json().get("response", "").strip()
            return self._extract_code(text)
        except requests.RequestException as e:
            # Ollama explains its errors in the body, e.g. a 404 carries
            # {"error": "model 'qwen2.5-coder:7b' not found"} when the model was never
            # pulled: show that message rather than the bare HTTP status line.
            detail = ""
            if e.response is not None:
                try:
                    detail = e.response.json().get("error", "")
                except ValueError:
                    detail = e.response.text.strip()
            self.log.error(f"Ollama API Error: {detail or e}")
            return ""

    def _extract_code(self, text: str) -> str:
        """Extracts code blocks from markdown or cleans up chatty LLM responses."""
        match = re.search(r"```(?:python)?(.*?)```", text, re.DOTALL)
        if match:
            return match.group(1).strip()

        # Fallback filter for common LLM conversational filler
        forbidden = ["Certainly", "Here is", "I've", "Explanation:"]
        lines = [l for l in text.splitlines() if not any(f in l for f in forbidden)]
        return "\n".join(lines).strip()
````

**src/core/docstring.py**

```python
import logging
import subprocess
from pathlib import Path

import libcst as cst

from core.llm import OllamaClient


class DocstringTask:
    """Handles automatic docstring generation using LibCST."""

    def __init__(self, llm: OllamaClient):
        self.llm = llm
        self.log = logging.getLogger("AI-Agent")

    class _Transformer(cst.CSTTransformer):
        def __init__(self, docstring: str, replace_existing: bool):
            self.docstring = docstring.strip('`"\'\n')
            self.replace_existing = replace_existing

        def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module:
            ds = cst.SimpleStatementLine([cst.Expr(cst.SimpleString(f'"""\n{self.docstring}\n"""'))])

            body = list(updated_node.body)
            # If we are forcing an overwrite, we pop the first element (the old docstring)
            if self.replace_existing and body:
                body = body[1:]

            return updated_node.with_changes(body=[ds] + body)

    def run(self, file_path: Path, code: str, force: bool = False) -> bool:
        tree = cst.parse_module(code)
        has_docstring = False

        if tree.body and isinstance(tree.body[0], cst.SimpleStatementLine):
            first_stmt = tree.body[0].body[0]
            if isinstance(first_stmt, cst.Expr) and isinstance(first_stmt.value, cst.SimpleString):
                has_docstring = True

        if has_docstring and not force:
            self.log.info(f"↷ Skipping docstring: Already exists. Use --force to overwrite.")
            return False

        prompt = (
            f"Write a 2-sentence module docstring for the following code. "
            f"DO NOT output Python code. DO NOT output imports or functions. "
            f"ONLY output the human-readable description.\n\n{code}"
        )
        ds = self.llm.call(prompt, "You are a technical writer. Output ONLY text.")

        if ds:
            if "import " in ds or "def " in ds:
                clean_lines = []
                for line in ds.splitlines():
                    if line.startswith(("import ", "def ", "class ", "logger")):
                        break
                    clean_lines.append(line)
                ds = "\n".join(clean_lines).strip()

            preview = ds[:100].replace('\n', ' ') + "..." if len(ds) > 100 else ds
            self.log.debug(f"Proposed Docstring: {preview}")

            modified = tree.visit(self._Transformer(ds, replace_existing=has_docstring))

            try:
                final_code = subprocess.run(
                    ["ruff", "format", "-"],
                    input=modified.code,
                    text=True,
                    capture_output=True,
                    check=True,
                ).stdout

                file_path.write_text(final_code, encoding="utf-8")
                return True

            except subprocess.CalledProcessError as e:
                self.log.error(f"Formatting failed on {file_path.name}. Ruff Exit Code: {e.returncode}")
                self.log.error(f"Ruff STDERR: {e.stderr.strip()}")
                return False

        return False
```

**src/core/logger.py**

```python
import logging
import sys
from typing import Final

class AgentLogger:
    """Premium structured logging helper."""
    FORMAT: Final[str] = "%(asctime)s | %(levelname)-8s | %(name)s | %(message)s"

    @staticmethod
    def setup(verbose: bool = False) -> logging.Logger:
        level = logging.DEBUG if verbose else logging.INFO
        logging.basicConfig(
            level=level,
            format=AgentLogger.FORMAT,
            handlers=[
                logging.StreamHandler(sys.stdout),
                logging.FileHandler("/tmp/agent.log")
            ]
        )
        return logging.getLogger("AI-Agent")
```

**src/tasks/unit\_test.py**

```python
"""Task for generating and executing unit tests."""

import logging
import os
import subprocess
import tempfile
from pathlib import Path

from core.llm import OllamaClient


class UnitTestTask:
    """Handles unit test generation and validation."""

    def __init__(self, llm: OllamaClient):
        self.llm = llm
        self.log = logging.getLogger("AI-Agent")

    def run(self, file_path: Path, code: str, run_tests: bool = False, force: bool = False) -> bool:
        test_dir = file_path.parent / "tests"
        test_dir.mkdir(exist_ok=True)
        test_path = test_dir / f"test_{file_path.name}"

        # Idempotency Check
        if test_path.exists() and not force:
            self.log.info(f"↷ Skipping test generation: {test_path.name} already exists. Use --force to overwrite.")
            return False

        prompt = (
            f"Generate a pytest file for the following code. "
            f"Import using 'from {file_path.stem} import *'. "
            f"Prefer real objects and pytest fixtures (tmp_path, monkeypatch) over unittest.mock.\n\n{code}"
        )
        test_code = self.llm.call(prompt, "Output ONLY raw Python code.")

        if test_code:
            self.log.debug(f"✓ Generated unit test code ({len(test_code)} bytes).")
            test_path.write_text(test_code, encoding="utf-8")

            subprocess.run(["ruff", "format", str(test_path)], capture_output=True)
            subprocess.run(["ruff", "check", "--fix", str(test_path)], capture_output=True)

            if run_tests:
                self.log.debug(f"Executing Pytest for {test_path.name}...")

                env = os.environ.copy()
                env["PYTHONPATH"] = f"{file_path.parent}:{env.get('PYTHONPATH', '')}"
                env["PYTHONDONTWRITEBYTECODE"] = "1"

                # Generated tests often write files relative to the current directory.
                # The container is read-only (/app included), so run pytest from a
                # throw-away folder on the /tmp tmpfs instead.
                with tempfile.TemporaryDirectory() as work_dir:
                    res = subprocess.run(
                        ["pytest", "-v", "--tb=short", "-p", "no:cacheprovider", str(test_path)],
                        capture_output=True,
                        text=True,
                        env=env,
                        cwd=work_dir,
                    )

                if res.returncode == 0:
                    # Last line of pytest's output, e.g. "5 passed in 0.02s".
                    summary = res.stdout.strip().splitlines()[-1].strip("= ")
                    self.log.info(f"✓ Tests PASSED for {file_path.name} ({summary})")
                    self.log.debug(f"Pytest Output:\n{res.stdout.strip()}")
                else:
                    self.log.error(f"✗ Tests FAILED for {file_path.name}")
                    self.log.error(f"Pytest Output:\n{res.stdout.strip()}\n{res.stderr.strip()}")
                    return False

            return True

        return False
```

Build the image:

```bash
$ cd ai-agent
$ make build
```

`make build` passes your user and group IDs to the build, so the user inside the image matches yours.

## Run It on Your Own Project

From the `ai-agent` folder, give `make run` an **absolute** path — a whole project, a single file, or a project with a lighter model:

```bash
$ make run PROJECT_PATH=/home/me/dev/my-project
$ make run PROJECT_PATH=/home/me/dev/my-project/invoice.py
$ make run PROJECT_PATH=/home/me/dev/my-project MODEL=qwen2.5-coder:3b
```

`make run` enables everything: docstring, test generation and test execution. When the target is a file, only its folder is mounted into the container and only that file is processed.

The agent walks the folder recursively and skips two kinds of files: anything inside a `tests/` folder, and any file named `main.py`. Generated tests land in a `tests/` folder **next to** each script.

### Running it again

Run the same command a second time and nothing is sent to the model: the docstring and the test file are already there.

```bash
$ make run PROJECT_PATH=/home/me/dev/demo
2026-12-04 07:54:32,108 | INFO     | AI-Agent | --- Analyzing helper.py ---
2026-12-04 07:54:32,111 | INFO     | AI-Agent | ↷ Skipping docstring: Already exists. Use --force to overwrite.
2026-12-04 07:54:32,111 | INFO     | AI-Agent | ↷ Skipping test generation: test_helper.py already exists. Use --force to overwrite.
2026-12-04 07:54:32,111 | INFO     | AI-Agent | Done. Total Execution Time: 0.00s
```

That is what makes it practical on a large project: process it folder by folder, delete a test file you don't like, and the next run only regenerates that one.

### Scripts with third-party imports

The tests run inside the agent's image, which only contains the agent's own dependencies. A script that imports `pandas` (or any package your project installs) still gets its docstring and its test file, but pytest stops at collection with `ModuleNotFoundError: No module named 'pandas'`. For such a project, run without `--run-tests` (see below) and execute the generated tests in your project's own environment.

### Without make

To run the image by hand, `cd` into the project to process and call `docker run` directly — this is exactly what `make run` does for you:

```bash
$ cd /home/me/dev/my-project
$ docker run --rm \
    -v "$PWD:/app/project" \
    --user "$(id -u):$(id -g)" \
    --read-only \
    --tmpfs /tmp:mode=1777 \
    --add-host=host.docker.internal:host-gateway \
    cavo789/ai-agent:latest --path /app/project --docstring --tests --run-tests --model qwen2.5-coder:7b
```

Drop `--tests --run-tests` to only get docstrings, drop `--docstring` to only get tests, and add `--force` to regenerate a docstring or a test file that already exists.

## Under the Hood (skip this if you just want to use it)

### The pipeline

`src/main.py` builds the list of files, then runs two independent tasks on each one:

1. **Docstring** (`src/core/docstring.py`) — the file is parsed with [LibCST](https://libcst.readthedocs.io/), a concrete syntax tree that keeps comments and formatting. If the module already starts with a string literal, the file is skipped. Otherwise the model is asked for a two-sentence description, any code it slips in anyway is cut off, and the result is inserted as the first statement. The whole file then goes through `ruff format`.
2. **Tests** (`src/tasks/unit_test.py`) — the model receives the code with two instructions: import it with `from <module> import *`, and prefer pytest fixtures such as `tmp_path` over `unittest.mock`. The answer is written to `tests/test_<module>.py`, cleaned up with `ruff format` and `ruff check --fix`, then executed by pytest with the script's folder on `PYTHONPATH`, so that import resolves.

`src/core/llm.py` is the only file talking to Ollama: one non-streamed call to `/api/generate`, temperature `0.0` for the most deterministic output, and the first fenced code block extracted from the answer.

Two limits come straight from that design. The docstring is a **module** docstring: functions and classes don't get one. And because of `ruff format`, a file that was not Ruff-formatted before will show formatting changes in its diff, on top of the docstring.

### The `docker run` flags

| Flag                                           | Why it's there                                                                                                         |
| ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `--rm`                                         | Deletes the container when the run ends.                                                                               |
| `-v "$PWD:/app/project"`                       | Mounts your project inside the container. The agent's own code lives in `/app/src`, so your project must go elsewhere. |
| `--user "$(id -u):$(id -g)"`                   | Runs as you, so generated files are owned by you and not by `root`.                                                    |
| `--read-only` + `--tmpfs /tmp`                 | The container filesystem is read-only; only `/tmp` (logs) and your mounted project are writable.                       |
| `--add-host=host.docker.internal:host-gateway` | Lets the container reach Ollama on your machine through the `host.docker.internal` name.                               |
| `--path`                                       | Folder or file to process, as seen **inside** the container.                                                           |
| `--docstring`, `--tests`, `--run-tests`        | The three tasks, each one optional.                                                                                    |
| `--model`                                      | The Ollama model to use; `qwen2.5-coder:7b` when omitted.                                                              |
| `--force`                                      | Regenerates existing docstrings and test files.                                                                        |

To see which models your Ollama instance has:

```bash
$ docker exec -it ollama ollama list
```

### `agent.yaml` and `make compose-run`

`make compose-run` is the mode to use while working **on the agent itself**: `compose.yaml` mounts `src/` and `agent.yaml` read-only into the container, so a change to the Python code is picked up on the next run without rebuilding the image.

`agent.yaml` holds the defaults — model, verbosity, Ollama URL, and which tasks to run. A task enabled there runs even when its command-line flag is absent; the flags can only **add** tasks, not remove them. The plain `make run` does not read this file, since it isn't copied into the image.

## Conclusion

A docstring and a test file for a script that had neither, in the time it takes to type `make run` — that's the whole value, and it doesn't pretend to be more than that. The model will sometimes get an assertion wrong, and that's fine: fixing one bad assertion is still faster than writing a test file from a blank page. Same idea as the rest of the local-Ollama tooling on this blog: a fast, private first draft, reviewed before it's trusted, never a replacement for reading your own code.

If you'd rather stay in your shell, [ai-test](/blog/ollama-test-generator) takes the other route: a zsh function that generates only the missing tests for a Bash, PHP or Python file, with no image to build.
