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

# 使用 Web 钩子

Web 钩子实现了从您的 LangSmith 应用程序到外部服务的事件驱动通信。例如，您可能希望在对 LangSmith 的 API 调用运行完成后，向另一个服务发送更新。

许多 LangSmith 端点接受一个 `webhook` 参数。如果一个可以接受 POST 请求的端点指定了此参数，LangSmith 将在运行完成时发送一个请求。

在使用 LangSmith 时，您可能希望在 API 调用完成后使用 Web 钩子来接收更新。Web 钩子对于在运行处理完成后触发您服务中的操作非常有用。要实现这一点，您需要公开一个可以接受 `POST` 请求的端点，并在 API 请求中将此端点作为 `webhook` 参数传递。

目前，SDK 不提供定义 Web 钩子端点的内置支持，但您可以使用 API 请求手动指定它们。

## 支持的端点

以下 API 端点接受 `webhook` 参数：

| 操作       | HTTP 方法 | 端点                                |
| -------- | ------- | --------------------------------- |
| 创建运行     | `POST`  | `/thread/{thread_id}/runs`        |
| 创建线程定时任务 | `POST`  | `/thread/{thread_id}/runs/crons`  |
| 流式运行     | `POST`  | `/thread/{thread_id}/runs/stream` |
| 等待运行     | `POST`  | `/thread/{thread_id}/runs/wait`   |
| 创建定时任务   | `POST`  | `/runs/crons`                     |
| 无状态流式运行  | `POST`  | `/runs/stream`                    |
| 无状态等待运行  | `POST`  | `/runs/wait`                      |

在本指南中，我们将展示如何在流式运行后触发 Web 钩子。

## 设置您的助手和线程

在进行 API 调用之前，请设置您的助手和线程。

<Tabs>
  <Tab title="Python">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langgraph_sdk import get_client

    client = get_client(url=<DEPLOYMENT_URL>)
    assistant_id = "agent"
    thread = await client.threads.create()
    print(thread)
    ```
  </Tab>

  <Tab title="JavaScript">
    ```js theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { Client } from "@langchain/langgraph-sdk";

    const client = new Client({ apiUrl: <DEPLOYMENT_URL> });
    const assistantID = "agent";
    const thread = await client.threads.create();
    console.log(thread);
    ```
  </Tab>

  <Tab title="CURL">
    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    curl --request POST \
        --url <DEPLOYMENT_URL>/assistants/search \
        --header 'Content-Type: application/json' \
        --data '{ "limit": 10, "offset": 0 }' | jq -c 'map(select(.config == null or .config == {})) | .[0]' && \
    curl --request POST \
        --url <DEPLOYMENT_URL>/threads \
        --header 'Content-Type: application/json' \
        --data '{}'
    ```
  </Tab>
</Tabs>

示例响应：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
    "thread_id": "9dde5490-2b67-47c8-aa14-4bfec88af217",
    "created_at": "2024-08-30T23:07:38.242730+00:00",
    "updated_at": "2024-08-30T23:07:38.242730+00:00",
    "metadata": {},
    "status": "idle",
    "config": {},
    "values": null
}
```

## 在图运行中使用 Web 钩子

要使用 Web 钩子，请在 API 请求中指定 `webhook` 参数。当运行完成时，LangSmith 会向指定的 Web 钩子 URL 发送一个 `POST` 请求。

例如，如果您的服务器在 `https://my-server.app/my-webhook-endpoint` 监听 Web 钩子事件，请在请求中包含此 URL：

<Tabs>
  <Tab title="Python">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    input = { "messages": [{ "role": "user", "content": "Hello!" }] }

    async for chunk in client.runs.stream(
        thread_id=thread["thread_id"],
        assistant_id=assistant_id,
        input=input,
        stream_mode="events",
        webhook="https://my-server.app/my-webhook-endpoint"
    ):
        pass
    ```
  </Tab>

  <Tab title="JavaScript">
    ```js theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    const input = { messages: [{ role: "human", content: "Hello!" }] };

    const streamResponse = client.runs.stream(
      thread["thread_id"],
      assistantID,
      {
        input: input,
        webhook: "https://my-server.app/my-webhook-endpoint"
      }
    );

    for await (const chunk of streamResponse) {
      // 处理流式输出
    }
    ```
  </Tab>

  <Tab title="CURL">
    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    curl --request POST \
        --url <DEPLOYMENT_URL>/threads/<THREAD_ID>/runs/stream \
        --header 'Content-Type: application/json' \
        --data '{
            "assistant_id": <ASSISTANT_ID>,
            "input": {"messages": [{"role": "user", "content": "Hello!"}]},
            "webhook": "https://my-server.app/my-webhook-endpoint"
        }'
    ```
  </Tab>
</Tabs>

## Web 钩子负载

LangSmith 以 [运行](/langsmith/runs) 的格式发送 Web 钩子通知。请求负载在 `kwargs` 字段中包含运行输入、配置和其他元数据。除了标准的运行字段外，Web 钩子负载还包括 `values`、`webhook_sent_at` 和 `error` 字段。

完整的 Web 钩子负载包含以下字段：

| 字段                   | 类型                    | 描述                                             |
| -------------------- | --------------------- | ---------------------------------------------- |
| `run_id`             | `string` (UUID)       | 运行的唯一标识符。                                      |
| `thread_id`          | `string` (UUID)       | 运行所属线程的标识符。                                    |
| `assistant_id`       | `string`              | 执行运行的助手的标识符。                                   |
| `status`             | `string`              | 运行的最终状态（例如，`"success"`、`"error"`）。             |
| `created_at`         | `string` (datetime)   | 运行创建的时间戳。                                      |
| `updated_at`         | `string` (datetime)   | 运行最后更新的时间戳。                                    |
| `run_started_at`     | `string` (datetime)   | 运行开始执行的时间戳。                                    |
| `run_ended_at`       | `string` (datetime)   | 运行结束的时间戳。如果运行尚未结束，则省略。                         |
| `webhook_sent_at`    | `string` (datetime)   | Web 钩子请求发送的时间戳。                                |
| `metadata`           | `JSON object`         | 与运行关联的自定义元数据。                                  |
| `kwargs`             | `JSON object`         | 运行输入、配置和其他调用参数。                                |
| `values`             | `JSON object`         | 线程最新检查点的状态值。仅对有状态运行存在。                         |
| `multitask_strategy` | `string`              | 运行使用的多任务策略。                                    |
| `error`              | `JSON object \| null` | 仅在运行失败时存在。包含 `error`（错误类型）和 `message`（详细信息）字段。 |

示例负载：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "run_id": "1ef6a5b8-4457-6db0-8b15-cffd3797fa04",
  "thread_id": "9dde5490-2b67-47c8-aa14-4bfec88af217",
  "assistant_id": "agent",
  "status": "success",
  "created_at": "2024-08-30T23:07:38.242730+00:00",
  "updated_at": "2024-08-30T23:07:40.120000+00:00",
  "run_started_at": "2024-08-30T23:07:38.300000+00:00",
  "run_ended_at": "2024-08-30T23:07:40.100000+00:00",
  "webhook_sent_at": "2024-08-30T23:07:40.150000+00:00",
  "metadata": {},
  "kwargs": {
    "input": {
      "messages": [{"role": "user", "content": "Hello!"}]
    }
  },
  "values": {
    "messages": [
      {"role": "user", "content": "Hello!"},
      {"role": "assistant", "content": "Hi there! How can I help you today?"}
    ]
  },
  "multitask_strategy": "reject",
  "error": null
}
```

当运行失败时，`error` 字段包含有关失败的详细信息：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "error": {
    "error": "TimeoutError",
    "message": "Run exceeded maximum execution time"
  }
}
```

## 保护 Web 钩子

为确保只有授权的请求能到达您的 Web 钩子端点，请考虑添加一个安全令牌作为查询参数：

```
https://my-server.app/my-webhook-endpoint?token=YOUR_SECRET_TOKEN
```

您的服务器应在处理请求之前提取并验证此令牌。

## 向 Web 钩子请求添加标头

<Note>
  在 `langgraph-api>=0.5.36` 中可用。
</Note>

您可以配置静态标头，以包含在所有出站 Web 钩子请求中。这对于身份验证、路由或向您的 Web 钩子端点传递元数据非常有用。

在您的 `langgraph.json` 文件中添加 `webhooks.headers` 配置：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "webhooks": {
    "headers": {
      "X-Custom-Header": "my-value",
      "X-Environment": "production"
    }
  }
}
```

### 在标头中使用环境变量

要包含机密或特定于环境的值，而无需将其签入配置文件，请使用 `${{ env.VAR }}` 模板语法：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "webhooks": {
    "headers": {
      "Authorization": "Bearer ${{ env.LG_WEBHOOK_TOKEN }}"
    }
  }
}
```

出于安全考虑，默认情况下只能引用以 `LG_WEBHOOK_` 开头的环境变量。这可以防止意外泄露不相关的环境变量。您可以使用 `env_prefix` 自定义此前缀：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "webhooks": {
    "env_prefix": "MY_APP_",
    "headers": {
      "Authorization": "Bearer ${{ env.MY_APP_SECRET }}"
    }
  }
}
```

<Note>
  缺少必需的环境变量将阻止服务器启动，确保您不会在配置不完整的情况下进行部署。
</Note>

## 限制 Web 钩子目标

<Note>
  在 `langgraph-api>=0.5.36` 中可用。
</Note>

出于安全或合规目的，您可以使用 `webhooks.url` 配置来限制哪些 URL 是有效的 Web 钩子目标：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "webhooks": {
    "url": {
      "allowed_domains": ["*.mycompany.com", "api.trusted-service.com"],
      "require_https": true
    }
  }
}
```

可用选项：

| 选项                 | 描述                                       |
| ------------------ | ---------------------------------------- |
| `allowed_domains`  | 主机名允许列表。支持子域名的通配符（例如，`*.mycompany.com`）。 |
| `require_https`    | 当为 `true` 时，拒绝 `http://` URL。            |
| `allowed_ports`    | 显式端口允许列表。默认为 443 (https) 和 80 (http)。    |
| `disable_loopback` | 当为 `true` 时，禁止相对 URL（内部回环调用）。            |
| `max_url_length`   | 允许的最大 URL 长度（以字符为单位）。                    |

## 禁用 Web 钩子

从 `langgraph-api>=0.2.78` 开始，开发者可以在 `langgraph.json` 文件中禁用 Web 钩子：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "http": {
    "disable_webhooks": true
  }
}
```

此功能主要针对自托管部署，平台管理员或开发者可能更倾向于禁用 Web 钩子以简化其安全状况——特别是在他们没有配置防火墙规则或其他网络控制的情况下。禁用 Web 钩子有助于防止不受信任的负载被发送到内部端点。

有关完整的配置详情，请参阅 [配置文件参考](/langsmith/cli?h=disable_webhooks#configuration-file)。

## 测试 Web 钩子

您可以使用在线服务测试您的 Web 钩子，例如：

* **[Beeceptor](https://beeceptor.com/)** – 快速创建一个测试端点并检查传入的 Web 钩子负载。
* **[Webhook.site](https://webhook.site/)** – 实时查看、调试和记录传入的 Web 钩子请求。

这些工具可帮助您验证 LangSmith 是否正确触发并向您的服务发送 Web 钩子。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs) 通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/langsmith/use-webhooks.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
