How to Build a Custom Agent Harness如何构建自定义智能体运行框架

Sydney Runkle
June 3, 2026
6
min分钟
Go back to blog

Key Takeaways关键要点

  • A harness is the scaffolding around the model that connects it to the real world.运行框架是模型周围的脚手架,将模型连接到现实世界。
  • How well a harness fits the task at hand determines how useful an agent is.运行框架与手头任务的匹配程度,决定了智能体有多大用处。
  • LangChain's create_agent is the easiest way to build a custom harness tailored to a given task.LangChain 的 create_agent 是构建针对给定任务定制的运行框架最简单的方式。

‍

Building useful agents is largely about customization: connecting your agent to the right context, data, and environment(s) for the task at hand.构建有用的智能体,很大程度上在于定制:将你的智能体连接到当前任务所需的正确上下文、数据和环境。

At its core, an agent is a model calling tools in a loop until it completes a task and returns a result:从核心上讲,智能体就是一个模型在循环中调用工具,直到完成任务并返回结果:

You can also define an agent as:你也可以这样定义智能体:

agent = model + harness智能体 = 模型 + 运行框架

The harness is the scaffolding around the model that connects it to the real world.运行框架是模型周围的脚手架,将模型连接到现实世界。

The remainder of this post assumes the following:本文余下部分基于以下前提:

  1. An agent is only as good as the context provided to the model智能体的表现,取决于提供给模型的上下文
  2. The job of a harness is to provide context to the model at every step运行框架的职责是在每一步为模型提供上下文

So, to build a useful agent, you need a harness that’s great at delivering the right context for the given task to the model.因此,要构建有用的智能体,你需要一个擅长为给定任务向模型传递正确上下文的运行框架。

The base harness基础运行框架

create_agent is LangChain's primitive for building a harness. Pass in a model, tools, and a system prompt, and you have a working agent:create_agent 是 LangChain 用于构建运行框架的原语。传入模型、工具和系统提示词,你就有了一个可工作的智能体:

from langchain.agents import create_agent
 
agent = create_agent(
    model="anthropic:claude-sonnet-4-6",
    tools=tools,
    system_prompt="you are a helpful assistant..."
)

Harnesses like Deep Agents and the Claude Agent SDK come pre-assembled with an opinionated middleware (explained below) stack: memory, context management, sandboxing, and more. They're designed to get you to a production-ready agent fast, and they work well for most cases. But many agents need finer grained customization than these harnesses support: custom prompting, business logic, guardrails, etc.像 Deep Agents 和 Claude Agent SDK 这样的运行框架预先装配了一套带有明确设计取舍的中间件(下文会解释)栈:记忆、上下文管理、沙箱等。它们旨在让你快速得到生产就绪的智能体,并且在大多数情况下都很好用。但许多智能体需要比这些运行框架所支持的更细粒度的定制:自定义提示词、业务逻辑、护栏等。

create_agent takes a different approach: it’s purposefully minimalistic. Our philosophy is similar to that of Pi, a highly configurable coding agent harness. create_agent just implements the core agent loop, and it exposes middleware as a primitive for customization.create_agent 采用不同的方法:它刻意保持极简。我们的理念类似于 Pi——一个高度可配置的编程智能体运行框架。create_agent 只实现核心智能体循环,并将中间件暴露为用于定制的原语。

Middleware: how you customize the harness中间件:如何定制运行框架

Middleware hooks into the agent loop at each step: before and after model calls, before and after tool calls, at agent startup and teardown. Each piece handles one concern and composes freely with any other:中间件会在每一步挂接到智能体循环中:模型调用前后、工具调用前后、智能体启动和拆除时。每个部分只处理一项关注点,并可与任何其他部分自由组合:

Middleware allows you to add capabilities to your agent via a few levers that often work together:中间件让你可以通过几个常常协同作用的机制,为智能体添加能力:

Deterministic Logic. Business logic, policy enforcement, dynamic agent control — anything that needs to fire at a specific point in the loop. This includes runtime control over the agent itself: swapping the model based on task complexity, adjusting the prompt, and updating the agent’s message history (during compaction, for example). The right place for anything that can't (or shouldn't) live in a prompt.确定性逻辑。业务逻辑、策略执行、动态智能体控制——任何需要在循环中特定时点触发的内容。这包括对智能体本身的运行时控制:根据任务复杂度切换模型、调整提示词,以及更新智能体的消息历史(例如在压缩期间)。任何不能(或不应)放在提示词里的东西,都适合放在这里。

Tools. Rather than registering tools directly on the agent, middleware can handle the full lifecycle — setup, teardown, registration — and hand the agent a clean set of tools to work with. This matters when tools have dependencies, require initialization, or need to be torn down cleanly at the end of a run. It also keeps tool configuration close to the logic that governs it, rather than scattered across the agent definition.工具。中间件不是直接在智能体上注册工具,而是可以处理完整生命周期——设置、拆除、注册——并把一组干净的工具交给智能体使用。当工具有依赖、需要初始化,或需要在一次运行结束时干净地拆除时,这一点很重要。它还能让工具配置贴近管理它的逻辑,而不是分散在智能体定义中。

Custom state. If your middleware needs to track state across hooks, middleware can extend the agent’s state with custom properties. This enables middleware to track state throughout execution (maintain counters, flags, or other values that persist throughout agent runs) and share data between hooks.自定义状态。如果你的中间件需要跨钩子跟踪状态,中间件可以用自定义属性扩展智能体的状态。这使中间件能够在整个执行过程中跟踪状态(维护计数器、标志或其他在智能体运行期间持续存在的值),并在钩子之间共享数据。

Stream handlers. Middleware can intercept and transform the agent's output stream — filtering events, injecting metadata, routing different event types to different consumers. Useful when different parts of your stack need to react to different things the agent does: a UI consuming token deltas, an audit log capturing tool calls, a monitoring system tracking latency.流处理器。中间件可以拦截并转换智能体的输出流——过滤事件、注入元数据,将不同事件类型路由到不同消费者。当技术栈中不同部分需要对智能体所做的不同事情做出反应时很有用:UI 消费 token 增量、审计日志捕获工具调用、监控系统跟踪延迟。

The beauty of middleware is that it:中间件的妙处在于它:

  1. Enables customization at any point in the agent loop能在智能体循环中的任何位置进行定制
  2. Bundles related logic in composable, sharable units of code将相关逻辑打包成可组合、可共享的代码单元

LangChain ships prebuilt middleware for the most common patterns. Anything bespoke to your use case is one custom middleware away. Because each piece is isolated, the same middleware can be reused across every agent in an organization so that new agents inherit battle-tested behavior without rebuilding it.LangChain 为最常见的模式提供了预构建中间件。任何针对你用法的定制需求,都只差一个自定义中间件。由于每一部分都是隔离的,同一个中间件可以在组织内的每个智能体之间复用,这样新智能体无需重建就能继承久经考验的行为。

Harness capabilities运行框架能力

The job of a harness is to get the model the right context at the right time for the given task.运行框架的职责是,针对给定任务,在正确的时间为模型提供正确的上下文。

The table below maps common capabilities to middleware that support them. Most production agents end up using several together, depending on the agent’s needs (is it long running? how complex are the tasks? how sensitive are the agent’s actions?, etc):下表将常见能力映射到支持它们的中间件。大多数生产环境中的智能体最终会组合使用其中几个,具体取决于智能体的需求(它是否长时间运行?任务有多复杂?智能体的操作有多敏感?等等):

Capability Why it Matters Middleware
Prevent context overflow Long-running sessions accumulate message history fast. Without intervention, it overflows the context window. SummarizationMiddleware, ContextEditingMiddleware
Access and update memory Load relevant knowledge at startup, write it back at the end of a run. Lets the agent improve over time from real usage. FilesystemMiddleware, MemoryMiddleware, SkillsMiddleware
Take actions in an environment A fixed toolset limits what an agent can do. Access to a filesystem and execution environment unlocks more creative solutions, often with greater token efficiency. ShellToolMiddleware, FilesystemMiddleware, CodeInterpreterMiddleware
Delegate tasks Subagents handle complex sub-tasks with clean context windows. A todo list tracks progress across a long run. SubAgentMiddleware, AsyncSubAgentMiddleware, TodoListMiddleware
Handle transient failures Models and tools fail unpredictably. Production agents need retry logic with backoff and fallbacks when a model is unavailable. ToolRetryMiddleware, ModelRetryMiddleware, ModelFallbackMiddleware
Enforce policies PII handling, compliance checks, approval gates — these need to fire on every call regardless of what the model does. They don't belong in a prompt. PIIMiddleware, HumanInTheLoopMiddleware
Steer the agent Full autonomy isn't always appropriate. Pause before consequential actions and wait for a human to approve, reject, or redirect. HumanInTheLoopMiddleware
Control costs Prompt caching reduces token spend on long-running tasks. Call limits prevent costs from accumulating unchecked. ModelCallLimitMiddleware, ToolCallLimitMiddleware, PromptCachingMiddleware

See the full list of prebuilt middleware here.在此查看预构建中间件的完整列表。

Task-harness fit任务与运行框架的匹配度

Task-harness fit is how well your harness matches the actual demands of the task: the context it needs, the failures it'll encounter, the policies it must enforce, the environment it operates in. A harness for a customer service agent looks very different from one built for a long-running coding agent.任务与运行框架的匹配度,是指你的运行框架在多大程度上匹配任务的实际需求:所需上下文、会遇到的故障、必须执行的策略、运行环境。客服智能体的运行框架,与为长时间运行的编程智能体构建的运行框架看起来非常不同。

Every agent we build at LangChain, including our GTM agent, asynchronous coding agent, and our no-code agent builder, is built on create_agent with a middleware stack tailored to that agent’s mission.我们在 LangChain 构建的每个智能体,包括我们的 GTM 智能体、异步编程智能体和无代码智能体构建器,都基于 create_agent 构建,并使用针对该智能体使命定制的中间件栈。

The best agents aren't just built with capable models, they're built with harnesses that tightly fit the task. The easiest way to build a custom harness is with create_agent.最好的智能体不仅由能力强的模型构建,还由与任务紧密匹配的运行框架构建。构建自定义运行框架最简单的方式是使用 create_agent。

References参考资料

Get Started开始使用

Acknowledgements致谢

Thanks to @hwchase17, @huntlovell, @masondrxy, and @Vtrivedy10 for their thoughtful review and feedback.感谢 @hwchase17、@huntlovell、@masondrxy 和 @Vtrivedy10 的悉心审阅和反馈。

S
e
e
w
h
a
t
y
o
u
r
a
g
e
n
t
i
s
r
e
a
l
l
y
d
o
i
n
g
看看你的智能体到底在做什么

LangSmith, our agent engineering platform, helps developers debug every agent decision, eval changes, and deploy in one click.LangSmith 是我们的智能体工程平台,帮助开发者调试智能体的每一项决策、评估变更,并一键部署。