> For the complete documentation index, see [llms.txt](https://docs.neuron-ai.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.neuron-ai.dev/neuron-v3-zh/gong-zuo-liu/middleware.md).

# 中间件

### 什么是中间件

中间件提供了一种挂钩工作流执行的方式，因此也可以作用于 Agent 和 RAG，因为它们本质上也是工作流。

核心的工作流执行涉及根据其他节点返回的事件来调用节点。中间件暴露出钩子，以便在执行过程中介入 `之前` 和 `之后` 节点的执行：

<figure><img src="/files/f1432da4b4f85598ea3ab494fa5d3bb0aa908ef7" alt=""><figcaption></figcaption></figure>

### 中间件可以做什么？

<table data-view="cards"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td><strong>控制</strong></td><td>转换提示词、工具选择和输出格式。</td></tr><tr><td><strong>护栏</strong></td><td>添加重试、速率限制，实施防护措施，拒绝提示词。</td></tr><tr><td><strong>监控</strong></td><td>通过日志、分析和调试跟踪 Agent 行为。</td></tr></tbody></table>

### 创建中间件

你可以使用下面的命令创建一个中间件类：

{% tabs %}
{% tab title="Unix" %}

```bash
vendor/bin/neuron make:middleware CustomMiddleware
```

{% endtab %}

{% tab title="Windows" %}

```powershell
.\vendor\bin\neuron make:middleware CustomMiddleware
```

{% endtab %}
{% endtabs %}

项目中将会创建一个带有默认中间件结构的新类：

```php
<?php

namespace App\Neuron\Middleware;

class CustomMiddleware implements WorkflowMiddleware
{
    /**
     * 在节点运行之前执行。
     */
    public function before(NodeInterface $node, Event $event, WorkflowState $state): void
    {
        // ...
    }
    
    /**
     * 在节点运行之后执行。
     */
    public function after(NodeInterface $node, Event $result, WorkflowState $state): void
    {
        // ...
    }
}
```

### 注册中间件

如果你想将中间件分配给特定节点，可以在定义工作流时覆盖 `middleware` 方法：

```php
class MyWorkflow extends Workflow
{
    /**
     * 定义节点中间件。
     */
    protected function middleware(): array
    {
        return [
            NodeOne::class => new CustomMiddleware(),
        ];
    }
}
```

你也可以将多个中间件分配给一个节点，定义为数组：

```php
class MyWorkflow extends Workflow
{
    /**
     * 定义节点中间件。
     */
    protected function middleware(): array
    {
        return [
            NodeOne::class => [
                new CustomMiddleware(),
                new AnotherMiddleware(),
            ]
        ];
    }
}
```

### 全局中间件

如果你希望中间件在每个节点之前和之后运行，可以将其添加到工作流中的全局中间件栈：

```php
class MyWorkflow extends Workflow
{
    /**
     * 定义全局中间件。
     */
    protected function globalMiddleware(): array
    {
        return [
            new CustomMiddleware(),
        ];
    }
}
```

### 示例

Neuron 为常见用例提供了预构建的中间件，例如工具审批或上下文摘要。你可以在 Agent 部分查看它们：

{% content-ref url="/pages/9ea2066a9f786ede6683c1553ff65e839e3105e5" %}
[中间件](/neuron-v3-zh/agent/middleware.md)
{% endcontent-ref %}
