DEV Community

Cover image for Build Self-Healing LangChain Deep Agents
Shivam Katare for Studio1

Posted on Originally published at studio1hq.com

Build Self-Healing LangChain Deep Agents

Have you ever watched an AI agent stop halfway through a task because one tool call failed? Or keep retrying a call that was never going to work?

Tool failures are hard to handle because they all look alike. When an API is busy, the right move is to wait and try again. When the agent sends the wrong input, it should fix the input. When the API key has expired, a person has to create a new one. And when the tool's own code has a bug, someone has to change the code. Four different problems, four different fixes, but the agent sees the same thing every time: an error.

A NeurIPS 2026 study tested this at scale. The authors took real tool faults from 57,240 issues and pull requests across 1,774 MCP repositories and injected them into AI agents. When most faults were permanent, task scores fell by 60%, and a 120B model did no better than a 20B one. In the traces, the agents treated every failure as temporary and kept retrying with small changes.

In this tutorial, we'll build a self-healing agent using LangChain's Deep Agents and DeepSeek-V4.1-Flash-1017-fast on Nebius Token Factory. The agent builds a monthly LLM cost report. When one of its tools fails, it works out why, and it repairs the tool's code only when the code is actually wrong.

To test it, we'll break the same task eight different ways and run each one three times, on the same Deep Agent with and without our self-healing layer. Without it, the agent finished 3 of 27 runs. With it, it finished all 27.

Here's one of those runs, from the crash to the fix:

Self-healing agent

What is Deep Agents?

DeepAgents Image

Deep Agents is an open-source Python library from LangChain for building agents that take on longer, multi-step jobs. You give it a model, a set of tools, and some instructions. It handles the loop in between: it sends the request to the model, runs whichever tool the model asks for, passes the result back, and keeps going until the job is finished.

It sits on top of LangChain and LangGraph, so it works with any LangChain chat model that can call tools. The whole agent is created with one function, create_deep_agent.

What makes it more than a basic loop is what comes built in:

  • File tools. The agent can list, read, and search files, and you decide which folders it's allowed to read or write.
  • Sub-agents. The main agent can hand a task to a helper agent. The helper works in its own separate conversation and returns one short answer.
  • Middleware. You can run your own code every time the agent calls the model or a tool.
  • Planning and approvals. It can keep a to-do list for long tasks, and pause so a person can approve chosen actions.

We'll use three of these. Middleware sorts every failure, a sub-agent fixes the broken code, and file permissions let that fixer read the code without writing anywhere. Repairing tools isn't something Deep Agents does on its own. That's the part we'll build.

What we're building

To test a self-healing agent, we first need an agent with a real job to do, and tools that can break in realistic ways.

So the agent we'll build makes a monthly cost report for LLM usage. If your team calls models through an API, you've probably seen one of these: how many requests went to each model, how many tokens they used, and what it all cost. Our agent builds that report on its own, for November 2026.

It works the same way a person would. First, it downloads the month's request logs from the provider's billing API. Then it adds up the tokens for each model, looks up each model's prices, and writes everything into a CSV file. Each of those four steps is a separate tool, which is just a small Python function the agent can call.

The agent calls fetch_usage, summarize_usage, fetch_pricing and export_report in order; two read the local billing API, the last writes the CSV.

The billing API here isn't a real provider. It's a small server that runs on your own machine, and that's on purpose. To see how the agent handles failures, we need to trigger them on demand: rename a field in the API response, return a rate-limit error, or expire the API key. A real provider won't do any of that when you ask.

We picked a cost report for one more reason: it has a single correct answer. Because we control the API, we can work out the true cost straight from its data, without going through the agent's tools at all. For November, it comes to $0.01402. So after every run, we compare the agent's CSV with that number. If they don't match, the run failed, even when the agent says it finished.

The full project is in the Awesome AI Apps repo, including the broken version of each tool, so you can run every situation in this article yourself. All it needs is a Nebius API key. We'll start with the plain agent and add one piece in each step.

Step 1: Start with a plain Deep Agent

Before we add anything clever, we need an agent that can do the job on a good day.

Deep Agents handles most of that for us. LangChain calls it "the agent harness for complex, multi-step work,", and in practice it runs the agent loop. We give it a model, some tools and instructions. The model picks a tool, Deep Agents runs it and hands the result back, and this repeats until the job is done.

It also comes with a few pieces we'll need later: a way to run our own code around every tool call, sub-agents that can take over a task, and built-in tools for reading files. For now, we only need the loop.

Install it, along with langchain-nebius, which connects LangChain to models on Nebius:

uv add deepagents langchain-nebius
Enter fullscreen mode Exit fullscreen mode

From that package, we use the ChatNebius class. By default, it points to Nebius's older endpoint, so we pass the Token Factory URL ourselves:

from langchain_nebius import ChatNebius

model = ChatNebius(
    model="deepseek-ai/DeepSeek-V4.1-Flash-1017-fast",
    base_url="https://api.tokenfactory.nebius.com/v1/",
    api_key=os.environ["NEBIUS_API_KEY"],
    temperature=0,
)
Enter fullscreen mode Exit fullscreen mode

Next come the tools. Each one is an ordinary Python function in its own file. Here's the pricing tool, which asks the billing API for a model's prices and returns them in a simple shape:

def fetch_pricing(model_id: str) -> dict:
    data = get_json(f"/v2/models/{quote(model_id, safe='')}")
    return {
        "model": data["model"],
        "input_usd_per_1m": float(data["pricing"]["unit_usd"]),
        "cached_usd_per_1m": float(data["pricing"]["cached_unit_usd"]),
        "output_usd_per_1m": float(data["pricing"]["output_unit_usd"]),
    }
Enter fullscreen mode Exit fullscreen mode

Keep an eye on those data["pricing"] lines. They're the first thing we'll break.

Now we hand the model, the four tools, and a short set of instructions to Deep Agents:

from deepagents import create_deep_agent
agent = create_deep_agent(
    model=model,
    tools=tools,  # fetch_usage, summarize_usage, fetch_pricing, export_report
    system_prompt=PROMPT,
}
agent.invoke({"messages": [{"role": "user", "content": "Build the LLM cost report for 2026-11."}]})

Enter fullscreen mode Exit fullscreen mode

The instructions describe the job: call the four tools in order, then reply with the total cost, the most expensive model, and where the CSV was saved.

In the repo, each tool is wrapped so that it loads its file fresh on every call. That doesn't matter yet, but it will once the agent starts editing those files.

Here's what a normal run looks like:

1.0s  tool  fetch_usage({"month": "2026-11"})
1.1s  ok    {"rows_fetched": 26, "total_reported": 26, ...}
2.1s  tool  summarize_usage({"path": "data/usage_2026-11.json"})
2.1s  ok    {"requests": 26, "models": [...]}
4.7s  tool  fetch_pricing x3 (one call per model)
4.8s  ok    prices for all 3 models
6.2s  tool  export_report({"rows": [...]})
6.2s  ok    {"path": "reports/cost_report_2026-11.csv", "rows": 3, "total_cost_usd": 0.01402}
7.7s  done  Total cost: $0.01402. Most expensive model: DeepSeek-V4.1-Flash-1017-fast.

Enter fullscreen mode Exit fullscreen mode

The total matches the true cost of $0.01402. I ran it three times, and all three reports were correct. Each run took about 7.5 seconds and cost about half a cent.

So on a good day, a plain Deep Agent handles this job well. Next, let's see what happens on a bad one.

Step 2: Break it, and watch the plain agent fail

Now we break things. I set up eight situations, each based on something that really happens to agents in production. The task stays the same in every one: build the November cost report. Only the failure changes.

The first four are real bugs in the tool's code. The other four aren't bugs at all, so the right move there is to leave the code alone.

I ran the plain agent from Step 1 three times in each situation. It finished only the 3 healthy runs, and none of the broken ones. It failed the same way every time, and the failures fell into three patterns.

Situation What goes wrong The right move
API renamed its pricing fields fetch_pricing reads a field that no longer exists Fix the tool
Messy log data Some token counts arrive as text, like "1,240" Fix the tool
Silent bad output The CSV is written without its cost column, and no error is raised Fix the tool
Pagination bug fetch_usage reads only page 1 of 3 Fix the tool
Rate limited The API answers "429 Too Many Requests" twice Wait and try again
Retired model id The logs use an old model name, and the API's 404 names the new one Call again with the new name
Expired API key Every call gets "401 Unauthorized" Stop and tell a person
Two tools broken The renamed fields and the missing column, in the same run Fix both tools

Most of the time, one error ended the whole run. In six of the eight situations, the agent never got a chance to react. The tool raised an error, and the run stopped right there, with no answer and no report.

The plain agent on the renamed-fields bug. One \ raw `KeyError\` endraw , and the run is over.

This comes from the layer Deep Agents runs on. By default, LangGraph's tool runner passes only one kind of error back to the model: when the model calls a tool with invalid arguments. Every other error is raised again, and that ends the run.

That includes the two failures that were easy to handle. A rate limit only means "wait a second and try again." The retired-model error even named the model to use instead. The answer was right there in the API's reply, but the run stopped before the agent could read it.

When nothing crashed, it called a broken report a success. In the silent-output case, the CSV came out without its cost column. The agent still replied, "Report built for 2026-11 (3 models, 26 requests). Total cost: $0.01402." The number in its reply was right, but the file had no costs in it. That happened in all three runs.

When it spotted the problem, it couldn't fix it. In the pagination case, the model noticed it had 10 rows while the API reported 26, and it stopped: "I stopped before exporting, because the data is incomplete." That was the right call. But it had no way to fix the tool, so the report was never made.

So the plain agent has two problems. Errors either end the run or never reach the model as errors at all. And even when the model understands what went wrong, it has nothing it can do about it.

LangChain does have a middleware for this, ToolErrorMiddleware, which sends errors back to the model instead of ending the run. But then a renamed field, a rate limit, and an expired key all reach the model as the same thing: "the tool call failed." That's exactly what the study in the intro found agents struggling with. So in the next step, we sort each failure before the model sees it.

Step 3: Sort the failure before fixing anything

The plain agent's real problem is that it can't tell failures apart. So before we add anything that fixes code, we add something that looks at each failure and works out what kind it is.

Deep Agents gives us a clean place to do that: middleware. Middleware is a piece of your own code that wraps every tool call. When the agent calls a tool, the call passes through it on the way out, and the result or the error passes through it on the way back. That's exactly where we want to stand, between the agent and its tools.

To sort a failure, the middleware needs two clues:

  1. The first is the API's status code. We make the small HTTP client our tools share turn each kind of API error into its own error type: a 429 becomes a RateLimitError, a 401 becomes an AuthError, a 404 becomes a RequestError. The agent can read this client but can't edit it.
  2. The second clue is whether the tool's own output makes sense. A crash is easy to spot, but the silent-output case from Step 2 never crashed. So after every call, we run a quick check on what the tool returned. For example, if fetch_usage says it saved 10 rows but the API reported 26, that's an error, even though nothing crashed:
def _check_usage(args, result):
    rows = json.loads(Path(result["path"]).read_text())
    if len(rows) != result["total_reported"]:
        raise ContractError(f"fetch_usage saved {len(rows)} rows but the API reported "
                            f"total={result['total_reported']}. Some request logs are missing.")

Enter fullscreen mode Exit fullscreen mode

With those two clues, every failure gets one of four labels:

A failed tool call passes the middleware's rule and gets one label: TEMPORARY, BAD_ARGUMENTS, NEEDS_HUMAN or CODE_BUG. Only CODE_BUG edits code.

Here's the middleware, shortened so the idea is easy to see:

class HealingMiddleware(AgentMiddleware):
    def wrap_tool_call(self, request, handler):
        try:
            return handler(request)                  # run the tool as usual
        except RateLimitError:
            ...                                      # wait, then run it again (up to 3 times)
        except AuthError as exc:
            return label("NEEDS_HUMAN", "The API key was rejected. No code change can fix this. "
                                        "Stop and tell the user what to do.")
        except RequestError as exc:
            return label("BAD_ARGUMENTS", f"The API rejected these arguments. Its reply: {exc.body}")        except Exception as exc:                     # a crash inside tools/, or a failed check
            return label("CODE_BUG", ...)

Enter fullscreen mode Exit fullscreen mode

And we hand it to Deep Agents with one extra line:

agent = create_deep_agent(model=model, tools=tools, system_prompt=PROMPT,
                          middleware=[HealingMiddleware(healer)])

Enter fullscreen mode Exit fullscreen mode

Notice that no model call decides the label. That's on purpose. A 429 always means "wait", and an expired key always needs a person, so a simple rule gets it right every time, instantly and for free. The model's job starts after the label: reading the API's reply, choosing better input, explaining the problem to the user, and, for real bugs, writing the fix.

That's also why we don't just add LangChain's ToolRetryMiddleware and retry everything. Retrying is right for a busy API, but a tool with a bug fails the same way every time, no matter how often you call it.

This step alone already fixes three of the eight situations. With the rate limit, the middleware waited a second, tried again, and the run finished with the correct report. Nobody touched the code.

The 429 run: two retries, a correct report, and "No code changed."

With the retired model, the agent read the API's reply and called fetch_pricing again with the new name. It even mentioned the change in its answer: "Qwen/Qwen3-235B-A22B-Instruct was retired and billed as Qwen/Qwen3-235B-A22B-Instruct-2507."

The retired model: the API's 404 names the new model, and the agent calls again with it.

With the expired key, it stopped and wrote: "I can't build the 2026-11 report. The provider rejected the API key… Create a new API key in the provider's billing console." That's a lot more useful than a raw 401 error.

The expired key: sorted as NEEDS_HUMAN, so the agent stops and says what to do.

That leaves the four real bugs. Each now gets the CODE_BUG label. Next, we give the agent what it needs to fix them.

Step 4: Show the fixer what a developer would look at

When a tool fails with a real bug, what would you want to see before fixing it?

Probably the error, the input that caused it, the line where it broke, the values of the variables on that line, and the code itself. Then, once you'd written a fix, you'd run the tests.

So that's what the middleware collects. For every CODE_BUG, it writes a failure report, a plain Markdown file in a failures/ folder. Here's part of the real report for the renamed-fields bug:

# Failure report: tools/fetch_pricing.py
error: KeyError: 'price_usd'
args: {"model_id": "meta-llama/Llama-3.3-70B-Instruct"}
## Values at the crashing line
data = {'model': 'meta-llama/Llama-3.3-70B-Instruct', 'api_version': '2026-11-01',
        'pricing': {'unit_usd': 0.13, 'cached_unit_usd': 0.013, 'output_unit_usd': 0.4, ...}}
## HTTP calls the tool made
GET /v2/models/meta-llama%2FLlama-3.3-70B-Instruct -> 200

Enter fullscreen mode Exit fullscreen mode

Below that, the report also has the traceback, the tool's full source, and the output of its tests.

Look at the data line. The code asked for price_usd, but the API now sends the prices inside a pricing object, under new names. Anyone reading this can see the fix, and so can the model. In every run, it changed the three lookups to read from data["pricing"], and nothing else.

I didn't get this report right the first time, though.

My first version had no "HTTP calls" section. That was fine for crashes, because the crash values showed what the API had sent back. But the pagination bug never crashes. fetch_usage returns normally, and only the output check notices the missing rows. So there were no crash values, and the fixer had no idea how this API pages its results.

So it guessed. Its first patch asked the API for an offset parameter that doesn't exist. The tests failed, and the patch was rolled back. Its second patch was 46 new lines that tried four different paging styles one after another. It also wrapped every request in except Exception: return {}.

That patch passed the tests, so it was kept. But it was a bad patch. That except line would have turned a rate limit or an expired key into "no data, carry on", which is exactly the kind of failure we're trying to stop hiding.

The fix was to record every HTTP call a tool makes, like the network tab in your browser, and add it to the report. The pagination report now showed the API's actual reply:

## HTTP calls the tool made
GET /v2/usage?month=2026-11 -> 200
  {"page": 1, "next_page": 2, "total": 26, "data": [{...}, "... 9 more items"]}
There it is: "next_page": 2. With that, the fixer wrote a short loop that follows next_page until it runs out, in all three runs:
-    payload = get_json(f"/v2/usage?month={month}")
-    rows = payload["data"]
-    total = payload["total"]
+    rows = []
+    page = 1
+    total = 0
+    while page is not None:
+        payload = get_json(f"/v2/usage?month={month}&page={page}")
+        rows.extend(payload["data"])
+        total = payload["total"]
+        page = payload.get("next_page")
Enter fullscreen mode Exit fullscreen mode

Same model, same prompt. The only thing that changed was what it could see. That's the main lesson of this step: before blaming the model for a bad fix, check what you showed it.

Step 5: Hand the bug to a sub-agent

We now have a good failure report. The next question is who reads it and writes the fix.

The main agent could do it itself, but that's messy. It's in the middle of building a report, and a fix means reading the failure report, the tests, the output checks, and the tool's code. All of that would land in the main agent's conversation and stay there until the run ends, even though none of it has anything to do with the cost report.

So we give the job to a separate agent. Deep Agents calls these sub-agents. A sub-agent starts with a fresh conversation, does one task, and sends back a short answer. Everything it reads along the way stays with it.

Adding one takes a few lines in create_deep_agent:

agent = create_deep_agent(
    model=model,
    tools=tools,
    system_prompt=PROMPT,
    middleware=[HealingMiddleware(healer)],
    subagents=[{
        "name": "tool-fixer",
        "description": "Repairs a tool in tools/ that has a CODE_BUG. Give it the tool name "
                       "and the failure report path.",
        "system_prompt": FIXER_PROMPT,
        "tools": [repair_tool],
        "model": model,
    }],
)
Enter fullscreen mode Exit fullscreen mode

Deep Agents then gives the main agent a task tool for handing work to tool-fixer. When a tool fails with CODE_BUG, the middleware's message tells the main agent exactly that:

call task with the tool's name and the report's path, then repeat the failed call once the fixer says the repair is verified.

The fixer's instructions are short. Read the failure report. If you need more, read the tool's tests or the output checks. Then call repair_tool with the smallest change that fixes the cause, and don't hardcode the test inputs.

For reading those files, the fixer uses Deep Agents' built-in read_file tool. We point it at the project folder, but with tight permissions:

PERMISSIONS = [
    FilesystemPermission(operations=["read"], mode="allow",
                         paths=["/tools/**", "/tests/**", "/failures/**", "/contracts.py"]),
    FilesystemPermission(operations=["read", "write"], mode="deny", paths=["/**"]),
]
Enter fullscreen mode Exit fullscreen mode

The fixer can read the tools, their tests, the failure reports, and the output checks. Everything else is off limits, including the .env file with the API key. It can't write anything at all. We also turn off Deep Agents' built-in editing tools, so the only way to change code is repair_tool, which we'll build next.

Here's the fixer at work on the renamed-fields bug. It read the failure report first, then the tests and the output checks, then the tool's source:

The main agent hands the bug over, and tool-fixer reads before it writes anything.

The main agent hands the bug over, and tool-fixer reads before it writes anything.

And here's why the separate conversation matters. By the time the fixer finished, its conversation had grown to almost 5,000 tokens. The main agent's grew by just 190, mostly the fixer's one-sentence answer:

REPAIR VERIFIED. The tool was reading flat price_usd / cached_price_usd / output_price_usd fields, but the API now nests them under pricing as unit_usd / cached_unit_usd / output_unit_usd.

Step 6: Don't trust a fix until it's tested

The fixer has everything it needs to write a patch. Now we need to make sure a bad patch can never stick around.

That's the job of repair_tool. It's the only way any code changes in this project, and it doesn't let the fixer write files directly. Instead, the fixer describes the change as small find-and-replace edits: "find this exact text, replace it with this." That keeps each fix small and easy to review, and it stops the model from rewriting a whole file when one line is wrong.

Every patch then goes through the same checks, in this order:

def repair(self, tool_name, reason, edits):
    if tool_name not in self.open_bugs                 # 1. only tools with a real code bug 
       return "REPAIR REFUSED: ..."
    if self.repairs_used.get(tool_name, 0) >= 2:  # 2. at most two tries per tool
        return "REPAIR REFUSED: ..."
    path = tool_path(tool_name)                   # 3. only files inside tools/
    new = apply_edits(old, edits)                 # 4. each "find" must match exactly once,
    ast.parse(new)                                #    and the result must be valid Python
    shutil.copy2(path, backup)                    # 5. keep a backup, then save the patch
    path.write_text(new)
    tests_ok, _ = self.run_tests(tool_name)       # 6. run the tool's tests,
    replay_ok, _ = self.replay(tool_name)         #    then the exact call that failed
    if not (tests_ok and replay_ok):
        shutil.move(backup, path)                 # 7. anything fails: put the old file back
        return "REPAIR FAILED VERIFICATION (rolled back) ..."
    return "REPAIR VERIFIED ..."
Enter fullscreen mode Exit fullscreen mode

That's shortened for the article, but the order is real. A few of these checks are worth a closer look.

  • Check 1 ties back to Step 3. A tool can only be repaired if the middleware labeled its last failure as CODE_BUG. So even if the model somehow decided to "fix" fetch_pricing after a rate limit, repair_tool would refuse.
  • Check 6 runs in a separate Python process. The tests and the replay never share memory with the running agent, so a patch can't pass because of something left over in memory. The replay matters as much as the tests. The tests check the cases someone thought of in advance. The replay checks the exact input that broke the tool a minute ago.
  • Check 7 is what makes mistakes safe. You saw it in Step 4: the fixer's first pagination patch failed its tests, the old file came back, and the fixer got the test output so it could try again.

On the renamed-fields bug, the checks took about four and a half seconds, and the patch was kept:

The patch, after the tests passed and the failed call worked again.

I also wanted proof that these checks hold without trusting the model, so I tested them directly, with no model calls at all. There are 10 of these tests. They try a patch on a tool with no open bug, a third attempt, a patch with broken syntax, and a patch that fails the tests. Each one is refused or rolled back, and the file always ends up exactly as it was. The same tests also check the sorting from Step 3: a 429 gets retried, a 401 needs a person, a retired model is a bad argument, and wrong output counts as a code bug. All 10 pass, along with the 9 tests for the tools themselves.

These checks make a bad patch hard to keep, though not impossible. Step 4's 46-line pagination patch passed every test, and it was still a bad patch. The tests decide what "fixed" means, so the agent can only be as careful as the tests you give it.

Step 7: Run all nine, three times each

Time to put everything together and run the full test. Both agents got the same task, the same model, the same tools, and the same nine situations: the healthy run plus the eight broken ones. Each situation ran three times.

To count as a pass, a run had to get two things right. The report's costs had to match the true cost we work out from the API's data. And the agent had to change exactly the files that were broken, and nothing else. For the expired key, "right" meant stopping without a report and telling the user what to do.

Situation Plain Deep Agent Self-healing agent Avg time Avg cost
Healthy run 3/3 3/3 6.5s $0.0031
API renamed its pricing fields 0/3 3/3 20.0s $0.0080
Messy log data 0/3 3/3 21.6s $0.0083
Silent bad output 0/3 3/3 20.4s $0.0087
Pagination bug 0/3 3/3 18.6s $0.0077
Rate limited 0/3 3/3 7.9s $0.0037
Retired model id 0/3 3/3 7.5s $0.0044
Expired API key 0/3 3/3 2.0s $0.0007
Two tools broken 0/3 3/3 32.9s $0.0131
Total 3/27 27/27

Time and cost are for the self-healing agent.

Every patch in these runs was kept on its first try, including both fixes in the two-tools run. In the situations that weren't bugs, no file changed at all.

A single-bug run took about 20 seconds from start to finished report, and cost under a cent. That includes the crash, the failure report, the fixer's work, the tests, the replay, and the rest of the report.

Here's the whole thing in one go: the renamed-fields run from start to finish, then the rate limit and the expired key.

Timeline: the renamed-field bug is patched and tested in 21.2 s, the 429 run retries and ends at 7.5 s, the expired key stops the run at 2.0 s.

All 27 runs together cost $0.17. That's 911,762 input tokens and 43,543 output tokens across 243 model calls, at Nebius's prices of $0.60 per million input tokens, $0.012 per million cached input tokens and $2.40 per million output tokens.

The number that keeps it cheap is caching: 89% of those input tokens came from the cache, at a fiftieth of the normal input price. That matters here because every model call starts with the same block of instructions and tool descriptions, about 3,000 tokens. Most of it comes from Deep Agents itself. In an early test, an agent with one tiny tool and a one-line prompt already sent 2,888 tokens on its first call. Because that block is identical on every call, it's cached almost every time.

We also trimmed it a little. Our agent switches off the Deep Agents tools it doesn't need, like the built-in editing tools and the to-do list. Its first call sent 3,079 tokens, against 3,468 for the plain agent.

The plain agent's 27 runs cost less in total, $0.055, but only because most of them ended within a few seconds of starting.

Wrapping up

Most of this agent is a normal Deep Agent. Three additions are what let it fix itself:

  • It sorts every failure before reacting. A busy API gets a retry, a wrong argument gets corrected, an expired key goes to a person, and only a real bug gets a code change.
  • It shows the fixer what a developer would look at: the error, the input, the values at the crash, the API's actual replies, the code, and the tests.
  • It keeps a patch only if it proves itself. The tool's tests have to pass, and the call that failed has to work, or the old file comes back.

Deep Agents kept each of these short to build. Middleware gave us one place to see every tool call. Sub-agents kept the fixing out of the main conversation. And file permissions let the fixer read the code without being able to write anywhere else.

It has limits. These were small, common bugs, not tricky logic errors. The fixer is only as careful as your tests, as the 46-line pagination patch showed. And in a real project, I'd let it patch on a branch and have a person review the diff before it ships.

I ran everything on Nebius Token Factory. The fast DeepSeek endpoint answered most model calls in a little over a second, and with caching, all 54 runs of both agents cost less than 25 cents together.

The code, both benchmarks and the replay player, is in our repo. To see the hardest case, run uv run run_demo.py S8 and watch it fix two tools in one run.

What's the most boring failure that has ever broken your agent?

Top comments (0)