跳转到内容

用于 ADK 的“Temporal”插件

在 ADK 中得到支持。Python

Temporal 它是一个通用且耐用的执行平台,能够提升 ADK(Android Development Kit)代理程序的稳定性、可扩展性以及其适应生产环境的能力。LLM(Large Language Model,大型语言模型)的调用以及各种工具的执行过程都通过 Temporal 这一技术框架来管理。 活动(Activities) 该系统支持自动重试和恢复功能;如果某个环节出现故障,代理程序会从上次停止的位置继续执行任务,无需进行任何手动会话管理或使用外部数据库。

使用场景

“Temporal”插件为您的客服代表提供了以下功能:

  • 可靠的执行能力(即系统能够稳定、高效地完成各项任务):永远不要放弃已经取得的进展。如果你的代理程序崩溃或出现故障,Temporal 会自动从上一次成功的操作步骤开始恢复运行——无需人工干预。 会话恢复(Session Resumption) 必填项。
  • 内置的重试机制和速率限制功能:可配置的 重试策略(Retry Policies) 使用 `with` 语句来确保代码块的正确执行;同时,还提供了退避(backoff)机制,以及用于处理来自大型语言模型(LLM)提供商的“背压”(backpressure)的机制。
  • 长时间运行的代理程序(long-running agents)以及那些在后台持续运行的代理程序(ambient agents)。:支持那些可以连续运行数小时、数天甚至无限时间的代理程序和工具;这些程序在运行过程中会占用系统资源(例如阻塞其他进程)。
  • “人在回路中”(Human-in-the-loop)是一种人工智能(AI)系统设计方法,强调在AI系统做出决策或执行任务时,需要人类的参与和监督。这种方法认为,尽管AI在某些方面可能具有很高的效率和准确性,但人类的判断力、创造力以及对情境的理解能力仍然是不可或缺的。通过人在回路中的机制,可以确保AI系统的决策符合人类的价值观、道德标准和社会需求,同时也可以及时发现和纠正AI可能产生的错误或偏差。:暂停执行,直到获得人工批准后,再从暂停的位置继续执行。 (Temporal 的功能说明。) 任务路由(Task Routing) 能够以可扩展的方式将传入的信号(例如用户聊天信息或审批请求)路由到相应的业务流程中。
  • 可观测性与调试:检查您的代理程序执行过程中的每一个步骤; 以确定性的方式重新执行工作流程(即确保每次执行的结果都相同); 并通过相关工具找出程序中的故障(即导致错误或异常的原因)。 Temporal UI.

先决条件

请注意:从 Temporal Python 1.24.0 版本开始,这种集成功能仍处于实验阶段,未来可能会发生导致程序崩溃的变更(即破坏性的修改)。

安装

请同时安装 Temporal Python SDK 以及 google-adk 扩展包。

pip install "temporalio[google-adk]"

与代理程序(agent)一起使用。

基本设置

这次集成包含两个方面: 工作流程相关部分(即与工作流程执行相关的组件或模块) (您的代理程序运行的位置)以及 该 **worker side**(工作节点端) (该服务器托管了执行环境。)

1. 定义您的代理(agent)和工作流程(workflow)。

创建一个 ADK(Application Development Kit)代理,并将其封装到一个临时工作流(Temporal Workflow)中。使用该方法即可实现相关功能。 TemporalModel 将大型语言模型(LLM)的调用通过“Temporal Activities”进行处理/路由。

from contextlib import aclosing
from datetime import timedelta
from google.adk.agents import Agent
from google.adk.runners import InMemoryRunner
from google.genai import types
from temporalio import activity, workflow
from temporalio.common import RetryPolicy
from temporalio.contrib.google_adk_agents import TemporalModel
from temporalio.contrib.google_adk_agents.workflow import activity_tool
from temporalio.workflow import ActivityConfig

# A Temporal Activity

@activity.defn
async def get_weather(city: str) -> str:
    """Get current weather for a city."""
    # Your weather API call here
    return f"72°F and sunny in {city}"

# Wrap the activity as an ADK tool.  This tool will get memoized, retried, and timed out.
weather_tool = activity_tool(
    get_weather,
    start_to_close_timeout=timedelta(seconds=30),
    retry_policy=RetryPolicy(maximum_attempts=3),
)

# Use your agent
agent = Agent(
    name="weather_agent",
    model=TemporalModel(
      "gemini-flash-latest",
      activity_config=ActivityConfig(summary="Weather Agent")),
    tools=[weather_tool],
)

# Drop your agent in a Workflow to give it durable execution.

@workflow.defn
class WeatherAgentWorkflow:
    @workflow.run
    async def run(self, user_message: str) -> str:
        # For testing; for production, use Runner()
        runner = InMemoryRunner(agent=agent, app_name="weather_app")
        session = await runner.session_service.create_session(
            user_id="user", app_name="weather_app"
        )
        result = ""
        async with aclosing(runner.run_async(
            user_id="user",
            session_id=session.id,
            new_message=types.Content(
                role="user", parts=[types.Part.from_text(text=user_message)]
            ),
        )) as events:
            async for event in events:
                if event.content and event.content.parts:
                    for part in event.content.parts:
                        if part.text:
                            result = part.text
        return result

2. 配置并启动工作进程(worker)。

使用 GoogleAdkPlugin 要配置该工作进程(worker),使其能够运行 ADK(Adobe Digital Kit),并在分布式系统中参与工作流(Workflow)的执行:

import asyncio
from temporalio.client import Client
from temporalio.worker import Worker
from temporalio.contrib.google_adk_agents import GoogleAdkPlugin

async def main():
    client = await Client.connect(
        "localhost:7233",
        plugins=[GoogleAdkPlugin()]
    )

    worker = Worker(
        client,
        task_queue="my-agent-task-queue",
        workflows=[WeatherAgentWorkflow],
        activities=[get_weather],
    )
    await worker.run()

asyncio.run(main())

3. 启动工作流的执行

import asyncio
from temporalio.client import Client
from temporalio.contrib.google_adk_agents import GoogleAdkPlugin

async def start():
    client = await Client.connect(
        "localhost:7233",
        plugins=[GoogleAdkPlugin()]
    )
    result = await client.execute_workflow(
        WeatherAgentWorkflow.run,
        "What's the weather in San Francisco?",
        id="weather-agent-1",
        task_queue="my-agent-task-queue",
    )
    print(result)

asyncio.run(start())

使用 MCP 工具

执行 MCP 工具作为时间序列数据(Temporal data)的存储或处理工具 活动(Activities): 1. 数据采集与预处理 2. 数据分析 3. 数据可视化 4. 模型构建与训练 5. 模型部署与监控

from google.adk.agents import Agent
from google.adk.tools.mcp_tool import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams
from mcp import StdioServerParameters
from temporalio.client import Client
from temporalio.contrib.google_adk_agents import (
    GoogleAdkPlugin,
    TemporalModel,
    TemporalMcpToolSet,
    TemporalMcpToolSetProvider,
)

# Define a shared factory for your MCP toolset.
# Both the worker (TemporalMcpToolSetProvider) and agent (TemporalMcpToolSet) use it.
def toolset_factory(_):
    return McpToolset(
        connection_params=StdioConnectionParams(
            server_params=StdioServerParameters(
                command="npx",
                args=["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"],
            ),
        ),
    )

# The provider tells the worker how to instantiate the toolset.
toolset_provider = TemporalMcpToolSetProvider("my-tools", toolset_factory)

# Configure the client with the toolset provider
async def main():
    client = await Client.connect(
        "localhost:7233",
        plugins=[GoogleAdkPlugin(toolset_providers=[toolset_provider])]
    )
    # ... start a worker or execute a workflow with this client

# Reference the toolset by name when you declare your Agent (inside a @workflow.run).
# not_in_workflow_toolset lets this agent also run locally with `adk web`.
agent = Agent(
    name="tool_agent",
    model=TemporalModel("gemini-flash-latest"),
    tools=[TemporalMcpToolSet("my-tools", not_in_workflow_toolset=toolset_factory)],
)

本地开发(使用相关工具或环境) adk web

为了便于本地开发,当 Temporal Wrappers 在 Temporal Workflow 之外运行时,它们会自动切换回直接执行模式。因此,你可以正常使用这些工具。 adk web 此外,还可以使用其他 ADK 开发命令来执行相关操作,但这些命令需要在没有运行中的 Temporal 服务器的情况下使用。在这种模式下,您无法享受到“持久性执行”带来的好处(即命令的执行结果会保持稳定、不会因系统重启等原因而丢失),也无法准确测试应用程序在生产环境中的实际行为。

  • TemporalModel 和 activity_tool 这些系统能够自动运行:当它们发现自己处于工作流程之外时,会直接调用底层的 large language model(LLM,即大型语言模型)或相关函数。
  • TemporalMcpToolSet 需要…… not_in_workflow_toolset 该参数(如上图中的 MCP 示例所示)用于让系统知道如何在本地实例化该工具集。

它是如何工作的?

该插件可确保您的 ADK 代理在 Temporal 工作流代码中按预定的方式运行,并使输入数据与输出数据被序列化并记录下来,从而实现可靠的系统恢复功能。例如:

  • LLM 调用 这些操作通过“Temporal Activities”(临时性活动)的方式被执行。 TemporalModel如果某个调用失败或相关进程(worker)崩溃,系统会从上一次成功执行的步骤开始重新尝试或重新执行相关操作,从而提高系统的弹性(resilience)并减少令牌(token)的使用量。
  • 非确定性操作(Non-deterministic operations) `like`(用于表示相似或喜欢)time.time(), uuid.uuid4()这些内容会自动被替换为 Temporal 提供的确定性等效实现(即那些具有可预测行为的功能)。workflow.now(), workflow.uuid4())在 Workflow 代码中运行时才会出现这种情况(而在 Activity 代码中则不会出现)。
  • ADK 模块和 Gemini 模块 这些配置是专门为 Temporal 服务的。 sandbox 具有自动“穿透”(即数据可以直接传输而无需额外处理)功能的环境。
  • Pydantic 的序列化功能 ADK 的数据类型会自动进行配置(即:系统会根据数据类型自动设置相应的配置选项)。

其他功能/特性

能力(或功能) 描述
工具执行的稳定性(即工具在执行过程中能够保持稳定的性能,不会出现意外错误或崩溃) activity_tool `wraps` 工具将工具功能封装为 `Activity`(活动),从而支持长时间运行的工具、自动重试机制以及心跳检测(即定期检查工具是否仍在运行)。
MCP 工具的支持 TemporalMcpToolSet 以“Activity”的形式执行 MCP 工具,并实现完整的事件传播(即所有事件都会被正确地传递和处理)。
“人在回路中”(Human-in-the-loop)是一种人工智能(AI)系统设计方法,强调在AI系统做出决策或执行任务时,需要人类的参与和监督。这种方法认为,尽管AI在某些方面可能具有很高的效率和准确性,但人类的判断力、创造力以及对情境的理解能力仍然是不可或缺的。通过人在回路中的机制,可以确保AI系统的决策符合人类的价值观、道德标准和社会需求,同时也可以及时发现和纠正AI可能产生的错误或偏差。 您的代理工作流程可以等待…… 信号(Signals) 和 更新 需要等待用户的输入;客户端可以发送这些输入信息来重新启动代理(Agent)。
确定性运行时(Deterministic Runtime) GoogleAdkPlugin 将那些具有非确定性行为(即结果无法预测)的函数调用,替换为具有“时间安全性”(即其行为在特定时间范围内始终可预测)的等效函数调用。
可调试性(Debuggability) 每次调用大型语言模型(LLM)或执行相关工具时,这些操作都会在“Temporal UI”中以“Activity”(活动)的形式显示出来,因此调试故障变得非常简单。
可观测性(Observability) 您可以使用 OpenTelemetry 与自己喜欢的可观测性(Observability)工具进行集成;这些工具支持跨进程的数据传输(即跨不同进程的“数据跨度”),并且能够在系统崩溃的情况下依然保持数据的完整性和可靠性。
安全的版本控制机制 使用以下方法部署新的代理版本: 时间序列数据处理的版本控制机制(Temporal Worker Versioning) 在不会中断正在进行的操作(即“在飞行中”的操作)的前提下
多智能体协同调度(Multi-agent orchestration) 在 Workflow 中组合多个代理(agent),或者通过使用相关工具将这些代理扩展到更复杂的用例中。 子工作流(Child Workflows) 或者 Nexus

其他资源