如何基于 OpenTelemetry 指标为 AI Agent 生成 Terraform 告警策略
如何基于 OpenTelemetry 指标为 AI Agent 生成 Terraform 告警策略【免费下载链接】skillsAgent Skills for Google products and technologies项目地址: https://gitcode.com/GitHub_Trending/skills29/skills如果你的 AI Agent运行在 Vertex AI Reasoning Engine 或 Cloud Run 上已经按 OpenTelemetryOTel规范输出指标那么 skills 仓库中的agent-platform-alert-configuration技能可以把这些指标转换成一组可直接部署的 Terraform 告警策略延迟异常、错误率 SLO 燃烧率、模型/工具调用错误率等输出为alerts.tf、variables.tf这类.tf文件。本文按技能的执行流程走一遍完整路径确认遥测 → 运行发现脚本 → 选择检测算法 → 编写 Terraform 配置 → 用技能自带的脚本完成去重与 Lint 校验。适用前提Agent 已埋点并实际发出 OTel 指标。文档明确说明如果 Agent 不发这些指标告警策略将没有可评估的数据流。本文覆盖 Reliability可靠性这一组 OTel 通用指标告警Quality质量告警依赖 Vertex AI Online Monitor与 Vertex AI 部署绑定且会产生额外费用不在本文路径内见文末限制。以下命令都在技能目录skills/cloud/agent-platform-alert-configuration/下执行{project_id}、{agent_name}、{location}、{agent_id}等花括号占位符分别替换为你的 GCP 项目 ID、Agent 显示名、区域和 Agent 资源 ID。前提确认 Agent 已开启遥测并安装脚本依赖先安装技能脚本的 Python 依赖版本锁定见 requirements.txt包含google-cloud-monitoring2.31.0、google-cloud-aiplatform1.160.0等pip install -r scripts/requirements.txt根据 telemetry_enablement.mdAgent 的部署规格中必须存在以下环境变量遥测才算开启环境变量取值GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRYtrue开启 tracing 与 Cloud Logging 导出OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENTEVENT_ONLY、SPAN_AND_EVENT或trueOTEL_SEMCONV_STABILITY_OPT_INgen_ai_latest_experimental如果 Agent 用 Terraform 管理对应写法是在google_vertex_ai_reasoning_engine资源的deployment_spec.env中补齐resource google_vertex_ai_reasoning_engine my_agent { # ... 其余配置不变 spec { deployment_spec { env { name GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY value true } env { name OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT value EVENT_ONLY } env { name OTEL_SEMCONV_STABILITY_OPT_IN value gen_ai_latest_experimental } } } }第一步运行发现脚本确认告警前置信息技能的强制前置流程是先运行gather_agent_info.py自动识别 Agent 运行时、验证遥测状态、指标范围Metric Scope和已链接的 BigQuery 数据集这些信息覆盖后续大部分手工核验python3 scripts/gather_agent_info.py --project-id {project_id} --agent-name {agent_name}脚本失败、返回部分数据或缺少所需信息时技能要求补跑手工回退步骤运行check_telemetry.py单独核验遥测开关顺带查询 token usage 指标在 Cloud Monitoring 中的命名空间python3 scripts/check_telemetry.py \ --project-id {project_id} \ --location {location} \ --agent-resource-name projects/{project_id}/locations/{location}/reasoningEngines/{agent_id} \ --query-monitoring-metadata输出形如文档示例格式--- [1] Checking agent {agent_id} telemetry status --- Agent support-bot Telemetry Status: ENABLED若显示DISABLED会同时打印缺失或取值不对的变量如ENABLE_TELEMETRYMISSING此时回到上一节补齐环境变量后重跑。如果指标范围仍未确定用 CLI 检查是否存在多项目 Metric Scopegcloud beta monitoring metrics-scopes list projects/{project_id}返回了 scoping project 时告警策略必须部署到那个 scoping project 下。第二步判断流量形态选择延迟检测算法延迟告警的算法必须匹配 Agent 的流量形态。错误率则不走算法选择文档规定错误率一律使用 Multi-Window Multi-Burn Rate SLO因为错误率序列天然稀疏大量 0标准差为 0 时 Z-Score 在数学上不稳定会误报。已有历史指标数据Agent 已上线有流量运行流量分析脚本分类延迟指标用workload.googleapis.com/gen_ai.invoke_agent.duration--reasoning-engine-id取 Agent 的metric.labels.gen_ai_agent_name值python3 scripts/analyze_traffic.py --live \ --project-id {project_id} \ --reasoning-engine-id {reasoning_engine_id} \ --metric-typeworkload.googleapis.com/gen_ai.invoke_agent.duration若报CredentialsMissingError退出码 1文档给出的处理是让用户在终端执行gcloud auth application-default login。脚本输出的形态映射见 has_historical_traffic_data.md方差比std_dev/mean1 周自相关流量分类延迟算法≤ 2.0≤ 0.75Steady / ConsistentLong-Window Z-Score1 周回看≤ 2.0 0.75Seasonal / CyclicalSeasonal Decomposition1w 与 1d 均值 2.0任意Bursty / InconsistentMoving Averages1 小时基线脚本因数据不足少于 14 天历史报ValueError或输出 New Agent / No Traffic 时按无历史数据处理。无历史数据全新 Agent文档不允许基于名字或描述猜测形态需要向使用者确认期望的流量模式若要求立即生成配置则采用默认的 Steady/Consistent 模式对应Short-Window Z-Score1 小时基线。此时要告知预热期延迟告警需要约 1 小时历史SLO Slow Burn 组件最长需要 3 天Fast Burn 的 1h/5m 部分 1 小时即可工作若改用 Seasonal Decomposition1woffset 会造成 1 周的告警盲区见 no_historical_traffic_data.md。本文后续示例以默认路径为准延迟用 Short-Window Z-Score。第三步编写 Terraform 告警策略文件位置优先使用使用者明确指定的路径未指定时放入项目已有的 Terraform/SRE 目录如monitoring/、ops/、sre/不要在仓库根目录盲写。技能规定输出只写 Terraformalerts.tf、variables.tf等并且除非使用者明确要求只针对某个 Agent否则条件中不得硬编码具体 Agent ID 或名称一律按gen_ai_agent_name分组动态覆盖全部 Agent。Reliability 一组必须配置恰好 5 个策略Latency异常检测、Error Rate Fast Burn SLO1 小时窗口、Error Rate Slow Burn SLO3 天窗口、Model Call Error RateSQL、Tool Call Error RateSQL。延迟和 SLO 错误率必须用condition_prometheus_query_languagePromQL下游模型/工具调用错误率必须用condition_sqlGoogleSQL 查询_Trace.Spans._AllSpans视图文档明确不要使用 MQL 或标准condition_threshold。variables.tf查询中引用了var.project_id与var.slo_targetvariable project_id { type string default {project_id} # 替换为你的 GCP 项目 ID } variable slo_target { type number default 0.95 }文档推荐按 5% 临界阈值配置错误率告警与 Vertex AI SLA 的可用性定义对齐查询中的(1 - ${var.slo_target})即对应这个 5% 预算因此slo_target取 0.95如需更早捕获降级文档提到可选配 1% 的 warning 阈值。策略 1LatencyShort-Window Z-Score已按算法选项组装以下代码块是把 reliability_alert_policies.md 中 Short-Window Z-Score 的 PromQL 查询填入模板后组装成的可直接使用形式duration 300s是文档要求回看 25 小时以内的短窗口告警Short-Window Z-Score、Moving Averages、Fast Burn SLO必须加 5 分钟缓冲过滤冷启动/部署期的瞬时尖峰。resource google_monitoring_alert_policy latency_short_window_zscore { project var.project_id display_name Agent Reliability - Latency Short-Window Z-Score combiner OR conditions { display_name Latency Z-Score 3 condition_prometheus_query_language { query EOT abs( histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resourcegeneric_node}[1m])) by (le, gen_ai_agent_name)) - histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resourcegeneric_node}[1h])) by (le, gen_ai_agent_name)) ) / stddev_over_time( (histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resourcegeneric_node}[1m])) by (le, gen_ai_agent_name)))[1h:1m] ) 3 EOT duration 300s # 5m buffer过滤瞬时冷启动尖峰 } } documentation { content High latency detected for the agent. mime_type text/markdown subject Agent Reliability - Latency Short-Window Z-Score on $${metric.label.gen_ai_agent_name} } user_labels { created-with-google-skill agent-platform-alert-configuration } }若第二步选到别的算法把查询换成长窗口 Z-Score、Moving Averages 或 Seasonal Decomposition 版本即可同一参考文档中有完整查询。注意 Seasonal Decomposition 只能追踪尖峰或回落单方向且分子不能加 offset这类长回看告警超过 25 小时文档要求不要设置duration。策略 2/3Fast Burn 与 Slow Burn SLO错误率查询通过${var.slo_target}引用变量——在字符串形式的 PromQL/SQL 中引用 Terraform 变量必须用${var.xxx}语法裸写var.xxx会在部署时失败。resource google_monitoring_alert_policy error_rate_fast_burn { project var.project_id display_name Agent Reliability - Error Rate Fast Burn SLO combiner OR conditions { display_name Error Rate Fast Burn (1h/5m) condition_prometheus_query_language { query EOT ( sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resourcegeneric_node,error_type!}[5m])) by (gen_ai_agent_name) / sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resourcegeneric_node}[5m])) by (gen_ai_agent_name) (1 - ${var.slo_target}) * 14.4 ) and ( sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resourcegeneric_node,error_type!}[1h])) by (gen_ai_agent_name) / sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resourcegeneric_node}[1h])) by (gen_ai_agent_name) (1 - ${var.slo_target}) * 14.4 ) EOT duration 300s # 5m buffer } } documentation { content Fast Burn error rate SLO violation detected. mime_type text/markdown subject Error Rate Fast Burn (1h/5m) on $${metric.label.gen_ai_agent_name} } user_labels { created-with-google-skill agent-platform-alert-configuration } } resource google_monitoring_alert_policy error_rate_slow_burn { project var.project_id display_name Agent Reliability - Error Rate Slow Burn SLO combiner OR conditions { display_name Error Rate Slow Burn (3d/6h) condition_prometheus_query_language { # 长回看25h按文档规则不设置 duration query EOT ( sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resourcegeneric_node,error_type!}[6h])) by (gen_ai_agent_name) / sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resourcegeneric_node}[6h])) by (gen_ai_agent_name) (1 - ${var.slo_target}) * 1.0 ) and ( sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resourcegeneric_node,error_type!}[3d])) by (gen_ai_agent_name) / sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resourcegeneric_node}[3d])) by (gen_ai_agent_name) (1 - ${var.slo_target}) * 1.0 ) EOT } } documentation { content Slow Burn error rate SLO violation detected. mime_type text/markdown subject Error Rate Slow Burn (3d/6h) on $${metric.label.gen_ai_agent_name} } user_labels { created-with-google-skill agent-platform-alert-configuration } }策略 4/5模型调用与工具调用错误率SQL 条件这两个策略查询的是导出到 Observability Analytics 的 Trace Spansstatus.code 2表示 ERROR表名来自第一步发现脚本输出的 Trace scope 表{trace_scope_table_name}需替换为该表名。如果gather_agent_info.py没有给出回退脚本是python3 scripts/list_trace_scope_table_names.py --project_id{project_id}。SQL 条件的前置依赖项目需要已链接 BigQuery 数据集type: LINKED且描述引用_Tracebucket。用bq ls --formatprettyjson --project_id{project_id}检查缺失时需使用者确认后再创建链接gcloud beta observability buckets datasets links create \ projects/{project_id}/locations/{location}/buckets/{bucket_id}/datasets/{dataset_id}/links/{link_id} \ --dataset{dataset_id} \ --bucket{bucket_id} \ --location{location} \ --project{project_id}参数默认值文档给定{bucket_id}默认_Trace{dataset_id}默认Spans{link_id}默认trace_bq_linked_dataset{location}从 analytics 表名中获取。被拒绝创建时跳过这两个 SQL 告警。resource google_monitoring_alert_policy model_call_error_rate { project var.project_id display_name Agent Reliability - High Model Call Error Rate combiner OR conditions { display_name Agent Model Call Error Rate Exceeds 5% condition_sql { query EOT SELECT JSON_VALUE(resource.attributes, $.cloud.resource_id) as agent_id, JSON_VALUE(attributes, $.gen_ai.request.model) as model, (COUNTIF(status.code 2) * 100.0) / COUNT(*) AS model_error_rate FROM {trace_scope_table_name} WHERE JSON_VALUE(attributes, $.gen_ai.request.model) IS NOT NULL GROUP BY agent_id, model HAVING model_error_rate 5.0 EOT # 周期性评估periodicity 取值范围 5 到 1440 分钟 minutes { periodicity 5 } # 查询返回任何一行有模型超阈值即触发 row_count_test { comparison COMPARISON_GT threshold 0 } } } user_labels { created-with-google-skill agent-platform-alert-configuration } }Tool Call Error Rate 策略结构相同SQL 查询改为按gen_ai.tool.name分组、过滤gen_ai.operation.name execute_tool的 span完整查询见参考文档。SQL 约束按文档执行不写手动时间戳过滤按cloud.resource_id分组实现动态监控不硬编码具体 Agent用HAVING过滤掉健康项。文档示例中 SQL 策略附带notification_channels [google_monitoring_notification_channel.email.name]。按技能主文档的规则默认不要配置任何通知渠道使用者没有明确提供渠道时保持不配置并在交付时主动询问是否需要配置不要从代码库中搜到渠道就擅自引用。第四步去重扫描与 Lint 校验写完.tf文件后按顺序跑两个脚本两者都位于 scripts/ 目录。重复策略扫描确保新策略与已有策略合并而不是追加重复python3 scripts/scan_duplicates.py {target_tf_dir} --engine-var ${var.gen_ai_agent_name}退出码 1 表示存在重复解析其 JSON 输出找到重复的资源目标在原文件上做合并式修改再重跑直到退出码 0。配置 Lint校验 PromQL 语法、引擎标签匹配与 HCL 结构python3 scripts/lint_syntax.py {path_to_tf_file}通过时输出Validation passed for {file}!非零退出或输出错误时按技能要求读取报错、定位到出错行修正 PromQL 或 HCL 问题然后重跑循环直到通过。部署与限制本文目标是生成并通过校验的.tf文件这一步不需要安装 Terraform。只有确认要部署时才需要安装且condition_sql要求 provider 版本 6.0.0或支持该特性的 5.x 后期版本。Agent 未发出 OTel 指标时Reliability、Cost、Safety、Security 四类告警都没有数据流可评估先按前提一节确认遥测。Quality 告警Final Response Quality、Tool Use Quality、Hallucination依赖 Vertex AI Online Monitor 与aiplatform.googleapis.com/online_evaluator/scores指标会引入 LLM 评估与 Cloud Trace/Cloud Logging 导出的额外费用技能要求执行前必须获得使用者明确确认本文不展开。文档提醒不要使用原始错误数/绝对失败数做边界流量变化下不可扩展应使用比率型错误率告警动态 Z-Score 基线对数天级的缓慢劣化存在盲区严格 SLA 场景建议并行配置静态阈值告警。完成校验后的状态目标目录下得到variables.tf与包含 5 个 Reliability 策略的alerts.tf若选择了 Cost 告警再按 cost_alert_policies.md 增加 Rapid Token Burn Rate 策略scan_duplicates.py退出码 0lint_syntax.py输出 Validation passed。若决定部署用 Terraform apply 该目录并留意延迟告警约 1 小时、Slow Burn SLO 最长 3 天的数据预热期。【免费下载链接】skillsAgent Skills for Google products and technologies项目地址: https://gitcode.com/GitHub_Trending/skills29/skills创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考