A developer stands beside a Python-powered quality-control line where documents pass through numbered inspection stages, two stamped PASS and one pulled aside as FAIL by a robot, beside a 90% gauge.

How to Set Up a Python Project for Agentic Coding

by Isabel Zimmerman Updated Reading time estimate 21m intermediate ai

Modern AI agents can write functions, refactor modules, generate tests, and implement entire features from a natural language prompt. But their output is only as reliable as the project they’re working in. A Python project for agentic coding answers the questions an agent would otherwise guess at: how your project is organized and which tools to run.

Fortunately, making agents more reliable doesn’t require longer prompts or a different coding agent. Instead, you can build a project that makes expectations explicit. Automated tests, linters, type checkers, configuration files, and concise project documentation create feedback loops that help both humans and AI catch mistakes early. The result is a development workflow that’s more predictable, regardless of which coding assistant you use.

In this tutorial, you’ll build a Python project optimized for agentic coding from an empty directory. Along the way, you’ll configure the tools that give agents fast, executable feedback, document your project’s conventions, and organize your repository so an agent can navigate it effectively. Although you’ll see examples of agent-specific instruction files, the overall approach is tool agnostic and works with a wide range of agents.

Before starting this tutorial, you should:

  • Be familiar with running commands in the terminal
  • Understand the basic Python package structure
  • Have Git installed and configured

Here’s the layout you’ll end up with, including every configuration file and check that an agent relies on:

File tree for AI-AGENT-PROJECT: tests/test_main.py, plus .env.example, .gitignore, main.py, pyproject.toml, README.md, uv.lock, and other config files.
The Final Project Structure

Each file in that tree does one job, and you’ll add them a few at a time across the next three steps.

Take the Quiz: Test your knowledge with our interactive “How to Set Up a Python Project for Agentic Coding” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

How to Set Up a Python Project for Agentic Coding

Check how well you can set up a Python project for agentic coding, with the tests, type checks, linting, and hooks that give AI agents fast feedback.

Step 1: Initialize Your Python Project

uv is a package and Python installation manager that can be used to set up new projects. If you haven’t already installed uv, then follow the installation instructions for your operating system. Once it’s installed, create a new project by running:

Language: Shell
$ uv init --package ai-agent-project
$ cd ai-agent-project

The uv init command creates a minimal Python project with sensible defaults. Depending on the version of uv you’re using, the generated files may vary slightly, but you’ll typically see something similar to this:

ai-agent-project/
│
├── src/
│   │
│   └── ai_agent_project/
│       └── __init__.py
│
├── .gitignore
├── .python-version
├── pyproject.toml
└── README.md

This gives you a working starting point without requiring you to manually create configuration files or virtual environments.

Layout matters more here than it might first appear, and the reason has to do with how agents read a repository. Humans naturally build a mental model of a project over time. After working in a repository, you probably know where to find files, tests, and configuration without thinking about it.

AI agents don’t have that advantage. Instead, they build a working model of your project from the files they can access. Each unnecessary directory, inconsistent name, or duplicated configuration increases the amount of information an agent has to process before it can make useful changes.

By following a standard package layout, like the one uv provides, you are able to give an agent more context with less ambiguity. This idea extends beyond directory structure. Every configuration file, automated check, and documentation file you’ll add later in this tutorial reduces uncertainty. Instead of repeatedly describing those expectations in prompts, you encode those preferences directly into the project itself.

Version control is an essential part of modern Python development, but it also plays an important role when working with AI agents. Agents often make changes across multiple files, and Git provides a reliable way to review, compare, or discard those changes before they’re merged.

Running uv init initializes both your Python project and a Git repository. Commit this initial state:

Language: Shell
$ git add .
$ git commit -m "Initial project scaffold"

That snapshot is your undo button. Even when working alone, frequent commits make it much easier to recover from an incorrect implementation or compare multiple agent-generated solutions.

Step 2: Build an Agent-Friendly Python Project Foundation

Well-organized projects help agents understand where code belongs. The next step is making it clear whether the code an agent writes is correct. Since agents generate code much faster than humans, fast feedback becomes even more valuable. An agent can implement a feature in seconds, but without automated checks it may continue building on incorrect assumptions. By the time the mistake is discovered, several files may need to be rewritten.

Rather than trying to describe every coding convention in your prompts, you can encode those expectations directly into your project’s tooling. Every failed test, linting error, or type error provides immediate, actionable feedback that helps the agent converge on a correct implementation. Whenever possible, configure tools to enforce conventions automatically rather than documenting them.

Enforce Consistent Code Style

Formatting and linting are among the fastest feedback mechanisms available. They identify stylistic issues, common bugs, unused imports, and many other problems before your code ever reaches the test suite.

A popular linter choice is Ruff, which you can install as a development dependency:

Language: Shell
$ uv add --dev ruff==0.16.7

Then configure it in pyproject.toml:

Language: TOML
[tool.ruff]
line-length = 80

[tool.ruff.lint]
extend-select = ["I"]  # Sort imports

Even a small configuration, like a maximum line length, establishes rules that both humans and AI agents must follow. To have Ruff fix your code automatically, run these two commands:

Language: Shell
$ uv run ruff check --fix
$ uv run ruff format

The first command runs the linter and applies safe fixes, which includes sorting your imports through the I rule. The second command reformats your code to match your style settings, such as the line length.

This means that if an agent writes code that doesn’t match your formatting rules, the feedback is automatic. There’s no need to include instructions like “Please organize imports correctly” in every prompt because the tooling already enforces the rule.

Validate Types Before Runtime

Ruff checks how your code looks, but not whether the types fit together. Static type checking catches another class of errors before the code even runs. If a function is annotated to accept an integer but you accidentally pass it a string, mypy reports the error before you run your code.

Here is an example of the type of mistake mypy catches:

Language: Python
def double(value: int) -> int:
    return value * 2

result = double("5")  # Incompatible type "str"; expected "int"

A type checker like mypy can identify the mismatch immediately. To fix this, change double("5") to double(5).

Install a type checker:

Language: Shell
$ uv add --dev mypy==2.3.1

Configure the type checker in your pyproject.toml via:

Language: TOML
[tool.mypy]
strict = true

Type hints also improve the context available to agents. Function signatures communicate intent explicitly, making it easier for an agent to understand how different parts of the project interact.

Verify Behavior With Automated Tests

Linters and type checkers catch many mistakes, but they can’t tell you whether your code behaves correctly. Automated tests verify that your program produces the expected results, making them one of the most valuable feedback mechanisms you can provide an AI coding agent. Before you can write a test, you need something to test.

Replace the contents of the generated src/ai_agent_project/__init__.py with a single function:

Language: Python
def double(value: int) -> int:
    return value * 2

The file you just replaced held a main() function that uv init wired up as a command-line entry point. Because main() no longer exists, also remove the [project.scripts] table from pyproject.toml. Otherwise, running uv run ai-agent-project fails with an ImportError.

Afterward, your pyproject.toml file should look like this:

Language: TOML
[project]
name = "ai-agent-project"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
authors = [
    { name = "Your Name", email = "you@example.com" }
]
requires-python = ">=3.14"
dependencies = []

[build-system]
requires = ["uv_build>=0.11.26,<0.12.0"]
build-backend = "uv_build"

[dependency-groups]
dev = [
    "mypy==2.3.1",
    "ruff==0.16.7",
]

[tool.ruff]
line-length = 80

[tool.ruff.lint]
extend-select = ["I"]  # Sort imports

[tool.mypy]
strict = true

Install pytest along with the pytest-cov plugin:

Language: Shell
$ uv add --dev pytest==9.1.1 pytest-cov==7.1.0

Then configure pytest in your pyproject.toml:

Language: TOML
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "--cov=src --cov-report=term-missing --cov-fail-under=90"

This configuration does more than simply run your test suite. It also measures code coverage and requires at least 90% of your source code to be exercised by tests before the suite passes. While the exact threshold is up to your team, a coverage gate encourages agents to write or update tests alongside new features instead of treating testing as an afterthought.

Create tests/test_main.py:

Language: Python
from ai_agent_project import double

def test_double_returns_twice_the_input() -> None:
    assert double(4) == 8

Running uv run pytest now gives you a passing test, verifies that the function behaves as expected, and contributes toward meeting your project’s coverage requirement. When you run pytest, you’ll see a coverage report because of the --cov-report=term-missing option, followed by a check against your 90% threshold:

Language: Text
======================== tests coverage ========================
_______ coverage: platform darwin, python 3.14.6-final-0 _______

Name                               Stmts   Miss  Cover   Missing
----------------------------------------------------------------
src/ai_agent_project/__init__.py       2      0   100%
----------------------------------------------------------------
TOTAL                                  2      0   100%
Required test coverage of 90% reached. Total coverage: 100.00%
====================== 1 passed in 0.03s =======================

Measuring coverage also writes a .coverage data file to your project’s root folder. The default .gitignore from uv doesn’t exclude it, so add it before your next commit to keep it out of the repository:

Language: Text
# Coverage
.coverage

Tests are especially valuable because they provide machine-verifiable feedback. Failures point directly to the behavior that needs to be corrected. Human developers can ask clarifying questions or infer intent from context, but an agent can only reason about information it can access.

Agents work best when that information exists as a file they can open, search, and reference while making changes. Whenever practical, write important output to files. One example could be outputting test runs into a file via uv run pytest --junitxml pytest-report.xml. Then, an agent can refer to the created pytest-report.xml to inspect errors.

The agent feedback loop fits naturally with test-driven development (TDD). Whether you follow TDD strictly or simply update tests before making significant changes, you’re giving the agent an executable specification instead of a natural language description. Well-written tests communicate expected behavior far more precisely than another paragraph in your prompt ever could.

Automate Checks Before Every Commit

Each of the tools you’ve configured so far provides useful feedback, but they’re only effective if they run consistently. Forgetting to format your code or letting type errors slip through before committing can allow small issues to accumulate over time.

The pre-commit framework automates these checks by running them before Git creates a commit. First, install it:

Language: Shell
$ uv add --dev pre-commit==4.6.2

Then create a .pre-commit-config.yaml file:

Language: YAML
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.16.7
    hooks:
      - id: ruff-check
      - id: ruff-format
  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v2.3.1
    hooks:
      - id: mypy

Finally, install the hooks:

Language: Shell
$ uv run pre-commit install

Now every commit automatically runs the configured checks. If Ruff detects a formatting issue or linting error, Git rejects the commit until the problem is fixed. You can try out running the checks in the terminal:

Language: Shell
$ uv run pre-commit run --all-files

If the formatting check fails, Ruff reformats the file for you. You will need to git add any updated files and commit again. Lint and type errors aren’t fixed automatically, so you or the agent need to correct them before the commit goes through. For AI agents, this creates another valuable feedback loop.

If a check fails, the agent receives an actionable error message and can correct the problem before continuing, instead of compounding the mistake across several more files. Pre-commit ensures those checks happen consistently. The result is a project that continuously communicates with the agent.

Each tool covers a different category of mistake, though, and a check you skip covers nothing at all. Turn the checks on and off against an agent’s change that carries three separate flaws, and watch which ones survive:

Interactive diagram — enable JavaScript to view.

Whatever your tooling doesn’t cover is what you’re left to catch by hand, in review.

Step 3: Add Agent Instructions and Manage Secrets

AI agents are most effective when your project clearly communicates its expectations. In this step, you’ll add repository-specific instructions, establish a consistent place for agent rules, and configure secrets so agents can work safely without exposing sensitive information or relying on ambiguous prompts.

Add an AGENTS.md File

Many AI agents look for an AGENTS.md file at the root of a repository. While support varies between tools, the underlying idea is to provide instructions that help an agent understand how to work within your project.

Think of AGENTS.md as a contributor guide written specifically for agents. It shouldn’t explain how your application works or duplicate your README.md. Instead, it should capture the project standards an agent should follow while making changes.

A simple example might look like this:

Language: Markdown Text
# `AGENTS.md`

## Development workflow

- This project is typed. Run mypy after adding or modifying code:
  - `uv run mypy .`
- Use Ruff for formatting and linting:
  - `uv run ruff format .`
  - `uv run ruff check .`
- Run the full test suite after modifying code:
  - `uv run pytest`
- Add or update tests when changing behavior.
- Before committing, run:
  - `uv run pre-commit run --all-files`
- Prefer small, focused functions.

## Documentation
- Update documentation when public behavior changes.

Recent versions of Claude Code read AGENTS.md directly, so the file above works without any extra setup. If your project also has a CLAUDE.md, Claude Code gives it precedence and skips AGENTS.md. In that case, add @AGENTS.md to the top of CLAUDE.md so both tools share a single set of instructions.

Notice that the instructions tell the agent to run tools such as Ruff, pytest, and mypy. Whenever possible, rely on commands instead of conversational guidance. “Run uv run ruff format . before committing” is far easier for both humans and AI agents to follow than “make sure the code is formatted.” Tool-enforced rules produce clear pass-or-fail results and reduce ambiguity.

Keep AGENTS.md concise. Rather than copying your README.md or coding standards, link to them. A shorter instruction file is easier to maintain and requires less context for an AI agent to process before starting work.

Some agents support additional rule systems beyond AGENTS.md. For example, Claude Code supports reusable project rules stored in .claude/rules/, which can be scoped to specific directories or automatically applied when editing matching files. These are useful for practices that aren’t easily enforced by tooling, such as preferred docstring formats or guidelines for writing tests.

Similar capabilities are beginning to appear in other agents, although the configuration mechanism varies. When available, think of these rule systems as a complement to your automated tooling: use tools like Ruff, pytest, and type checkers to enforce requirements, and reserve agent-specific rules for conventions that cannot be validated automatically.

Manage Secrets Safely

Store secrets in environment variables, never in source code. Start by adding .env to your .gitignore so local secrets never get committed:

Language: Text
# Environment variables
.env

Then commit a .env.example file containing placeholder values, which shows contributors and agents which variables the project expects:

Language: Text
# Copy this file to .env and fill in the values your project needs.
# .env is git-ignored, so real secrets never reach the repository.
API_KEY=your-api-key-here

Finally, document the required variables in your README.md.

AI agents introduce one additional consideration: they can read files, shell output, and command history while completing tasks. Even if a secret is ignored by Git, it may still appear in the agent’s context or logs if the agent reads it. Before granting an agent broad filesystem access, verify how it handles sensitive files.

For example, Claude Code lets you explicitly deny access to files like .env through its permissions configuration. For production projects, consider using a dedicated secrets manager rather than local environment files. Regardless of where they’re stored, avoid pasting secrets directly into conversations with AI assistants unless you understand how the service handles prompt retention and logging.

Step 4: Review Your Python Project for Agentic Coding

By now, you’ve configured more than a collection of development tools. You’ve built a project that communicates its expectations clearly to both humans and AI coding agents. Rather than relying on increasingly detailed prompts, you’ve encoded those expectations directly into your repository.

A completed project might look something like this:

ai-agent-project/
│
├── src/
│   │
│   └── ai_agent_project/
│       └── __init__.py
│
├── tests/
│   └── test_main.py
│
├── .env.example
├── .gitignore
├── .pre-commit-config.yaml
├── .python-version
├── AGENTS.md
├── pyproject.toml
├── README.md
└── uv.lock

Five of these entries carry most of the weight:

  • pyproject.toml defines your project’s dependencies and configures tools such as Ruff, pytest, and your type checker.
  • AGENTS.md documents the workflows and conventions that can’t be enforced automatically.
  • tests/ provides executable specifications that verify behavior.
  • .pre-commit-config.yaml ensures important checks run consistently before code is committed.
  • .env.example documents the environment variables contributors need without exposing secrets.

Notice that no single file contains every rule. Project structure, tool configuration, tests, documentation, and Git hooks each communicate different expectations. Together, they create an environment where AI agents can validate their work continuously instead of relying solely on prompts.

Troubleshooting

Even with a well-configured project, you’ll occasionally encounter situations where an AI agent produces unexpected results or struggles to follow rules. The following troubleshooting tips cover some common issues and practical ways to make your project easier for AI agents to work with.

The Agent Writes Correct Code That Doesn’t Match Project Rules

Sometimes an implementation works perfectly but doesn’t follow your preferred coding style. Whenever possible, solve these issues with tooling instead of documentation. Make sure the formatters, linters, type checkers, and tests you rely on are the ones you have documented in your AGENTS.md.

The Agent Ignores Your Documented Workflow

Occasionally, an agent appears to ignore documented workflows. This often happens because the project’s guidance is fragmented or inconsistent. For example, your README.md recommends one workflow, your AGENTS.md recommends another, and the tool configuration enforces something different.

When this happens, simplify. Choose one source of truth for each topic, remove duplicated instructions, and ensure that your documentation matches the behavior enforced by your tooling. A project with fewer, clearer rules is easier for both humans and AI agents to understand.

The Agent Repeatedly Introduces Bugs During Refactoring

Refactoring is one of the areas where feedback loops provide the greatest benefit. If an agent consistently introduces regressions, ask yourself whether the project provides enough feedback.

Some ways to improve reliability include:

  • Increase unit test coverage
  • Add integration tests for critical workflows
  • Strengthen type annotations
  • Reduce the size of requested changes
  • Break large refactorings into smaller tasks

Large, open-ended requests force an AI coding agent to reason about many parts of a project simultaneously. Smaller tasks make it easier for both the agent and the automated tooling to validate correctness after each change.

Conclusion

A well-structured Python project gives AI coding agents continuous feedback. Tests verify behavior, linters enforce style, type checkers validate interfaces, and concise documentation explains the conventions that automation can’t capture. Together, these tools reduce guesswork and allow humans and AI agents to collaborate confidently.

In this tutorial, you’ve learned how to:

  • Initialize a modern Python project using uv and a standard package layout
  • Configure automated feedback loops with Ruff, pytest, type checking, coverage thresholds, and pre-commit hooks
  • Document project conventions using an AGENTS.md file while avoiding duplicated documentation
  • Manage secrets safely with environment variables and appropriate Git ignore rules
  • Spread expectations across the project so structure, configuration, tests, and hooks each carry part of the contract

The same practices that make projects easier for AI agents also make them easier for future contributors, including you. Clear structure, automated validation, and concise documentation reduce ambiguity regardless of how the code is created.

To dive deeper into how to use agents, you may want to learn more about the four workflow types of agents. If you’re looking for the right AI-powered IDE to use for your new Python project, this overview of Cursor versus Windsurf can help you make your decision.

Frequently Asked Questions

Now that you have some experience preparing a Python project for AI coding agents, you can use the questions and answers below to check your understanding and recap what you’ve learned.

These FAQs are related to the most important concepts you’ve covered in this tutorial. Click the Show/Hide toggle beside each question to reveal the answer.

Start with uv init --package to get a standard layout and a Git repository. Then add fast feedback tools like Ruff, mypy, and pytest with a coverage threshold, and run them automatically with pre-commit hooks. Finish with a short AGENTS.md file that documents the workflows your tooling can’t enforce.

The project structure is agent agnostic, so it works with nearly any AI coding assistant. If you switch agents later, the project carries its conventions with it, and the same AGENTS.md works for most of them.

No, a project can work well without one. Still, an AGENTS.md file gives you a convenient place to document workflows that your tooling can’t enforce. Most projects benefit from a short one that links to the README.md for details.

No. If a tool like Ruff or mypy can check a convention, configure the tool instead, since a failed check gives the agent clear feedback it can act on. Save AGENTS.md for the things tools can’t check, like architectural guidance and workflow expectations.

AGENTS.md is an open format that many AI coding agents read, while CLAUDE.md is specific to Claude Code. Claude Code can read either one, but if both are present it uses CLAUDE.md and skips AGENTS.md. To keep a single source of truth, add an @AGENTS.md import to the top of your CLAUDE.md.

Take the Quiz: Test your knowledge with our interactive “How to Set Up a Python Project for Agentic Coding” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

How to Set Up a Python Project for Agentic Coding

Check how well you can set up a Python project for agentic coding, with the tests, type checks, linting, and hooks that give AI agents fast feedback.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Dictionary merging in Python 3.5+

About Isabel Zimmerman

Isabel is an open source tool builder passionate about data science.

» More about Isabel

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!