NEWn1n v2.0.1 is live! Enterprise Unified LLM API Gateway with 500+ AI Models, up to 90% off,Try now

Guide to Writing an AGENTS.md File for a Python Project

Authors
  • avatar
    Name
    Nino
    Occupation
    Senior Tech Editor

As AI-driven coding assistants like Cursor, Windsurf, and custom LangChain agents become standard in the modern developer's toolkit, the way we document codebases is shifting. Traditional README.md files are written for human developers, detailing high-level architecture, installation steps, and licensing. However, an AI agent needs something different: precise constraints, strict coding conventions, quality gates, and context boundaries.

To bridge this gap, the community has adopted the concept of an AGENTS.md file. This specialized markdown file acts as a system prompt and operational manual for any AI agent interacting with your codebase. By accessing advanced LLMs like Claude 3.5 Sonnet and DeepSeek-V3 via n1n.ai, developers can leverage these files to dramatically reduce hallucination rates, prevent breaking changes, and ensure the agent writes idiomatic Python code.

In this comprehensive guide, we will explore the foundational blocks of an AGENTS.md file, analyze why a lean file performs better than a sprawling one, and test your knowledge with a technical quiz.


Why You Need to Write an AGENTS.md File for Your Python Project

AI agents operate by reading your codebase, parsing your prompt, and generating code based on their training weights and the context provided. Without an AGENTS.md file, the agent has to guess your project's architectural patterns, testing strategies, and styling preferences. This often results in:

  • Style Drift: The agent mixing object-oriented patterns with functional programming, or using outdated setup.py configurations instead of modern pyproject.toml setups.
  • Dependency Chaos: The agent attempting to install packages using pip install when your project relies strictly on Poetry or uv for lockfile integrity.
  • Broken Quality Gates: The agent writing code that bypasses your static analysis tools (mypy, ruff, black), leading to failed CI/CD pipelines.

By placing a structured AGENTS.md file in your root directory, you give the LLM a single source of truth. When routing requests through n1n.ai to power your custom agent workflows, this file helps maintain consistency across different model architectures.


The Anatomy of an AGENTS.md File

A production-ready AGENTS.md file is divided into distinct, functional blocks. Each block addresses a specific dimension of the developer-agent collaboration.

1. Project Domain & Context

This section defines what the project is and who it is for. It prevents the agent from making false assumptions about the application's environment (e.g., assuming a Web3 context for a standard Django REST API).

2. Setup & Environment Management

Python has a fragmented packaging ecosystem. You must explicitly state whether the project uses Poetry, uv, Conda, or standard virtual environments (venv).

3. Coding Conventions & Style

Define the Python standards. Do you enforce PEP 8? Do you use strict type hints? Are async patterns preferred over synchronous ones? Specify these here.

4. Project Structure

A visual representation of the directory layout helps the agent locate files quickly without recursively reading every directory, saving tokens and reducing latency.

5. Quality Gates

State the exact commands the agent must run to verify their changes. If the tests do not pass, the agent should not mark the task as complete.

6. Constraints & Ignore Rules

Define the boundaries. For example, prevent the agent from modifying the database schema directly or using deprecated libraries.


Production-Ready AGENTS.md Template

Below is a highly optimized template designed specifically for modern Python projects. You can copy and adapt this for your codebase.

# AGENTS.md - AI Developer Instructions

## 1. Project Domain & Context

- **Project Name**: FastQuery
- **Domain**: High-performance asynchronous database wrapper for PostgreSQL using `asyncpg`.
- **Target Environment**: Python 3.11+ / Dockerized Linux containers.
- **Core Goal**: Provide type-safe, low-latency query execution with automatic connection pooling.

## 2. Setup & Environment Management

- **Dependency Manager**: Poetry (do NOT use raw `pip` or `requirements.txt`).
- **Virtual Env Activation**: `poetry shell`
- **Installation Command**: `poetry install --with dev`
- **Lockfile Policy**: Never run `poetry update` unless explicitly requested. Only use `poetry add [package]`.

## 3. Coding Conventions

- **Formatting**: Code must strictly conform to Ruff's formatting rules. Run `poetry run ruff format`.
- **Type Hinting**: Mandatory for all function signatures. Use `from typing import ...` or native subscription types (e.g., `list[str]` instead of `List[str]`).
- **Concurrency**: Use `async`/`await` paradigms. Avoid blocking synchronous calls inside async loops (e.g., do not use `time.sleep()`, use `await asyncio.sleep()`).
- **Error Handling**: Always catch specific exceptions. Never use bare `except:` clauses.

## 4. Project Structure

```text
fastquery/
├── src/
│   └── fastquery/
│       ├── __init__.py
│       ├── pool.py         # Connection pooling logic
│       └── client.py       # Main API client interface
├── tests/
│   └── test_client.py      # Integration and unit tests
├── pyproject.toml          # Poetry and tool configurations
└── AGENTS.md               # This file
```

5. Quality Gates

Before submitting any code changes, you MUST run and pass the following checks:

  1. Linting & Formatting: poetry run ruff check . and poetry run ruff format --check .
  2. Type Checking: poetry run mypy src/ (must return 0 errors, strict mode enabled).
  3. Testing: poetry run pytest tests/ (minimum coverage threshold: 90%).

6. Constraints & Ignore Rules

  • Database Safety: Never write raw SQL migrations. All migrations must go through Alembic.
  • File Modifications: Do not modify files in the tests/fixtures/ directory.
  • Performance: Ensure database query latency is kept < 50ms. Avoid N+1 query patterns.

---

## Lean vs. Sprawling: The Science of Context Windows

When writing an `AGENTS.md` file, there is a common temptation to include every single detail, error log, and architectural decision record (ADR). This leads to a "sprawling" file.

### The Cost of Context Bloat
1. **Attention Dilution (Lost in the Middle)**: Large Language Models use self-attention mechanisms. When you feed an LLM a massive context file, the model's ability to recall instructions located in the middle of the document drops significantly.
2. **Latency and Token Costs**: Every prompt sent to the LLM will prepend the `AGENTS.md` content. A 5,000-word file adds latency and drives up API costs. Using an aggregator like [n1n.ai](https://n1n.ai) to test models like Claude 3.5 Sonnet reveals that keeping instructions lean directly correlates with faster response times.
3. **Conflicting Instructions**: The larger the file, the higher the probability of introducing contradictory rules (e.g., demanding strict type safety in one section but showing dynamic, untyped examples in another).

### Keep it Lean: The "Need to Know" Principle
*   **Keep it under 150 lines**: If your `AGENTS.md` exceeds 150 lines, split it. Keep core operational instructions in `AGENTS.md`, and put architectural deep-dives into a separate `/docs/architecture.md` file which the agent can read only when necessary.
*   **Use Declarative Bullet Points**: Avoid long paragraphs. Use clear, imperative statements (e.g., "Use Ruff for linting" instead of "We have chosen to transition our styling standards to Ruff because...").

---

## Interactive Quiz: Test Your Understanding

Test your knowledge of writing effective instructions for AI agents in Python projects. Select your answers and review the explanations below.

### Question 1: Context Management
**An agent keeps writing code that violates your formatting standards despite your `AGENTS.md` specifying Ruff. The file is currently 350 lines long and contains detailed histories of your architectural decisions. What is the most effective way to resolve this?**

*   A) Add more examples of properly formatted code to the `AGENTS.md` file.
*   B) Delete the architectural history, trim the file down to under 150 lines, and place the formatting command at the top of the "Quality Gates" section.
*   C) Switch to a different LLM because the current one is incapable of following instructions.
*   D) Write a custom script that runs Ruff automatically every time the agent saves a file.

*Answer Explanation:*
**B** is the correct answer. Adding more examples (Option A) increases context bloat and worsens the "lost in the middle" effect. While automated scripts (Option D) are useful, they fix the symptom rather than the cause of agent misalignment. Trimming the file reduces attention dilution, allowing the agent to parse and execute the formatting constraints successfully.

### Question 2: Python Dependency Constraints
**Your Python project uses Poetry. The AI agent needs to add a dependency (`httpx`) to write a new feature. Which instruction in `AGENTS.md` best prevents the agent from breaking your lockfile?**

*   A) "Install dependencies using pip."
*   B) "Run `poetry update` to make sure all packages are up to date."
*   C) "Only add packages using `poetry add [package]`. Never run `poetry update` or modify `pyproject.toml` directly."
*   D) "Dependencies are managed automatically. Do not add any new packages."

*Answer Explanation:*
**C** is the correct answer. Running `poetry update` (Option B) can update unrelated dependencies, potentially introducing breaking changes. Modifying `pyproject.toml` manually without running the lock command causes inconsistencies. Explicitly instructing the agent to use `poetry add` ensures the lockfile is updated safely.

### Question 3: Formatting & Syntax Safety
**Why must you escape characters like `<` (as `&lt;`) or avoid raw curly braces `{}` in markdown files read by certain MDX parser integrations?**

*   A) It prevents the markdown parser from interpreting the symbols as HTML tags or React/JavaScript components, which would break the rendering engine.
*   B) LLMs cannot read the `<` symbol and will hallucinate if they encounter it.
*   C) It is a Python-specific requirement for parsing markdown metadata.
*   D) It increases the semantic density of the prompt.

*Answer Explanation:*
**A** is correct. Many modern documentation sites and agent interfaces use MDX (Markdown + JSX). Raw `<` signs followed by text or raw curly braces `{}` can cause build-time errors because the parser attempts to evaluate them as JSX code. Keeping files clean and escaped ensures compatibility across parser engines.

---

## Pro Tips for Python-Specific AGENTS.md Files

1. **Leverage Pyproject.toml Integration**: Instead of listing all your linting rules in `AGENTS.md`, configure them in `pyproject.toml` under `[tool.ruff]` and `[tool.mypy]`. Then, in `AGENTS.md`, simply tell the agent: "Run `ruff check .` to verify formatting." This keeps your markdown file clean and leverages the configuration files the agent is already reading.
2. **Dynamic Agent Routing**: Different tasks require different models. For code refactoring, a reasoning model like OpenAI o3-mini or DeepSeek-R1 is ideal. For standard documentation or boilerplate generation, Claude 3.5 Sonnet excels. Using [n1n.ai](https://n1n.ai) allows you to dynamically route these tasks to the optimal model while passing your structured `AGENTS.md` file as context.
3. **The "Agent Verification" Step**: Always include a rule in `AGENTS.md` that instructs the agent to run the quality gate command *before* returning its response. This forces the agent to self-correct errors in its own workspace before presenting the solution to you.

Get a free API key at [n1n.ai](https://n1n.ai)