Module 30.4: Cloud Telemetry, BigQuery Analytics & Cost Control
Theoryโ
Figure: Two-tier privacy-preserving cloud telemetry (NO_CONTENT Cloud Trace spans + GCS/BigQuery support_ops_agent_telemetry) paired with ADK 2.0's four enterprise FinOps levers.
From Local Observability Hooks to Managed Enterprise FinOpsโ
๐งญ Completing Part 6 โ Enterprise AgentOps (
Modules 30.1 โ 30.4): Over the first three modules of Part 6, you scaffoldedsupport-ops-agentfrom a spec (Module 30.1), built an automatedEvaluationDataset+ GEPA optimization flywheel (Module 30.2), and locked down releases withagents-cli-extension.yamland GitOps Terraform pipelines (Module 30.3). Now, before pushingsupport-ops-agentto live cloud runtimes in Part 7, you must master production telemetry, PII-safe auditing, and FinOps cost control.
In Module 26, you built in-process BasePlugin error interceptors and saw how standalone ADK scripts wire OpenTelemetry manually with get_gcp_exporters(). When you graduate to an enterprise service scaffolded with google-agents-cli (v1.10), two critical architectural shifts happen:
- Zero-Boilerplate Cloud Telemetry & Two-Tier Privacy Isolation: You no longer write manual
get_gcp_exporters()setup code. Instead,agents-cliwires OpenTelemetry at container startup and uses Terraform (telemetry.tf+service.tf) to enforce a strict privacy split: SREs debug live latency waterfalls in Cloud Trace with zero customer PII in spans, while authorized compliance and evaluation pipelines query full structured prompt/response payloads in Cloud Storage and BigQuery. - Proactive Agent FinOps: Multi-turn tool-using agents can silently burn 10xโ20x their expected budget if full conversation histories grow quadratically ($O(N^2)$), static instructions miss context caches, reasoning models hit uncalibrated output caps, or idle containers stay warm 24/7 in non-production environments.
1. Zero-Boilerplate Cloud Trace in Scaffolded Servicesโ
In a scaffolded ADK Python project, never paste manual get_gcp_exporters() or maybe_set_otel_providers() calls into app/agent.pyโdoing so registers duplicate span processors alongside the managed FastAPI launcher. Instead, inspect app/fast_api_app.py:
# Excerpt from scaffolded app/fast_api_app.py
# On Cloud Run and GKE, Cloud Trace export is enabled unconditionally:
otel_to_cloud = True
# (On Agent Runtime, the template gates this on the platform env var instead:
# otel_to_cloud = os.environ.get(
# "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY", ""
# ).lower() in ("true", "1"))
app: FastAPI = get_fast_api_app(
agents_dir=AGENT_DIR,
web=True,
artifact_service_uri=services.ARTIFACT_SERVICE_URI,
allow_origins=allow_origins,
session_service_uri=services.SESSION_SERVICE_URI,
otel_to_cloud=otel_to_cloud, # Wires Cloud Trace & Cloud Logging automatically
lifespan=lifespan,
)
Startup Telemetry Wiring Across Runtimes & Languagesโ
| Environment / Template | How Telemetry Starts | Destination |
|---|---|---|
Cloud Run / GKE (adk Python) | Automatic at startup via get_fast_api_app(..., otel_to_cloud=True) in app/fast_api_app.py | Cloud Trace + Cloud Logging |
Agent Runtime (adk Python) | Automatic when GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY="true" (set automatically by agents-cli deploy) | Cloud Trace + Cloud Logging + Agent Runtime Console |
ADK Go (--agent adk_go) | Automatic via setupObservability() in observability.go over OTLP to telemetry.googleapis.com | Cloud Trace + Cloud Logging |
| Local Interactive Dev | Run agents-cli playground with active Google Cloud ADC (gcloud auth application-default login) | Cloud Trace Explorer (Trace -> Trace explorer) |
The ADK OpenTelemetry Span Hierarchyโ
Every request into your deployed agent emits a hierarchical OpenTelemetry trace tree so SREs can pinpoint whether latency came from orchestration, model inference, or a slow downstream API tool:
invocation / invoke_workflow (top-level session turn)
โโโ agent_run / invoke_agent [gen_ai.agent.name = "support_ops_agent"]
โโโ call_llm (ADK model request wrapper)
โ โโโ generate_content (underlying google-genai SDK call)
โโโ execute_tool (Python function, MCP tool, or A2A AgentTool execution)
โ ๏ธ Critical Manifest Invariant (
gen_ai.agent.name): Inapp/agent.py,root_agent = Agent(name="support_ops_agent", ...)must stay synchronized withroot_agent_nameinagents-cli-manifest.yaml. Telemetry stamps that exact string onto spans and log labels asgen_ai.agent.name. RenamingAgent(name=...)in Python without updating the manifest breaks trace filters and dashboards!
2. Two-Tier Privacy-Preserving Telemetry Architecture (telemetry.tf)โ
In regulated enterprises (banking, healthcare, telco support), logging raw user prompts into OpenTelemetry spans is a compliance violation because any engineer with roles/cloudtrace.user could read customer PII in Trace Explorer. Conversely, disabling prompt logging altogether blinds your evaluation and compliance teams.
agents-cli solves this contradiction by separating telemetry into two completely independent tiers provisioned by deployment/terraform/single-project/telemetry.tf (and its cicd/ counterpart):
Tier 1: Metadata-Only Spans (Always Safe for Broad Engineering Access)โ
In deployment/terraform/single-project/service.tf, agents-cli injects three OpenTelemetry environment variables into your container by default:
OTEL_SEMCONV_STABILITY_OPT_IN="gen_ai_latest_experimental"โ Activates the OpenTelemetry GenAI semantic conventions.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT="NO_CONTENT"โ Strips prompt and completion text fromgoogle-genaispans and Cloud Logging span events.ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS="false"โ ADK Python specific: ADK's own span tracer defaults totruelocally; Terraform explicitly sets"false"so ADK'scall_llmandexecute_toolspans also omit message payloads.
๐จ Polyglot Pitfall โ Python Semconv Enum vs. Go Boolean: Both ADK Python and ADK Go read
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT, but they parse incompatible value types:
- ADK Python expects the semconv enum:
"NO_CONTENT"(default),"EVENT_ONLY","SPAN_ONLY", or"SPAN_AND_EVENT". Setting"true"or"false"in Python is invalid and silently falls back to"NO_CONTENT".- ADK Go (
--agent adk_go) parses the exact same variable as a boolean:"1"or"true"captures content, while every other string (including"false"and"NO_CONTENT") elides content!
Tier 2: Audited GCS + BigQuery Completions Warehouseโ
Tier 2 operates independently of OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT. Even when Tier 1 is locked to "NO_CONTENT", setting the upload hook variables in service.tf exports full structured interactions to an IAM-locked GCS bucket and joins them in BigQuery:
LOGS_BUCKET_NAME="<project-id>-<project-name>-logs"(bare bucket name, withoutgs://)OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK="upload"OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH="gs://<bucket>/completions"OTEL_INSTRUMENTATION_GENAI_UPLOAD_FORMAT="jsonl"
When agents-cli infra single-project --apply --project $PROJECT_ID runs before agents-cli deploy, telemetry.tf provisions:
- Hyphen-Normalized BigQuery Dataset (
{project_name//-/_}_telemetry): BigQuery dataset IDs cannot contain hyphens. Terraform runsreplace("${var.project_name}_telemetry", "-", "_"). Thus, our projectsupport-ops-agentmaps to datasetsupport_ops_agent_telemetry! - Runtime-Specific Log Sink Table: A Cloud Logging project sink routes
gen_ai.client.inference.operation.detailsentries (carrying GCS file referenceslabels.gen_ai_input_messages_refandlabels.gen_ai_output_messages_ref, token usage labels, andgen_ai.agent.name) into a day-partitioned BigQuery table whose name depends on the target runtime:- Cloud Run & GKE:
gen_ai_client_inference_operation_details - Agent Runtime:
aiplatform_googleapis_com_reasoning_engine_stdout(because Reasoning Engine containers emit structured GenAI logs via stdout)
- Cloud Run & GKE:
- External Table & Deduplicated
completions_view: Using a BigQuery Cloud Resource Connection (roles/storage.objectVieweron the logs bucket),telemetry.tfcreates thecompletionsexternal table overgs://<bucket>/completions/*and buildscompletions_view, which joins log metadata (trace,span_id,conversation_id,usage_input_tokens,usage_output_tokens,finish_reasons) with the unpacked NDJSON message parts (role,content,tool_name,tool_args,tool_response) while deduplicating repeated multi-turn history!
# Verify Tier 2 telemetry in BigQuery (note the ${PROJECT_NAME//-/_} hyphen-to-underscore rule!)
PROJECT_ID="my-gcp-project"
PROJECT_NAME="support-ops-agent"
bq query --use_legacy_sql=false \
"SELECT conversation_id, role, tool_name, usage_input_tokens, usage_output_tokens
FROM \`${PROJECT_ID}.${PROJECT_NAME//-/_}_telemetry.completions_view\`
LIMIT 10"
โ ๏ธ Deployment Order Rule: If you want Terraform-managed Tier 2 logging or BigQuery Analytics, always run
agents-cli infra single-project --apply --project $PROJECT_IDfirst, andagents-cli deploysecond. On Agent Runtime in particular, Terraform owns the Reasoning Engine resource, so runningterraform applyafter an imperativeagents-cli deploycannot reconcile cleanly without recreating the deployment.
3. Opt-In Conversational Analytics (--bq-analytics)โ
While Tier 2 Prompt-Response Logging archives raw OpenTelemetry GenAI request/response files for compliance auditing, product and data teams often want real-time, structured ADK agent lifecycle analytics ready for Looker Studio and SQL evaluation pipelines.
Scaffolding a Python ADK project with --bq-analytics (or wiring the plugin post-scaffold in app/agent.py) enables ADK's BigQueryAgentAnalyticsPlugin:
agents-cli create support-ops-agent --agent adk --bq-analytics
Under the hood, BigQueryAgentAnalyticsPlugin + BigQueryLoggerConfig adds four enterprise capabilities on top of Tier 2 logging:
- High-Throughput Storage Write API + Auto-Schema Evolution: Streams structured event rows directly into BigQuery via the asynchronous
BigQueryWriteAsyncClient(Apache Arrow serialization) and automatically upgrades table schemas across ADK releases without manual migrations. - Multimodal GCS Offloading: Large binary attachments (screenshots, audio streams, PDFs) are offloaded automatically to GCS via
BigQueryLoggerConfig(gcs_bucket_name=os.environ.get("BQ_ANALYTICS_GCS_BUCKET"), connection_id=os.environ.get("BQ_ANALYTICS_CONNECTION_ID"))so BigQuery rows remain fast and compact. - Tool Provenance & HITL Classification: Every tool execution is tagged with its architectural originโ
LOCAL,MCP,SUB_AGENT,A2A, orTRANSFER_AGENTโalongside Human-in-the-Loop pause kinds (hitl_confirmation,hitl_input,hitl_credential) and OpenTelemetrytrace/span_idcorrelation. - Pre-Built Analytical Views (
v_llm_response): Provides ready-to-query SQL surfaces for Looker Studio executive dashboards (latency percentiles, token burn by agent node, tool error rates) and feeds real production failure trajectories directly back into Module 30.2'sEvaluationDatasetflywheel.
# Zero-RPC, offline-safe initialization pattern in app/agent.py
# (Terraform `telemetry.tf` provisions `support_ops_agent_telemetry` ahead of time,
# so container startup performs zero blocking `create_dataset` network calls!)
import logging
import os
def build_telemetry_plugins() -> list:
"""Initializes BigQueryAgentAnalyticsPlugin only when GCP env & extras are present."""
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
if not project_id:
return []
try:
from google.adk.plugins.bigquery_agent_analytics_plugin import (
BigQueryAgentAnalyticsPlugin,
BigQueryLoggerConfig,
)
dataset_id = os.environ.get(
"BQ_ANALYTICS_DATASET_ID", "support_ops_agent_telemetry"
)
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "us-central1")
return [
BigQueryAgentAnalyticsPlugin(
project_id=project_id,
dataset_id=dataset_id,
location=location,
config=BigQueryLoggerConfig(
gcs_bucket_name=os.environ.get("BQ_ANALYTICS_GCS_BUCKET"),
connection_id=os.environ.get("BQ_ANALYTICS_CONNECTION_ID"),
),
)
]
except Exception as exc:
logging.warning("Skipping BigQueryAgentAnalyticsPlugin setup: %s", exc)
return []
๐ก Why Lazy-Import Inside
if project_id:?bigquery_agent_analytics_pluginimportsgoogle.cloud.bigquery_storage_v1andpyarrow(google-adk[bigquery-analytics]). Importing them lazily insidetry ... except Exception:guarantees that localuv run pytestand API-key-only prototype runs never crash withModuleNotFoundErroror missing ADC credentials!
4. The 4 Enterprise Cost Optimization Levers (FinOps for Agents)โ
Once completions_view and BigQueryAgentAnalyticsPlugin make token and compute consumption visible, you govern production spend across four architectural levers:
| Lever | Where Configured | Primary Cost Driver Addressed | Typical Production Impact |
|---|---|---|---|
| 1. Context Caching | App(context_cache_config=ContextCacheConfig(...)) | Repeated static SOPs, rubrics & tool schemas on every turn | Up to 75% reduction on cached static input tokens |
| 2. History Compaction | App(events_compaction_config=EventsCompactionConfig(...)) | Quadratic $O(N^2)$ multi-turn conversation & tool JSON growth | Bounds multi-turn input cost from $O(N^2)$ to $O(N)$ |
| 3. Output Guardrails & Model Tiering | Agent(model="gemini-3.8-flash", generate_content_config=...) + eval compare | Runaway output tokens, thinking starvation, or oversized models | 5xโ10x lower unit cost with verified rubric parity |
| 4. Compute Scaling | agents-cli deploy --min-instances 0 vs. service.tf scaling | Idle container CPU/RAM charges during off-peak hours | $0 idle compute in dev/bursty workloads vs. zero cold start in prod |
Lever 1: Context Caching (ContextCacheConfig) & Prefix Hygieneโ
Enterprise agents frequently carry 4,000+ tokens of static SLA runbooks, compliance policies, and MCP tool schemas. Without caching, you pay full input-token pricing to re-tokenize that identical prefix on every LLM call.
from google.adk.agents.context_cache_config import ContextCacheConfig
from google.adk.apps import App
context_cache = ContextCacheConfig(
min_tokens=4096, # Only create caches when static prefix >= 4,096 tokens
ttl_seconds=1800, # Keep cached prefix warm for 30 minutes
cache_intervals=10, # Refresh cache lifecycle across multi-invocation bursts
)
- Golden Rule of Prefix Determinism: Place static SOPs, policies, and examples at the very top of
instruction(note: curriculum snippets abbreviateSTATIC_SLA_SOPfor readability, whereas production enterprise runbooks + MCP tool schemas routinely exceed the4,096-token caching floor). Never inject volatile per-second strings (datetime.now().isoformat(), random UUIDs, or turn counters) into the staticinstructionprefixโchanging even one character at the top invalidates prefix cache reuse on every single turn! Expose dynamic timestamps via tools or append volatile context at the tail of the turn instead.
Lever 2: History Compaction (EventsCompactionConfig)โ
In an uncompacted N-turn troubleshooting session where each turn appends T_turn tokens of user messages and verbose JSON tool outputs, cumulative history tokens grow quadratically:
Cumulative_History_Tokens_uncompacted = sum(t * T_turn for t in 1..N) = N * (N + 1) / 2 * T_turn = O(N^2)
Enabling EventsCompactionConfig on App(...) instructs ADK to periodically summarize older session events while keeping overlap_size recent turns intact so the agent never loses immediate context:
from google.adk.apps.app import EventsCompactionConfig
# Turn-based compaction (or use token_threshold=32000, event_retention_size=5)
compaction = EventsCompactionConfig(
compaction_interval=10, # Summarize older history every 10 turns
overlap_size=2, # Retain the 2 most recent turns verbatim for continuity
)
app = App(
name="app",
root_agent=root_agent,
context_cache_config=context_cache,
events_compaction_config=compaction,
)
Lever 3: Output & Thinking Token Guardrails + Eval-Driven Model Tieringโ
Set generate_content_config=types.GenerateContentConfig(max_output_tokens=2048) on Agent(...) so a looping or overly verbose turn cannot emit tens of thousands of output tokens (which cost significantly more per token than input tokens).
from google.adk.agents import Agent
from google.genai import types
root_agent = Agent(
name="support_ops_agent",
model="gemini-3.8-flash",
instruction=STATIC_SLA_SOP,
tools=[lookup_ticket, check_sla_policy, escalate_ticket],
generate_content_config=types.GenerateContentConfig(
max_output_tokens=2048, # Leaves headroom for Gemini 3.8 thinking + final reply!
),
)
๐ง Gemini 3.8 Thinking Token Headroom Trap: In reasoning-capable models like
gemini-3.8-flash, internal thinking tokens count againstmax_output_tokens! If you setmax_output_tokens=256, the model can consume all 256 tokens during internal reasoning and stop withfinish_reason = MAX_TOKENSbefore emitting a single visible character to the user. Always budget headroom for both reasoning and output (e.g.,1024โ2048tokens for structured operational triage) and watchfinish_reasonsincompletions_view.
Pair output guardrails with Eval-Driven Model Tiering: standardize high-throughput operational agents on gemini-3.8-flash, and validate every prompt or model change with agents-cli eval compare (Module 30.2) against your holdout EvaluationDataset so cost reductions never degrade multi_turn_task_success or hallucination scores.
Lever 4: Compute Right-Sizing (--min-instances 0 vs. Warm service.tf)โ
LLM tokens are only half the bill; container compute is the other half. Inspect deployment/terraform/single-project/service.tf:
# Production default in scaffolded service.tf (Cloud Run v2)
max_instance_request_concurrency = 8
session_affinity = true
scaling {
min_instance_count = 1 # Eliminates cold starts for strict customer SLAs
max_instance_count = 10 # Caps runaway horizontal autoscaling during traffic spikes
}
- Dev, Staging & Bursty Internal Agents: Deploy with
agents-cli deploy --min-instances 0(or setmin_instance_count = 0in non-prod Terraform workspaces). Cloud Run scales down to zero containers ($0 compute) when idle and handles up to8concurrent async ADK turns per warm container when traffic arrives. - Customer-Facing SLA Production: Keep
min_instance_count >= 1inservice.tfso Python, FastAPI, and OpenTelemetry exporters are already warm before the first P1 ticket arrives.
Key Takeawaysโ
- Zero-Boilerplate Cloud Trace: Scaffolded FastAPI entrypoints enable
get_fast_api_app(..., otel_to_cloud=True)automatically on Cloud Run/GKE (and honorGOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRYon Agent Runtime)โnever duplicate OTel exporters manually inapp/agent.py. - Two-Tier Privacy Split:
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT="NO_CONTENT"+ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS="false"keep customer PII out of Cloud Trace spans, whileOTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK="upload"independently archives full NDJSON completions to GCS and{project_name//-/_}_telemetry.completions_view. - Know Your Naming & Polyglot Rules: BigQuery replaces hyphens with underscores (
support-ops-agentโsupport_ops_agent_telemetry), sink table names vary by runtime (gen_ai_client_inference_operation_detailsvs.aiplatform_googleapis_com_reasoning_engine_stdout), and Python uses semconv enums (NO_CONTENT) whereas Go uses booleans (true/false). - Four FinOps Levers: Combine
ContextCacheConfig(min_tokens=4096)(with deterministic static prefixes),EventsCompactionConfig, thinking-awaremax_output_tokens, and right-sizedmin_instance_countscaling to run enterprise agents at predictable unit economics.
๐ง Interactive Knowledge Checkโ
Your team scaffolds 'support-ops-agent' in ADK Python and deploys it with Terraform defaults (OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT='NO_CONTENT', ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS='false', and OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK='upload'). Where can an authorized auditor inspect full prompt and tool-response text?
1. Why does injecting datetime.now() at the top of an agent's instruction destroy ContextCacheConfig savings?
Prefix context caching matches identical token sequences starting from token 0 of the system prompt and tool declarations. Placing a per-second timestamp at the top of instruction mutates the very first tokens on every turn, causing 100% cache misses. Keep static SOPs and schemas at the top, and supply live timestamps via tools or end-of-turn user context.
2. What happens in ADK Python vs. ADK Go if an engineer sets OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT="true"?
In ADK Go, "true" (or "1") is parsed as a boolean and enables prompt/response capture in traces. In ADK Python, the variable expects an OpenTelemetry GenAI experimental semconv enum (NO_CONTENT, EVENT_ONLY, SPAN_ONLY, SPAN_AND_EVENT); "true" is invalid and silently falls back to NO_CONTENT!
3. Why must max_output_tokens leave extra headroom on gemini-3.8-flash?
Reasoning models bill and count internal thinking tokens against the same max_output_tokens budget as the visible response. Setting an overly tight cap like 128 or 256 can exhaust the budget mid-thought, returning an empty or truncated answer with finish_reason = MAX_TOKENS.
Closing Out Part 6: Ready for Cloud Runtimes & Enterprise (Part 7)โ
Congratulationsโyou have completed Part 6: Enterprise AgentOps with Google Agents CLI (v1.10)! Across Modules 30.1 through 30.4, you transformed support-ops-agent from a raw specification into a scaffolded, rubric-evaluated, GEPA-optimized, extension-governed, privacy-audited, and cost-controlled production package.
Next, in Part 7: Cloud Runtimes & Enterprise (Modules 31โ36), you will take this hardened support-ops-agent package and deploy it across Google Cloud's production execution surfacesโstarting in Module 31 with the Cloud Runtime Decision Matrix & Workload Identity (Agent Identity vs. custom Service Accounts), followed by hands-on rollouts to Cloud Run (Module 32), GKE (Module 33), Remote MCP Servers (Module 34), Agent Runtime & Agent Gateway (Module 35), and Gemini Enterprise & Agent Registry (Module 36)!