跳到正文
Hacker News (official RSS)(newsletter.maartengrootendorst.com)·· 4 小時前品質評分66

圖解 Pi、OpenCode、Hermes 和 OpenClaw 如何把大型語言模型變成 AI 助理

A Visual Guide to Agent Harnesses

重點導讀

同一個大型語言模型放進不同框架,做事方式也可能差很多,因為框架負責提供記憶、工具和工作流程。

  • 作者檢視 Pi、OpenCode、Hermes 和 OpenClaw 的原始碼,並用圖解說明它們的差異:Pi 著重簡潔與可修改的程式碼工作流程,OpenCode 用共用伺服器和資料庫儲存工作進度,Hermes 加入聊天工具與個人偏好記憶,OpenClaw 則能定時檢視訊息並整理長期記憶。
  • 這份比較也說明,挑選框架時要看自己需要哪些工具和工作方式。

AI 伴隨問答

自備 Key 深度分析

針對這篇報導有疑問?可直接點選快捷問題或向 AI 追問背景脈絡與技術細節:

正文

Not all agent harnesses are created equally. Harnesses like Pi, OpenCode, Hermes, and OpenClaw each have their own philosophy and give you different capabilities. Choosing one over the other can have a significant impact on your application and choosing which one to use isn’t all that straightforward.

In fact, if we place the exact same LLM inside each of them, we get four completely different agents:

Pi is your most minimalistic agent whereas OpenCode uses a shared server to handle different clients. Hermes loops skills back into its memory while OpenClaw has over 30 chat channels. And these are only some of the differences...

I dove into the source code and explored in more than 30 custom visuals how these harnesses work from the ground up. To do so, we start from an educational harness that my co-author and I created called TinyAgent for our book An Illustrated Guide to AI Agents.

Because these frameworks update quickly, I thought it might be helpful if I focused on a specific snapshot. That will also make it easier to update this guide in a year ;)

Here are the snapshots for you to inspect them yourself:

To explore agent harnesses, let’s start from the beginning!

By itself, an LLM is nothing more than a text-in -> text-out machine. It reads tokens and it generates tokens. To have it become something more, we augment the LLM (typically a reasoning model) with additional capabilities like Memory and Tools so that it can interact with the environment.

While the LLM does the reasoning, these augmentations connect it to the world outside of tokens. This essentially gives us two pieces of the puzzle:

  • Model Weights: The LLM itself

  • Agent Harness: What augments the LLM and converts its tokens into actions

It’s an interesting boundary to draw and neatly explains what the difference then is between an LLM and a Harness:

The model itself is stateless (which means it doesn’t change or remember what happened in the past). The agent harness is everything around the model and creates the prompts, executes tools, stores sessions, enforces guardrails, etc.

Together, they create what we call the agent!

These agents can be quite different from each other. If we choose a small LLM then we can expect worse performance over a frontier model. However, the harness arguably has an equal and perhaps even greater influence on the output.

Some harnesses are small. Some use many tools. Some have fewer guardrails. Some have more connectors. Etc. Once we look inside the harness, we can see many differences between frameworks, especially regarding their scale:

On the left, we start with the TinyAgent, an educational framework that essentially shows you what it means to build a harness by yourself. It’s small because it has to fit in the book ;)

Production-grade frameworks are quite a bit bigger to handle things like guardrails, states over multiple sessions, more complex memory systems, etc. Pi and OpenCode have a decently sized codebase whereas especially OpenClaw is quite hefty. Note that I differentiate here between the core app and whatever plugins/extensions a framework might have. I’m not sure it’s fair to count those, but it gives you an idea of how much plugins can add to a framework.

Although they are all coding agents, Hermes and OpenClaw focus more on the “personal assistant” use case rather than the other two frameworks. That’s not an easy thing to do which makes their codebases a bit bigger:

As such, all four harnesses share a “Coding“ core that can read/edit/execute code. Hermes and OpenClaw have an additional “Personal Assistant“ layer that allows for chat connectors (like Slack), personal memory, scheduled wake-ups, etc.

This increase in complexity of their codebases allows me to nicely build up from small (TinyAgent) all the way to complex (OpenClaw) one step at a time.

So... let’s explore each framework starting with our tiny baseline to understand the fundamental components of an agent harness that turns the LLM into an agent.

In the book (and all code is of course open-source), we create a TinyAgent entirely from scratch in Python. TinyAgent is the harness that converts a local Gemma 4 model into an agent. Compared to the other four frameworks, this is not meant for production but is purely educational. It only has around 600 lines of code to demonstrate what the core of the loop looks like. We cover things like reasoning, memory, tools, planning, subagents, and more!

Meet TinyAgent: six chapter-mapped Python modules composing a 600-line baseline agent

It has a number of small modules that connect the TinyAgent to different chapters, like LLM(), Memory(), Tools(), and more. Together, they form the most minimal agent we could think of with no server, chat connectors, or anything else fancy ;)

Inside that tiny codebase, the core loop that is being used is called Reason and Act or ReAct. Although it seems like an “old” technique (2022!), it is the loop that is still being used in every framework that we talk about in this guide. Instead of answering in one pass, ReAct instructs the model to go through loops of reasoning, acting, and observing.

At every single loop the model first reasons about what it should do next, then it executes that particular action, and finally observes the consequence of taking that action. This repeats until the model decides it has gathered enough information to answer the question. Modern reasoning LLMs are trained specifically for this pattern and will use specific tokens to indicate when to reason, call a tool, and stop.

Let’s visualize these steps by mapping it onto the core loop of TinyAgent. At each step, it will:

  • Reason: The model will think about the next best step to take.

  • Call a tool: It will output a tool call that the harness will execute.

  • Observe: Add the output of the tool call to its memory.

This core loop in TinyAgent actually fits in fewer than twenty lines of Python:

def _step(self) -> str | None:
    response = self.llm.generate(
        self.memory.get_messages(), tools=self.tools.schemas
    )
    self.memory.add(
        "assistant", response.content, tool_call=response.tool_call
    )
    if self.tools.is_done(response):
        return response.content

    result = self.tools.execute(response)
    role, observation = self.tools.observation(result)
    self.memory.add(role, observation)
    return None

And that is more than enough to build a working educational agent!

Pi has a great philosophy:

“Pi is a minimal, extensible agent harness that you can make your own.”

It is the first production-grade harness in our comparison with a bit more than 100K lines of code. It runs in your terminal with no server and just four default tools (read, write, edit, and bash).

Compared to TinyAgent, it adds better compaction, specific tools, can be steered during a run, and more!

Coding sessions will eventually reach context limits as it goes through large codebases, does research, writes code itself, etc. Rather than dropping old turns, Pi uses a technique called compaction. In compaction, a part of the conversation history is trimmed to free up this context window. In Pi, when the context window fills up to 184k tokens, its conversation history is compacted.

During compaction older turns are put through an LLM to summarize its history. Meanwhile, the most recent 20k tokens stay exactly the same so the model has an accurate understanding of what it was doing.

Even if we were to add compaction to TinyAgent, it does not save its conversation. So when we close the terminal, the entire conversation is gone. In contrast, Pi writes each turn to JSONL linked through id and parent pointers:

A huge benefit of this system is that you can easily revert an earlier turn in the conversation and create a new branch. Much like you would do with git!

Tools are arguably one of the most important components of an agent. They typically target an agent’s capability of writing, editing, and creating files. In TinyAgent we gave it tools to write entire files. However, when you only want to update a single line of code, you would have to rewrite the whole file. In contrast, Pi has an edit tool that allows it to update a very specific line which significantly reduces the amount of writing the model has to do.

The Pi harness also allows for a better handling of logging information. If you were to run a pytest for instance, you might get back a very large logfile (e.g., pytest.log). With Pi, all that information will be stored locally and only the last 2,000 lines plus the file path are given back to the model.

Since test failures can usually be found at the end of the trace, the model can still see the error and search pytest.log when needed with Agentic RAG.

As such, both explicit tools that the model can use (e.g., edit) and the harness tools (e.g., truncating logs) are important components of the agentic harness.

Finally, Pi has another interesting capability we can explore, namely steering it while it is running!

This means that while the model is running you can steer it by querying the model and it will continue. The way it does that is by running independent tools in parallel and right before it gives that output back to the LLM, it injects the query. The model will see the tool output and notice that the user will have had something to add that he/she might have forgotten.

We essentially have two types of messages, a steer message that redirects the next LLM call and a follow-up message that waits until the model is completely done.

In Pi’s engine (agent-loop.ts#L294-L308), that split takes only a couple of lines:

while (hasMoreToolCalls || pendingMessages.length > 0) {
  // ... run turn and execute tools ...
  explicitContinuation = decision?.action === "continue";
  pendingMessages = (await config.getSteeringMessages?.()) || [];
  if (hasMoreToolCalls || pendingMessages.length > 0) {
    explicitContinuation = false;
  }
}

// Agent would stop here. Check for follow-up messages.
const followUp = (await config.getFollowUpMessages?.()) || [];
if (followUp.length > 0) {
  explicitContinuation = false;
  pendingMessages = followUp;
  continue;
}

getSteeringMessages() runs inside the active inner loop, while getFollowUpMessages() waits until the agent would otherwise stop. All four production harnesses adopt compaction, surgical edits, and truncation from this baseline. Next, let’s see how OpenCode decouples this loop from the terminal.

OpenCode‘s codebase is roughly the same size as that of Pi but it adds an HTTP server in front of the agent such that various clients (terminal, desktop, etc.) share one SQLite session.

Compared to Pi, OpenCode introduces that shared server, a SQLite database for tracking sessions, a special Code Mode with subagents, and more!

If we close Pi’s terminal, the loop will stop as everything is being executed in it. With OpenCode, it decouples this behavior by writing all of its traces to a database (e.g., opencode.db). This means that if you close the terminal, you can continue the process with the web app.

On every step, the server reads the session history from the database, runs one pass of the model, and saves that new information to be queried in the next step. That next step can be run from anywhere.

When an agent has to face complex use cases it might need to run several tools in the right order. With simpler harnesses, that would mean that the LLM runs one tool per turn and waits for the output of each tool before calling the next one.

OpenCode does it a bit differently and uses something they call the Code Mode. Essentially, this mode allows the LLM to write one short script that chains those calls. Instead of having to execute tools one per step, it now calls them all at once and only sees the output when they are all finished.

This Code Mode is a nice example of a methodology called CodeAct. CodeAct is a pattern where a model writes executable code (for instance Python) to orchestrate its list of tool calls. With how capable these models are becoming, we can leave it to them to write their own scripts. As such, they can leverage it not only to orchestrate multiple tool calls, but create new ones as well!

Something interesting I noticed while going through the codebase was how it handled its planning mode. I was expecting some sort of specialized or complex planning architecture. Instead, they used a rather simple but elegant way of switching between Build Mode and Plan Mode.

In this method, the agent loop stays identical and nothing changes. It is still the same ReAct-like loop we have seen before. However, when you switch to the Plan Mode, the harness blocks the edit tool for everything except plan.md. That limitation steers the model to focus on planning. It cannot do anything else anyway!

When you switch to Build Mode, the edit tool can edit your selected files again.

These simple tricks feel like a nice example of the direction we are headed in. As LLMs are becoming more and more capable, there is less need to create these complicated systems.

Compaction is a great technique to manage large traces that take up too much space from the model’s context window. However, it is not a perfect technique. Let’s say you want the agent to explore a new repository to find a specific function. The agent might use thousands of tokens just to find that specific function. Although compaction can then be run to reduce its conversation history, it is a rather inefficient technique!

OpenCode has a more efficient way of performing compression: use subagents!

Whenever the model has to execute read-like tasks (read, grep, glob), it asks a subagent to do that instead. The subagent will perform the task, fill up its context window, but only give back a summary of the things it has done:

This turns a large context window into a summary that the main agent can leverage. All of the search the subagent did is essentially thrown out.

This is another nice example of using simple techniques to prevent bigger problems. Spin up a subagent to handle a task and throw away its context window to prevent noise from entering the main agent.

Hermes is already a much bigger framework mostly because of one reason: it adds a Personal Assistant layer that allows it to go beyond coding. As a result, it has integration with various chat apps (like Slack and WhatsApp), more tools (> 50), and has a large variety of skills (>50) you can use.

Compared with coding-only harnesses, Hermes adds a multi-chat gateway, self-learning skills, an approval judge and parallel workers inside, and several pluggable sandbox backends.

Memory in a primarily coding harness versus a personal assistant has to be a bit different. With coding, an AGENTS.md is typically enough and will get you there most of the way. A harness to create a personal assistant has to go beyond that and often requires learning your preferences.

Hermes is a great example of how you can approach personalization by using markdown files. It has a USER.md and MEMORY.md that the agent can write to and update what it knows about you and your preferences.

These markdown files contain different types of ever-changing information:

  • MEMORY.md: Environment facts, project structures, tooling quirks, and technical lessons the agent discovered.

  • USER.md: Facts about the user, like their role, communication style, workflow habits, and preferences (for example, always using pytest).

As such, there is a split between the technical environment and structure (MEMORY.md) and the user (USER.md). This modularity allows the model to easily differentiate between project information and user preferences.

Hermes has more than 50 skills baked in for various purposes:

  • Productivity: obsidian, notion, google-workspace, etc.

  • Software: github-pr-workflow, test-driven-development, docker-management, etc.

  • Security: 1password, oss-forensics, etc.

  • External agents: claude-code, codex, etc.

These skills are all bundled with Hermes and easily allow it to do a wide variety of tasks without the user needing to install many different skills themselves.

As is typical for skills, Hermes only loads in their header to understand which skills are accessible. When the agent needs to read the full skill, it can use the skill_view("...") tool to selectively load skills.

When the agent starts working, it only sees the small YAML header with the name and description of a skill.

As shown before, Hermes has a bigger focus on learning flows (and the user) compared to other harnesses. Although MEMORY.md and USER.md are a part of that, what if the agent wants to learn a specific pattern? Dumping all of that information in those markdown files will make them quite noisy.

Instead, it simply creates new skills!

It does so with a review agent that triggers at the end of a session and reviews whether it needs to create a new skill or update an existing one:

The review agent will trigger after a session has called more than 10 tools. When it does, the review agent will look at the entire trace and think about whether it should be compressed into a pattern. For instance, the model could have used 3 tool calls instead of more than 10. Capturing this pattern will make future runs much more efficient.

It’s an interesting approach and seems to combine ideas from Voyager for a growing skill library and Reflexion for reflecting on its own behavior.

Much like OpenCode, Hermes can spawn subagents to do some of its work for it. However, compared to OpenCode, Hermes can spawn them in parallel and combines the output of these subagents to create a set of summaries for the main agent to look at:

These subagents are asked to focus on one particular piece of the puzzle (a single file or a folder) and give back a summary of its results. The summaries are then passed back to the main agent for it to look at.

Hermes is a great example of the personal assistant layer, but there is always room for even more functionalities. Let’s take a look at the biggest framework, OpenClaw.

OpenClaw is one of the most well-known harnesses and is definitely the largest framework. A big part of that has to do with the many chat channels, tools, and backends it has to essentially do it all.

This harness essentially can do everything the previous harnesses could, with a couple of differences and additional capabilities.

Hermes already has a gateway to route chat apps to the LLM. OpenClaw goes a step further with a multi-channel gateway that separates personal chats from group chats, creating a privacy boundary between them.

It is split into two sessions, the Main Session and the Group Session. The Main Session contains all of your personal direct messages whereas Group Sessions are separate group chats to make sure nothing personal leaks into them.

One thing that OpenClaw made famous was the introduction of the heartbeat. A heartbeat is essentially a 30-minute trigger that wakes up the agent and asks it to check if there are new messages and whether it should start a new task.

If the agent decides there is no need to work on something, it stays quiet. If it sees there is an important e-mail for instance, it can notify the user on one of the chat channels. The rules are captured in HEARTBEAT.md so it knows what to look out for every 30 minutes.

In this example, there is a cron-job that starts every morning at 08:00 to create and send a summary of new emails. At 8:30 (the first heartbeat) and 9:00 (the second heartbeat) the agent checks whether an action is needed. If not, nothing happens. At 9:30, an important email comes in and the agent notifies the user.

OpenClaw is meant to be always on. However, as sessions can run for multiple days or even weeks, compaction will eventually remove important information from the traces.

Instead, OpenClaw will run something called a memory flush right before compaction, which is a fancy way of saying that it writes the memory to disk:

To query all of that information, OpenClaw uses Agentic RAG to easily be able to query that information when needed. It uses a hybrid variant of RAG which leverages both a classical technique (BM25) and a more modern technique (embeddings):

It then applies a 30-day recency decay to reduce the relevance of files that are older. Maximal Marginal Relevance (MMR) is used to then de-duplicate and rerank the output. This re-ranked information is then fed to the LLM so that it can be up to date on important information.

But that’s not it!

Daily logs are likely to still accumulate noisy information over weeks. To prevent this from happening, OpenClaw runs a second pass called Scheduled Dreaming:

Every night, the agent will go through three stages of “sleep”, namely light, deep, and REM. The agent will score the daily logs as we’ve seen before (light), search for and extract important facts (deep), and finally save that into its long-term memory, namely MEMORY.md (REM).

I like how the framework tries to mimic what we are doing. Since the user is sleeping anyway, why not take that opportunity to consolidate what happened during the day?

To end this guide, I thought it would be nice to put these harnesses side-by-side and see where they differ, starting with the system prompt.

Before you type a single word, every harness already fills part of the context window with system instructions, workspace files, and tool schemas.

Hermes and OpenClaw are quite interesting to see. They spend almost the same amount of tokens but for very different reasons. Hermes focuses on tool schemas (21 default tools) while OpenClaw exposes only 7 core tools by default and focuses on workspace files (SOUL.md, MEMORY.md, rules).

Then, when a session grows toward a given context window, each harness uses a different compaction mechanism:

Hermes compacts relatively early compared to all other harnesses, whereas OpenClaw also saves much of its context to daily logs for tracking purposes.

Finally, we can compare how all five harnesses manage session storage, durable files, and cross-session recall side-by-side:

You can see how memory evolves as harnesses become more complex. It’s interesting to see, for instance, OpenCode using a database to track its sessions whereas OpenClaw saves daily files.

It just shows you how much different harnesses can be!

Choosing one though isn’t all that straightforward. It very much depends on what you are looking for. Here’s an overview of some of the considerations:

Jay and I spent quite a bit of time making sure there is this one overarching idea of what an agent is. So when you use that and connect it back to everything we discussed here, we can create a nice overview of some of the principles in the context of the harness:

The LLM is at the center of the harness but the harness does not alter it. Instead, it is everything around the LLM that turns it from a great chatbot into something that interacts with the world.

It’s quite beautiful to see how the world of AI changed in the last couple of years:

“From words to actions and from LLMs to agents.”

This ends our visual journey through open-source agent harnesses!

Hopefully, seeing these frameworks side-by-side gives you a clear mental map when choosing a harness or even designing your own. If you want to build these foundations from scratch with full code and hundreds more visuals, check out our book An Illustrated Guide to AI Agents.

來源: Hacker News (official RSS) (newsletter.maartengrootendorst.com)
開啟原文

讀者討論

理性交流 · 即時討論