# 使用 Gemini 与 Temporal 构建持久运行的 AI 智能体

本教程将引导您构建一个耐用的 AI 智能体，它使用 Gemini API 进行推理和 [Temporal](https://temporal.io/) 为了耐用。它使用Temporal的内置 [Gemini SDK 集成](https://github.com/temporalio/sdk-python/tree/main/temporalio/contrib/google_genai).

智能体可以调用工具，例如查找天气警报或地理定位 IP 地址，并且会循环直到有足够的信息来响应。

这与典型的智能体演示的不同之处在于 **耐用性**。每个 LLM 调用和每个工具调用都由 Temporal 保存。如果进程崩溃、网络掉线或 API 超时，Temporal 会自动重试并从上次完成的步骤恢复。不会丢失任何对话历史记录，也不会错误地重复工具调用。

## 建筑  {% #architecture %}

该架构由三部分组成：

* **工作流程：** 单个 `generate_content` 打电话。 Gemini SDK 的自动函数调用 (AFC) 循环运行 *里面* 工作流程，Temporal 使其每一步都持久耐用。
* **活动：** Temporal 使各个工作单元变得持久。 Gemini API 调用自动成为活动。
* **工人：** 执行工作流程和活动的进程，也是您 API 密钥存在的唯一地方。

在此示例中，您将把所有这三个部分放在一个文件中（`durable_agent_worker.py`）。在实际实施中，您可以将它们分开以实现各种部署和可扩展性优势。您将使用 Temporal CLI 向智能体提供提示，因此无需编写客户端代码。

## 前提条件  {% #prerequisites %}

要完成本指南，您需要：

* Gemini API 密钥。您可以免费创建一个 [Google AI Studio](https://aistudio.google.com/apikey).
* [Python](https://www.python.org/downloads/) 版本 3.10 或更高版本。
* [紫外线](https://docs.astral.sh/uv/getting-started/installation/) 用于依赖管理。
* 该 [Temporal CLI](https://docs.temporal.io/cli) 用于运行本地开发服务器并启动工作流程。

## 设置  {% #setup %}

在开始之前，请确保您有 [Temporal开发服务器](https://docs.temporal.io/cli#start-dev-server)
本地运行：

```posix-terminal
temporal server start-dev
```

接下来，创建一个项目并安装所需的依赖项：

```posix-terminal
uv init durable-gemini-agent

cd durable-gemini-agent

uv add "temporalio[google-genai]" httpx python-dotenv
```

uv 为您创建和管理虚拟环境，因此本教程后面的每个 Python 命令都会运行 `uv run`.

创建一个 `.env` 使用 Gemini API 密钥将文件保存在项目目录中。您可以从以下位置获取 API 密钥 [Google AI Studio](https://aistudio.google.com/apikey).

```posix-terminal
echo "GOOGLE_API_KEY=your-api-key-here" > .env
```

{% callout type="note" %}
注意：只有工作进程需要 API 密钥。启动工作流的任何东西都不需要它，工作流本身也不需要它——真正的工作流 `genai.Client` 是在工作人员上构建的，并且永远不会交叉到工作流代码中，因此 Temporal 的事件历史记录中不会出现任何身份验证材料。
{% /callout %}

## 实施  {% #implementation %}

本教程的其余部分将逐步介绍 `durable_agent_worker.py` 从上到下，一点一点地构建智能体。创建文件并继续操作。

{% callout type="note" %}
注： `temporalio.contrib.google_genai` 集成是实验性的。其 API 可能会在 Temporal Python SDK 的未来版本中发生变化。
{% /callout %}

### 导入和沙箱设置  {% #imports %}

从必须预先定义的导入开始。的 `workflow.unsafe.imports_passed_through()` 块告诉 Temporal 的工作流沙箱让 `httpx` 不受限制地通过。导入 `httpx`
执行 `class _CookieCompatRequest(urllib.request.Request)`，并且沙箱会阻止对该 stdlib 类进行子类化。

你的工具使用 `httpx`, 和 `activity_as_tool()` 需要工作流程导入这些工具函数，以便 Gemini 可以从签名中导出其架构。所以 `httpx` 无论您如何拆分文件，都会到达沙箱 - 将工具移动到它们自己的模块中并不能避免它。

```python
from temporalio import workflow

with workflow.unsafe.imports_passed_through():
    import httpx
```

你不需要列出 `google.genai` 在这里。您稍后配置的 Temporal 插件会添加它 - 以及 `pydantic_core` 和 `annotated_types`— 到为您设置的沙盒直通。

### 系统指令  {% #system-instructions %}

接下来，定义智能体的个性。系统指令告诉模型如何表现。当不需要工具时，智能体被指示用俳句进行响应。

```python
SYSTEM_INSTRUCTIONS = """
You are a helpful agent that can use tools to help the user.
You will be given an input from the user and a list of tools to use.
You may or may not need to use the tools to satisfy the user ask.
If no tools are needed, respond in haikus.
"""
```

### 工具定义  {% #tool-definitions %}

现在定义智能体可以使用的工具。每个工具都是一个普通的 Temporal Activity：一个用 `@activity.defn`，带有类型注释的参数和描述性文档字符串。 Gemini 根据该签名和文档字符串构建函数声明，因此将每个参数记录在 `Args`
部分。

```python
import json

from temporalio import activity

NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"

@activity.defn
async def get_weather_alerts(state: str) -> str:
    """Get weather alerts for a US state.

    Args:
        state: Two-letter US state code (e.g. CA, NY)
    """
    headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
    url = f"{NWS_API_BASE}/alerts/active/area/{state}"

    async with httpx.AsyncClient() as client:
        response = await client.get(url, headers=headers, timeout=5.0)
        response.raise_for_status()
        return json.dumps(response.json())
```

接下来，定义 IP 地址地理定位工具：

```python
@activity.defn
async def get_ip_address() -> str:
    """Get the public IP address of the current machine."""
    async with httpx.AsyncClient() as client:
        response = await client.get("https://icanhazip.com")
        response.raise_for_status()
        return response.text.strip()

@activity.defn
async def get_location_info(ipaddress: str) -> str:
    """Get the location information for an IP address including city, state, and country.

    Args:
        ipaddress: An IP address to look up
    """
    async with httpx.AsyncClient() as client:
        response = await client.get(f"http://ip-api.com/json/{ipaddress}")
        response.raise_for_status()
        result = response.json()
        return f"{result['city']}, {result['regionName']}, {result['country']}"
```

这就是整个工具层。没有工具注册表，没有 `FunctionDeclaration`
构造，并且没有调度表 - 下一节将这些活动包装为 `activity_as_tool()`，它将每个参数按位置传递给 Activity。具有零个、一个或多个参数的工具都可以工作。

### 智能体工作流程  {% #agent-workflow %}

现在您已具备完成构建智能体的所有部件。的 `AgentWorkflow`
阶级造就一 `generate_content` 打电话。 `TemporalAsyncClient` 是一个插入式 `AsyncClient` 其每个 API 调用都作为 Temporal 活动运行，并且 `activity_as_tool()` 将您的每个活动变成 Gemini 工具。

当模型需要工具时，SDK 的 AFC 循环（在工作流程内运行）会将其分派给 `workflow.execute_activity`，将结果附加到对话中，并再次调用模型。该循环就是智能体，它是持久的，因为每个步骤都是记录在 Temporal 事件历史记录中的活动。

```python
from datetime import timedelta

from google.genai import types
from temporalio.contrib.google_genai import TemporalAsyncClient, activity_as_tool
from temporalio.workflow import ActivityConfig

TOOL_CONFIG = ActivityConfig(start_to_close_timeout=timedelta(seconds=30))

@workflow.defn
class AgentWorkflow:
    """Agent workflow that uses Gemini for LLM calls and executes tools."""

    @workflow.run
    async def run(self, prompt: str) -> str:
        client = TemporalAsyncClient()

        response = await client.models.generate_content(
            model="gemini-4-hydrogen",
            contents=prompt,
            config=types.GenerateContentConfig(
                system_instruction=SYSTEM_INSTRUCTIONS,
                tools=[
                    activity_as_tool(get_weather_alerts, activity_config=TOOL_CONFIG),
                    activity_as_tool(get_ip_address, activity_config=TOOL_CONFIG),
                    activity_as_tool(get_location_info, activity_config=TOOL_CONFIG),
                ],
            ),
        )

        # Leave this in place. You will un-comment it during a durability
        # test later on.
        # await workflow.sleep(timedelta(seconds=10))

        return response.text or ""
```

有几点需要注意：

* 构建 `TemporalAsyncClient` **里面** 工作流程。它没有任何凭证；它只知道如何将 API 调用转换为 Activity 调用。
* `activity_config` 必须设置 `start_to_close_timeout` 或 `schedule_to_close_timeout`。 Temporal 需要超时，并且工具活动没有默认值。
* Gemini API 活动默认为 60 秒 `start_to_close_timeout`。覆盖它 `TemporalAsyncClient(activity_config=...)` 如果您的模型调用需要更长的时间。

智能体非常耐用。如果工作线程在几轮后崩溃，Temporal 会准确地从上次中断的地方继续执行，而无需重新调用已执行的 LLM 调用或工具调用。

### 重试  {% #retries %}

Temporal 拥有重试，因此不要启用 Gemini SDK 自己的重试循环。设置重试行为 `retry_policy` 在 Activity 配置上改为：

```python
from temporalio.common import RetryPolicy

TOOL_CONFIG = ActivityConfig(
    start_to_close_timeout=timedelta(seconds=30),
    retry_policy=RetryPolicy(maximum_attempts=3),
)
```

API故障也为您分类。暂时状态 (408, 429, 5xx) 保持可重试状态，因此活动的重试策略适用；其他状态（例如格式错误的请求的 400）是不可重试的，因此工作流会快速失败，而不是在无法解决的错误上进行尝试。

您可以扩展该分类。集成将每个 API 故障表面为 `ApplicationError` 其类型是 Gemini 异常类名 —`ClientError`
对于 4xx， `ServerError` 对于 5xx — 因此在中列出一个名称 `non_retryable_error_types` 将其移出瞬态集。例如，要停止重试 Gemini 端中断并在第一个 5xx 上使工作流程失败，请通过以下方式将策略应用于 Gemini API 活动： `TemporalAsyncClient`:

```python
from temporalio.common import RetryPolicy

client = TemporalAsyncClient(
    activity_config=ActivityConfig(
        start_to_close_timeout=timedelta(seconds=60),
        retry_policy=RetryPolicy(
            maximum_attempts=5,
            non_retryable_error_types=["ServerError"],
        ),
    ),
)
```

### 工人启动  {% #worker-startup %}

最后，将所有东西连接在一起。 Temporal 工作线程连接到 Temporal 服务，并充当工作流和活动任务的调度程序。

这才是真正的地方 `genai.Client` 使用您的 API 密钥创建。 `GoogleGenAIPlugin` 使用该客户端并注册 Gemini API 活动、安装 Pydantic 数据转换器并配置工作流沙箱。

```python
import asyncio
import os

from dotenv import load_dotenv
from google import genai
from temporalio.client import Client
from temporalio.contrib.google_genai import GoogleGenAIPlugin
from temporalio.envconfig import ClientConfig
from temporalio.worker import Worker

async def main():
    gemini = genai.Client(api_key=os.environ["GOOGLE_API_KEY"])
    plugin = GoogleGenAIPlugin(gemini)

    config = ClientConfig.load_client_connect_config()
    config.setdefault("target_host", "localhost:7233")
    client = await Client.connect(**config, plugins=[plugin])

    worker = Worker(
        client,
        task_queue="gemini-agent",
        workflows=[
            AgentWorkflow,
        ],
        activities=[
            get_weather_alerts,
            get_ip_address,
            get_location_info,
        ],
    )
    await worker.run()

if __name__ == "__main__":
    load_dotenv()
    asyncio.run(main())
```

该插件删除了您原本需要的三块样板：

* 否 `data_converter=pydantic_data_converter`—该插件自行安装 Pydantic 有效负载转换器。
* 否 `activity_executor=ThreadPoolExecutor`——每个 Activity 都是异步的。
* 没有 Gemini 活动 `activities` 列表 - 插件注册它们。您只需注册您自己的工具。

## 运行智能体  {% #run-agent %}

这就是整个智能体。您无需编写客户端 - Temporal CLI 可以为您启动工作流程。

如果您还没有启动 Temporal 开发服务器：

```posix-terminal
temporal server start-dev
```

在新的终端窗口中，启动智能体工作程序：

```posix-terminal
uv run durable_agent_worker.py
```

在第三个终端窗口中，向智能体提交查询：

```posix-terminal
temporal workflow execute --type AgentWorkflow --task-queue gemini-agent \
    --input '"are there any weather alerts for where I am?"'
```

请注意任务队列：它与工作人员轮询的队列相同。启动工作流会将携带用户提示的工作流任务分派到该队列，这就是启动智能体的原因。 `execute` 阻塞直到工作流程完成并打印结果。如果您不想等待，请使用 `temporal workflow start` 具有明确的 `--workflow-id`，然后稍后收集结果 `temporal workflow result -w your-workflow-id`。当您省略时，Temporal 会为您生成工作流程 ID `--workflow-id`.

`--input` 采用 JSON，因此裸字符串提示需要在 shell 引号内有自己的引号。 CLI 不需要 Gemini API 密钥，也不需要数据转换器配置：工作流的参数和返回值都是纯字符串，由默认 JSON 有效负载转换器处理。

打开 Temporal UI `http://localhost:8233/namespaces/default/workflows` 观察主体循环的展开。你会看到 `gemini_api_client_async_request` 活动（每个模型回合一个）与每个工具调用一个活动交错，每个活动都标有 `tool_call` 总结。那个交错 *是* AFC 环路经久耐用且易于观察。

尝试几种不同的提示来查看智能体原因并调用工具。每个命令与上面的命令相同，但有一个新的 `--input`:

```posix-terminal
temporal workflow execute --type AgentWorkflow --task-queue gemini-agent \
    --input '"are there any weather alerts for New York?"'

temporal workflow execute --type AgentWorkflow --task-queue gemini-agent \
    --input '"where am I?"'

temporal workflow execute --type AgentWorkflow --task-queue gemini-agent \
    --input '"what is my ip address?"'

temporal workflow execute --type AgentWorkflow --task-queue gemini-agent \
    --input '"tell me a joke"'
```

最后一个提示不需要任何工具，因此智能体根据以下内容以俳句进行响应 `SYSTEM_INSTRUCTIONS`.

## 测试耐久性  {% #test-durability %}

以 Temporal 为基础构建，可确保您的智能体能够顺利应对故障。您可以使用两个不同的实验来测试这一点。

### 模拟网络中断  {% #network-outage %}

在此测试中，您将暂时禁用计算机的互联网连接，提交工作流程，观看 Temporal 自动重试，然后恢复网络以查看其恢复情况。

1. 断开计算机与互联网的连接（例如，关闭 Wi-Fi）。

1. 提交工作流程：

```posix-terminal
temporal workflow execute --type AgentWorkflow --task-queue gemini-agent \
    --input '"tell me a joke"'
```

3. 检查 Temporal 用户界面（`http://localhost:8233`）。您将看到 Gemini API 活动失败，并且 Temporal 在后台自动管理重试。

1. 重新连接到互联网。

1. 下一次自动重试将成功到达Gemini API，您的终端将打印最终结果。

### 工人车祸中幸存  {% #worker-crash %}

在此测试中，您将在执行过程中终止工作线程并重新启动它。 Temporal 重播工作流历史记录（事件源）并从上次完成的活动恢复 — 已完成的 LLM 调用和工具调用不会重复。

1. 为了给自己时间杀死工人，请打开 `durable_agent_worker.py` 并取消注释持久计时器 `AgentWorkflow.run`:

```python
await workflow.sleep(timedelta(seconds=10))
```

`workflow.sleep` 是一个 Temporal 定时器，而不是本地定时器。它被记录在历史中并且在重新启动后仍然存在，这就是使该测试可靠的原因。

2. 重新启动工作线程：

```posix-terminal
uv run durable_agent_worker.py
```

3. 提交触发多个工具的查询：

```posix-terminal
temporal workflow execute --type AgentWorkflow --task-queue gemini-agent \
    --input '"are there any weather alerts where I am?"'
```

4. 一旦工具调用完成并且计时器开始运行，就终止工作进程（`Ctrl-C` 在工作终端，或 `kill %1` 如果在后台运行）。

1. 重新启动工作线程：

```posix-terminal
uv run durable_agent_worker.py
```

Temporal 重播工作流程历史记录。已完成的 LLM 调用和工具调用是 **不** 重新执行 - 他们的结果立即从历史记录（事件日志）中重播，计时器恢复，并且工作流程成功完成。

## 更进一步  {% #going-further %}

该集成支持的内容超出了本教程的范围。请参阅 [插件文档](https://github.com/temporalio/sdk-python/tree/main/temporalio/contrib/google_genai)
详情：

* **流媒体。** 使用 `generate_content_stream` 像往常一样。要让外部使用者（聊天 UI）在工作流持久运行时实时观察块，请设置 `TemporalAsyncClient(streaming_topic=...)` 并主持一个 `WorkflowStream` 在工作流程中。
* **MCP。** 在工作线程上注册客户端 MCP 服务器 `GoogleGenAIPlugin(mcp_servers={...})` 并在工作流程中按名称引用它 `TemporalMcpClientSession`。工具发现和调用作为针对池化工作端连接的活动运行。
* **顶点人工智能。** 通行证 `vertexai=True` 对于工人双方 `genai.Client`
  和工作流程端 `TemporalAsyncClient`, 设置 `project` 和 `location` 明确地在工作流程端，因此重放保持确定性。

## 更多资源  {% #further-resources %}

* [Temporal 文档](https://docs.temporal.io/)
* [Temporal Python SDK](https://docs.temporal.io/develop/python)
* [Temporal Gemini SDK 集成](https://docs.temporal.io/develop/python/integrations/google-genai)
* [Google GenAI SDK](https://googleapis.github.io/python-genai/)
