> ## 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/agent/invoke`](../api-reference/agents/invoke) 端点,处理身份验证,支持流式响应和多模态输入,并同时提供同步和 `asyncio` 两种变体。

## 安装

```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 Keys](../workspace/api-keys) 了解如何创建和轮换密钥。

## 基本示例

向智能体发送消息并读取最终响应:

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

client = FetchHive()

reply = client.invoke_agent(
    agent="AGENT_UUID",
    message="Summarize the latest AI infrastructure trends",
)

print(reply["response"])
```

请参阅[非流式响应结构](../api-reference/agents/invoke#response)。

## 方法参考

| 参数          | 类型                                               | 必填 | 说明                                                                               |
| ----------- | ------------------------------------------------ | -- | -------------------------------------------------------------------------------- |
| `agent`     | `str`                                            | 是  | 智能体 ID                                                                           |
| `message`   | `str`                                            | 是  | 你想发送的消息                                                                          |
| `thread_id` | `str`                                            | 否  | 标识持久会话线程的任意字符串。Fetch Hive 会在首次使用时创建该线程,并在后续调用中恢复该线程。                             |
| `messages`  | `list[dict]`                                     | 否  | 调用方管理的对话历史。每一项格式为:`{"role": "user" \| "assistant" \| "system", "content": str}`。 |
| `user`      | `str`                                            | 否  | 在[用户追踪](../user-tracking/overview)中显示的不透明调用方标识符                                  |
| `metadata`  | `dict[str, str \| int \| float \| bool \| None]` | 否  | 由调用方定义的扁平元数据,用于审计和日志筛选。请参阅[调用元数据](../user-tracking/invoke-metadata)              |

该 SDK 为 `invoke_agent` 注入 `streaming: false`。要进行流式调用,请使用 `invoke_agent_stream`(见下文)。

## 处理响应

```python theme={null}
reply = client.invoke_agent(agent="AGENT_UUID", message="Hello")

print(reply["response"])      # final text
print(reply["model"])         # model identifier
print(reply["usage"])         # token usage breakdown
print(reply["request_id"])    # use this to look up the run in Logs
print(reply.get("tool_calls"))  # tool invocations made during the run
```

## 流式

使用 `invoke_agent_stream` 在事件到达时接收 Server-Sent Events。该方法返回一个生成器,会产出解析后的事件字典:

```python theme={null}
for chunk in client.invoke_agent_stream(
    agent="AGENT_UUID",
    message="Summarize the latest AI infrastructure trends",
    thread_id="user-456-support-session",
):
    if chunk.get("type") == "response":
        print(chunk.get("response", ""), end="", flush=True)
    elif chunk.get("type") == "tool":
        print(f"\n[Calling tool: {chunk.get('tool')}]")
    elif chunk.get("type") == "usage":
        print("\n\nUsage:", chunk["usage"])
```

该流会产出在 [Invoke Agent → Response](../api-reference/agents/invoke#response) 中记录的相同事件类型:`summary`(在自动摘要触发时)、`reasoning`、`response`、`tool`、最终的 `usage` 事件,或在提供商在流过程中失败时的 `error` 事件。

### 异步流式

对于 `asyncio` 应用,使用 `ainvoke_agent_stream`。它的参数相同,但返回一个异步迭代器:

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

async def main():
    client = FetchHive()
    async for chunk in client.ainvoke_agent_stream(
        agent="AGENT_UUID",
        message="Hello",
        thread_id="user-456-support-session",
    ):
        if chunk.get("type") == "response":
            print(chunk.get("response", ""), end="", flush=True)

asyncio.run(main())
```

## 多轮对话

### 持久化线程

将任意字符串作为 `thread_id` 传入,Fetch Hive 会在首次调用时创建该线程,并在每次使用相同值的后续调用中恢复该线程:

```python theme={null}
client.invoke_agent(
    agent="AGENT_UUID",
    message="What are the main AI infrastructure trends right now?",
    thread_id="user-456-support-session",
)

client.invoke_agent(
    agent="AGENT_UUID",
    message="Which of those trends have the most enterprise adoption?",
    thread_id="user-456-support-session",
)
```

### 无状态历史

自行管理状态,在 `messages` 中传入先前的回合。Fetch Hive 会将提供的历史用作上下文,但不会持久化:

```python theme={null}
client.invoke_agent(
    agent="AGENT_UUID",
    message="Which of those trends have the most enterprise adoption?",
    messages=[
        {"role": "user", "content": "What are the main AI infrastructure trends right now?"},
        {"role": "assistant", "content": "Teams are focusing on evals, tool routing, and observability."},
    ],
)
```

## 多模态输入

使用 `attachments` 在当前消息上附加图像:

```python theme={null}
result = client.invoke_agent(
    agent="vision-agent",
    message="Describe this image",
    attachments=["https://example.com/photo.jpg"],
)
print(result["response"])
```

URL 必须以 `https://` 开头。

## 配置

| 选项         | 默认值                            | 说明              |
| ---------- | ------------------------------ | --------------- |
| `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=120,
)
```

## 错误

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

```python theme={null}
import httpx

try:
    reply = client.invoke_agent(agent="AGENT_UUID", message="Hello")
except httpx.HTTPStatusError as exc:
    print("Fetch Hive returned", exc.response.status_code, exc.response.text)
```

请参阅[错误和速率限制](../api-reference/errors-and-rate-limits)了解状态码含义。

## 链接

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

## 下一步

* [通过 API 运行](./run-with-api) - 使用 cURL 的相同流程
* [使用 Node.js SDK 运行](./run-with-nodejs-sdk)
* [使用 Ruby SDK 运行](./run-with-ruby-sdk)
* [使用 PHP SDK 运行](./run-with-php-sdk)
* [Invoke Agent](../api-reference/agents/invoke) - 完整端点参考
