Home / Articles

Five Agent Engineering Patterns Worth Borrowing From DeepSeek's Harness

Event-log-as-truth, graded loop warnings, explicit truncation, permission-checked code mode and fresh-agent handoffs: five patterns for building debuggable agent systems.

Publisher: REACTAPP.TOP9 min read1995 words

This article is published in English.

Sources: 5 Agent-Engineering Patterns I Learned From DeepSeek’s Open-Source Harness

Agents keep getting better at writing code, calling tools, searching files and sticking with long tasks. Underneath all that sits a duller problem: what keeps an agent from turning messy, unpredictable and close to impossible to debug? Reading through the engineering choices in DeepSeek's open-source agent harness turns up five ideas that are worth borrowing even if you never touch the harness. They're not DeepSeek tricks so much as sound patterns for agent systems generally.

1. Make the event log the source of truth

Most agent systems hold the conversation in a list that is handed to the model:

messages = [...]

Elsewhere, a logger records what happened:

logger.info({
    "messages": messages,
    "tool_calls": tool_calls,
    "tokens": tokens
})

That seems reasonable, but it produces two accounts of the same events, and that's the risky part. Suppose the application edits the message list before sending it, for instance by slipping in an extra instruction:

messages.append({
    "role": "system",
    "content": "Remember to be concise."
})

If the event log never recorded that edit, the model saw something your logs know nothing about. Six hours later the agent does something strange, and you open the logs wondering why. The explanation could be a system message that doesn't appear anywhere in the recorded history.

The better approach

Make the event log the single authority. It holds the facts, such as the user's request, each tool call, each result and the assistant's replies:

events = [
    UserMessage("Fix the authentication bug"),
    ToolCall("grep", {"query": "auth"}),
    ToolResult("Found 12 matches"),
    AssistantMessage("I'll inspect the middleware")
]

The model's context is then derived from those events and not kept as a separate list:

def build_context(events):
    return [
        event.to_message()
        for event in events
        if event.visible_to_model
    ]

The point is that no private, hidden message array exists. You compute it each time. Compare the two shapes. The preferred one runs from the log through a context builder to the request:

Event Log
    ↓
Context Builder
    ↓
LLM Request

The one to avoid forks the log, with one branch feeding logs and another feeding the messages that go to the model:

Event Log ─────────→ Logs
       \
        → Messages ─→ LLM

That small structural change makes debugging far easier.

Go further and verify it

During development you can add a check that rebuilds the expected context from the log and compares it with what is really about to be sent:

expected = build_context(event_log)
actual = request.messages
if actual != expected:
    raise RuntimeError(
        "log-reconstruction desync"
    )

With that in place, drift in context becomes a failing test and no longer a puzzling production bug. There's a bonus too. Observability gets much more useful. If a trajectory view shows model calls, tool calls, tool results, token usage and timing, nobody has to assemble a separate story of what happened, because the information is already present: the agent needs it to rebuild its own context. A single source of truth ends up doing two jobs.

2. Don't hard-block agent loops straight away

Every agent developer meets this sooner or later. The model runs the same search again and again:

grep "authentication"
grep "authentication"
grep "authentication"
grep "authentication"
...

The problem is plain, and the obvious fix is plain as well: refuse repeated calls.

if previous_call == current_call:
    raise LoopError()

Trouble is, repetition is sometimes legitimate. A network request can fail, a file may have changed, and a retry may really be needed. Rather than blocking the model, warn it.

Picture a pressure system that grows with the repeat count:

3 repeats → gentle reminder
5 repeats → stronger reminder
8 repeats → very strong reminder

The first level might say that the same tool call is being repeated and suggest re-reading the last result:

if repeat_count >= 3:
    inject(
        "You are repeating the same tool call. "
        "Re-read the last result and consider another approach."
    )

The second level is firmer, telling the agent to stop and reassess:

if repeat_count >= 5:
    inject(
        "You have repeated this exact operation several times. "
        "Stop and reassess the approach."
    )

By the third, the message says this looks like a loop and the approach needs to change, or the work should be wrapped up:

if repeat_count >= 8:
    inject(
        "This appears to be a loop. "
        "Change your approach or wrap up."
    )

Notice what the harness doesn't do. It never returns a flat refusal like this:

return False

Control stays with the model. The harness only supplies more information and lets the model decide, which is an important distinction.

Count real repeats

A good detector can't be fooled by unrelated calls slipped in between. This sequence should still count as repetition:

grep foo
todo update
grep foo

Otherwise the model could reset its own counter by doing pointless work between identical calls. Arguments should be normalised as well, so these two count as the same operation:

{"query": "foo", "path": "src"}

and:

{"path": "src", "query": "foo"}

Key order in a dictionary shouldn't matter. Denied calls should count too. If the model keeps attempting something like this:

run dangerous command
→ denied
run dangerous command
→ denied
run dangerous command
→ denied

that is exactly when it needs to realise it may be wise to stop trying.

The general pattern

The weak approach is a blunt reaction to bad behaviour:

Bad behavior → hard block

A stronger one detects the behaviour, increases the feedback and lets the model recover:

Bad behavior
     ↓
Detect
     ↓
Increase feedback
     ↓
Let model recover

It's a deceptively simple idea, and it fits nearly any agent framework that exposes tool calls.

3. Tell the model what it didn't see

This sounds obvious, yet many tools get it wrong. Say a repository holds this much:

4,000 files

and a search tool hands back only this:

100 files

If the response is simply those hundred files, the model may conclude that exactly a hundred files match. In fact the tool was saying "here are a hundred because I stopped looking", and the two meanings are completely different.

Make truncation explicit

A better response states what happened and where the rest lives:

Showing 100 of 4,000 results.
The result set was truncated.
Full results:
~/.agent/search-results/results.txt

The model now knows three things: more results exist, what it has is a subset, and the full list is reachable if needed. That's a much safer position.

Sampling can beat taking the first N

Suppose there are 4,000 files and room for 100. The naive way is a plain slice:

results[:100]

With sorted results that can be dangerous, since you may get a hundred files from one directory or one naming pattern. Spreading the sample across the whole list is more informative:

def sample_results(results, limit=100):
    step = len(results) / limit
return [
        results[int(i * step)]
        for i in range(limit)
    ]

The exact algorithm matters less than the principle: never let the model confuse what exists with what the tool showed.

Errors deserve the same care

Tool errors can mislead an agent too. Suppose a command is blocked by a security policy. A bare message such as this is poor:

Permission denied

because the model may decide its syntax was wrong, and then try again, and again, and again. A far better message is explicit:

Policy denial.
This command was intentionally blocked by the sandbox.
The command itself may be valid, but this operation is not permitted.
Do not retry using another method to bypass the policy.

That's more than a friendlier message. It's guidance for the agent. Your tools do more than execute operations, since they talk to another reasoning system. Tool output should answer one question: what does the model need to know to make its next decision correctly?

4. Code execution mustn't bypass permissions

Another pattern across modern agent systems is code mode. Rather than allowing one tool call per turn, you give the model a programming environment:

files = search("authentication")
for file in files:
    content = read_file(file)
    print(analyze(content))

This is powerful. Where the usual loop alternates between model and tool call, round after round:

LLM
 ↓
search
 ↓
LLM
 ↓
read
 ↓
LLM
 ↓
read
 ↓
LLM
 ↓
read

code mode lets the model run a program that makes many calls and returns a summary:

LLM
 ↓
run_code(...)
 ↓
50 tool calls
 ↓
summary

That can cut round trips and context use dramatically, but it raises a serious security question.

Who checks the calls inside the program?

Your ordinary architecture sends every model action through a permission layer before it reaches a tool:

Model
 ↓
Permission Layer
 ↓
Tool

Add code execution carelessly and the code can reach tools directly:

Model
 ↓
Code
 ↓
Tool

If that's the case you've built a back door around your permission system, which is clearly bad. The right design keeps every call from the program on the same security path:

Model
 ↓
run_code
 ↓
Program
 ↓
Permission Layer
 ↓
Tool

Each tool call still goes through the same pipeline. Conceptually, the file-reading function itself checks permission before doing anything:

def read_file(path):
    permission = check_permission(
        operation="read",
        path=path
    )
if not permission.allowed:
        raise PermissionError(
            "File access denied"
        )
    return actual_read(path)

The code interpreter receives no special version of the function. It gets the same one everybody else uses.

Turn denials into normal program errors

A subtler detail follows. If a program attempts something it isn't allowed to do:

try:
    delete_file("/important/file")
except PermissionError as e:
    print(e)

it should receive an ordinary, catchable error. It shouldn't be left hanging indefinitely:

hang forever

It shouldn't silently get an empty result:

return None

And it shouldn't behave as if nothing happened:

pretend nothing happened

The program has to understand that the operation failed, which matters most when the model writes programs on the fly. Code mode is powerful precisely because it gives the model more control, and that means the permission boundary must get stronger and not weaker.

5. Sometimes the best context strategy is no context

This is the idea more agent builders should try. Long-running agents pile up huge amounts of conversation history. At first that helps, then it becomes baggage. You end up with a chain of rounds feeding a giant context:

Round 1
 ↓
Round 2
 ↓
Round 3
 ↓
Round 4
 ↓
Round 5
 ↓
Huge context

Now the model spends its attention rereading its own past and not solving the task. Summarisation is one remedy, but there's another: end the conversation and keep the workspace.

Take a coding task that runs five rounds. In round one, the first agent inspects the repository, makes changes, saves its work and writes a handoff note:

Agent A
→ inspect repository
→ make changes
→ save work
→ write handoff

Round two begins with a brand-new agent that reads the workspace and the handoff and carries on:

Agent B
→ read workspace
→ read handoff
→ continue

There's no giant history, no stale reasoning and no accumulated tool noise. All it has is the current state.