fix(docs): update middleware guide to current AgentMiddleware API (#4968)

This commit is contained in:
Battleplus 2026-08-24 09:15:00 +08:00 committed by GitHub
parent 41b3c17447
commit 34ba2cdf38
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 51 additions and 46 deletions

View File

@ -276,28 +276,28 @@ tools:
```python ```python
# packages/harness/deerflow/agents/middlewares/my_middleware.py # packages/harness/deerflow/agents/middlewares/my_middleware.py
from langchain.agents.middleware import BaseMiddleware from langchain.agents import AgentState
from langchain_core.runnables import RunnableConfig from langchain.agents.middleware import AgentMiddleware
from langgraph.runtime import Runtime
class MyMiddleware(BaseMiddleware): class MyMiddleware(AgentMiddleware[AgentState]):
"""Middleware description.""" """Middleware description."""
def transform_state(self, state: dict, config: RunnableConfig) -> dict: def before_model(self, state: AgentState, runtime: Runtime) -> dict | None:
"""Transform the state before agent execution.""" """Runs before each model call. Return a dict of state updates, or None."""
# Modify state as needed return None
return state
def after_model(self, state: AgentState, runtime: Runtime) -> dict | None:
"""Runs after each model call. Inspect or modify the result."""
return None
``` ```
2. Register in `packages/harness/deerflow/agents/lead_agent/agent.py`: 2. Register via `custom_middlewares` when building the agent:
```python ```python
middlewares = [ middlewares = build_middlewares(
ThreadDataMiddleware(), config, model_name, custom_middlewares=[MyMiddleware()], ...
SandboxMiddleware(), )
MyMiddleware(), # Add your middleware
TitleMiddleware(),
ClarificationMiddleware(),
]
``` ```
### Adding New API Endpoints ### Adding New API Endpoints

View File

@ -25,19 +25,21 @@ To add a custom middleware:
2. Pass your middleware to the `custom_middlewares` parameter when building the agent. 2. Pass your middleware to the `custom_middlewares` parameter when building the agent.
```python ```python
from langchain.agents import AgentState
from langchain.agents.middleware import AgentMiddleware from langchain.agents.middleware import AgentMiddleware
from deerflow.agents.thread_state import ThreadState from langgraph.runtime import Runtime
class AuditMiddleware(AgentMiddleware):
async def on_start(self, state: ThreadState, config): class AuditMiddleware(AgentMiddleware[AgentState]):
# Runs before each model call def before_model(self, state: AgentState, runtime: Runtime) -> dict | None:
"""Runs before each model call."""
print(f"[audit] turn starts: {len(state.messages)} messages in context") print(f"[audit] turn starts: {len(state.messages)} messages in context")
return state, config return None
async def on_end(self, state: ThreadState, config): def after_model(self, state: AgentState, runtime: Runtime) -> dict | None:
# Runs after each model call """Runs after each model call."""
print(f"[audit] turn ends: last message type = {state.messages[-1].type}") print(f"[audit] turn ends: last message type = {state.messages[-1].type}")
return state, config return None
``` ```
Custom middlewares are injected into the chain immediately before `ClarificationMiddleware`, which always runs last. Custom middlewares are injected into the chain immediately before `ClarificationMiddleware`, which always runs last.

View File

@ -235,15 +235,13 @@ The basic structure is:
from langchain.agents.middleware import AgentMiddleware from langchain.agents.middleware import AgentMiddleware
class MyMiddleware(AgentMiddleware): class MyMiddleware(AgentMiddleware):
async def on_start(self, state, config): def before_model(self, state, runtime) -> dict | None:
# Runs before the model call """Runs before each model call."""
# Modify state or config here return None
return state, config
async def on_end(self, state, config): def after_model(self, state, runtime) -> dict | None:
# Runs after the model call """Runs after each model call."""
# Inspect or modify the result return None
return state, config
``` ```
Custom middlewares are passed to `make_lead_agent` via the `custom_middlewares` parameter in `build_middlewares`. They are injected immediately before `ClarificationMiddleware` at the end of the chain. Custom middlewares are passed to `make_lead_agent` via the `custom_middlewares` parameter in `build_middlewares`. They are injected immediately before `ClarificationMiddleware` at the end of the chain.

View File

@ -25,19 +25,21 @@ DeerFlow 的可插拔架构意味着系统的大多数部分都可以在不 fork
2. 在构建 Agent 时通过 `custom_middlewares` 参数传入你的中间件。 2. 在构建 Agent 时通过 `custom_middlewares` 参数传入你的中间件。
```python ```python
from langchain.agents import AgentState
from langchain.agents.middleware import AgentMiddleware from langchain.agents.middleware import AgentMiddleware
from deerflow.agents.thread_state import ThreadState from langgraph.runtime import Runtime
class AuditMiddleware(AgentMiddleware):
async def on_start(self, state: ThreadState, config): class AuditMiddleware(AgentMiddleware[AgentState]):
# 在每次模型调用前运行 def before_model(self, state: AgentState, runtime: Runtime) -> dict | None:
"""在每次模型调用前运行。"""
print(f"[审计] 轮次开始:上下文中有 {len(state.messages)} 条消息") print(f"[审计] 轮次开始:上下文中有 {len(state.messages)} 条消息")
return state, config return None
async def on_end(self, state: ThreadState, config): def after_model(self, state: AgentState, runtime: Runtime) -> dict | None:
# 在每次模型调用后运行 """在每次模型调用后运行。"""
print(f"[审计] 轮次结束:最后一条消息类型 = {state.messages[-1].type}") print(f"[审计] 轮次结束:最后一条消息类型 = {state.messages[-1].type}")
return state, config return None
``` ```
自定义中间件在链末尾 `ClarificationMiddleware` 之前注入,后者始终最后运行。 自定义中间件在链末尾 `ClarificationMiddleware` 之前注入,后者始终最后运行。

View File

@ -216,16 +216,19 @@ summarization:
自定义中间件可以注入到链中用于专业用途。中间件必须实现 `langchain.agents.middleware` 中的 `AgentMiddleware` 接口: 自定义中间件可以注入到链中用于专业用途。中间件必须实现 `langchain.agents.middleware` 中的 `AgentMiddleware` 接口:
```python ```python
from langchain.agents import AgentState
from langchain.agents.middleware import AgentMiddleware from langchain.agents.middleware import AgentMiddleware
from langgraph.runtime import Runtime
class MyMiddleware(AgentMiddleware):
async def on_start(self, state, config):
# 在模型调用前运行
return state, config
async def on_end(self, state, config): class MyMiddleware(AgentMiddleware[AgentState]):
# 在模型调用后运行 def before_model(self, state: AgentState, runtime: Runtime) -> dict | None:
return state, config """在模型调用前运行。"""
return None
def after_model(self, state: AgentState, runtime: Runtime) -> dict | None:
"""在模型调用后运行。"""
return None
``` ```
自定义中间件在链末尾 `ClarificationMiddleware` 之前注入。 自定义中间件在链末尾 `ClarificationMiddleware` 之前注入。