Module 08

AI Observability, Evaluation & Tracing

You cannot improve what you cannot measure. This module covers the complete discipline of monitoring, evaluating, and debugging AI systems in production — across LangSmith, Azure, AWS, GCP, and open-source stacks.

TracesMetricsEvalsLangSmithAzure AIAWS BedrockGCP VertexLangfuseFinance Compliance

What You Will Learn

01
Why AI Observability is Different
Non-determinism, probabilistic outputs, cost visibility, regulatory requirements
02
The Three Pillars
Traces, metrics, and logs — how they work together in AI systems
03
Evaluation (Evals)
Types, metrics, LLM-as-judge, golden sets, regression testing
04
LangSmith Deep Dive
Tracing, datasets, eval runs, annotation queues, production monitoring
05
Azure AI Observability
AI Foundry evaluators, Azure Monitor, Prompt Flow, compliance logging
06
AWS Bedrock Observability
CloudWatch, X-Ray, SageMaker Clarify, BFSI patterns
07
GCP Vertex AI
Vertex Evaluation Service, Cloud Trace, Model Monitoring, BigQuery
08
Open-Source Tools
Langfuse, W&B Weave, Phoenix, Helicone, OpenTelemetry for AI
09
Finance-Specific Requirements
PII in logs, SR 11-7 evidence, audit trails, cost attribution, drift alerts
10
Production Monitoring Dashboard
Key metrics, alert thresholds, drift detection, incident response
1

Why AI Observability is Different

Traditional software observability answers: "Did it crash? Is it slow?" AI observability must answer: "Is the output any good? Is it getting worse over time? Is it leaking data? Is it hallucinating more than last week?"

Traditional SoftwareAI Systems
Success = no error thrownSuccess = output is accurate, grounded, safe, and on-task
Same input → same output (deterministic)Same input → different output each time (probabilistic) — need many runs
Bugs are binary (crash or not)Quality is a spectrum — need continuous measurement
Monitoring: CPU, memory, latency, error rateMonitoring: hallucination rate, groundedness, relevancy, cost per query, injection detection hits
Regressions caused by code changesRegressions caused by code changes, prompt changes, model updates, data drift
Test once before deployTest continuously — vendor model updates happen silently
Quality is invisible without measurement

A model can be wrong 20% of the time and no alert fires. You need evals running continuously to catch this.

Cost can spiral silently

An agent loop with no step limit can consume $10,000 in API credits overnight. Token-level cost attribution is essential.

Regulatory mandate

SR 11-7 requires ongoing monitoring evidence. EU AI Act requires human oversight documentation. RBI guidelines expect audit trails.

Model drift is external

Your vendor updates the underlying model. Your code didn't change. Your prompts didn't change. But behaviour changed. You need to detect this.

2

The Three Pillars: Traces, Metrics & Logs

🔍

Traces

The end-to-end journey of one request through your AI pipeline. A trace contains spans — each span is one step (embedding query, vector search, LLM call, tool call). Traces let you see the full picture: what went into the model, what came out, which step was slow.

A compliance check trace shows: user query → retrieval of 5 regulation chunks (which ones?) → LLM call (which prompt version? what temperature?) → guardrail check → response. If it's wrong, you can see exactly why.

📊

Metrics

Quantitative measurements aggregated over time. Unlike traces (per-request), metrics tell you about trends: is accuracy declining? Is cost per query rising? Are injection attempts increasing?

Track: hallucination rate on regulatory Q&A (target <5%), average latency (target <3s), cost per compliance check ($), guardrail hit rate (injection attempts detected).

📋

Logs

Structured records of events — prompts, responses, tool arguments, errors. More detail than metrics, more queryable than traces. In finance, logs are the audit trail. They must be stored securely, with PII redacted, and retained per policy.

Every prompt and response is logged to a SIEM (Sentinel, Splunk) with: user ID, app ID, timestamp, token count, cost, verdict (allowed/blocked), PII redacted text.

Anatomy of an LLM Trace

Trace: compliance_check  [total: 2.3s | $0.0042 | verdict: allowed]
│
├── span: retrieve_context         [180ms]
│   ├── input: "What are RBI KYC requirements for NRIs?"
│   ├── filter: user_id=u123, classification≤confidential
│   ├── results: 5 chunks from rbi_master_direction_kyc.pdf
│   └── scores: [0.92, 0.88, 0.85, 0.81, 0.79]
│
├── span: prompt_assembly          [5ms]
│   ├── system: "You are a compliance assistant..."  (cached ✓)
│   ├── context: [chunk_1, chunk_2, chunk_3, chunk_4, chunk_5]
│   └── user: "What are RBI KYC requirements for NRIs?"
│
├── span: llm_call                 [1.9s | 2,840 tokens | $0.0038]
│   ├── model: claude-sonnet-4-6
│   ├── temperature: 0.1
│   └── output: "According to RBI Master Direction on KYC..."
│
├── span: guardrail_output         [95ms]
│   ├── pii_scan: no PII detected
│   ├── groundedness: 0.94 (pass)
│   └── verdict: allowed
│
└── span: log_audit                [12ms]
    ├── stored: siem_sentinel (redacted)
    └── cost_tag: team=compliance, app=kyc_assistant
3

Evaluation (Evals) — The Core Discipline

Evals answer the question: "How good is this AI system on the tasks it actually needs to do?" Not in theory — measurably, on real-world inputs, at a specific point in time.

Types of Evals

Offline Evals (pre-deployment)

Run against a fixed dataset before any change goes to production. Fast, cheap, reproducible. Your first gate before a prompt change or model upgrade ships.

500 financial Q&A pairs with known correct answers. Run nightly. Fail the CI build if accuracy drops >2%.

Online Evals (in production)

Sample live traffic and score it in real time (or near real time). Catches drift that offline evals miss — real user queries are always messier than your test set.

Score 5% of live compliance queries for groundedness. Alert if 7-day rolling average drops below 0.85.

Human Evals

Domain experts review a sample of outputs and label them. The ground truth — but slow and expensive. Use for calibrating automated metrics and for high-stakes decisions.

Weekly: compliance officers review 20 flagged outputs. Their labels feed back into the golden dataset.

LLM-as-Judge

Use a separate, more capable model to evaluate outputs at scale. Much faster and cheaper than human eval. Can be biased — always calibrate against human labels before trusting it.

Use Claude Opus to score whether a credit analysis output correctly identifies all material risks. Calibrated on 200 human-labelled examples first.

Key Evaluation Metrics

MetricWhat It MeasuresFinance UseTool
Groundedness / FaithfulnessIs the answer supported by the provided sources? No hallucinated facts.Regulatory Q&A, compliance checks — wrong citations are dangerousAzure AI Content Safety, RAGAS, DeepEval
Answer RelevancyDoes the answer actually address the question asked?Advisor chatbot — off-topic responses frustrate clientsRAGAS, LangSmith evaluators
Context RecallDid RAG retrieve all the information needed to answer correctly?Missed a regulatory clause = material riskRAGAS
Hallucination RateWhat fraction of outputs contain factual errors?Credit analysis — a wrong number in a memo is a compliance failureDeepEval HallucinationMetric, custom judges
Task Success RateDid the agent complete the task as specified?Trade break investigation — did it correctly identify the break cause?Custom eval harness with expected outcomes
Toxicity / Safety ScoreDoes the output contain harmful, biased, or inappropriate content?Client-facing chatbots — regulatory and reputational riskAzure AI Content Safety, Llama Guard, DeepEval
Latency P9595th percentile response time — what slow users experienceAdvisor tools need sub-3s; real-time trading systems need sub-500msAPM tools, LangSmith, custom dashboards
Cost per QueryToken cost per request — for budget management and chargebackHigh-volume compliance monitoring needs cost attribution per teamGateway logs, LangSmith, Helicone

LLM-as-Judge Pattern

# LLM-as-Judge: evaluating compliance answer quality
import anthropic

JUDGE_PROMPT = """You are a senior compliance officer evaluating an AI assistant's response.

Question asked: {question}
AI Response: {response}
Source documents used: {sources}

Evaluate on these dimensions (score 1-5 each):
1. Accuracy: Is the information factually correct based on the sources?
2. Completeness: Are all material obligations mentioned?
3. Citation quality: Are specific regulation sections cited?
4. Risk: Does it identify any compliance risks?

Output JSON: {{"accuracy": X, "completeness": X, "citation": X, "risk": X, "overall": X, "issues": ["..."]}}"""

def evaluate_response(question, response, sources):
    client = anthropic.Anthropic()
    judge_response = client.messages.create(
        model="claude-opus-4-8",   # use best model as judge
        max_tokens=500,
        messages=[{
            "role": "user",
            "content": JUDGE_PROMPT.format(
                question=question,
                response=response,
                sources=sources
            )
        }]
    )
    return json.loads(judge_response.content[0].text)
4

LangSmith — Deep Dive

LangSmith is LangChain's observability and evaluation platform. It integrates natively with LangChain and LangGraph but works with any Python code via its SDK. It is the most widely adopted LLM observability tool as of 2026.

Tracing

Automatic tracing of every LangChain/LangGraph call. Manual tracing for any code via @traceable decorator. See full prompt, response, latency, cost, token count per span.

Datasets

Upload golden test sets, capture production traces as examples, curate via annotation queues. Version-controlled. The foundation of all eval runs.

Eval Runs

Run evaluators (built-in or custom LLM-as-judge) against a dataset. Compare two prompt versions. Track scores over time. Regression detection built in.

Annotation Queues

Route interesting or edge-case traces to human reviewers (domain experts, compliance officers). Their labels feed back into datasets automatically.

Monitoring

Production dashboard: live metrics, charts for latency/cost/quality over time, alert rules, feedback integration.

Prompt Hub

Centralised prompt management — versioning, tags, pull prompts by version in code. Integrates with eval runs (test prompt v3 vs v4).

Setup & Integration

# 1. Install and configure
pip install langsmith
export LANGCHAIN_API_KEY="ls__..."
export LANGCHAIN_TRACING_V2="true"
export LANGCHAIN_PROJECT="finance-compliance-bot"

# 2. Automatic tracing — LangChain code traces with zero changes
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(model="claude-sonnet-4-6")
response = llm.invoke("Summarise this 10-K...")  # → auto-traced

# 3. Manual tracing for any code
from langsmith import traceable

@traceable(name="compliance_check", tags=["compliance", "kyc"])
def check_kyc_compliance(client_data: dict) -> dict:
    # your custom logic — fully traced
    result = run_kyc_pipeline(client_data)
    return result

# 4. Eval run — compare prompt versions
from langsmith.evaluation import evaluate

results = evaluate(
    target=my_rag_pipeline,          # function to evaluate
    data="kyc-golden-set-v3",        # dataset name in LangSmith
    evaluators=[
        groundedness_evaluator,
        answer_relevancy_evaluator,
    ],
    experiment_prefix="kyc-prompt-v4-vs-v3",
)
5

Azure AI Observability

Azure provides a layered observability stack for AI — from built-in safety evaluators in AI Foundry to enterprise-grade monitoring via Azure Monitor. Most Indian and global banks running on Azure use this stack.

Azure AI Foundry — Built-in Evaluators

AI Foundry (formerly Azure AI Studio) includes built-in evaluators you run directly on your data, no code needed.

  • Groundedness — is the response supported by the provided context?
  • Coherence — is the response logically structured and clear?
  • Fluency — is the language natural and well-formed?
  • Relevance — does the response address the query?
  • Similarity — how close to a reference answer?
  • Safety evaluators — violence, self-harm, sexual content, hate — all scored by severity

Azure Monitor + Application Insights

Standard Azure monitoring extended for LLM workloads. Captures custom metrics, traces, and logs from your AI gateway.

  • Custom metrics: emit token_count, cost, quality_score as App Insights custom events
  • Distributed tracing: correlate LLM spans with upstream HTTP requests via X-Correlation-ID
  • Alert rules: fire when hallucination_rate > 0.1 or latency_p95 > 5s
  • Workbooks: pre-built dashboards for LLM cost and quality trends
  • Log Analytics: KQL queries over all prompt/response logs (PII redacted)

Azure AI Content Safety Monitoring

Real-time monitoring of content safety decisions across all apps using your gateway.

  • Prompt Shield hit rate — how often injection attacks are detected
  • Harm category distribution — which categories are being triggered
  • False positive tracking — which legitimate queries are being blocked
  • Trend alerts — spike in injection attempts may indicate active attack

Microsoft Purview — Data Lineage for AI

Tracks where data flows through your AI system — essential for compliance and right-to-be-forgotten.

  • Sensitivity label propagation — if source doc is Confidential, the RAG chunk is Confidential
  • Data lineage: trace which source documents fed which model responses
  • DLP integration — alert when data classified as MNPI reaches an unauthorised AI app
  • Audit reports for regulators: where did this client's data go?
# Azure AI Foundry evaluation — Python SDK
from azure.ai.evaluation import evaluate, GroundednessEvaluator

groundedness_eval = GroundednessEvaluator(
    model_config={
        "azure_endpoint": os.environ["AZURE_OPENAI_ENDPOINT"],
        "azure_deployment": "gpt-4o",
    }
)

results = evaluate(
    data="kyc_test_cases.jsonl",          # dataset with question/answer/context
    evaluators={"groundedness": groundedness_eval},
    output_path="./eval_results.json",
    azure_ai_project={                     # log results to AI Foundry
        "subscription_id": "...",
        "resource_group_name": "...",
        "project_name": "finance-ai-platform",
    },
)
6

AWS Bedrock Observability

Amazon Bedrock Model Invocation Logging

Enable per-model-deployment. Logs every request/response to S3 or CloudWatch Logs. Configurable — log full prompts, or metadata only (for PII-sensitive workloads). Queryable via Athena for cost analysis.

AWS CloudWatch — LLM Metrics

Custom metrics from Bedrock: InvocationLatency, InputTokenCount, OutputTokenCount. Build dashboards and alarms. Cost alert: alarm when daily_tokens > budget. Latency alert: alarm when p95 latency > 4s.

AWS X-Ray — Distributed Tracing

Trace requests across Lambda → Bedrock → DynamoDB → S3 in one trace. See the full request path including the LLM call. Identify which part of your agent pipeline is slow or failing.

Amazon SageMaker Clarify

Bias and explainability monitoring for ML models (including fine-tuned models deployed on SageMaker). Monitors for data drift and model drift over time. More relevant for fine-tuned/traditional ML models than Bedrock-hosted LLMs.

Amazon Bedrock Guardrails Monitoring

Bedrock Guardrails (AWS's content filtering layer) provides built-in metrics: how many requests triggered PII filters, topic restrictions, grounding checks. Dashboard in AWS console, metrics in CloudWatch.

AWS Security Lake — AI Audit Trail

Centralise Bedrock invocation logs, CloudTrail API calls, and GuardDuty findings into Security Lake (OCSF format). Full audit trail for compliance. Query with Athena. Forward to third-party SIEM if needed.

7

GCP Vertex AI Observability

Vertex AI Evaluation Service

Built-in evaluators for Gemini models and custom models: summarisation quality, QA accuracy, grounding, text generation quality. Run against datasets stored in BigQuery. Results stored in BigQuery for trend analysis.

Cloud Trace

Distributed tracing for all GCP services. Capture LLM call latency, token counts as custom attributes on spans. Integrate with OpenTelemetry for vendor-neutral instrumentation.

Cloud Monitoring + Cloud Logging

Emit custom metrics (token counts, quality scores, cost) from your Vertex AI apps. Build dashboards. Set alerting policies. Cloud Logging stores all LLM request/response logs — query with log-based metrics.

Vertex AI Model Monitoring

Monitor deployed models for training-serving skew and prediction drift. Most relevant for fine-tuned models and traditional ML models deployed on Vertex. Gemini API monitoring is handled separately via Cloud Monitoring.

BigQuery for Eval Storage

Store all eval results, trace data, and quality metrics in BigQuery. Run SQL analysis over months of eval history. Create Looker dashboards for business-facing quality reporting. Cost-effective at scale.

GCP Audit Logs (Cloud Audit Logs)

All Vertex AI API calls are captured in Admin Activity and Data Access audit logs. Essential for compliance: who called which model, with what data, when. Forward to Chronicle SIEM for security analysis.

8

Open-Source & Platform-Agnostic Tools

ToolWhat It IsHostingBest For Finance
LangfuseOpen-source LangSmith alternative. Tracing, datasets, evals, prompt management, human annotation.Self-host (Docker/Kubernetes) or cloudFirms that can't send prompt data to a third-party SaaS. Full data sovereignty.
Weights & Biases / WeaveW&B is the ML experiment tracker. Weave is their new LLM observability layer — traces, evals, datasets.W&B cloud or self-hostTeams already using W&B for ML model training — natural extension to LLM monitoring
Arize PhoenixOpen-source LLM observability and eval platform. Strong on embedding drift detection and RAG evaluation.Self-host or Arize cloudDetecting embedding drift in RAG pipelines; visualising retrieval quality over time
HeliconeLightweight LLM proxy with built-in analytics. One-line integration — change your API base URL.Cloud or self-hostQuick setup; good for teams that want immediate cost and latency visibility with minimal code
OpenTelemetry for AIEmerging standard semantic conventions for LLM observability spans (gen_ai.* attributes). Vendor-neutral.Instrument once, export anywhereLong-term: instrument code once and ship to Datadog, Grafana, Jaeger, or any OTEL-compatible backend
PromptfooEval and red-team framework. YAML-driven test cases. CI/CD integration.Open source, run anywhereSecurity-focused evals, regression testing in CI — see also Module 6 (Security)

Self-Host Decision for Finance

If your prompts contain client data, MNPI, or anything classified above Internal — use Langfuse or Phoenix self-hosted. Sending those prompts to a third-party SaaS (LangSmith, Helicone) adds a data residency risk you need a DPA and legal review to accept. The self-host path gives you all the features with full data sovereignty.

9

Finance-Specific Requirements

PII in Logs — Non-Negotiable

Every prompt and response that goes through your AI system is a potential log. Logs are stored, indexed, and accessed by operations teams, vendors, and regulators. PII must be redacted before logging.

# Redact before logging — use Presidio
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine

def redact_for_logging(text: str) -> str:
    results = analyzer.analyze(text, language="en")
    return anonymizer.anonymize(
        text=text,
        analyzer_results=results,
    ).text

# In your gateway — redact prompt BEFORE logging
def audit_log(prompt, response, metadata):
    log_entry = {
        "prompt": redact_for_logging(prompt),
        "response": redact_for_logging(response),
        "metadata": metadata,
        "timestamp": datetime.utcnow().isoformat(),
    }
    siem_client.send(log_entry)
SR 11-7 Evidence Package

Model validators need: eval results over time (accuracy, groundedness, task success rate), red-team reports, change log (every prompt/model change), monitoring alerts and responses, ongoing performance metrics. Your observability system generates most of this automatically — design it with validators in mind.

Audit Trail Structure

Every AI-assisted decision must be traceable: which model made it, on which data, using which prompt version, reviewed by which human, at what timestamp. Retention: 7 years minimum for most financial records.

Cost Attribution (Chargeback)

Tag every LLM call with: team, app, use_case, data_classification. Report monthly cost by team. This creates accountability — teams that build expensive agent loops feel the cost. Standard in mature AI programs.

Information Barrier Monitoring

If your firm has information barriers (investment banking vs trading), AI logs must confirm no cross-wall data access occurred. Tag every query with the side it originated from; alert if a response contains data from the other side.

10

Production Monitoring Dashboard

Every AI system in production needs a dashboard. Here are the panels every financial AI monitoring dashboard should have.

Quality Over Time

Groundedness rate, task success rate, hallucination rate — 7-day rolling average with trend line. Alert threshold line marked.

Alert if groundedness drops below 0.85 for 2 consecutive days

Cost & Volume

Daily token spend by team/app, cost per query, total monthly spend vs budget, query volume trend.

Alert if daily cost > 120% of 7-day average

Latency Distribution

P50, P90, P95, P99 latency. Breakdown by step (retrieval, LLM call, guardrail). Trend over time.

Alert if P95 latency > 5 seconds for 10+ minutes

Safety & Security

Guardrail hit rate, injection detection rate, PII detection rate, off-topic refusal rate. Spike detection.

Alert on any spike >3 sigma above baseline — may indicate active attack

Human Review Queue

Items pending human review, SLA compliance (reviewed within 48h), annotation throughput, disagreement rate with automated scores.

Alert if queue depth > 200 items (review team capacity)

Drift Detection

Track 10 canonical test questions weekly. Plot score trends. Model vendor updates show up here before users notice.

Alert if any canonical question score drops >15% from baseline

The Maturity Ladder

Level 1

Basic logging — prompts and responses stored somewhere.

Level 2

Metrics — latency and cost tracked per app.

Level 3

Quality evals — automated scoring against golden sets, run in CI.

Level 4

Full observability — traces, drift detection, human review queues, chargeback, SR 11-7 evidence package generated automatically.

🧪
Try Lab 7: Observability & Evaluation Stack
Trace a RAG assistant, score it on a 20-question golden set with an LLM judge, and set release gates. Optional Langfuse step. About 90 minutes.
Try the Lab →