> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fetchhive.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Invoke

> 使用智能体 ID 和消息，通过公开的 Fetch Hive API 向智能体发送消息

# 调用智能体

`POST /v1/agent/invoke`

从你自己的应用或服务向智能体发送一条消息。

## 身份验证

在 `Authorization` 请求头中发送工作区 API 密钥。

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

智能体 webhook 触发器使用智能体 webhook 密钥，而非 API 密钥。请参阅 [Webhook 触发器](#webhook-trigger)。

## 请求体

在编辑器中打开智能体并点击 **Code Snippet**，可以在 Fetch Hive 中查看当前的公开请求结构。

## Webhook 触发器

`POST /v1/agent/webhooks/{agent_id}`

当外部服务需要在不使用工作区 API 密钥的情况下启动智能体运行时，使用智能体 webhook 触发器。请求必须在 `X-Fetch-Hive-Webhook-Secret` 中包含智能体 webhook 密钥。如果第三方工具无法设置自定义请求头，可以退而使用 `?secret=YOUR_WEBHOOK_SECRET`。

智能体 webhook 触发器始终使用回调投递。包含 `async.callback_url`；Fetch Hive 返回 `202`，带有 `request_id` 和 `run_status: "running"`，随后向回调 URL 投递 `agent.completed` 或 `agent.failed`。

```bash theme={null}
curl 'https://api.fetchhive.com/v1/agent/webhooks/YOUR_AGENT_ID' \
  -H 'X-Fetch-Hive-Webhook-Secret: YOUR_WEBHOOK_SECRET' \
  -H 'Content-Type: application/json' \
  --data-raw '{
    "message": "Summarize the latest ticket",
    "thread_id": "external-thread-123",
    "metadata": {
      "customer_id": "cus_123",
      "plan": "enterprise"
    },
    "user": "external-user-1",
    "async": {
      "callback_url": "https://example.com/callback"
    }
  }'
```

`message` 是必填项。`thread_id` 可选，可以重复使用以恢复由调用方管理的线程。`metadata` 遵循与普通智能体调用相同的扁平且仅含标量的规则，并会出现在日志筛选中。

Fetch Hive 使用与入站触发器认证相同的 webhook 密钥对出站回调进行签名。
回调 `data` 在 `agent.completed` 时包含 `response`，在 `agent.failed` 时包含 `error`；使用顶层的 `event_type` 和 `request_id` 来表示终态和关联。

| 字段            | 类型      | 是否必填 | 描述                                                                                                                                          |
| ------------- | ------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `agent`       | string  | 是    | 智能体 ID                                                                                                                                      |
| `message`     | string  | 是    | 你想发送的消息                                                                                                                                     |
| `streaming`   | boolean | 否    | 流式传输响应事件,而不是等待一条最终的 JSON 响应                                                                                                                 |
| `thread_id`   | string  | 否    | 标识会话线程的任意字符串。Fetch Hive 在首次使用时创建新线程,并在后续以相同值调用时恢复该线程。适合持久的多轮对话。                                                                             |
| `messages`    | array   | 否    | 作为上下文使用的之前的会话轮次,不会将历史持久化到数据库。每项: `{ "content": string, "role": "user" \| "assistant" \| "system", "attachments"?: array }`。当你自行管理会话状态时使用此项。 |
| `attachments` | array   | 否    | 附加在当前 `message` 上的 HTTPS 文件 URL。每项可以是 URL 字符串,也可以是带有 `file_url` 的对象。受支持的文档类型按扩展名识别为 CSV、XLSX、PDF、DOCX 以及文本/Markdown。此处也可传入图片。               |
| `metadata`    | object  | 否    | 调用方定义的扁平元数据,用于审计和日志筛选。不会加入到智能体提示词中。                                                                                                         |

`metadata` 必须是扁平对象。键必须是非空字符串,值必须是字符串、数字、布尔值或 `null`。数组和嵌套对象会在运行启动前被拒绝。

`attachments` 项可以是简单的 URL 字符串：

```json theme={null}
[
  "https://example.com/customer-brief.pdf",
  "https://uploads.fetchhive.com/uploads/grme67114iieusl54m3u4swipr3v"
]
```

当你想提供元数据时,也可以使用如下对象结构：

```json theme={null}
{
  "file_url": "https://example.com/customer-brief.pdf",
  "file_name": "customer-brief.pdf",
  "file_type": "application/pdf"
}
```

仅接受 `https://` URL。每条消息最多允许五个附件。文档附件通过系统 `read_file` 工具以 `<available_files>` 清单的形式暴露给智能体；智能体在依赖文档内容前会先调用 `read_file`。如果附件 URL 或类型无效,Fetch Hive 会返回 `422 Unprocessable Entity`,而不会打开流。

受支持的文档附件：

* CSV: `text/csv`, `.csv`
* XLSX: `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`, `.xlsx`
* PDF: `application/pdf`, `.pdf`
* DOCX: `application/vnd.openxmlformats-officedocument.wordprocessingml.document`, `.docx`
* 按扩展名识别的文本和 Markdown: `.txt`, `.md`, `.markdown`

对于没有扩展名的 URL（例如 Fetch Hive 媒体库 URL),请直接传入该 URL。Fetch Hive 会将该 URL 加入 `read_file` 的允许名单,文件工具在抓取文件时会检测真实类型。

有效示例：

```json theme={null}
{
  "metadata": {
    "customer_id": "cus_123",
    "plan": "enterprise",
    "trial": false,
    "invoice_count": 12,
    "region": null
  }
}
```

无效示例：

```json theme={null}
{
  "metadata": {
    "customer": {
      "id": "cus_123"
    },
    "tags": ["enterprise"]
  }
}
```

代码片段对话框使用以下请求体结构：

```json theme={null}
{
  "agent": "AGENT_UUID",
  "message": "Your message here",
  "streaming": true,
  "attachments": [
    "https://example.com/customer-brief.pdf"
  ],
  "metadata": {
    "customer_id": "cus_123",
    "plan": "enterprise"
  }
}
```

使用 `thread_id` 进行持久会话时：

```json theme={null}
{
  "agent": "AGENT_UUID",
  "message": "What did we discuss last time?",
  "streaming": true,
  "thread_id": "user-456-support-session"
}
```

使用 `messages` 进行由调用方管理的（无状态）历史时：

```json theme={null}
{
  "agent": "AGENT_UUID",
  "message": "What else should I know?",
  "streaming": true,
  "messages": [
    {
      "content": "What are the latest AI trends?",
      "role": "user",
      "attachments": [
        "https://example.com/market-data.csv"
      ]
    },
    { "content": "Teams are focusing on evals, routing, and observability.", "role": "assistant" }
  ]
}
```

如果之前的 assistant 轮次生成了文件,请通过 `messages[].attachments` 在相应的历史消息中将该文件传回。Fetch Hive 使用当前消息和历史消息中结构化的附件 URL 来为后续轮次授权 `read_file` 访问；仅在纯文本中提到的 URL 不会被视为文件工具附件。

## 响应

如果 `streaming` 为 `true`，Fetch Hive 返回事件流。如果在流打开后提供商失败,Fetch Hive 会在关闭流前发送一个最终的 `error` 事件。如果客户端先断开连接,Fetch Hive 会将其视为静默取消,不会创建失败的智能体运行、计费用量或报告提供商错误事件,除非提供商已经完成并提交了用量。

推理事件示例：

```json theme={null}
{
  "request_id": "req_019d52846ea37682b03522fd0695cc43",
  "type": "reasoning",
  "response": "Looking at the latest model releases..."
}
```

响应事件示例：

```json theme={null}
{
  "request_id": "req_019d52846ea37682b03522fd0695cc43",
  "type": "response",
  "response": "Teams are standardizing around evals, routing, and observability.",
  "done": false
}
```

工具事件示例：

```json theme={null}
{
  "request_id": "req_019d52846ea37682b03522fd0695cc43",
  "type": "tool",
  "tool_id": "tool_123",
  "tool": "google_search",
  "tool_input": {
    "query": "latest AI infrastructure trends 2026"
  },
  "observation": {
    "results": []
  }
}
```

最终 usage 事件示例：

```json theme={null}
{
  "request_id": "req_019d52846ea37682b03522fd0695cc43",
  "type": "usage",
  "usage": {
    "duration": 4.79230260848999,
    "input_tokens": {
      "total_tokens": 24,
      "cached_tokens": 0
    },
    "output_tokens": {
      "total_tokens": 170,
      "reasoning_tokens": 64
    },
    "total_tokens": 194
  },
  "stop_reason": "completed"
}
```

错误事件示例：

```json theme={null}
{
  "request_id": "req_019d52846ea37682b03522fd0695cc43",
  "type": "error",
  "id": "msg_019d52846ea37682b03522fd0695cc43",
  "error": "openai provider stream error: HTTP 400: invalid request",
  "message": "openai provider stream error: HTTP 400: invalid request",
  "provider": "openai",
  "error_type": "provider_stream_error",
  "status_code": 502
}
```

如果 `streaming` 为 `false`，Fetch Hive 返回一条 JSON 响应。提供商执行失败时返回 `502 Bad Gateway`，带有 `error` 消息。

```json theme={null}
{
  "request_id": "req_019d528660dd7e22b15e5b13a1931c50",
  "model": "gpt-5-nano-2025-08-07",
  "duration": 4.641960144042969,
  "response": "Teams are moving from simple wrappers to systems with evals, tool routing, and tighter cost controls.",
  "reasoning": "The request asks for a short summary of current infrastructure trends.",
  "usage": {
    "input_tokens": {
      "total_tokens": 24,
      "cached_tokens": 0
    },
    "output_tokens": {
      "total_tokens": 187,
      "reasoning_tokens": 64
    },
    "total_tokens": 211
  },
  "stop_reason": "completed"
}
```

## 示例

```bash theme={null}
curl 'https://api.fetchhive.com/v1/agent/invoke' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  --data-raw '{
    "agent": "AGENT_UUID",
    "message": "Summarize the latest AI infrastructure trends",
    "metadata": {
      "customer_id": "cus_123",
      "plan": "enterprise"
    },
    "streaming": true
  }' \
  --compressed
```

## 相关内容

* 请参阅[身份验证](./authentication)了解 API 密钥设置
* 请参阅[智能体](../agents/overview)了解智能体设置和运行时上下文
* 请参阅[使用聊天进行测试](../agents/testing-with-chat)了解编辑器内的测试流程
* 请参阅[通过 API 运行](../agents/run-with-api)获取面向智能体的指南
