You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
First-class OpenTelemetry support when running ADK agents outside Google Cloud #474
core[Component] This issue is related to the core interface and implementationneeds review[Status] The PR/issue is awaiting review from the maintainerrequest clarification[Status] The maintainer need clarification or more information from the author
Is your feature request related to a problem? Please describe.
In our company, we are piloting the Agent Development Kit to run AI agents entirely on-prem (inside an air-gapped Google Distributed Cloud rack).
While opentelemetry-api and opentelemetry-sdk are part of ADK’s dependencies, the current documentation only explains how telemetry is emitted when agents run on Vertex AI Agent Engine. There is no guidance or helper for configuring OTLP exporters when we deploy agents on our own Kubernetes cluster.
Describe the solution you’d like
A simple telemetry config block (or CLI flags) that lets us specify:
OTLP endpoint / headers
Service name / version
Sampling strategy
Optional automatic instrumentation for:
LLM requests (trace_call_llm)
Tool invocations (trace_tool_call)
Agent-to-agent (A2A) messaging
Docs + example showing how to push traces to an on-prem collector (Jaeger, Tempo, GCP Ops Agent in hybrid mode, etc.).
Describe alternatives you’ve considered
Manually initialising the OTEL SDK in our main.py and decorating each callback.
Works, but duplicates boilerplate and misses deeper internals (e.g. planner traces).
Exporting logs only – doesn’t give us span correlation across micro-services.
Additional context
We already have an OpenTelemetry collector running inside our data-centre; exposing ADK spans would let us view agent reasoning latency alongside the rest of our CI/CD traces.
Thank you @aabmass and @michaelsafyan will you also help to update the ADK documentation to provide instructions of OTel export part? That will be super cool! If that's the case, I guess we can close this ticket?
If you don't mind, it would be helpful for tracking and for prioritization/acceptance discussions with other contributors/maintainers to leave this open until the request is fully resolved.
But, yes, we would also like to ensure that documentation is updated and contains appropriate examples.
Realistically, the pull request that Aaron linked to will probably need to be broken down into smaller pull requests to make it in (as well as for simplifying incremental testing of its various pieces). Is there anything you can share with us regarding the level of urgency of this request? (Also helpful as a prioritization signal for us).
@rwang1987 Not sure exactly about the issue but I export traces like this, if its any helpful to you
importosfromopentelemetryimporttracefromopentelemetry.sdk.resourcesimportResourcefromopentelemetry.sdk.traceimportTracerProviderfromopentelemetry.sdk.trace.exportimportBatchSpanProcessorfromopentelemetry.exporter.otlp.proto.http.trace_exporterimportOTLPSpanExporterLANGFUSE_PUBLIC_KEY="pk-lf-8d838188-6390-4cb5-a30f-0a58c3d30752"LANGFUSE_SECRET_KEY="sk-lf-30df3ce3-472b-4018-a1fb-ae6866ce65c2"LANGFUSE_AUTH=base64.b64encode(
f"{LANGFUSE_PUBLIC_KEY}:{LANGFUSE_SECRET_KEY}".encode()
).decode()
os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = (
"http://localhost:3000/api/public/otel"# Original Local dev for Langfuse or mention your endpoint
)
# os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "https://us.cloud.langfuse.com/api/public/otel" # US data regionos.environ["OTEL_EXPORTER_OTLP_HEADERS"] =f"Authorization=Basic {LANGFUSE_AUTH}"provider=TracerProvider(resource=Resource.create({"service.name": "langfuse"}))
exporter=OTLPSpanExporter()
provider.add_span_processor(BatchSpanProcessor(exporter))
trace.set_tracer_provider(provider)
tracer=trace.get_tracer("bcc_agents")
fromfastapiimportFastAPI, Request, HTTPExceptionimportloggingimportjsonimportosfromdatetimeimportdatetimefromopentelemetry.proto.collector.trace.v1.trace_service_pb2import (
ExportTraceServiceRequest,
)
fromgoogle.protobuf.json_formatimportMessageToJson# Configure logginglogging.basicConfig(level=logging.INFO)
logger=logging.getLogger(__name__)
app=FastAPI()
# Create data directory if it doesn't existDATA_DIR="data"os.makedirs(DATA_DIR, exist_ok=True)
# Global counter for incremental request IDsrequest_counter=0defsave_payload_to_file(payload_data, content_type, request_id=None):
"""Save payload data to a JSON file in the data directory."""timestamp=datetime.now().strftime("%Y%m%d_%H%M%S_%f")
ifrequest_id:
filename=f"payload_{timestamp}_{request_id}.json"else:
filename=f"payload_{timestamp}.json"filepath=os.path.join(DATA_DIR, filename)
try:
withopen(filepath, "w", encoding="utf-8") asf:
json.dump(payload_data, f, indent=2, ensure_ascii=False)
logger.info(f"Payload saved to: {filepath}")
returnfilepathexceptExceptionase:
logger.error(f"Error saving payload to file: {e}", exc_info=True)
returnNone@app.post("/v1/traces")asyncdefreceive_traces(request: Request):
globalrequest_countercontent_type=request.headers.get("content-type")
logger.info(f"Received request to /v1/traces with Content-Type: {content_type}")
# Generate an incremental numeric request IDrequest_counter+=1request_id=request_countertry:
raw_payload=awaitrequest.body()
logger.info(f"Received raw payload (length: {len(raw_payload)} bytes)")
payload_to_save=Noneifcontent_type=="application/x-protobuf":
try:
trace_request=ExportTraceServiceRequest()
trace_request.ParseFromString(raw_payload)
# Pretty print the JSON outputjson_payload=MessageToJson(trace_request, indent=2)
logger.info(
f"Received OTLP Protobuf payload (converted to JSON):\n{json_payload}"
)
# Parse the JSON string to a dict for savingpayload_to_save=json.loads(json_payload)
exceptExceptionase:
logger.error(
f"Error parsing/converting OTLP Protobuf payload: {e}",
exc_info=True,
)
logger.info(
f"Raw Protobuf payload (hex) for failed conversion: {raw_payload.hex()}"
)
# Save the raw hex data if parsing failspayload_to_save= {"raw_hex": raw_payload.hex(), "error": str(e)}
elifcontent_type=="application/json":
# If OTLP exporter was configured for JSONtry:
payload_json=json.loads(raw_payload.decode("utf-8"))
logger.info(
f"Received OTLP JSON payload:\n{json.dumps(payload_json, indent=2)}"
)
payload_to_save=payload_jsonexceptExceptionase:
logger.error(f"Error decoding OTLP JSON payload: {e}", exc_info=True)
logger.info(f"Raw payload (hex) for failed JSON: {raw_payload.hex()}")
# Save the raw hex data if parsing failspayload_to_save= {"raw_hex": raw_payload.hex(), "error": str(e)}
else:
# Fallback for unexpected content typeslogger.warning(
f"Unexpected Content-Type: {content_type}. Attempting to log raw payload as hex."
)
logger.info(f"Raw payload (hex): {raw_payload.hex()}")
# Save the raw hex data for unexpected content typespayload_to_save= {"raw_hex": raw_payload.hex()}
# Save the payload to fileifpayload_to_save:
save_payload_to_file(payload_to_save, content_type, request_id)
return {"message": "Traces received successfully"}
exceptExceptionase:
logger.error(f"Error processing /v1/traces request: {e}", exc_info=True)
raiseHTTPException(status_code=500, detail="Internal server error")
if__name__=="__main__":
importuvicornuvicorn.run(app, host="0.0.0.0", port=1111)
@Jainish-S thank you for providing the sample code, but have you figure out a way to enable Opentelemetry to work with adk commands like adk web, adk run, adk api_server? Just using the root agent, not with any customized runner.
FYI we plan to add customization of OTel setup via cli flags and env variables over next few weeks. It should cover most requirements from the request and comments.
Any news regarding the missing user_id and session_id in Langfuse?
I'm running a similar setup to start the agent
`import os
import base64
if not os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") is None and not os.environ.get("OTEL_EXPORTER_OTLP_HEADERS") is None:
# LANGFUSE_AUTH = base64.b64encode(
# f"{os.environ.get('LANGFUSE_PUBLIC_KEY')}:{os.environ.get('LANGFUSE_SECRET_KEY')}".encode()
# ).decode()
# os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = os.environ.get("LANGFUSE_BASE_URL") + "/api/public/otel"
# os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Basic {LANGFUSE_AUTH}"
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
trace_provider = TracerProvider()
trace_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter()))
# Sets the global default tracer provider
from opentelemetry import trace
trace.set_tracer_provider(trace_provider)
tracer = trace.get_tracer(__name__)
import uvicorn
from starlette.middleware.base import BaseHTTPMiddleware
from google.adk.cli.fast_api import get_fast_api_app
from fastapi import Request
class DynamicRootPathMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
forwarded_host = request.headers.get("x-forwarded-host")
if forwarded_host:
# Set the root_path dynamically
x_forwarded_host = request.headers.get("x-forwarded-host", "")
request.scope["root_path"] = "/" + x_forwarded_host.split("/", 1)[1] #f"/{forwarded_host}".rstrip("/")
response = await call_next(request)
return response
app = get_fast_api_app(
agents_dir=".",
web=True, # set to true if you want to use their interface but keep it false to test your own endpoints
# session_db_url=db_url,
# lifespan=lifespan, # here you set your regular lifespan events
)
app.add_middleware(DynamicRootPathMiddleware)
if name == "main":
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 9000)))
Though any missing span attributes are unrelated to ADK being run inside/outside of GCP, so please open a new issue for it if anything is still missing. Here I think we should focus on allowing an easy setup of OTel exporting outside of GCP.
Speaking of which - AFAIU the only missing piece here that we want to add before closing the issue is documentation.
This issue has been automatically marked as stale because it has not had recent activity for 7 days after a maintainer requested clarification. It will be closed if no further activity occurs within 7 days.
core[Component] This issue is related to the core interface and implementationneeds review[Status] The PR/issue is awaiting review from the maintainerrequest clarification[Status] The maintainer need clarification or more information from the author
Activity
aabmass commentedon Apr 30, 2025
@rwang1987 have you seen #320? cc @michaelsafyan
rwang1987 commentedon May 1, 2025
Thank you @aabmass and @michaelsafyan will you also help to update the ADK documentation to provide instructions of OTel export part? That will be super cool! If that's the case, I guess we can close this ticket?
michaelsafyan commentedon May 1, 2025
If you don't mind, it would be helpful for tracking and for prioritization/acceptance discussions with other contributors/maintainers to leave this open until the request is fully resolved.
But, yes, we would also like to ensure that documentation is updated and contains appropriate examples.
Realistically, the pull request that Aaron linked to will probably need to be broken down into smaller pull requests to make it in (as well as for simplifying incremental testing of its various pieces). Is there anything you can share with us regarding the level of urgency of this request? (Also helpful as a prioritization signal for us).
rwang1987 commentedon May 1, 2025
@michaelsafyan Yes, for sure, I would love to keep this ticket open!
Jainish-S commentedon Jun 17, 2025
@rwang1987 Not sure exactly about the issue but I export traces like this, if its any helpful to you
rwang1987 commentedon Jun 17, 2025
@Jainish-S thank you for providing the sample code, but have you figure out a way to enable Opentelemetry to work with adk commands like adk web, adk run, adk api_server? Just using the root agent, not with any customized runner.
Jainish-S commentedon Jun 18, 2025
@rwang1987 Currently we don't have any options to pass it like an argument in the adk web or any cli command. But we can do this
File:
google/adk/cli/fast_api.pyOne thing we can do is set the tracer before initializing the app like this
svelezdevilla commentedon Jul 7, 2025
@Jainish-S
Hello, I tried your approach, and while the trace appears in langfuse, a few things don't work as expected.
Overriding of current TracerProvider is not allowed.user_idandsession_idin Langfuse.Currently using
langfuse==3.1.2andgoogle-adk==1.5.0.Any idea how this could be fixed?
Thank you very much!
jawoszek commentedon Aug 25, 2025
FYI we plan to add customization of OTel setup via cli flags and env variables over next few weeks. It should cover most requirements from the request and comments.
jawoszek commentedon Sep 19, 2025
Some related experimental changes were recently merged - e.g. 7870480, cee365a, f157b2e
They include support for standard OTel env variables - https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/ - if the
*_ENDPOINTvars are set, ADK (if run viaadk web/adk api_server/get_fast_api_app(...)) will send telemetry to specified collectors. Headers, sampling, service name/version or other resource attributes can be also controlled via env variables - https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration.Within next few weeks we should add documentation for the above and more instrumentation.
salvatore-cipolla commentedon Dec 11, 2025
Any news regarding the missing user_id and session_id in Langfuse?
I'm running a similar setup to start the agent
`import os
import base64
if not os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") is None and not os.environ.get("OTEL_EXPORTER_OTLP_HEADERS") is None:
import uvicorn
from starlette.middleware.base import BaseHTTPMiddleware
from google.adk.cli.fast_api import get_fast_api_app
from fastapi import Request
class DynamicRootPathMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
forwarded_host = request.headers.get("x-forwarded-host")
if forwarded_host:
# Set the root_path dynamically
x_forwarded_host = request.headers.get("x-forwarded-host", "")
request.scope["root_path"] = "/" + x_forwarded_host.split("/", 1)[1] #f"/{forwarded_host}".rstrip("/")
response = await call_next(request)
return response
app = get_fast_api_app(
agents_dir=".",
web=True, # set to true if you want to use their interface but keep it false to test your own endpoints
# session_db_url=db_url,
# lifespan=lifespan, # here you set your regular lifespan events
)
app.add_middleware(DynamicRootPathMiddleware)
if name == "main":
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 9000)))
`
jawoszek commentedon Apr 17, 2026
Session id attribute should be now present in
invoke_agentandgenerate_contentspans (seeGEN_AI_CONVERSATION_IDusage in https://github.com/google/adk-python/blob/main/src/google/adk/telemetry/tracing.py)User id should be now present in
generate_contentspans (see USER_ID usage in https://github.com/google/adk-python/blob/main/src/google/adk/telemetry/tracing.py)Though any missing span attributes are unrelated to ADK being run inside/outside of GCP, so please open a new issue for it if anything is still missing. Here I think we should focus on allowing an easy setup of OTel exporting outside of GCP.
Speaking of which - AFAIU the only missing piece here that we want to add before closing the issue is documentation.
adk-bot commentedon Apr 27, 2026
This issue has been automatically marked as stale because it has not had recent activity for 7 days after a maintainer requested clarification. It will be closed if no further activity occurs within 7 days.
mhenc commentedon Apr 28, 2026
Prepared an update for documentation: google/adk-docs#1686
mhenc commentedon Apr 29, 2026
Docs update merged https://adk.dev/observability/