<!--
  canonical-url: https://www.avonture.be/fr/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.
-->

# Documenter et tester automatiquement vos scripts Python

> Un agent dockerisé qui lit un fichier Python, écrit une vraie docstring, génère un fichier pytest et l'exécute dans la foulée — le tout via un modèle Ollama local, sans qu'une ligne de code ne quitte la machine.

---
![Documenter et tester automatiquement vos scripts Python](/img/v2/python-ai-helper.webp)

**TL;DR**

`ai-agent` est un petit programme Python packagé sous forme d'image Docker. Pointez-le vers un dossier ou un seul fichier `.py` : pour chaque script, il demande une docstring de module à un modèle Ollama local, écrit un fichier pytest dans `tests/` et l'exécute immédiatement. Rien ne quitte votre machine, les fichiers restent à vous, et le container tourne en lecture seule. Le test généré est un premier jet à relire, pas un verdict sur votre code.

J'ai des scripts Python éparpillés dans plusieurs projets, sans docstring et sans test — écrits vite, jamais relus, et chaque fois que j'en rouvre un des mois plus tard, je dois tout relire pour me souvenir de ce qu'il fait. Écrire la docstring à la main est rapide pour un fichier ; pour le quarantième script d'un projet dont j'ai hérité, beaucoup moins.

À la fin de cet article, un seul `make run` documentera et testera tout un dossier de scripts Python, en utilisant le modèle Ollama qui tourne déjà sur votre machine.

**Quick Jump:** [Le voir à l'œuvre](#what-ai-agent-does-for-you) | [Récupérer les fichiers et construire l'image](#build-the-image) | [L'exécuter sur votre projet](#run-it-on-your-own-project)

## Ce que ai-agent fait pour vous {#what-ai-agent-does-for-you}

Ici, l'agent tourne sur un dossier contenant un seul script, `helper.py` : cinq utilitaires de manipulation de fichiers, aucune docstring, aucun 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
```

Trois choses se sont produites en moins de quatre secondes. Une docstring a été écrite en haut de `helper.py` — les trois premières lignes ci-dessous sont nouvelles, tout le reste est le code d'origine :

**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
```

Un fichier `tests/test_helper.py` a été créé à côté, un test par fonction, travaillant sur de vrais fichiers dans le dossier `tmp_path` de pytest :

**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()
```

Et pytest l'a exécuté : cinq tests, tous au vert.

> **Relisez le test généré avant de lui faire confiance:**
>
> Une assertion qui échoue ne veut pas forcément dire que votre code est cassé — le modèle peut se tromper sur une valeur attendue. Une assertion qui passe ne veut pas dire grand-chose non plus si le test vérifie seulement qu'une clé existe. Traitez un test généré comme la pull request d'un collègue junior : relisez-la avant de vous appuyer dessus.

## Pourquoi ça fonctionne {#why-it-works}

* **Un container, un appel au modèle par tâche.** Pas de plugin d'IDE, pas de clé d'API, pas de compte : l'agent parle à l'instance Ollama que vous faites déjà tourner, donc votre code ne quitte jamais la machine.
* **La docstring est insérée, pas réécrite.** La source est parsée en arbre syntaxique et la docstring est ajoutée comme première instruction — le modèle n'a jamais l'occasion d'« améliorer » vos fonctions.
* **Les tests sont exécutés, pas seulement écrits.** Un fichier de test qui ne s'importe même pas est détecté sur-le-champ, pendant que vous avez encore le contexte en tête.
* **On peut le lancer deux fois sans risque.** Les fichiers qui ont déjà une docstring ou un fichier de test sont ignorés, sauf si vous demandez explicitement de les régénérer : relancer sur un projet à moitié traité ne coûte que les fichiers manquants.
* **Il ne peut pas tout casser.** Le container tourne avec un système de fichiers en lecture seule et votre propre identifiant utilisateur : tout ce qu'il écrit vous appartient, et il ne peut écrire que dans le dossier que vous lui confiez.

## Construire l'image {#build-the-image}

L'image n'est pas publiée sur Docker Hub : vous la construisez une fois, en local, à partir des fichiers ci-dessous. Il vous faut Docker, `make`, et Ollama à l'écoute sur le port `11434` de votre machine — j'ai déjà parlé de [installing Ollama as a Docker container](/blog/ollama-installation).

Téléchargez le modèle utilisé par défaut par l'agent (environ 4,7 Go). La commande suppose qu'Ollama tourne dans un container nommé `ollama` ; avec une installation native, supprimez simplement `docker exec -it ollama` :

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

Créez ensuite le projet. Utilisez le bouton **Script** pour créer tous les fichiers en un seul copier-coller, ou **ZIP** pour les télécharger :

**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
```

Construisez l'image :

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

`make build` transmet vos identifiants d'utilisateur et de groupe au build, pour que l'utilisateur dans l'image corresponde au vôtre.

## L'exécuter sur votre propre projet {#run-it-on-your-own-project}

Depuis le dossier `ai-agent`, donnez à `make run` un chemin **absolu** — un projet entier, un seul fichier, ou un projet avec un modèle plus léger :

```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` active tout : docstring, génération des tests et exécution des tests. Quand la cible est un fichier, seul son dossier est monté dans le container et seul ce fichier est traité.

L'agent parcourt le dossier récursivement et ignore deux types de fichiers : tout ce qui se trouve dans un dossier `tests/`, et tout fichier nommé `main.py`. Les tests générés atterrissent dans un dossier `tests/` **à côté** de chaque script.

### Relancer la commande {#running-it-again}

Lancez la même commande une seconde fois et rien n'est envoyé au modèle : la docstring et le fichier de test sont déjà là.

```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
```

C'est ce qui le rend utilisable sur un gros projet : traitez-le dossier par dossier, supprimez un fichier de test qui ne vous plaît pas, et la prochaine exécution ne régénérera que celui-là.

### Scripts avec des imports tiers {#scripts-with-third-party-imports}

Les tests tournent dans l'image de l'agent, qui ne contient que les dépendances de l'agent lui-même. Un script qui importe `pandas` (ou n'importe quel package installé par votre projet) obtient quand même sa docstring et son fichier de test, mais pytest s'arrête à la collecte avec `ModuleNotFoundError: No module named 'pandas'`. Pour ce genre de projet, lancez sans `--run-tests` (voir plus bas) et exécutez les tests générés dans l'environnement de votre projet.

### Sans make {#without-make}

Pour lancer l'image à la main, placez-vous (`cd`) dans le projet à traiter et appelez `docker run` directement — c'est exactement ce que `make run` fait pour vous :

```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
```

Retirez `--tests --run-tests` pour n'obtenir que les docstrings, retirez `--docstring` pour n'obtenir que les tests, et ajoutez `--force` pour régénérer une docstring ou un fichier de test qui existe déjà.

## Sous le capot (passez votre chemin si vous voulez juste l'utiliser) {#under-the-hood-skip-this-if-you-just-want-to-use-it}

### Le pipeline {#the-pipeline}

`src/main.py` construit la liste des fichiers, puis exécute deux tâches indépendantes sur chacun :

1. **Docstring** (`src/core/docstring.py`) — le fichier est parsé avec [LibCST](https://libcst.readthedocs.io/), un arbre syntaxique concret qui conserve les commentaires et le formatage. Si le module commence déjà par une chaîne littérale, le fichier est ignoré. Sinon, on demande au modèle une description en deux phrases, tout code qu'il glisserait malgré tout est supprimé, et le résultat est inséré comme première instruction. Le fichier entier passe ensuite par `ruff format`.
2. **Tests** (`src/tasks/unit_test.py`) — le modèle reçoit le code avec deux consignes : l'importer via `from <module> import *`, et privilégier les fixtures pytest comme `tmp_path` plutôt que `unittest.mock`. La réponse est écrite dans `tests/test_<module>.py`, nettoyée avec `ruff format` et `ruff check --fix`, puis exécutée par pytest avec le dossier du script dans `PYTHONPATH`, pour que l'import se résolve.

`src/core/llm.py` est le seul fichier qui parle à Ollama : un appel non streamé à `/api/generate`, température `0.0` pour la sortie la plus déterministe possible, et extraction du premier bloc de code de la réponse.

Deux limites découlent directement de ce choix de conception. La docstring est une docstring de **module** : les fonctions et les classes n'en reçoivent pas. Et à cause de `ruff format`, un fichier qui n'était pas formaté avec Ruff auparavant affichera des changements de formatage dans son diff, en plus de la docstring.

### Les flags de `docker run` {#the-docker-run-flags}

| Flag                                           | Pourquoi il est là                                                                                                                     |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `--rm`                                         | Supprime le container à la fin de l'exécution.                                                                                         |
| `-v "$PWD:/app/project"`                       | Monte votre projet dans le container. Le code de l'agent vit dans `/app/src`, votre projet doit donc aller ailleurs.                   |
| `--user "$(id -u):$(id -g)"`                   | Tourne sous votre identité, pour que les fichiers générés vous appartiennent et pas à `root`.                                          |
| `--read-only` + `--tmpfs /tmp`                 | Le système de fichiers du container est en lecture seule ; seuls `/tmp` (les logs) et votre projet monté sont accessibles en écriture. |
| `--add-host=host.docker.internal:host-gateway` | Permet au container de joindre Ollama sur votre machine via le nom `host.docker.internal`.                                             |
| `--path`                                       | Dossier ou fichier à traiter, tel que vu **depuis l'intérieur** du container.                                                          |
| `--docstring`, `--tests`, `--run-tests`        | Les trois tâches, chacune optionnelle.                                                                                                 |
| `--model`                                      | Le modèle Ollama à utiliser ; `qwen2.5-coder:7b` si omis.                                                                              |
| `--force`                                      | Régénère les docstrings et les fichiers de test existants.                                                                             |

Pour voir les modèles dont dispose votre instance Ollama :

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

### `agent.yaml` et `make compose-run` {#agentyaml-and-make-compose-run}

`make compose-run` est le mode à utiliser quand vous travaillez **sur l'agent lui-même** : `compose.yaml` monte `src/` et `agent.yaml` en lecture seule dans le container, donc une modification du code Python est prise en compte à l'exécution suivante sans reconstruire l'image.

`agent.yaml` contient les valeurs par défaut — modèle, verbosité, URL d'Ollama, et quelles tâches exécuter. Une tâche activée là s'exécute même si son flag en ligne de commande est absent ; les flags peuvent seulement **ajouter** des tâches, pas en retirer. Le simple `make run` ne lit pas ce fichier, puisqu'il n'est pas copié dans l'image.

## Conclusion {#conclusion}

Une docstring et un fichier de test pour un script qui n'avait ni l'un ni l'autre, le temps de taper `make run` — c'est toute la valeur de l'outil, et il ne prétend pas faire plus. Le modèle se trompera parfois sur une assertion, et ce n'est pas grave : corriger une mauvaise assertion reste plus rapide que d'écrire un fichier de test en partant d'une page blanche. Même idée que le reste de l'outillage local-Ollama de ce blog : un premier jet rapide et privé, relu avant d'être validé, jamais un remplacement de la lecture de votre propre code.

Si vous préférez rester dans votre shell, [ai-test](/blog/ollama-test-generator) prend l'autre chemin : une fonction zsh qui génère uniquement les tests manquants pour un fichier Bash, PHP ou Python, sans image à construire.
