ADK 环境代理的事件触发与结果路由

ADK 支持将代理配置为环境代理,由云事件或新数据触发运行而无需人工输入。文章对比 /run 端点与触发端点两种接入方式,并说明结果可通过结构化日志或 Pub/Sub 路由到通知渠道。

## 对环境代理的触发动作[¶](<https://adk.dev/runtime/ambient-agents/#trigger-actions-with-ambient-agents>) 在 ADKPython v1.29.0GO v1.1.0中支持 在运行代理工作流程时,您可能想要针对某个事件或新数据可用而激活它,而不是等待人类的输入。您可以配置带有触发器的ADK代理以响应事件并进行工作,称为 *环境剂*。这些代理可以运行为背景过程,处理数据、监测事件、在没有人类干预的情况下同步应对。您可以使用环境代理来: - **答云事迹.** 上传到的文件处理 [云存储](<https://cloud.google.com/storage>),响应数据库的更改,或处理审计日志条目。 - **从队列处理消息 。** 分析收到的支持票,中度内容,将文件分类,或作为物品到达时运行 QA. - **按计划运行。** 编制每日报告,进行定期监测检查,或定期处理批量工作。 - **监测基础设施。** 响应整个基础设施的连续事件流,并自主地对变化采取行动。 ## 从环境剂中获得结果[¶](<https://adk.dev/runtime/ambient-agents/#getting-results-from-ambient-agents>) 因为环境剂运行时没有人类的相互作用,所以需要将其输出引导到通知通道. 常见的规律包括: - **[结构化伐木](<https://adk.dev/observability/logging/>).** 写入 JSON 日志并配置 [云监测](<https://cloud.google.com/monitoring/support/notification-options>) 通过电子邮件、Slack或PagerDuty通知的警告。 - **[Pub/Sub](<https://cloud.google.com/pubsub>).** 将结果发布给下游服务消费的话题. - **[应用程序集成](<https://cloud.google.com/application-integration/docs/listen-pub-sub-topic-send-email>).** 路线代理输出到电子邮件,Jira,或其他系统. ## 如何建造环境剂[¶](<https://adk.dev/runtime/ambient-agents/#how-to-build-ambient-agents>) ADK提供了两种方法: | | [`/run`](<https://adk.dev/runtime/api-server/>) | 触发端点 | | --- | --- | --- | | **事件来源** | 任意(Pub/Sub、webhooks、cron、定制服务) | [云泡/亚种](<https://cloud.google.com/pubsub>), [偶数c](<https://cloud.google.com/eventarc>) ([标准](<https://cloud.google.com/eventarc/standard/docs/overview>) 财务报告和财务报告 [高级](<https://cloud.google.com/eventarc/advanced/docs/overview>)) | | **有效载荷分析** | 你处理好了 | 自动( Base64 解码, CloudEvent 解析) | | **会话创建** | 启用 `--auto_create_session` | 自动( 每个事件一次) | | **会话存储** | 您的配置 [`SessionService`](<https://adk.dev/sessions/session/>) | 您的配置 [`SessionService`](<https://adk.dev/sessions/session/>) | | **货币管制** | 你处理好了 | 内建的可配置限制Semaphore | | **重试逻辑** | 你处理好了 | 暂时性错误时带有缓冲的反向指示器 | | **最好还是** | 自定义集成, 非 GCP 源 | GCP-事件驱动的工作量 | ## 使用( E) `/run`[¶](<https://adk.dev/runtime/ambient-agents/#using-run>) 使用该 [`/run`](<https://adk.dev/runtime/api-server/>) 当您需要完全控制集成或正在使用非 GCP 事件源时, 结束点。 启用 `--auto_create_session` 以便自动创建会话,然后连接任何 HTTP 客户端以调用 `/run` 当事情降临。 ``` adk api_server --auto_create_session path/to/your/agent ``` 这种模式与任何事件源一起工作,可以提出HTTP请求. 示例:处理收到的webhooks 以下内容: [云运行函数](<https://cloud.google.com/functions/docs/writing/write-event-driven-functions>) 从外部服务(例如 GitHub ) 接收一个网络hook 并将其转发给您的代理 : ``` import json import uuid import functions_framework import requests AGENT_URL = "https://my-agent-service-xxxxx.run.app" @functions_framework.http def handle_webhook(request): """Cloud Run function that receives webhooks and forwards to the agent.""" payload = request.get_json(silent=True) or {} requests.post( f"{AGENT_URL}/run", json={ "app_name": "my_agent", "user_id": payload.get("account", "webhook-caller"), "session_id": str(uuid.uuid4()), "new_message": { "role": "user", "parts": [{"text": json.dumps(payload)}], }, }, ) return ("ok", 200) ``` 示例: 发送卷曲事件 ``` curl -X POST http://localhost:8000/run \ -H "Content-Type: application/json" \ -d '{ "app_name": "my_agent", "user_id": "webhook-caller", "session_id": "session-123", "new_message": { "role": "user", "parts": [{"text": "{\"order_id\": \"1234\", \"status\": \"new\"}"}] } }' ``` ## 使用触发端点[¶](<https://adk.dev/runtime/ambient-agents/#using-trigger-endpoints>) 当事件源为 Pub/Sub 或 Eventarc 时使用触发端点, 您想要 ADK 处理有效载荷解析、 会话创建、 货币和重试 。 ### 事件处理方式[¶](<https://adk.dev/runtime/ambient-agents/#how-events-are-processed>) Pub/Sub和Eventarc 将事件作为 HTTP POST 请求传递给您的代理商。当触发端点收到事件时,它: 1. **解析请求** 根据源格式(Pub/Sub push message 或 CloudEvent ). 2. **解码有效载荷。** Base64-encoded消息数据解码,如有可能,解码为JSON. 3. **创建会话** 自动使用生成的 UUID 。不同于 `/run` 结束点, 您不需要启用 `--auto_create_session` ——触发端点总是每个事件产生新的会话. 4. **运行您的代理** 以解码事件为用户消息。 5. **返回状态代码 。** A `200` 响应告诉 Pub/Sub 或 Eventarc 事件处理成功。 A `500` 响应表示失败,事件源根据其重试政策重试发送. ### 支助来源[¶](<https://adk.dev/runtime/ambient-agents/#supported-sources>) | 来源 | 终点 | 说明 | | --- | --- | --- | | **Pub/Sub** | `/apps/{app_name}/trigger/pubsub` | 从 a 接收信件 [Pub/Sub 推订阅](<https://cloud.google.com/pubsub/docs/push>). | | **偶数c** | `/apps/{app_name}/trigger/eventarc` | 接收 [CloudEvents](<https://cloudevents.io/>) 执行人 [偶数c](<https://cloud.google.com/eventarc>) ([标准](<https://cloud.google.com/eventarc/standard/docs/overview>) 或 时 间 [高级](<https://cloud.google.com/eventarc/advanced/docs/overview>)),支持结构化和二进制内容模式。 | ### 示例代理人[¶](<https://adk.dev/runtime/ambient-agents/#example-agent>) PythonGo 以下代理从触发端点处理事件。 它使用 a `parse_event` 工具来提取事件数据和属性,然后分析内容。 代理代码( E)`event_processing_agent/agent.py`) ``` import json from google.adk.agents import LlmAgent def parse_event(raw_event: str) -> dict: """Parse and extract structured data from a trigger event. Trigger endpoints deliver events as a JSON string with 'data' and 'attributes' fields. This tool extracts those fields so the agent can reason about the event contents. """ try: event = json.loads(raw_event) except json.JSONDecodeError as e: return {"error": f"Failed to parse event JSON: {e}"} return { "data": event.get("data"), "attributes": event.get("attributes", {}), } root_agent = LlmAgent( model="gemini-flash-latest", name="event_processor", instruction="""You are an event-processing agent that handles incoming events from Pub/Sub and Eventarc triggers. When you receive an event: 1. Use the `parse_event` tool to extract the event data and attributes. 2. Analyze the event contents and determine what action to take. 3. Summarize what you found and what action you would recommend. Be concise and structured in your responses.""", tools=[parse_event], ) ``` 以下代理从触发端点处理事件。它提取事件数据和属性,然后分析内容。 代理代码( E)`event_processing_agent.go`) ``` import ( "context" "log" "os" "google.golang.org/genai" "google.golang.org/adk/v2/agent" "google.golang.org/adk/v2/agent/llmagent" "google.golang.org/adk/v2/cmd/launcher" "google.golang.org/adk/v2/cmd/launcher/full" "google.golang.org/adk/v2/model/gemini" ) func main() { ctx := context.Background() model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{ APIKey: os.Getenv("GOOGLE_API_KEY"), }) if err != nil { log.Fatalf("Failed to create model: %v", err) } a, err := llmagent.New(llmagent.Config{ Name: "event_processor", Model: model, Description: "Agent to process the events from Pub/Sub and Eventarc triggers.", Instruction: ` You are an event-processing agent that handles incoming events from Pub/Sub and Eventarc triggers. When you receive an event: 1. Analyze the event contents and determine what action to take. 2. Summarize what you found and what action you would recommend. Be concise and structured in your responses.`, }) if err != nil { log.Fatalf("Failed to create agent: %v", err) } config := &launcher.Config{ AgentLoader: agent.NewSingleLoader(a), } l := full.NewLauncher() if err = l.Execute(ctx, config, os.Args[1:]); err != nil { log.Fatalf("Run failed: %v\n\n%s", err, l.CommandLineSyntax()) } } ``` ### 启用触发[¶](<https://adk.dev/runtime/ambient-agents/#enable-triggers>) PythonGo 触发端点默认已被禁用。 启用它们与 `--trigger_sources` 旗帜 : ``` adk api_server --trigger_sources "pubsub,eventarc" path/to/your/agent ``` 对于生产部署,可以在自定义的FastAPI切入点上程序启用触发: 部署入境点`main.py`) Python 键 ``` import os import uvicorn from google.adk.cli.fast_api import get_fast_api_app AGENT_DIR = os.path.dirname(os.path.abspath(__file__)) app = get_fast_api_app( agents_dir=AGENT_DIR, web=False, trigger_sources=["pubsub", "eventarc"], ) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8000))) ``` 触发端点默认被禁用。 启用它们时使用相应的触发标记 : ``` go run agent.go web api pubsub eventarc ``` ### 试试吧[¶](<https://adk.dev/runtime/ambient-agents/#try-it-locally>) **1. 启用触发器启动服务器 :** PythonGo ``` adk api_server --trigger_sources "pubsub" event_processing_agent ``` ``` go run event_processing_agent.go web api pubsub ``` 对于 Go 服务器, 请使用 `http://localhost:8080/api/apps/event_processor/trigger/pubsub` 作为以下请求中的URL. **2. 发送测试事件 :** ``` curl -X POST http://localhost:8000/apps/event_processing_agent/trigger/pubsub \ -H "Content-Type: application/json" \ -d '{ "message": { "data": "eyJvcmRlcl9pZCI6ICIxMjM0IiwgInN0YXR1cyI6ICJuZXcifQ==", "attributes": {"source": "orders-service"} }, "subscription": "projects/my-project/subscriptions/orders-sub" }' ``` Base64 值解码为 `{"order_id": "1234", "status": "new"}`. 成功的对策: ``` {"status": "success"} ``` ## 触发源[¶](<https://adk.dev/runtime/ambient-agents/#trigger-sources>) ### 参数映射[¶](<https://adk.dev/runtime/ambient-agents/#parameter-mapping>) 密码 `/run` 结束点需要您提供 `app_name`, `user_id`,以及 `session_id`。触发端点自动导出这些 : | 参数 | 来源 | | --- | --- | | `app_name` | 摘自 URL 路径 (`/apps/{app_name}/trigger/...`) | | `session_id` | 每个事件自动生成的 UUID | | `user_id` | Pub/Sub: 联合国 `subscription` 字段。偶数 `source` 或 时 间 `ce-source` 头曰. | ### 信件格式[¶](<https://adk.dev/runtime/ambient-agents/#message-format>) 所有触发端点都会将即将到来的事件正常化为一致的JSON结构,然后传递给您的代理作为用户消息: ``` { "data": "<decoded event payload>", "attributes": {"key": "value"} } ``` - **`data`**: 解码事件有效载荷。 如果原始数据为 JSON , 则被解析成结构化对象。 否则, 它会被传递为纯字符串 。 - **`attributes`**: 来自事件源的密钥值元数据( 例如, Pub/ Sub 消息属性或 CloudEvents 头像 `ce-type`, `ce-source`). 您的代理接收了这个作为输入消息的 JSON 字符串, 可以解析它以提取数据和属性 。 ### Pub/Sub[¶](<https://adk.dev/runtime/ambient-agents/#pubsub>) Pub/Sub 触发端点处理来自 a 的信息 [Pub/Sub 推订阅](<https://cloud.google.com/pubsub/docs/push>)。当您的应用程序或服务发布针对某一主题的信息时使用它,例如: - 一个支持门户公布入场券,用于分门别类和路由. - 内容管道发送文件进行分类或节制。 - 监测服务发布自动分析警报。 #### 请求格式[¶](<https://adk.dev/runtime/ambient-agents/#request-format>) Pub/Sub 推动订阅以此格式发送请求 : ``` { "message": { "data": "eyJvcmRlcl9pZCI6ICIxMjM0IiwgInN0YXR1cyI6ICJuZXcifQ==", "attributes": {"source": "orders-service"}, "messageId": "123456789", "publishTime": "2026-04-08T12:00:00Z" }, "subscription": "projects/my-project/subscriptions/my-sub" } ``` 密码 `data` 字段为 Base64-encode。触发端点自动解码。 #### 回应[¶](<https://adk.dev/runtime/ambient-agents/#response>) | HTTP 状态 | 含义 | | --- | --- | | **200** | 已成功处理事件。 Pub/ Sub 确认信件 。 | | **400** | 无效的请求( malformated Base64 编码) 。 信件没有重试 。 | | **500** | 处理失败( 短暂或非短暂的代理错误) 。 pub/ Sub retrievies excutive at its [重试策略](<https://cloud.google.com/pubsub/docs/handling-failures>)配置 a [死字母队列](<https://cloud.google.com/pubsub/docs/dead-letter-topics>) 以捕捉屡次失败的信息。 | ### 偶数c[¶](<https://adk.dev/runtime/ambient-agents/#eventarc>) Eventarc 触发端点进程 [CloudEvents](<https://cloud.google.com/eventarc/docs/cloudevents>) 执行人 [偶数c](<https://cloud.google.com/eventarc>),两者 [标准](<https://cloud.google.com/eventarc/standard/docs/overview>) 财务报告和财务报告 [高级](<https://cloud.google.com/eventarc/advanced/docs/overview>) 。用它来应对Google Cloud上的事件,例如: - 文件被上传到 [云存储](<https://cloud.google.com/storage>) (对文档进行分类、归纳或提取数据)。 - 记录是写给 [BigQuery](<https://cloud.google.com/bigquery>) (运行异常检测或生成警报). - 一个 [审计日志](<https://cloud.google.com/logging/docs/audit>) 设立入境(违反国旗政策或可疑活动)。 支持两种内容模式: - **二进制内容模式** (Eventarc 默认值): CloudEvents 属性作为 `ce-*` HTTP头,正文包含事件数据(一般是Pub/Sub消息包装). - **结构化内容模式**:所有CloudEvents属性和数据都在JSON体中. 卷曲试验( 结构化模式) ``` curl -X POST http://localhost:8000/apps/my_agent/trigger/eventarc \ -H "Content-Type: application/json" \ -d '{ "specversion": "1.0", "type": "google.cloud.storage.object.v1.finalized", "source": "//storage.googleapis.com/projects/my-project", "id": "event-123", "data": { "bucket": "my-bucket", "name": "uploads/document.pdf" } }' ``` 使用卷曲( 二进制模式) 测试 ``` curl -X POST http://localhost:8000/apps/my_agent/trigger/eventarc \ -H "Content-Type: application/json" \ -H "ce-type: google.cloud.storage.object.v1.finalized" \ -H "ce-source: //storage.googleapis.com/projects/my-project" \ -H "ce-id: event-456" \ -H "ce-specversion: 1.0" \ -d '{ "message": { "data": "eyJidWNrZXQiOiAibXktYnVja2V0IiwgIm5hbWUiOiAiZG9jLnBkZiJ9", "attributes": {"eventType": "OBJECT_FINALIZE"} }, "subscription": "projects/my-project/subscriptions/eventarc-sub" }' ``` #### 回应[¶](<https://adk.dev/runtime/ambient-agents/#response_1>) | HTTP 状态 | 含义 | | --- | --- | | **200** | 成功处理事件, Eventarc 确认已交付 。 | | **500** | 处理失败。 Eventarc 根据其重试政策重试发送 。 | ## 配置[¶](<https://adk.dev/runtime/ambient-agents/#configuration>) ### 货币管制[¶](<https://adk.dev/runtime/ambient-agents/#concurrency-control>) 触发端点使用 semaphore 来限制同时代理引用的数量 。 这样可以防止您的代理在事件间断时超过您的 LLM 模型配额 。 PythonGo | 设置 | 默认 | 环境变量 | | --- | --- | --- | | 最大同时援引 | 10 | `ADK_TRIGGER_MAX_CONCURRENT` | | 设置 | 默认 | 旗帜 | | --- | --- | --- | | 最大同时援引 | 100 | `--trigger_max_concurrent_runs` | 默认情况下,ADK Go允许100同时引用,而ADK Python允许10. Pub/Sub 触发币值ADK滚开 ADK Go v2.3.0通过v2.5.0 不适用 `--trigger_max_concurrent_runs` 到 Pub/ Sub 触发器,所以 Pub/ Sub 事件运行时没有货币限制。为了限制 Pub/ Sub 的货币,请使用 ADK Go v2.6.0 或更高。 当达到货币限制时, 将收到的请求排队, 并在槽可用时处理。 货币控制是每个进程。 如果您部署多个 Cloud Run 实例, 则每个实例都会保持自己的独立 semaprore 。 PythonGo ``` # Allow up to 5 concurrent agent invocations export ADK_TRIGGER_MAX_CONCURRENT=5 ``` ``` go run event_processing_agent.go web api eventarc --trigger_max_concurrent_runs=5 ``` ### 自动重试后退[¶](<https://adk.dev/runtime/ambient-agents/#automatic-retry-with-backoff>) 触发端点包括内置重试逻辑, 用于瞬态错误, 如 `429 RESOURCE_EXHAUSTED` 响应。当检测到瞬态错误时,请求会用指数回转和焦急进行重试。 PythonGo | 设置 | 默认 | 环境变量 | | --- | --- | --- | | 最大重试尝试 | 3 | `ADK_TRIGGER_MAX_RETRIES` | | 基础备份延迟 | 1.0s | `ADK_TRIGGER_RETRY_BASE_DELAY` | | 最大后退延迟 | 30.0s | `ADK_TRIGGER_RETRY_MAX_DELAY` | | 设置 | 默认 | 旗帜 | | --- | --- | --- | | 最大重试尝试 | 3 | `--trigger_max_retries` | | 基础备份延迟 | 1.0s | `--trigger_base_delay` | | 最大后退延迟 | 10.0s | `--trigger_max_delay` | 默认情况下,ADK Go在10秒时封顶后退延迟,而ADK Python在30秒时封顶. 如果全部重试已用尽, 端点返回 HTTP 500, 信号 Pub/ Sub 或 Eventarc 重试更高层次的送货。 非短暂错误在不重试的情况下立即失效 。 ### 处理错误和灾后恢复[¶](<https://adk.dev/runtime/ambient-agents/#error-handling-and-disaster-recovery>) 由启动服务处理, 而不是由ADK处理: - 如果您的代理崩溃或返回错误, Pub/ Sub 或 Eventarc 将不会收到确认, 并自动重写信件 。 - 最大重试已用尽后, 未处理的信件会移动到 a [死字母队列( DLQ )](<https://cloud.google.com/pubsub/docs/dead-letter-topics>) 如果配置的话。 - 每次重交付都会产生新的会话,触发工作量从设计上来说是无国籍的. ### 超时考虑[¶](<https://adk.dev/runtime/ambient-agents/#timeout-considerations>) 所有触发端点都同步处理, 等待您的代理在返回回复之前完成。 其设计是: 保持 HTTP 请求的生命力, 确保在您的代理仍然工作期间, 主机基础设施不会终止进程 。 同步响应代码( 200 或 500 ) 是允许 Pub/Sub 和 Eventarc 正确识别成功或触发重试的原因 。 最大处理时间由上游服务规定: | 服务 | 最大超时 | | --- | --- | | Pub/Sub推车 | 10 分钟(交回截止日期) | | 偶数c | 10分钟[标准](<https://cloud.google.com/eventarc/standard/docs/overview>) 使用Pub/Sub作为运输工具; [高级](<https://cloud.google.com/eventarc/advanced/docs/overview>) (通过管道交货) | 触发端点是为在10分钟内完成的代理设计,这适合于处理单个事件,运行验证,对文档进行分类,并将结果写入下游服务. 长期代理商 触发端点不适合需要超过10分钟才能完成的代理。对于长期的工作量,请使用 [Pub/Sub 拉式订阅](<https://cloud.google.com/pubsub/docs/pull>), [云运行任务](<https://cloud.google.com/run/docs/create-jobs>),或者工人池建筑代之以。 ### 届会周期[¶](<https://adk.dev/runtime/ambient-agents/#session-lifecycle>) 会话遵循了所有其他 ADK 切入点的相同模式。它们都是通过您配置的 [`SessionService`](<https://adk.dev/sessions/session/>)。默认情况下, ADK 使用 `InMemorySessionService`,它使触发会话具有时空性:每个事件创建并在处理后丢弃。 如果您配置了持久性 `SessionService` (例如, `DatabaseSessionService`),触发会话会自动存储。这可用于审计、调试和事件驱动工作量的死后分析。 ## 部署[¶](<https://adk.dev/runtime/ambient-agents/#deploy>) 以下实例 [云运行](<https://cloud.google.com/run>) 作为部署目标。云运行是目前建议部署带有触发端点的环境剂的平台。 认证和安全 触发端点是 HTTP 网络服务器内的标准的 ADK 路由。 认证和安全是在部署级别上执行的, 与其它 ADK 端点相同。 当使用认证启用( 建议使用) 部署时, 所有端点都需要有效的认证。 GCP 服务使用认证 [服务账户](<https://cloud.google.com/iam/docs/service-accounts>) 身份。 详情请见每个服务处的文件。 PythonGo 使用启用的触发器将您的代理人部署到 Cloud Run `--trigger_sources` 旗帜 : ``` adk deploy cloud_run \ --project=$GOOGLE_CLOUD_PROJECT \ --region=$GOOGLE_CLOUD_LOCATION \ --trigger_sources="pubsub,eventarc" \ path/to/your/agent ``` 派你的探员到云里去 `adkgo` CLI和每个触发器的旗帜: ``` ./adkgo deploy cloudrun \ -p $GOOGLE_CLOUD_PROJECT \ -r $GOOGLE_CLOUD_LOCATION \ -s $SERVICE_NAME \ -e ./main.go \ --pubsub \ --eventarc \ --eventarc_max_concurrent_runs=5 ``` ADK GO为触发点服务 `/api` 路径前缀,所以点推订阅和 Eventarc 触发器位于 `/api/apps/{app_name}/trigger/pubsub` 财务报告和财务报告 `/api/apps/{app_name}/trigger/eventarc`. 在部署后, 将相应的 GCP 基础设施连接到您的代理触发端点 : - **Pub/Sub**: 创建一个 [推动订阅](<https://cloud.google.com/pubsub/docs/push>) 指点 `/apps/{app_name}/trigger/pubsub`. - **偶数c**: 创建一个 [标准触发器](<https://docs.cloud.google.com/eventarc/standard/docs/event-providers-targets>) 或一个 [Eventarc 高级管道](<https://cloud.google.com/eventarc/advanced/docs/overview>) 路径到 `/apps/{app_name}/trigger/eventarc`. - **云表调度器**: 创建一个 [调度工作](<https://cloud.google.com/scheduler/docs/creating>) 向您的 Pub / Sub 专题发布在 cron 日程表上。 见 [部署到云运行中](<https://adk.dev/deploy/cloud-run/>) 需要全员部署指示。 ## 接下来呢?[¶](<https://adk.dev/runtime/ambient-agents/#whats-next>) - 学会如何学习 [调用您的代理到云运行](<https://adk.dev/deploy/cloud-run/>) - 探索 [API 服务器端点](<https://adk.dev/runtime/api-server/>) 用于交互式代理引用 - 使用该 [Pub/ Sub 工具集](<https://adk.dev/integrations/pubsub/>) 赋予您的代理发布和调取消息的能力

查看原始来源