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.
What You Will Learn
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 Software | AI Systems |
|---|---|
| Success = no error thrown | Success = 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 rate | Monitoring: hallucination rate, groundedness, relevancy, cost per query, injection detection hits |
| Regressions caused by code changes | Regressions caused by code changes, prompt changes, model updates, data drift |
| Test once before deploy | Test continuously — vendor model updates happen silently |
A model can be wrong 20% of the time and no alert fires. You need evals running continuously to catch this.
An agent loop with no step limit can consume $10,000 in API credits overnight. Token-level cost attribution is essential.
SR 11-7 requires ongoing monitoring evidence. EU AI Act requires human oversight documentation. RBI guidelines expect audit trails.
Your vendor updates the underlying model. Your code didn't change. Your prompts didn't change. But behaviour changed. You need to detect this.
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_assistantEvaluation (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
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%.
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.
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.
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
| Metric | What It Measures | Finance Use | Tool |
|---|---|---|---|
| Groundedness / Faithfulness | Is the answer supported by the provided sources? No hallucinated facts. | Regulatory Q&A, compliance checks — wrong citations are dangerous | Azure AI Content Safety, RAGAS, DeepEval |
| Answer Relevancy | Does the answer actually address the question asked? | Advisor chatbot — off-topic responses frustrate clients | RAGAS, LangSmith evaluators |
| Context Recall | Did RAG retrieve all the information needed to answer correctly? | Missed a regulatory clause = material risk | RAGAS |
| Hallucination Rate | What fraction of outputs contain factual errors? | Credit analysis — a wrong number in a memo is a compliance failure | DeepEval HallucinationMetric, custom judges |
| Task Success Rate | Did 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 Score | Does the output contain harmful, biased, or inappropriate content? | Client-facing chatbots — regulatory and reputational risk | Azure AI Content Safety, Llama Guard, DeepEval |
| Latency P95 | 95th percentile response time — what slow users experience | Advisor tools need sub-3s; real-time trading systems need sub-500ms | APM tools, LangSmith, custom dashboards |
| Cost per Query | Token cost per request — for budget management and chargeback | High-volume compliance monitoring needs cost attribution per team | Gateway 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)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.
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.
Upload golden test sets, capture production traces as examples, curate via annotation queues. Version-controlled. The foundation of all 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.
Route interesting or edge-case traces to human reviewers (domain experts, compliance officers). Their labels feed back into datasets automatically.
Production dashboard: live metrics, charts for latency/cost/quality over time, alert rules, feedback integration.
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",
)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",
},
)AWS Bedrock Observability
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.
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.
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.
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.
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.
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.
GCP Vertex AI Observability
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.
Distributed tracing for all GCP services. Capture LLM call latency, token counts as custom attributes on spans. Integrate with OpenTelemetry for vendor-neutral instrumentation.
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.
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.
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.
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.
Open-Source & Platform-Agnostic Tools
| Tool | What It Is | Hosting | Best For Finance |
|---|---|---|---|
| Langfuse | Open-source LangSmith alternative. Tracing, datasets, evals, prompt management, human annotation. | Self-host (Docker/Kubernetes) or cloud | Firms that can't send prompt data to a third-party SaaS. Full data sovereignty. |
| Weights & Biases / Weave | W&B is the ML experiment tracker. Weave is their new LLM observability layer — traces, evals, datasets. | W&B cloud or self-host | Teams already using W&B for ML model training — natural extension to LLM monitoring |
| Arize Phoenix | Open-source LLM observability and eval platform. Strong on embedding drift detection and RAG evaluation. | Self-host or Arize cloud | Detecting embedding drift in RAG pipelines; visualising retrieval quality over time |
| Helicone | Lightweight LLM proxy with built-in analytics. One-line integration — change your API base URL. | Cloud or self-host | Quick setup; good for teams that want immediate cost and latency visibility with minimal code |
| OpenTelemetry for AI | Emerging standard semantic conventions for LLM observability spans (gen_ai.* attributes). Vendor-neutral. | Instrument once, export anywhere | Long-term: instrument code once and ship to Datadog, Grafana, Jaeger, or any OTEL-compatible backend |
| Promptfoo | Eval and red-team framework. YAML-driven test cases. CI/CD integration. | Open source, run anywhere | Security-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.
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)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.
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.
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.
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.
Production Monitoring Dashboard
Every AI system in production needs a dashboard. Here are the panels every financial AI monitoring dashboard should have.
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
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
P50, P90, P95, P99 latency. Breakdown by step (retrieval, LLM call, guardrail). Trend over time.
Alert if P95 latency > 5 seconds for 10+ minutes
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
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)
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
Basic logging — prompts and responses stored somewhere.
Metrics — latency and cost tracked per app.
Quality evals — automated scoring against golden sets, run in CI.
Full observability — traces, drift detection, human review queues, chargeback, SR 11-7 evidence package generated automatically.