Observability — Agent 365 SDK with LangGraph
This sample shows how to add the Microsoft Agent 365 Python SDK to a LangGraph agent that already uses OpenTelemetry. After running this, both your existing exporter and the Agent 365 backend receive every span produced by the agent.
This sample uses the following Agent 365 packages:
- microsoft-agents-a365-observability-core · PyPI
- microsoft-agents-a365-observability-extensions-langchain · PyPI
The structure mirrors Google Cloud's LangGraph + OpenTelemetry reference sample: an OTel TracerProvider is set up first, an auto-instrumentor handles the LLM and tool spans, and a manual top-level span wraps agent.invoke(...) so the trace tree has a clear "agent run" root.
This is not a from-scratch tracing setup. For a full agent host with Microsoft 365 Agents SDK, see the
python/openai/sample-agentsample.
Demonstrates
- The recommended init order: existing OTel → Agent 365
configure()→ LangChain instrumentor. - Auto-instrumentation via
microsoft-agents-a365-observability-extensions-langchain— every LangChain LLM and tool callback emits an OTel span automatically; no per-call wrapping in the agent body. - A manual
InvokeAgentScopearoundagent.invoke(...)for the top-levelinvoke_agent <agent_name>span (the Agent 365 equivalent of Google'stracer.start_as_current_span("invoke agent")). - Default
ConsoleSpanExporterfor zero external setup, with a one-line swap to OTLP/gRPC for real backends (including Google Cloud Trace).
Prerequisites
- Python 3.11+
- An OpenAI or Azure OpenAI key
No collector or external service is required — the sample defaults to ConsoleSpanExporter so spans print to stdout.
Setup
Copy the env template and fill in your values:
cp .env.template .envThe template includes
ENABLE_OBSERVABILITY=true— leave this as-is. Without it, the SDK silently emits zero spans.Create a virtualenv and install:
python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install -e .
Run
python main.py
Expected output (truncated):
- A one-line weather answer for Seattle.
- Multiple JSON span dumps printed by
ConsoleSpanExporter. Look for spans namedinvoke_agent WeatherAgent,chat ChatOpenAI(typically twice — one per ReAct cycle), andexecute_tool get_weather.
Swap to a real OTLP endpoint
In main.py, comment out the ConsoleSpanExporter lines and uncomment the OTLPSpanExporter block. Set OTEL_EXPORTER_OTLP_ENDPOINT in .env (e.g. http://localhost:4317 for a local OTLP/gRPC collector, or https://telemetry.googleapis.com:443/v1/traces for Google Cloud Trace per the reference guide).
For Cloud Trace specifically, the reference guide also configures gRPC channel credentials with Google ADC; copy that block into Step 1 if you target Google Cloud.
What to look for
The console output (or your OTLP backend) should contain a span tree rooted at invoke_agent WeatherAgent. Inside it you'll see the LangGraph ReAct loop nested under the agent and tools graph nodes, with three spans that matter for Agent 365 telemetry:
invoke_agent WeatherAgent(the outer span — one per user turn; emitted byInvokeAgentScope)chat ChatOpenAI— one per LLM call (twice for a tool-using turn); the LangChain instrumentor renames LLM runs tochat <run_name>when the underlying response carries a chat-completion id, matching the OpenTelemetry GenAI semantic conventionsexecute_tool get_weather— the tool runs (renamed by the same instrumentor; carriesgen_ai.operation.name=execute_toolandgen_ai.tool.name=get_weather)
The instrumentor also emits internal LangGraph spans (LangGraph, agent, tools, call_model, should_continue, RunnableSequence, Prompt) — those are normal and reflect the underlying graph execution. The Agent 365 backend receives the same spans when the dedicated app-only OBS exporter below is enabled.
Where the integration happens
main.py is organized into the following sections (Step 2b is a sub-step that must run after Step 2):
- Step 1 — OTel SDK setup. Build a
TracerProvider, attach aBatchSpanProcessorwith the exporter, calltrace.set_tracer_provider(...). This is the part of the file you'd already have in your real app. - Step 2 — Agent 365
configure(). Detects the TracerProvider set by Step 1 and adds its processors to it. Optional A365 S2S export uses the sample-local app-only resolver; your existing exporter remains unchanged. - Step 2b —
CustomLangChainInstrumentor. Must run afterconfigure(); the constructor raisesRuntimeErrorotherwise. Construction auto-calls.instrument(). After this, every LangChain LLM and tool callback flows through Agent 365's tracer. - Step 3 — Build the agent. Standard
langgraph.prebuilt.create_react_agent(...)with alangchain-openaimodel and a@tool-decoratedget_weatherfunction. No observability code needed (the instrumentor handles it). - Step 4 — Run + flush.
InvokeAgentScopewrapsagent.invoke(...)so the run gets a top-levelinvoke_agent <agent_name>span;force_flush()is critical — without it, batched spans may not export before the process exits.
To diff against your own app: copy Steps 1, 2, and 2b into the file where your app currently initializes its TracerProvider, and apply the Step 4 InvokeAgentScope wrapping pattern around your agent.invoke(...) calls.
Going further
- Integration patterns and pitfalls: Use existing OpenTelemetry instrumentation with the distro
- Manual instrumentation example (no agent framework):
python/observability-with-otlp - Auto-instrumented OpenAI Agents SDK example:
python/observability-with-azure-monitor - Google Cloud reference this sample mirrors: LangGraph + OpenTelemetry on Stackdriver
Troubleshooting
- Sample runs without errors but no spans appear — most commonly
ENABLE_OBSERVABILITYis not set to a truthy value. The SDK gates span creation behind this env var and produces zero spans silently when it's missing. The sample's.env.templateincludes it; if you assembled.envmanually, addENABLE_OBSERVABILITY=true. - No spans printed to stdout —
BatchSpanProcessormay not have flushed; the sample callsforce_flush()on exit, so make sure the script ran to completion. KeyErroror auth error from OpenAI — verifyOPENAI_API_KEY(orAZURE_OPENAI_*variables) in.env.langchain-openaireads these directly.- Spans missing from your OTLP backend (after swap) — temporarily fall back to
ConsoleSpanExporterto confirm the SDK is producing spans. If they appear on stdout but not in your backend, the issue is in the exporter / collector / network. SystemExit: Agent 365 observability configuration failed— check logs for the failing step and the dedicated OBS prerequisites below.RuntimeError: Tracing SDK is not configured—CustomLangChainInstrumentor()ran beforeconfigure(). Make sure Step 2 (configure(...)) executes successfully before Step 2b.TypeError: wrap_function_wrapper() got an unexpected keyword argument 'module'— the LangChain extension useswrapt's legacy keyword-argument call style, whichwrapt 2.xremoved.pyproject.tomlpinswrapt<2to keep the extension working; if you assemble dependencies manually, do the same until the SDK ships a fix.
Optional A365 S2S export
Console/OTLP-only operation needs no OBS credentials. Enable A365 with:
ENABLE_A365_OBSERVABILITY_EXPORTER=true
AGENT365_OBS_TENANT_ID=<<YOUR_TENANT_ID>>
AGENT365_OBS_AGENT_ID=<<YOUR_AGENT_INSTANCE_CLIENT_ID>>
AGENT365_OBS_BLUEPRINT_CLIENT_ID=<<YOUR_BLUEPRINT_CLIENT_ID>>
AGENT365_OBS_BLUEPRINT_CLIENT_SECRET=<<YOUR_BLUEPRINT_CLIENT_SECRET>>
Use the actual instance client ID, never its blueprint or object/user IDs. Permissionless S2S export is conditional on eligible agent instance registration and authorization, not merely Entra identity creation or selecting the S2S endpoint. This sample does not provision identities or grant OBS permissions; workload permissions remain independent.
This sample provider is single-instance: one configured tenant and agent instance, plus a separate blueprint secret. It has no managed-identity option and requests tokens from login.microsoftonline.com, so sovereign clouds need provider changes. Multi-instance or multi-tenant deployments should cache per agent/tenant and reuse the hosting connection credential.
Absent or empty roles are accepted only with idtyp=app, or without idtyp when
oid equals sub. Valid nonempty roles also support legacy app tokens without
idtyp; any scp claim is rejected.
The sample-local resolver adapts the autonomous sample's
two-step FMI flow.
Blueprint credentials with fmi_path=agent instance client ID acquire T1 for
api://AzureADTokenExchange/.default; the instance uses T1 as its client assertion for
api://9b975845-388f-4429-889e-eab1ef63949c/.default. Both grants use
client_credentials. When enabled, the demo's AgentDetails uses the configured
tenant/agent, rather than demonstration IDs. Existing caller baggage is not repurposed.
Active export rejects missing/placeholder config, tenant/agent mismatches and delegated
scp tokens. The dedicated cache uses real expires_in/exp with a 60-second margin.
Safe errors replace stale, empty, delegated or legacy-route fallback. On 401/403
check IDs, blueprint credentials, registration and authorization for the exact agent
instance; never rewrite incoming baggage to bypass identity mismatches. Client secrets
are for development; production should implement the documented
certificate/managed-identity assertion flow.