> ## 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.

# 使用 Python SDK 运行

> 使用 fetch-hive-sdk 包从 Python 调用工作流部署

# 使用 Python SDK 运行

当你想从 Python 调用工作流部署时，请使用官方的 `fetch-hive-sdk` 包。SDK 包装了公共的 [`POST /v1/workflow/invoke`](../api-reference/workflows/invoke) 端点，处理身份验证，并同时支持直接响应和回调投递。

## 安装

```bash theme={null}
pip install fetch-hive-sdk
```

SDK 需要 Python 3.9+，底层使用 `httpx`。

## 身份验证

将 `FETCH_HIVE_API_KEY` 环境变量设置为你的工作区 API 密钥（SDK 会自动读取它）：

```bash theme={null}
export FETCH_HIVE_API_KEY=fhk_...
```

```python theme={null}
from fetch_hive_sdk import FetchHive

client = FetchHive()
```

或显式传入密钥：

```python theme={null}
client = FetchHive(api_key="fhk_...")
```

有关如何创建和轮换密钥，请参阅 [API 密钥](../workspace/api-keys)。

## 基本示例

直接运行工作流部署。该调用会阻塞，直到工作流完成：

```python theme={null}
from fetch_hive_sdk import FetchHive

client = FetchHive()

run = client.invoke_workflow(
    deployment="YOUR_DEPLOYMENT_NAME",
    variant="YOUR_VARIANT_NAME",
    inputs={"topic": "State of enterprise AI in 2026"},
)

print(run["run_status"])
print(run["output"])
```

请参阅 [直接响应结构](../api-reference/workflows/invoke#response)。

## 方法参考

| 参数             | 类型                                               | 必填 | 描述                                                                  |
| -------------- | ------------------------------------------------ | -- | ------------------------------------------------------------------- |
| `deployment`   | `str`                                            | 是  | 工作流部署名称                                                             |
| `variant`      | `str`                                            | 否  | 部署变体名称                                                              |
| `inputs`       | `dict[str, Any]`                                 | 否  | **Start** 步骤定义的变量的键值对                                               |
| `async_mode`   | `bool`                                           | 否  | 当为 `True` 时，立即返回，并通过签名回调投递结果                                        |
| `callback_url` | `str`                                            | 否  | 当 `async_mode=True` 时必填 - 运行完成时调用的 HTTPS 回调 URL                     |
| `user`         | `str`                                            | 否  | 在 [用户跟踪](../user-tracking/overview) 中显示的不透明调用方标识符                   |
| `metadata`     | `dict[str, str \| int \| float \| bool \| None]` | 否  | 调用方定义的扁平元数据，用于审计和日志过滤。请参阅 [调用元数据](../user-tracking/invoke-metadata) |

`invoke_workflow` 会为你构建请求体。当你传入 `async_mode=True` 时，SDK 会发送：

```json theme={null}
{
  "async": { "enabled": true, "callback_url": "https://example.com/webhook" }
}
```

## 处理响应

```python theme={null}
run = client.invoke_workflow(deployment="my-workflow", variant="default")

print(run["run_status"])    # "completed" | "failed" | "running" | "queued"
print(run["output"])        # final workflow output
print(run["request_id"])    # use this to look up the run in Logs
```

## 回调投递

传入 `async_mode=True` 以立即返回，并让 Fetch Hive 在运行完成时调用你的回调 URL：

```python theme={null}
run = client.invoke_workflow(
    deployment="YOUR_DEPLOYMENT_NAME",
    variant="YOUR_VARIANT_NAME",
    inputs={"topic": "State of enterprise AI in 2026"},
    async_mode=True,
    callback_url="https://example.com/callback",
)

print("Queued:", run["run_status"])
print("Webhook secret:", run["webhook_secret"])
```

请保存 `webhook_secret`，以便你能验证传入回调的签名。请参阅 [回调投递与 Webhook 触发](./async-and-webhooks) 了解验证流程和签名负载结构。

## 配置

| 选项         | 默认值                            | 描述                            |
| ---------- | ------------------------------ | ----------------------------- |
| `api_key`  | `FETCH_HIVE_API_KEY` 环境变量      | 来自仪表板的 Bearer 令牌              |
| `base_url` | `https://api.fetchhive.com/v1` | 覆盖 API 基础 URL                 |
| `timeout`  | `120`                          | 请求超时（秒）- 对于长时间运行的直接工作流请求请增大该值 |

```python theme={null}
client = FetchHive(
    api_key="fhk_...",
    base_url="https://api.fetchhive.com/v1",
    timeout=600,
)
```

## 错误

非 2xx 响应会引发 `httpx.HTTPStatusError`，其中包含状态码和响应体：

```python theme={null}
import httpx

try:
    run = client.invoke_workflow(deployment="my-workflow", variant="default")
except httpx.HTTPStatusError as exc:
    print("Fetch Hive returned", exc.response.status_code, exc.response.text)
```

有关工作流特有的失败案例，请参阅 [错误处理](./error-handling)；有关 HTTP 状态码含义，请参阅 [错误与速率限制](../api-reference/errors-and-rate-limits)。

## 链接

* [PyPI 上的软件包](https://pypi.org/project/fetch-hive-sdk/)
* [GitHub 上的源码](https://github.com/Fetch-Hive/python-sdk)

## 后续步骤

* [回调投递与 Webhook 触发](./async-and-webhooks) - 验证回调签名
* [使用 API 运行](./run-with-api) - 使用 cURL 的相同流程
* [使用 Node.js SDK 运行](./run-with-nodejs-sdk)
* [使用 Ruby SDK 运行](./run-with-ruby-sdk)
* [使用 PHP SDK 运行](./run-with-php-sdk)
* [调用工作流](../api-reference/workflows/invoke) - 完整端点参考
