Tracing, Token Analytics and Latency
30-second answer
Tracing records each agent run, model call and tool call as a span with a duration and token counts. Connect an Application Insights resource to the project, opt in to GenAI tracing, configure Azure Monitor and instrument the SDK, then read the spans to see latency by step and tokens by model. Recording message content is a separate switch and should stay off in production, because prompts and answers can contain personal data.
Simulate it » No Azure account neededExam objective: 2.3.3 Set up observability by implementing tracing, token analytics, safety signals and latency breakdowns. (Skills measured as of April 16, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
Tracing needs an <strong>Application Insights</strong> connection on the project. That’s where the spans are stored.
👆 Click the glowing item in the portal to continue
Read the steps as text
- Tracing needs an Application Insights connection on the project. That’s where the spans are stored.
- The Tracing page lists runs with duration and tokens. Open the slow one.
- Each span is one step: the agent run, a model call with its tokens, and a tool call. The tool call is the slowest, so that’s where to look first.
- Tracing in code is opt-in and content capture is a separate switch. Monitoring then gives token and latency charts from the same data.
🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.
🖱️ Drag to rotate · scroll or pinch to zoom
Trace every call and count tokens
OpenTelemetry spans record each agent run, model call and tool call, with tokens and latency, and Application Insights stores them. Tracing is opt-in, and recording message content is for development only because it captures prompts and answers.
🤔 What happens if…
Read this tour as text
- Deploy a model, call the deployment. A deployment is a named copy of a model with a version, a deployment type and capacity. Your app calls the deployment name, never the model name. Pick a large model for hard work and a small language model for cheap, fast, simple work.
- RAG: retrieve first, then answer. Retrieval-augmented generation searches your own content (Azure AI Search, hybrid keyword plus vector), puts the best chunks in the prompt and asks the model to answer from them with citations. Without retrieval the model guesses.
- A multistep flow with checks. A workflow breaks one big request into steps you control: classify, extract to a JSON schema, call a tool, draft, then verify. Retries, fallbacks and a final check live in code, so one bad step can’t slip through unseen.
- Evaluate before you ship. Evaluators score each answer on a test set: groundedness (is it supported by the context?), relevance, coherence and safety checks. A fabrication shows up as a low groundedness score on one row, so you fix it before users see it.
- SDK, project endpoint and connections. The Foundry SDK (
azure-ai-projects) opens one door: AIProjectClient with the project endpoint and DefaultAzureCredential. From it your app gets an OpenAI-compatible client, deployments and connections (Azure AI Search, Application Insights) with no secrets in code. - Design the agent: role, goal, tool schema. An agent is a model plus instructions (role and goal), tools and a conversation (thread). A strict function schema names each parameter and marks the required ones, so the model asks the user instead of inventing a value.
- Retrieval, function calling and memory. One agent can use file search for documents, a function for live data and memory for what it learned about a user. The model asks to call a function; your code runs it and returns the result. Memory survives into a new conversation.
- Multi-agent orchestration. Several specialist agents can share a job. Sequential passes work down a line, concurrent fans out and merges, handoff moves control to the right specialist, group chat lets agents take turns in one shared conversation and Magentic lets a manager agent plan and delegate. Microsoft Agent Framework builds all five.
- Autonomy with approvals. Reads are safe, writes are not. A tool marked approval required pauses the run until a person decides. A hard limit in code blocks what no one should approve, whatever the model says.
- Monitor and debug agent runs. Agent evaluators read the whole run: intent resolution, tool call accuracy and task adherence. Error analysis groups the failing rows, such as a made-up tool argument, and points to the fix.
- Tune prompts and parameters. Instructions shape tone and rules, a few-shot example shows the format, temperature and top_p change how adventurous the wording is, and max output tokens caps length. A self-critique loop drafts, checks against a checklist and revises once.
- Trace every call and count tokens. OpenTelemetry spans record each agent run, model call and tool call, with tokens and latency, and Application Insights stores them. Tracing is opt-in, and recording message content is for development only because it captures prompts and answers.
- Route requests to the right model. A hybrid design puts rules first for answers code can decide, a small model for easy language work and a large or reasoning model only when needed. A model router can pick for you. Fewer big-model calls means a lower bill and faster replies.
The order agent passes demos, but real runs look odd. Score recorded runs with agent evaluators, read the error analysis, then switch on tracing to Application Insights and measure tokens and latency.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
Replies take four seconds, the bill keeps growing, and nobody knows which step is to blame.
😊 THE SOLUTION
Trace every run and read tokens and latency by span.
- Slow runs✓ Latency by span
- Token spend✓ Tokens by model and operation
- Prompts holding personal data✓ Content recording off in production
Start with a question
Why does a delivery app show you each stop and how long it took?
When a parcel arrives late, a total time doesn’t help. You want to see the steps: packed, left the depot, waited at the hub, out for delivery. The long wait at the hub tells you where to fix things.
A trace is that tracking page for an AI run. Each step is a span with its time and, for model calls, its tokens. You see where the time and the money went.
Explain it like I’m 10
The technical explanation
What a trace looks like
| Span | Duration | Tokens |
|---|---|---|
invoke_agent order-agent | 2140 ms | n/a (the whole run) |
chat support-chat (plan) | 610 ms | 412 in |
execute_tool get_order_status | 940 ms | n/a |
chat support-chat (answer) | 590 ms | 96 out |
Read it top to bottom: the agent run contains model calls and tool calls. The slowest child is the first place to look.
Set it up
- Connect Application Insights to the project (Foundry portal, Tracing, or a connection).
- Opt in to the GenAI instrumentation, which is a preview as of 25 November 2026.
- Configure Azure Monitor with the project’s connection string and instrument the SDK.
# pip install azure-ai-projects opentelemetry-sdk azure-core-tracing-opentelemetry azure-monitor-opentelemetry
# export AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING=true (opt in)
# export OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true (dev only: records prompts and answers)
from azure.ai.projects.telemetry import AIProjectInstrumentor
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor(connection_string=project.telemetry.get_application_insights_connection_string())
AIProjectInstrumentor().instrument()
openai = project.get_openai_client(agent_name="order-agent")
conversation = openai.conversations.create()
print(openai.responses.create(conversation=conversation.id, input="Where is order ORD-1042?").output_text)
Token analytics and latency in KQL
Spans carry attributes such as gen_ai.request.model, gen_ai.usage.input_tokens and gen_ai.usage.output_tokens. Summarise them:
dependencies
| where timestamp > ago(1d) and isnotempty(customDimensions["gen_ai.operation.name"])
| extend model = tostring(customDimensions["gen_ai.request.model"]),
tokens_in = toint(customDimensions["gen_ai.usage.input_tokens"]),
tokens_out = toint(customDimensions["gen_ai.usage.output_tokens"])
| summarize calls=count(), tokens_in=sum(tokens_in), tokens_out=sum(tokens_out),
p50=percentile(duration, 50), p95=percentile(duration, 95) by name, model
Use it to answer: which model costs most, which operation is slow, and is the p95 much worse than the p50? Safety signals work the same way: filter results and blocked requests show up as annotations you can count and alert on.
Privacy
Message content recording is off by default and separate from tracing. Turn it on in development to debug prompts. In production keep it off unless your policy allows it, restrict who can read the Application Insights data, and set a retention period.
Architect level Client-side and service-side views
Client-side tracing, shown here, instruments your code with OpenTelemetry, so you see the app’s own spans next to the SDK calls. Foundry also shows agent runs and monitoring dashboards in the portal. Use the client-side traces to follow one request across your own services, and the portal views to watch quality, tokens and latency over time. Both read from Application Insights.
Real-world business scenario
Contoso Retail (fictional)
- The problem
- The order agent took about four seconds per reply, the monthly bill rose, and nobody knew which step caused either.
- What they used
- Application Insights connected to the Foundry project, GenAI tracing opted in, content recording off in production, and a KQL query for tokens and p50 and p95 latency by model and operation.
- Why that choice
- The trace showed the get_order_status tool took 940 ms and the planning call used 412 input tokens that a shorter prompt could cut.
- The result
- The team added a cache for the order lookup and trimmed the prompt, and the p95 latency dropped without touching the model.
When to use it and when not to
✓ Use it when…
- You need to find slow or costly steps in a model or agent run.
- You must audit which tools an agent called.
- You want token and latency numbers by model and operation.
✕ Think twice when…
- Recording message content in production without a privacy decision.
- Looking only at average latency.
- Tracing instead of evaluating quality. Traces don't say if answers are right.
↔ Alternatives to consider
- Evaluators for answer quality.
- Azure Monitor metrics for simple request counts and errors.
- Foundry monitoring dashboards for trends over time.
Test yourself with exercises
5 original practice questions in the AI-103 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner What is a trace?
Model answer
It's the story of one run, step by step. Each step, like a model call or a tool call, is a span with how long it took and, for models, how many tokens it used.
Intermediate How do you find the slowest step of an agent run?
Model answer
I open the trace and compare span durations. In the example the tool call took 940 ms and the model calls 610 ms and 590 ms, so the tool is the first thing I would look at.
Experienced developer How do you get token usage per model?
Model answer
Model spans record input and output token counts and the model name. I query those attributes in Application Insights with KQL, summarising by model and operation, and compare p50 and p95 latency too.
Scenario Compliance says no personal data may be stored in telemetry. What do you check?
Model answer
That message content recording is off, so spans keep timings, token counts and names but not prompts or answers. I also check retention and who can read the Application Insights data.
Quick revision
Key points
- Spans show duration and tokens for each step.
- Application Insights stores the traces.
- Tracing is opt-in; content recording is a separate opt-in.
- Query token attributes to analyse cost by model.
- Look at p95 latency, not just the average.
Important terminology
- Trace
- The record of one request or agent run, made of spans in order.
- Span
- One timed step inside a trace, such as a model call or a tool call.
- OpenTelemetry
- The open standard for collecting traces, metrics and logs that Foundry tracing builds on.
- Application Insights
- The Azure Monitor service that stores the traces and lets you query them.
- Token analytics
- Looking at input and output tokens by model and operation to understand cost.
- Content recording
- An opt-in setting that stores prompts and answers in spans. Useful for debugging, risky for privacy.
Common mistakes
- Forgetting to opt in, then seeing no spans.
- Leaving content recording on in production.
- Judging latency only by the average.
Exam tips
- "Find the slowest step" = span durations in the trace.
- "No prompts in telemetry" = content recording off.
- "Where traces are stored" = Application Insights connected to the project.
Five quick revision questions
-
1.What is one timed step called?Show
A span.
-
2.Where are traces stored?Show
Application Insights.
-
3.Is content recording on by default?Show
No, it is a separate opt-in.
-
4.What does a model span record?Show
Model name and token counts.
-
5.Why check p95 latency?Show
It shows the slow tail that averages hide.
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: Orchestrate Multiple Models and Rules Engines
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.