> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 如何添加自定义中间件

将智能体部署到 LangSmith 时，你可以向服务器添加自定义中间件，以处理诸如记录请求指标、注入或检查请求头、执行安全策略等需求，而无需修改核心服务器逻辑。这与[添加自定义路由](/langsmith/custom-routes)的工作方式相同。你只需提供自己的 [`Starlette`](https://www.starlette.io/applications/) 应用（包括 [`FastAPI`](https://fastapi.tiangolo.com/)、[`FastHTML`](https://fastht.ml/) 和其他兼容的应用）。

添加中间件可以让你全局拦截和修改请求与响应，无论它们是访问你的自定义端点还是内置的 LangSmith API。

以下是一个使用 FastAPI 的示例。

<Note>
  "仅限 Python"
  目前我们仅在 Python 部署中支持自定义中间件，且需要 `langgraph-api>=0.0.26`。
</Note>

## 创建应用

从一个**现有的** LangSmith 应用开始，将以下中间件代码添加到你的 `webapp.py` 文件中。如果你是从零开始，可以使用 CLI 从模板创建一个新应用。

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
langgraph new --template=new-langgraph-project-python my_new_project
```

拥有一个 LangGraph 项目后，添加以下应用代码：

```python {highlight={5}} theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# ./src/agent/webapp.py
from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware

app = FastAPI()

class CustomHeaderMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        response = await call_next(request)
        response.headers['X-Custom-Header'] = '来自中间件的问候！'
        return response

# 将中间件添加到应用
app.add_middleware(CustomHeaderMiddleware)
```

## 配置 `langgraph.json`

将以下内容添加到你的 `langgraph.json` 配置文件中。确保路径指向你上面创建的 `webapp.py` 文件。

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "dependencies": ["."],
  "graphs": {
    "agent": "./src/agent/graph.py:graph"
  },
  "env": ".env",
  "http": {
    "app": "./src/agent/webapp.py:app"
  }
  // 其他配置选项，如 auth、store 等。
}
```

### 自定义中间件顺序

默认情况下，自定义中间件在身份验证逻辑之前运行。若要让自定义中间件在身份验证**之后**运行，请在 `http` 配置中将 `middleware_order` 设置为 `auth_first`。（此自定义功能从 API 服务器 v0.4.35 及更高版本开始支持。）

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "dependencies": ["."],
  "graphs": {
    "agent": "./src/agent/graph.py:graph"
  },
  "env": ".env",
  "http": {
    "app": "./src/agent/webapp.py:app",
    "middleware_order": "auth_first"
  },
  "auth": {
    "path": "./auth.py:my_auth"
  }
}
```

## 启动服务器

在本地测试服务器：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
langgraph dev --no-browser
```

现在，任何发送到你服务器的请求的响应中都将包含自定义请求头 `X-Custom-Header`。

## 部署

你可以将此应用按原样部署到云端或你的自托管平台。

## 后续步骤

现在你已向部署中添加了自定义中间件，你可以使用类似的技术来添加[自定义路由](/langsmith/custom-routes)或定义[自定义生命周期事件](/langsmith/custom-lifespan)，以进一步定制服务器的行为。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\langsmith\custom-middleware.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
