Level 2 Agentic Coding · Building with AI
AI Coding Assistants and Agents
Coding assistants grew from autocomplete into agents that read a code base, edit files, run the tests and iterate. This chapter shows how they work inside, how to use them well, how to review what they produce, and where they still fail.
- Level
- ●●●●● Easy
- Reading
- 12 min
- To learn it well
- 1 hour to read, then daily practice
- Builds on
- 10 concepts →
- Quiz
- 5 questions ↓
Read first
AI AgentsThis leads to
—The full path from zero — 10 concepts before this one
- What Is AI?
- Python for AI
- How Machines Learn
- Large Language Models, Explained Simply
- Using LLM APIs
- Prompt Engineering
- Structured Output and JSON
- Chain-of-Thought and Reasoning Prompts
- Tool Use and Function Calling
- AI Agents
- AI Coding Assistants and Agents
Read them roughly in this order. See it on the concept map →
Why it matters
Software is where AI agents work best today. Code has a property most tasks lack: you can check it automatically. Run the tests, run the type checker, run the program, and you learn within seconds whether a change worked. That fast, honest feedback is exactly what the agent loop needs, so coding has become the proving ground for agents.
The tools have moved quickly. In 2021 GitHub Copilot suggested the next few lines as you typed. By 2025 coding agents such as Claude Code, OpenAI's Codex, Cursor's agent mode, Aider and others could take a request like "add CSV export to the reports page, with tests", explore the repository, edit several files, run the test suite, fix what broke and hand back a finished change. Many professional developers now use them daily. Knowing how they work is useful even if you never build one: it tells you how to give them good instructions, and what to check before you trust their output.
The intuition
There are three generations of tool, and they map onto three kinds of human help:
- Code completion is a fast typist reading over your shoulder. It predicts the next line or block from the surrounding code. It is fast, it is right often, and it needs nothing from you except a good start. Under the hood it is plain next-token prediction, often with "fill in the middle" training so it can use the code after the cursor too.
- Chat assistants are a knowledgeable colleague you can ask. You paste code and a question, and you get an explanation or a snippet back. You do the copying, running and checking.
- Coding agents are a junior developer given a ticket. They find the relevant files themselves, make changes, run the tests and keep going until done. They can do much more, and they can go wrong in much bigger ways.
The junior-developer analogy holds up well. They are quick and widely read, and they don't get tired. They also don't know your team's conventions unless someone tells them. They sometimes "fix" a failing test by changing the test. And they need code review.
Key idea A coding agent is the agent loop with tools for searching, reading, editing and running code. It is only as good as its feedback. Tests and a clear definition of "done" turn a guessing machine into one that checks its own work.
How it works
The tools
Look inside any coding agent and you'll find a small set of tools:
- Search: find files by name pattern (
glob) and find text inside files (grep, ripgrep). Agents use these constantly to locate the code that matters. - Read: show a file, or a range of lines, with line numbers.
- Edit: change a file. Making this reliable turned out to be hard (see below).
- Run: execute shell commands, such as tests, linters, builds,
git, or the program itself. - Optional extras: web fetch for documentation, MCP servers for issue trackers or browsers, and sub-agents that search a large code base and report back.
Gathering context: agentic search
The agent can't read a million-line repository at once, so how does it find the right code? There are two approaches. Early tools built an embedding index of the code base and retrieved chunks by semantic similarity, much like Retrieval-Augmented Generation. Many current agents mostly use agentic search instead: the model itself runs grep and glob, reads what it finds and follows the trail, much as a developer would. Agentic search needs no index that can go stale and handles exact identifiers well. It costs more tool calls.
Agents also read an instructions file at the start of each session: a Markdown file in the repository (CLAUDE.md for Claude Code, AGENTS.md as a cross-tool convention) that records how to build and test, coding conventions, and things to avoid. It is the onboarding document you would give a new colleague, written for the model.
Editing: the edit format
How should a model change a file? The obvious answer, "write out the whole new file", is slow and expensive for large files, and models sometimes silently drop parts of the file when rewriting it. The edit format is the convention the agent uses to express a change. Common ones:
- Whole file: simple, wasteful, risky for big files.
- Search and replace: give an exact snippet of the old text and its replacement. The tool refuses if the snippet doesn't appear exactly once, which catches the model's mistakes about what the file contains. Claude Code's edit tool works this way.
- Unified diff: the format
git diffprints. It is compact, but models often get the line numbers and context lines slightly wrong.
The Aider project documented that the choice of edit format changes a model's measured coding success noticeably. Even here, interface design matters as much as model intelligence, which is the agent-computer interface lesson again.
Feedback: tests close the loop
After editing, a good agent runs the relevant tests or the type checker. If they fail, the error message is a precise observation: file, line, expected versus actual. The agent reads it and tries again. A task with tests is a task the agent can verify. A task without tests ("make the UI nicer") leaves the agent judging its own work, which it does poorly.
Permissions and sandboxes
An agent that can run shell commands can also run rm -rf or push to production. Coding agents therefore have permission modes: ask before every edit or command, allow edits but ask before commands, or run fully automatically. Fully automatic is only sensible inside a sandbox: an isolated container or virtual machine with no access to secrets or production systems, and limited network access. Version control is your undo button. Commit before an agent starts, and review its changes as a diff.
Measuring coding agents: SWE-bench
How do we know these agents are improving? HumanEval (OpenAI, 2021) gave 164 small hand-written Python functions to complete, checked by unit tests. It was soon too easy. SWE-bench (Princeton, 2023) took 2,294 real GitHub issues from 12 popular Python repositories. The agent gets the repository and the issue text and must produce a patch. The patch is judged by running the project's tests: tests that failed before the real fix must now pass, and tests that passed before must still pass. In the original paper the best model resolved under 2% of issues. SWE-bench Verified (August 2024) is a subset of 500 issues that human engineers checked to be clear and fairly testable. By 2025 the leading agents resolved well over half of them. Check the current leaderboard rather than any number printed in a book.
Do they make developers faster?
Less obviously than you would think. In a 2025 randomised trial by METR, 16 experienced open-source developers worked on 246 real tasks in projects they knew well. Allowing AI tools (mainly Cursor with Claude models, as of early 2025) made them 19% slower on average. Before starting, they had predicted a 24% speed-up, and afterwards they still believed they had been about 20% faster. That doesn't mean coding agents are useless. The setting was experts in large, familiar code bases with high quality standards, and the tools have improved since. But it is a strong warning that feeling productive and being productive differ. Measure on your own work.
In code
A miniature coding agent's tool layer: a search-and-replace edit tool that refuses ambiguous edits, and a test runner whose output is the feedback. As in AI Agents, a scripted list of steps stands in for the model so the loop is checkable offline. Runs as written.
import pathlib, subprocess, sys, tempfile
repo = pathlib.Path(tempfile.mkdtemp())
(repo / "stats.py").write_text("def mean(xs):\n return sum(xs) / len(xs) + 1\n") # a bug
(repo / "test_stats.py").write_text(
"from stats import mean\nassert mean([2, 4]) == 3, mean([2, 4])\nprint('all tests pass')\n")
def read_file(path):
return (repo / path).read_text()
def str_replace(path, old, new):
text = (repo / path).read_text()
if text.count(old) != 1: # refuse ambiguous or missing edits
return f"Error: old text found {text.count(old)} times; it must be unique"
(repo / path).write_text(text.replace(old, new))
return "edited"
def run_tests():
r = subprocess.run([sys.executable, "test_stats.py"], cwd=repo, capture_output=True, text=True)
return "PASS: " + r.stdout.strip() if r.returncode == 0 else "FAIL: " + r.stderr.strip().splitlines()[-1]
TOOLS = {"read_file": read_file, "str_replace": str_replace, "run_tests": run_tests}
script = [ # what a model might do; a real agent chooses each step from the last result
("run_tests", {}),
("read_file", {"path": "stats.py"}),
("str_replace", {"path": "stats.py", "old": "xs", "new": "values"}), # ambiguous: refused
("str_replace", {"path": "stats.py", "old": " + 1", "new": ""}),
("run_tests", {}),
]
for step, (tool, args) in enumerate(script, 1):
result = TOOLS[tool](**args)
print(f"{step}. {tool}{args or ''} -> {result!r}")
if result.startswith("PASS"):
break
# 1. run_tests -> 'FAIL: AssertionError: 4.0'
# 2. read_file{'path': 'stats.py'} -> 'def mean(xs):\n return sum(xs) / len(xs) + 1\n'
# 3. str_replace{'path': 'stats.py', 'old': 'xs', 'new': 'values'} -> 'Error: old text found 3 times; it must be unique'
# 4. str_replace{'path': 'stats.py', 'old': ' + 1', 'new': ''} -> 'edited'
# 5. run_tests -> 'PASS: all tests pass'
Step 1 is the habit that matters most: run the tests before editing, so you know what "broken" looks like. Step 3 shows why the edit tool insists on a unique match. A blind replace-all would have renamed the parameter in three places, which was not the intended change.
Using coding agents well
- Write the instructions file. Build and test commands, style rules, directories to avoid. A few dozen lines save many corrections.
- Give it a way to check its work. Point it at the tests, or ask it to write a failing test first and then make it pass.
- Ask for a plan before code on anything non-trivial, and correct the plan. That is cheaper than correcting the code.
- Keep tasks small and specific. "Add a
--jsonflag to theexportcommand that writes the same fields as the CSV" beats "improve export". - Commit often, so a wrong turn costs one
git reset. - Start a fresh session for a new task, so stale context from the last one doesn't mislead it.
Reviewing what it produces
Read the diff as you would a stranger's pull request:
- Does it do what was asked, and only that? Look for unrequested refactors.
- Were tests changed? Weakened assertions, deleted tests or new
skipmarkers are red flags. - Do the functions, libraries and versions it uses actually exist? Check imports and new dependencies.
- Are errors handled, or silently swallowed?
- Security: input validation, SQL built by string concatenation, secrets in code, overly broad permissions.
- Would you understand this code in six months? Agents often produce verbose, over-defensive code.
Common pitfalls
- Plausible but wrong. Code that reads well and passes a shallow test can still mishandle edge cases. Ask for tests of edge cases (empty input, unicode, time zones) explicitly.
- Invented APIs. Models sometimes call library functions that don't exist, or use an older version's API. Running the code catches most of these. Reading the docs catches the rest.
- Made-up packages. Models sometimes suggest dependencies that don't exist, and attackers have registered such names with malicious code (called "slopsquatting"). Check every new dependency before installing it.
- Tampering with the check. Told to make the tests pass, agents sometimes edit the tests or special-case the test inputs. Say "don't modify tests" and check the diff.
- Scope creep and context drift. Long sessions wander. Restate the goal, or start fresh.
- Over-trust. The METR result shows how easy it is to feel faster without being faster.
Watch out Never run an agent in fully automatic mode on a machine with production credentials, SSH keys or customer data. A prompt injection hidden in a README, an issue or a web page the agent reads can make it run commands on your behalf. Use a sandbox or container, limit network access, and keep approval switched on for anything that leaves the machine.
Where it leads
- Evaluating LLM Applications: SWE-bench is one kind of eval. For your own code base, the best eval is your own test suite plus a set of past tasks.
- Model Context Protocol: connect agents to your issue tracker, documentation or browser.
- Multi-Agent Systems: sub-agents for searching big code bases. Keep the editing in one agent.
- Context Engineering and Memory: instructions files, compaction and memory are what make long coding sessions work.
- Building AI Products: the same principles (feedback, guardrails, human review) apply to any agent you ship.
A bit of history
OpenAI's Codex model (2021), a GPT-3 fine-tuned on public code, powered GitHub Copilot, whose preview launched in June 2021, and was measured with the new HumanEval benchmark. DeepMind's AlphaCode (2022) reached roughly median human performance in programming competitions by sampling huge numbers of candidate programs and filtering them. Chat-based coding help followed ChatGPT in late 2022. Agentic tools appeared in 2023 and 2024: Aider pioneered terminal-based pair programming with git integration, Cognition's Devin (March 2024) was announced as an "AI software engineer", and SWE-agent showed that interface design mattered. In 2025 agentic coding went mainstream with Claude Code, OpenAI's Codex agent, and agent modes in Cursor, VS Code and other editors, and SWE-bench Verified scores rose steeply through the year.
Try it
- Add a
grep(pattern)tool to the mini agent that returnspath:line: textfor every match in the repo. Use it to find wheremeanis defined.- Add a second test that checks
mean([])raisesValueError. Run the script: the old fix now fails the suite. Write the extra script steps that make it pass.- Pick a small real task in one of your own projects. Do it once by hand and once with a coding agent, timing both and counting how many corrections the agent needed. Was it faster?
Hint for 2: the edit must replace the
returnline with anif not xs: raise ValueError(...)check followed by the return. Youroldstring must be unique.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Claude Code: Best practices for agentic coding
Concrete workflows for coding agents: CLAUDE.md files, explore-plan-code-commit, test-driven loops, course-correcting early, and running agents safely.
SWE-bench: Can Language Models Resolve Real-World GitHub Issues?
Real GitHub issues from Python projects, scored by whether the model's patch makes the project's tests pass.
SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering
Shows that designing the agent's tools (file viewer, search, editor with linting) carefully, the agent-computer interface, greatly improves success at fixing real GitHub issues.
Aider
An open-source AI pair programmer in the terminal that works with many models and commits each change to git. Its docs on edit formats and its leaderboards are instructive.
Evaluating Large Language Models Trained on Code
The Codex paper: a GPT model fine-tuned on public code, the HumanEval benchmark of 164 hand-written problems, and the pass@k metric.
Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity
A randomised trial with 16 experienced developers on 246 real tasks: allowing AI tools made them 19% slower, although they believed it made them faster.
Claude Code documentation
Docs for Anthropic's terminal-based coding agent: setup, permission modes, memory files, MCP servers, sub-agents, hooks and the Agent SDK.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/coding-agents.md