Conversational AI (artificial intelligence) · 14 / 22

Telemetry & KQL (Kusto Query Language) Examples

OpenTelemetry traces, metrics and events for the booking platform, with Kusto queries for latency, cost, guardrails, the funnel and alerts.

What the telemetry is for

OpenTelemetry is the vendor-neutral standard for traces, metrics and logs. The booking platform emits one trace per guest turn and links the turns of a conversation by a session identifier, so an operator can answer three questions: is it fast and available, is it safe and correct, and what does it cost. Telemetry carries identifiers, outcomes and measurements. It never carries raw guest messages, tail numbers or names (ADR-006).

Traces

Spans for each step of a turn, parent and child, from the edge to the booking system. One trace identifier follows the turn across services and the gateway.

Metrics

Counters and histograms for turn latency, tokens, cost and guardrail blocks. Cheap to store and good for alerts.

Events

Business events with a name and properties: hold placed, confirmation received, commit, handoff, guardrail block.

Correlation

The W3C trace context header travels from the channel through the AI gateway and tool gateway, so their logs join the same trace.

The shape of a trace

A trace for one booking turn A root span for the booking turn contains child spans for identity verification, a prompt scan, a fast-model call, retrieval, a policy check, a quote tool call, a reasoning-model call and a reply scan, drawn as bars on a shared time axis. ONE BOOKING TURN · ILLUSTRATIVE 2.9 SECONDS booking.turn 2900 ms edge.verify 90 ms airs.scan.prompt 140 ms gateway.llm_call booking-fast 700 ms retrieval.search 320 ms policy.check 60 ms tool.call quote_services 560 ms gateway.llm_call booking-reasoner 800 ms airs.scan.reply 120 ms service span gateway or tool retrieval security scan
Each box in the architecture shows up as a span, so the slow or failing step is visible at a glance.
SpanKindKey attributes
booking.turnServer (root)session.id (hashed), channel, airport, turn.number, outcome
edge.verifyInternalauth.method, account.verified
airs.scan.prompt, airs.scan.replyClientairs.profile, airs.action, airs.detections (names only)
gateway.llm_callClientgen_ai.request.model (alias), gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gateway.cost_usd, gateway.fallback_used
retrieval.searchClientknowledge.index, filter.airport, results.count, top.score
policy.checkInternalpolicy.rule, policy.decision
tool.callClienttool.name, tool.outcome, tool.confirmed, booking.hold_id (not the guest's details)

What must never be in telemetry

DataRuleHow
Guest message textNeverNot an attribute. Debugging uses the masked conversation table in the lakehouse
Tail numbers, passenger names, phone, emailNever in clearDropped or hashed by the collector before export
Session and account identifiersHashedKeyed hash, so queries can group by session without exposing it
Blocked contentNeverRecord the detection names and the verdict only
Prices and quantitiesAllowedNeeded for cost and funnel analysis

Instrumenting the service

A sketch in Python with the OpenTelemetry SDK (Software Development Kit) and the Azure Monitor distribution, which sends to Application Insights. The root span is a server span so it appears as a request; child spans appear as dependencies; business events are logged with a custom event name. Check the current package and attribute names before you build.

telemetry.py · spans, metrics and business events
import logging, os
from opentelemetry import trace, metrics
from opentelemetry.trace import SpanKind
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor(connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"])
tracer = trace.get_tracer("booking.assistant")
meter = metrics.get_meter("booking.assistant")
turn_ms = meter.create_histogram("booking.turn.duration", unit="ms")
blocks = meter.create_counter("booking.guardrail.blocks")
log = logging.getLogger("booking.events")

def handle_turn(msg, session, channel, airport):
    with tracer.start_as_current_span("booking.turn", kind=SpanKind.SERVER) as turn:
        turn.set_attributes({"session.id": hash_id(session), "channel": channel, "airport": airport})

        with tracer.start_as_current_span("airs.scan.prompt") as sp:
            verdict = scan(prompt=msg)
            sp.set_attributes({"airs.profile": "booking-chat-prod", "airs.action": verdict["action"]})
            if verdict["action"] != "allow":
                blocks.add(1, {"detection": detection_name(verdict), "channel": channel})
                log.warning("guardrail block", extra={"microsoft.custom_event.name": "guardrail.block",
                            "session.id": hash_id(session), "airs.detection": detection_name(verdict)})
                return safe_reply()

        with tracer.start_as_current_span("gateway.llm_call") as llm:
            reply, usage = call_model("booking-fast", msg)
            llm.set_attributes({"gen_ai.request.model": "booking-fast",
                                "gen_ai.usage.input_tokens": usage.input, "gen_ai.usage.output_tokens": usage.output,
                                "gateway.cost_usd": usage.cost})
        ...
        log.info("hold placed", extra={"microsoft.custom_event.name": "booking.hold",
                 "session.id": hash_id(session), "airport": airport})
        turn_ms.record(elapsed_ms(turn), {"channel": channel})

A collector in the middle

An OpenTelemetry Collector receives telemetry from the service and the gateway, removes or hashes sensitive attributes, keeps every error and every block, samples the rest, and sends it to Azure Monitor for operations and to the lakehouse for long-term analysis.

otel-collector.yaml · redact, keep what matters, fan out
receivers:
  otlp:
    protocols: { grpc: {}, http: {} }

processors:
  attributes/privacy:
    actions:
      - { key: guest.message,  action: delete }
      - { key: aircraft.tail,  action: hash }
      - { key: guest.email,    action: delete }
  tail_sampling:
    decision_wait: 10s
    policies:
      - { name: keep-errors, type: status_code, status_code: { status_codes: [ERROR] } }
      - { name: keep-blocks, type: string_attribute, string_attribute: { key: airs.action, values: [block] } }
      - { name: sample-rest, type: probabilistic, probabilistic: { sampling_percentage: 10 } }
  batch: {}

exporters:
  azuremonitor:
    connection_string: ${env:APPLICATIONINSIGHTS_CONNECTION_STRING}
  otlphttp/lakehouse:
    endpoint: ${env:LAKEHOUSE_OTLP_ENDPOINT}

service:
  pipelines:
    traces:  { receivers: [otlp], processors: [attributes/privacy, tail_sampling, batch], exporters: [azuremonitor, otlphttp/lakehouse] }
    metrics: { receivers: [otlp], processors: [batch], exporters: [azuremonitor] }
    logs:    { receivers: [otlp], processors: [attributes/privacy, batch], exporters: [azuremonitor, otlphttp/lakehouse] }

KQL queries operators use

These queries use the workspace-based Application Insights tables in Log Analytics: AppRequests for the root span, AppDependencies for child spans, AppEvents for business events and AppMetrics for metrics. Custom attributes appear in the Properties column. Table and column names can differ with your setup, so adjust them to your workspace. The same Kusto Query Language also runs in Azure Data Explorer if you export telemetry there.

Turn latency by channel

Median and 95th percentile latency per channel, hourly, for the last day.

KQL
AppRequests
| where TimeGenerated > ago(1d) and Name == "booking.turn"
| extend channel = tostring(Properties["channel"])
| summarize turns = count(), p50 = percentile(DurationMs, 50), p95 = percentile(DurationMs, 95)
    by channel, bin(TimeGenerated, 1h)
| order by TimeGenerated desc, channel asc

Where the time goes

Average and slowest duration for each step of a turn, to find the step to optimise.

KQL
AppDependencies
| where TimeGenerated > ago(1d)
| where Name in ("edge.verify", "airs.scan.prompt", "gateway.llm_call", "retrieval.search",
                 "policy.check", "tool.call", "airs.scan.reply")
| summarize calls = count(), avg_ms = avg(DurationMs), p95_ms = percentile(DurationMs, 95),
            failures = countif(Success == false)
    by Name
| order by p95_ms desc

Guardrail blocks by detection

How often each Prisma AIRS detection fired, by hour, to spot an attack or a noisy rule.

KQL
AppEvents
| where TimeGenerated > ago(7d) and Name == "guardrail.block"
| extend detection = tostring(Properties["airs.detection"])
| summarize blocks = count(), sessions = dcount(tostring(Properties["session.id"]))
    by detection, bin(TimeGenerated, 1h)
| order by TimeGenerated desc, blocks desc

Tokens and cost by model alias

Spend and token use per model alias and per day, from gateway metadata.

KQL
AppDependencies
| where TimeGenerated > ago(14d) and Name == "gateway.llm_call"
| extend model = tostring(Properties["gen_ai.request.model"]),
         tin = toint(Properties["gen_ai.usage.input_tokens"]),
         tout = toint(Properties["gen_ai.usage.output_tokens"]),
         cost = todouble(Properties["gateway.cost_usd"]),
         fallback = tobool(Properties["gateway.fallback_used"])
| summarize calls = count(), input_tokens = sum(tin), output_tokens = sum(tout),
            cost_usd = round(sum(cost), 2), fallbacks = countif(fallback)
    by model, day = bin(TimeGenerated, 1d)
| order by day desc, cost_usd desc

The booking funnel

How many conversations reach each stage, by airport, and the share that complete.

KQL
AppEvents
| where TimeGenerated > ago(7d)
| where Name in ("booking.quote", "booking.hold", "booking.confirm", "booking.commit")
| extend airport = tostring(Properties["airport"]), session = tostring(Properties["session.id"])
| summarize quoted = dcountif(session, Name == "booking.quote"),
            held = dcountif(session, Name == "booking.hold"),
            confirmed = dcountif(session, Name == "booking.confirm"),
            committed = dcountif(session, Name == "booking.commit")
    by airport
| extend completion_pct = round(100.0 * committed / quoted, 1)
| order by quoted desc

Commits without a confirmation (must be zero)

Finds any commit with no matching confirmation in the same session. Any row is an incident.

KQL
let confirms = AppEvents
    | where Name == "booking.confirm"
    | project session = tostring(Properties["session.id"]), confirm_time = TimeGenerated;
AppEvents
| where Name == "booking.commit"
| extend session = tostring(Properties["session.id"])
| join kind=leftanti (confirms) on session
| project TimeGenerated, session, airport = tostring(Properties["airport"]), OperationId

Why conversations go to a person

Handoff reasons ranked, with a daily trend, to decide what to automate next.

KQL
AppEvents
| where TimeGenerated > ago(30d) and Name == "booking.handoff"
| extend reason = tostring(Properties["handoff.reason"])
| summarize handoffs = count() by reason, bin(TimeGenerated, 1d)
| summarize total = sum(handoffs), per_day = make_list(handoffs) by reason
| order by total desc

Tool errors and slow tools

Failure rate and slowest calls for each tool, to find a failing backend.

KQL
AppDependencies
| where TimeGenerated > ago(1d) and Name == "tool.call"
| extend tool = tostring(Properties["tool.name"]), outcome = tostring(Properties["tool.outcome"])
| summarize calls = count(), failed = countif(Success == false or outcome == "error"),
            p95_ms = percentile(DurationMs, 95)
    by tool
| extend failure_pct = round(100.0 * failed / calls, 2)
| order by failure_pct desc, p95_ms desc

Follow one conversation

Everything that happened in one session, in time order. Use the hashed session identifier.

KQL
let sid = "9f2c41b7";
let ops = toscalar(AppRequests
    | where TimeGenerated > ago(2d) and tostring(Properties["session.id"]) == sid
    | summarize make_set(OperationId));
union AppRequests, AppDependencies, AppEvents
| where TimeGenerated > ago(2d)
| where OperationId in (ops) or tostring(Properties["session.id"]) == sid
| project TimeGenerated, Type, Name, DurationMs, Success, OperationId
| order by TimeGenerated asc

Alert: block rate spike

Compares the hourly block rate with its normal pattern and returns hours that are anomalously high. Use it as an alert query.

KQL
let turns = AppRequests | where Name == "booking.turn"
    | make-series turns = count() default = 0 on TimeGenerated from ago(14d) to now() step 1h;
let blocked = AppEvents | where Name == "guardrail.block"
    | make-series blocked = count() default = 0 on TimeGenerated from ago(14d) to now() step 1h;
turns
| join kind=inner (blocked) on $left.TimeGenerated == $right.TimeGenerated
| project TimeGenerated, rate = series_divide(blocked, turns)
| extend (flag, score, baseline) = series_decompose_anomalies(rate, 2.5)
| mv-expand TimeGenerated to typeof(datetime), rate to typeof(double), flag to typeof(int), score to typeof(double)
| where flag == 1 and TimeGenerated > ago(3h)

Service-level objectives and alerts

ObjectiveSignalTargetAlert
Fast repliesbooking.turn p95Under 6 secondsp95 over target for 15 minutes
AvailableShare of turns not ending in errorAt least 99.5%Below target for 10 minutes
Safe commitsCommits without confirmationZeroAny occurrence, page the on-call
Scans on all trafficModel calls with a scan span100%Any unscanned model call
Attacks visibleBlock rate versus baselineWithin normal rangeAnomaly flagged for 1 hour
Cost under controlCost per booking, dailyWithin budgetOver 120% of the 7-day average
Grounded answersUnsupported-answer rateUnder 2%Over target for a day

Dashboards

Operations

Turn latency and errors by channel, step breakdown, tool health and gateway fallbacks.

Security

Blocks by detection, anomalies, repeat sessions, scan coverage and unconfirmed commits.

Business

Funnel by airport, handoff reasons, after-hours volume and time to quote.

Finance

Tokens and cost by model and channel, cost per booking and budget burn.

Build this for your business

This example is a booking assistant for a ground-handling network, but the same pattern, a governed gateway, runtime security, grounded knowledge, deterministic commits and measured quality, fits any customer-facing assistant that takes actions. We can scope a pilot on your own systems.

Book a discovery call