跳转到主要内容

使用 Python SDK 运行

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

安装

pip install fetch-hive-sdk
SDK 需要 Python 3.9+,底层使用 httpx

身份验证

FETCH_HIVE_API_KEY 环境变量设置为你的工作区 API 密钥(SDK 会自动读取它):
export FETCH_HIVE_API_KEY=fhk_...
from fetch_hive_sdk import FetchHive

client = FetchHive()
或显式传入密钥:
client = FetchHive(api_key="fhk_...")
有关如何创建和轮换密钥,请参阅 API 密钥

基本示例

直接运行工作流部署。该调用会阻塞,直到工作流完成:
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"])
请参阅 直接响应结构

方法参考

参数类型必填描述
deploymentstr工作流部署名称
variantstr部署变体名称
inputsdict[str, Any]Start 步骤定义的变量的键值对
async_modebool当为 True 时,立即返回,并通过签名回调投递结果
callback_urlstrasync_mode=True 时必填 - 运行完成时调用的 HTTPS 回调 URL
userstr用户跟踪 中显示的不透明调用方标识符
metadatadict[str, str | int | float | bool | None]调用方定义的扁平元数据,用于审计和日志过滤。请参阅 调用元数据
invoke_workflow 会为你构建请求体。当你传入 async_mode=True 时,SDK 会发送:
{
  "async": { "enabled": true, "callback_url": "https://example.com/webhook" }
}

处理响应

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:
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 触发 了解验证流程和签名负载结构。

配置

选项默认值描述
api_keyFETCH_HIVE_API_KEY 环境变量来自仪表板的 Bearer 令牌
base_urlhttps://api.fetchhive.com/v1覆盖 API 基础 URL
timeout120请求超时(秒)- 对于长时间运行的直接工作流请求请增大该值
client = FetchHive(
    api_key="fhk_...",
    base_url="https://api.fetchhive.com/v1",
    timeout=600,
)

错误

非 2xx 响应会引发 httpx.HTTPStatusError,其中包含状态码和响应体:
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)
有关工作流特有的失败案例,请参阅 错误处理;有关 HTTP 状态码含义,请参阅 错误与速率限制

链接

后续步骤