Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • Zero-Shot, Few-Shot or Reasoning: Pick the Cheapest Prompting Technique the Failure Asks For
  • Prompting Fundamentals for Code: Prescriptive, Outcome-Based and Guided Prompts
  • AI Tools for Developers: Five Kinds, Tokens, Context and the Shape of a Model Call
  • Prompting for Code: System Prompts, Few-Shot, Plans First, Context and Debugging
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Agentic Search or RAG: an Index Decides Before the Call, Search Tools Decide During It
  • A Retrieval Router: Match the Route to the Data Shape and the Query Pattern
  • Progressive Discovery or Monolithic Context: Load It All, Fetch by Index, or Both
  • Building a Claims Assistant: RAG, an Eval Harness With a Gate, and OpenTelemetry Tracing
  • RAG in LangChain: Documents, a Text Splitter, a Retriever and an LCEL Chain, Next to the Same Pipeline by Hand
  • RAG on pgvector in FastAPI: an Ingest and an Ask Endpoint, a Supabase Login Token That Picks the Owner, and Answers With Citations
  • Citations in Scanned PDF Tables: Cite the Cell, Gate the Cell, Keep the Proof
  • Embeddings and pgvector in Spring AI: EmbeddingModel, VectorStore, Distance Operators and the HNSW Index
  • RAG Ingestion in Spring AI: Parse Markdown, Chunk by Section, Embed Into pgvector With Stable Ids
  • Tuning Retrieval in Spring AI: Top-k, a Minimum Score, a Tenant Filter Inside the Query, Hybrid Search and a Reranker
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • A Remote MCP Server in Production: Tokens Bound to One Server, Tool Versions Side by Side, and a Gateway With Its Own Upstream Token
  • MCP, an API/CLI Call or Agent-to-Agent: Choosing How Claude Connects to a Capability
  • Supervisor and Worker Agents in LangGraph: One Boss, Three Workers, One Shared State and a Stop Rule in Plain Code
  • Parallel Agents, Handoffs and Memory in LangGraph: Send to Fan Out, Command to Hand Off, a Postgres Saver to Remember
  • The A2A Protocol in Python: An Agent Card, a Message and a Task Between Two Agents That Share No Code
  • LangGraph vs CrewAI vs the Claude Agent SDK: One Support Job, Three Short Files, Control Against Speed of Setup
  • A LangGraph Agent With MCP Tools: Load a FastMCP Server's Tools With langchain-mcp-adapters, Survive a ToolError, Then Plug the Same Server Into Claude Code
  • Mock Interview: Layer the Guardrails on a Refund Agent, Scored From 6 to 20 of 24
  • Tool Calling in Spring AI 2: @Tool Methods, the ToolCallingAdvisor Loop and a Tool-Call Limit
  • Building an MCP Server in Java With Spring AI: @McpTool, Stateless Streamable HTTP and Least-Privilege Tools
  • Consuming MCP Servers From Spring AI: a stdio Child Process and a Remote Streamable HTTP Server, Compared
  • A Supervisor and Specialist Agents in Spring AI: Own Prompts, Own Tools, Explicit State and a Menu Checked in Code
  • Choosing a JVM Agent Framework: the Same Two-Step Triage in Spring AI, LangChain4j Agentic and Embabel
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Keeping an Eval Suite Valid: Check It for Contamination, Saturation and Coverage Before You Trust a Green Gate
  • Eval Metrics by Task Type, and Evaluating a Non-Deterministic Agent With Repeated Trials
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • The Failure Nobody Saw: Finding the Instrumentation Gap in an LLM Agent
  • Six Metrics, Not One Score: Accuracy, Groundedness, Latency, Cost, Safety and Security for an LLM Agent
  • The Metric That Would Have Caught It: Finding Eval Coverage Gaps After a Green Suite
  • Eval Datasets and Mixed-Method Test Frameworks: Code Checks, an LLM Judge and Human Review
  • Calibrating an LLM Judge: Diagnosing Position, Verbosity, Self-Preference and Drift
  • Trials per Case: Separating a Real Effect From Run-to-Run Variance When You Compare Two Prompts
  • Diagnosing a Bad Answer: Prompt Failure, Hallucination or Model Mismatch?
  • Building a Claims Assistant: RAG, an Eval Harness With a Gate, and OpenTelemetry Tracing
  • LangSmith Tracing for a LangGraph App: Two Settings, @traceable, Tags and Metadata, and Filtering Runs by User and Version
  • LangSmith Datasets and Experiments: Upload a Golden Set, Run Two Prompt Versions With evaluate(), and Read the Score Diff
  • Agentic Evals: Grade the Outcome, the Trajectory and the Side Effects, Then Gate the Release
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Retries With Limits for LLM Calls: Jitter Under a Capped Ceiling, a Retry Budget, a Circuit Breaker and a Graceful Reply
  • Multi-Tenant Quotas for One Shared LLM: a Bounded Line per Tenant, Fair Turns and a Pause When the Model Says Wait
  • Find the Binding Constraint Before You Tune: Requests, Input Tokens or Output Tokens per Minute, and When to Send a Batch
  • SLIs and SLOs for an LLM Service: Count Good Events, Promise a Level, Page on Burn Rate
  • Drift After a Model Update: Tag Every Event, Split the Dashboard by Version, Alert Against a Baseline
  • Trace Analysis at Scale: Tail-Sample to Read, Count Every Trace by Failure Cohort to Measure
  • Incident Response for an LLM Agent: Triage, Flip the Pointer, Check the Canaries, Then Tell People
  • From Incident to Regression Eval and Postmortem: One Incident, Three Things Left Behind, and a Gate That Remembers
  • Fleet Cost Forecasting for an LLM Service: Profile per Workload, Times Mix, Times Volume
  • From One Claude Call to a System: Input, Processing, Output and the Feedback Loop
  • Stress-Testing an LLM Architecture: Find the Component That Fails First
  • Five Reference Architectures for Claude Systems: Read the Cue, Name the Shape
  • Business Value Pillars for an LLM System: Turn "Cheaper and Faster" Into Targets, Then Pick the Lane
  • The Claude Model Ladder: Pick the Cheapest Model That Passes, Then Price the Month
  • Connecting Claude to a Legacy System You Can't Change: The Adapter Pattern
  • Speed Has a Price and the Rate Limit Is the Ceiling: Choosing Model, Effort and Fast Mode per Path
  • Reliability Controls for Claude Apps: Backoff, Idempotency Keys, Fallback Routing and Circuit Breakers
  • Observability at Scale and a Gated Rollout: Metrics for All, Traces by Rule, Content on Trigger
  • The Failure Nobody Saw: Finding the Instrumentation Gap in an LLM Agent
  • An Ops Runbook for Claude Failures: Case Cards, Request IDs, Owners and a Read-Only Investigation
  • Support Copilot Architecture and Starter Kit: One Folder, Settings in .env, Postgres Before the API, and a Four-Event Contract With React
  • Scaling Out an AI Help Desk: Two Copies Behind nginx, the Chat Memory Bug, Sticky Sessions and the Redis Fix
  • Consistency and CAP: What You Give Up When the Network Breaks, Strong vs Eventual, Chosen Row by Row
  • High Availability and Disaster Recovery: SLOs, the Nines as Minutes, Single Points of Failure, RPO and RTO
  • Failure Drills for an AI Help Desk: Stop Redis, the Replica, Slow the Model, Kill a Worker and Time a Restore
  • Designing an AI App for a Million Users: Requirements First, Then QPS, Tokens, Cost, a Latency Budget and the Real Bottleneck
  • Where Time Goes in an LLM Request: A Seven-Stage Budget, Time to First Token and the Clock Your SLO Should Watch
  • Autoscaling Concepts: Reactive, Scheduled and Predictive Scaling, the Right Signal, Cooldowns and Warm Pools
  • Terraform for a Help Desk: One Module, Two Provider Blocks (AWS and LocalStack), Checked in Python Before Plan
  • Multi-Region for an AI App: Active-Passive vs Active-Active, RTO and RPO in Numbers, Write Homes and Data Residency
  • Design Review for a Global AI App: Scoring Cost, Latency and Availability in One Table and Saying the Trade-off
  • Database Index for an AI App: Read the Query Plan, Pick the Column Order, Name the Write Cost
  • Replication and Replica Lag: Why a Revoked User Still Sees the Folder, and Which Reads Go to the Primary
  • Sharding a Vector Store: Tenant Key, Split Only the Giants, Merge a Full Top-k, Grow With Fixed Buckets
  • Token Rate Limits: One Bucket per Team, Reserve Input Plus Max Output, Refund the Rest
  • One Request Through Every Pattern: a Map of 25 AI System Design Patterns, Stop by Stop
  • Sandbox Execution for Agent-Written Code: Isolate Every Run, Cut the Reach, Check What Comes Out
  • A System Design Interview, Worked End to End: The Order-Tracking Page of a Food-Delivery App in Seven Steps
  • Caching With Spring and Redis: Cache-Aside, a TTL per Kind of Data, Eviction on Edit and Stopping the Stampede
  • A PostgreSQL Read Replica in Spring Boot: Route readOnly Transactions, Size the Pool, Find the Index, Read Your Own Writes
  • Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work
  • Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency
  • An API Gateway With Spring Cloud Gateway: Check the JWT Once at the Edge, Pass the Caller Inward, and Know What the Network Now Trusts
  • Distributed Tracing Across Spring Boot Services and Kafka: One Trace ID From the Gateway to the Last Reader, Even Through an Outbox
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  • Tuning an LLM Guard: False Positives Against False Negatives, a Review Band, and Model Refusals
  • Red-Teaming an LLM Agent with the OWASP LLM Top 10 and the NIST AI RMF: Judge What It Did, Not What It Said
  • Least-Privilege Tools and an Audit Log for Agent Actions: Grant by Job, Decide in Code, Record Every Allow and Deny
  • Agent Identity with Workload Identity Federation: a Short-Lived Token Instead of a Static Key, and Tool Secrets Kept in the Harness
  • Memory Poisoning and Tool Poisoning in LLM Agents: Three Doors In, Two Ways Out, and the Controls That Hold
  • Authentication and Authorization for Claude Agents: Find the Gaps Hop by Hop
  • Risk Framing for LLM Systems: A Risk Register Ranked by Exposure, Not by Odds
  • Ranking Deployment Risk: Attack Surface, Failure Modes, Quota Exhaustion and Supply Chain
  • Human-in-the-Loop Routing: Send Each Agent Action to Auto, Review or Block by Confidence, Reversibility and Cost
  • Compliance for an LLM System: Tie Every Obligation to a Control, an Owner and Evidence
  • Control Sets for Compliance: Residency, Retention and ZDR, PII Redaction, Audit Logs and Tenant Isolation
  • Bias, Fairness and Transparency in LLM Decisions: Find the Source of a Gap, Then Pick the Fix
  • An AI Governance Operating Model on One Page: Risk Tiers, Named Gates and Re-Gating on Change
  • A Regulated Dispute Desk on Claude: Pin the Geography, Gate by Risk, Log Before Release, Fail Closed
  • The AI Reply Is Untrusted Too: Links, Commands and Hidden Content in What It Writes Back
  • Poisoned Data, Poisoned Models and the AI Supply Chain: Attacks Before Anyone Types a Prompt
  • How Data Leaks from AI Tools: Five Quiet Ways Out, Shadow AI and a Table of What May Go Where
  • AI for Defenders, and AI in Attackers' Hands: Faster Alert Triage, Cleaner Phishing, Cloned Voices and the Habits That Still Work
  • AI Security Frameworks in Plain Words: NIST AI RMF, ISO/IEC 42001, the EU AI Act and the OWASP Top 10 for LLMs
  • AI Policy, the Risk Register and Who Owns What: An Inventory, One Owner, a Two-Question Score and a One-Page Policy
  • Sandbox Execution for Agent-Written Code: Isolate Every Run, Cut the Reach, Check What Comes Out
  • Reading a Business Requirement Like an Architect: Function, Quality, Constraints and Assumptions
  • Discovery for an AI Project: Running the First Conversation, Five Question Groups and Three Red Flags
  • Communicating AI Decisions, Trade-offs and Risk to Executives: The Decision Card, the Risk Matrix and One Ask
  • Feedback Loops, Expectations and SLAs for an AI Service: Find the Promise the Architecture Can't Keep
  • Documenting an AI Architecture for Handoff: One Document per Reader, a Handoff Gate and Rules With a Reason
  • The Architecture Decision Record for a Claude System: Context, Options, Decision, Consequences and the Evidence You Will Need
  • The Evidence Readout: Presenting Eval Numbers and Traces to Stakeholders as a Decision
  • What a Forward Deployed Engineer Does: One Customer, Their Systems, and a Week From Discovery to Roll-Out
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  • Debugging AI at the Customer: Read a Retrieval Log, a Span Tree and an Eval Diff Instead of the Servers
  • Capstone: Moving a Support Copilot to a New Customer, Clean Their Data, Add One Read-Only Tool, Test on Their Questions
  • AI Engineer, ML Engineer, FDE: What Each Interview Tests, and the Trap of Answering for the Wrong Room
  • Mock Interview for a Forward Deployed Engineer: a Private RAG Assistant in One Region, Scored From 4 to 30 of 36
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Evals and Testing

LangSmith Tracing for a LangGraph App: Two Settings, @traceable, Tags and Metadata, and Filtering Runs by User and Version

A flight recorder for a planner, researcher and writer graph. Two lines in .env decide whether traces leave your machine, run_config adds the tags v1.3.0 and support-copilot plus a user id, and an offline trace tree shows the researcher as the slowest step, 350 tokens and a failing get_ticket call.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Evals and Testing

What you will learn

  • Turn LangSmith tracing on and off with LANGSMITH_TRACING and LANGSMITH_API_KEY
  • Attach a run name, tags and metadata to a LangGraph run so you can filter by user and app version
  • Add your own Python functions to the trace tree with @traceable
  • Read a trace tree offline to find the slowest step, the token total and a failing tool call

Before you start

  • LangGraph Nodes, Edges and State
  • Observability and Tracing for LLM Apps

When an agent gives a wrong or slow answer, you want to replay exactly what happened inside it. In this article we switch on LangSmith tracing for a small multi-agent support app, read a trace tree, find the slow step and the failing tool call, and filter runs by user and by app version. The graph runs on a scripted stand-in test model, so the code works without a model key. Only the LangSmith part needs your own LangSmith key.

A flight data recorder for agents

A plane has a flight data recorder. Every step of the trip is logged, so after a problem you can replay it. Our app is the plane: one request, "handle ticket T-100", goes through three agents, a planner, a researcher and a writer. Tracing is the recorder. For every step it writes down how long it took, how many tokens it used and whether a tool call failed. From that log you can answer real questions: which step was the slowest, and which user on which version sent this request?

The app we trace

agents_graph.py is a three-node LangGraph graph. TICKETS holds two made-up tickets, T-100 and T-200, and get_ticket is a tool that raises an error for an unknown id.

@tool
def get_ticket(ticket_id: str) -> str:
    """Look up a support ticket by id."""
    if ticket_id not in TICKETS:
        raise ValueError(f"Ticket {ticket_id} not found")
    return TICKETS[ticket_id]


def get_model(replies: list[str] | None = None):
    """Test model reply source. Swap for init_chat_model(...) when you have a key."""
    replies = replies or [
        "Plan: look up the ticket, then write a short reply.",
        "Hi, we found the issue with your reset email and have fixed it. Please try again.",
    ]
    msgs = [
        AIMessage(
            content=text,
            usage_metadata={
                "input_tokens": 120 + 40 * i,
                "output_tokens": 30 + 10 * i,
                "total_tokens": 150 + 50 * i,
            },
        )
        for i, text in enumerate(replies)
    ]
    return GenericFakeChatModel(messages=iter(msgs))

Each scripted reply carries usage_metadata, so the test model reports tokens just like a real one: 150 for the first call and 200 for the second. These are example numbers, not a real bill.

    def planner(state: State) -> State:
        reply = model.invoke(f"Plan how to handle ticket {state['ticket_id']}")
        return {"plan": reply.content}

    def researcher(state: State) -> State:
        time.sleep(ticket_delay)  # stands in for a slow lookup
        try:
            notes = get_ticket.invoke({"ticket_id": state["ticket_id"]})
        except ValueError as exc:
            notes = f"lookup failed: {exc}"
        return {"notes": notes}

    def writer(state: State) -> State:
        reply = model.invoke(f"Write a reply using: {state['notes']}")
        return {"answer": reply.content}

The edges run START, planner, researcher, writer, END. If you need a refresher on nodes and edges, see LangGraph Nodes, Edges and State.

Two settings decide whether anything is sent

.env.example lists what tracing needs, with no secret in it: LANGSMITH_TRACING=false, an empty LANGSMITH_API_KEY and LANGSMITH_PROJECT=support-copilot-dev. Copy it to .env; your key goes only into that private copy.

import os

from dotenv import load_dotenv

load_dotenv()

DEFAULT_PROJECT = "support-copilot-dev"


def tracing_status() -> dict:
    """Return what LangSmith will do, without revealing the key."""
    enabled = os.getenv("LANGSMITH_TRACING", "false").lower() == "true"
    has_key = bool(os.getenv("LANGSMITH_API_KEY"))
    return {
        "tracing_requested": enabled,
        "api_key_set": has_key,
        "will_send_traces": enabled and has_key,
        "project": os.getenv("LANGSMITH_PROJECT", DEFAULT_PROJECT),
    }

01_check_tracing_env.py prints this dictionary. With the fresh copy:

tracing_requested  False
api_key_set        False
will_send_traces   False
project            support-copilot-dev

Traces are sent only when tracing is true and a key is set. Otherwise the same code runs and nothing leaves your machine.

Tags and metadata on every run

def run_config(user_id: str, app_version: str, tags: list[str] | None = None) -> dict:
    """Tags and metadata that let you filter runs by user and version in LangSmith."""
    return {
        "run_name": "support_copilot_request",
        "tags": ["support-copilot", f"v{app_version}", *(tags or [])],
        "metadata": {"user_id": user_id, "app_version": app_version},
    }

The run name becomes the name of the trace in LangSmith. The tags are the app name and the version with a v in front. The metadata holds the user id and the version. Tags and metadata are what you filter on later. 02_run_graph.py passes this config to the graph:

graph = build_graph()
result = graph.invoke({"ticket_id": "T-100"}, config=run_config("user-42", "1.3.0"))
print("plan  :", result["plan"])
print("notes :", result["notes"])
print("answer:", result["answer"])
plan  : Plan: look up the ticket, then write a short reply.
notes : Customer cannot reset password; reset email never arrives.
answer: Hi, we found the issue with your reset email and have fixed it. Please try again.

The plan and the answer are test model replies. The notes came from the real get_ticket tool.

@traceable for your own functions

LangChain and LangGraph record their own steps. Your plain Python functions need the traceable decorator from the langsmith package to show up in the tree.

from langsmith import traceable

from agents_graph import build_graph
from tracing_config import run_config


@traceable(name="clean_ticket_id", run_type="chain")
def clean_ticket_id(raw: str) -> str:
    return raw.strip().upper()


@traceable(name="handle_request", run_type="chain", tags=["support-copilot"],
           metadata={"app_version": "1.3.0"})
def handle_request(raw_ticket: str, user_id: str) -> str:
    ticket_id = clean_ticket_id(raw_ticket)
    graph = build_graph()
    result = graph.invoke({"ticket_id": ticket_id}, config=run_config(user_id, "1.3.0"))
    return result["answer"]


if __name__ == "__main__":
    print(handle_request("  t-100 ", user_id="user-42"))

The messy id " t-100 " gets cleaned to T-100, and the whole graph run sits inside the handle_request step. With tracing off, the decorators do nothing extra.

How a run becomes a trace

From graph.invoke to a LangSmith trace support_copilot_request tags: support-copilot, v1.3.0 | metadata: user_id, app_version planner (model call, 150 tokens) researcher get_ticket (tool) writer (model call, 200 tokens) LangSmith support-copilot-dev only if TRACING=true + key set
The request is the parent run, and every node, model call and tool call is a child. The tags and metadata sit on the parent. Your code doesn't change; two settings decide whether the tree is sent.

Read a trace tree on your own machine

Before sending anything, you can collect the same run objects LangSmith would receive. 04_local_trace_tree.py uses LangChain's RunCollectorCallbackHandler:

from langchain_core.tracers.run_collector import RunCollectorCallbackHandler

from agents_graph import build_graph
from tracing_config import run_config


def collect(ticket_id: str, user_id: str, version: str, delay: float = 0.0):
    collector = RunCollectorCallbackHandler()
    graph = build_graph(ticket_delay=delay)
    cfg = run_config(user_id, version)
    cfg["callbacks"] = [collector]
    graph.invoke({"ticket_id": ticket_id}, config=cfg)
    return collector.traced_runs[0]


def seconds(run) -> float:
    return (run.end_time - run.start_time).total_seconds()


def walk(run, depth=0):
    yield depth, run
    for child in run.child_runs:
        yield from walk(child, depth + 1)


def slowest_step(root):
    return max(root.child_runs, key=seconds)


def token_total(root) -> int:
    total = 0
    for _, run in walk(root):
        for gens in (run.outputs or {}).get("generations", []):
            for gen in gens:
                usage = (gen.get("message") or {}).get("kwargs", {}).get("usage_metadata")
                if usage:
                    total += usage["total_tokens"]
    return total


def failed_tool_calls(root):
    return [r.name for _, r in walk(root) if r.run_type == "tool" and r.error]

The script runs T-100 for user-42 with a 0.3 second delay in the researcher (a stand-in for a slow lookup), prints the tree, and then runs the unknown ticket T-999 for user-7 on version 1.4.0 to get a failing tool call. In the recorded run, the parent support_copilot_request took about 306 ms, and the researcher alone about 302 ms, with get_ticket inside it. Timings differ a little on every run. The summary lines below the tree are:

tags      : ['support-copilot', 'v1.3.0']
metadata  : {'user_id': 'user-42', 'app_version': '1.3.0'}
slowest   : researcher
tokens    : 350
failed    : ['get_ticket']

The slowest step is the researcher, which is the delay we added. The tokens add up to 150 + 200 = 350. And the failed list shows get_ticket from the T-999 run: the node caught the error and wrote "lookup failed" into its notes, so the graph finished, but the trace still marks the tool run as failed. The project's tests run the same checks offline: 7 passed.

Turn tracing on and read it in LangSmith

In your own .env, set LANGSMITH_TRACING=true and paste your LangSmith key on the next line. Run the check again and all three values are True. Then run 02_run_graph.py and 03_traceable_steps.py. The output looks the same as before, but both runs are now sent to LangSmith in the background.

On the Tracing page, the project support-copilot-dev appears with two traces: handle_request and support_copilot_request, each with its latency. Open support_copilot_request and you see:

  • The parent run with six runs inside it: the three nodes, the two model calls with 150 and 200 tokens, and the get_ticket tool call.
  • The input of the whole request (ticket id T-100) and the output (answer, notes and plan).
  • Click get_ticket and you see exactly what it was called with, ticket_id: T-100, and the ticket text it returned. A failing tool call would show its error here.

Filter by tag and by user

Tick the tag v1.3.0 and only one trace is left. handle_request drops out because its own tags are only support-copilot. Then add a metadata filter, metadata.user_id is user-42, in the search box after the tag filter. It's still the same run, and now you know who sent it and on which version.

Change line 7 of 02_run_graph.py to run_config("user-7", "1.4.0") and run it again. The project now shows three traces. Tick v1.4.0 and filter on user-7, and only the new run is left. Its latency column read 0.17 seconds in the recorded run. With a real model, compare latency and token counts run by run to spot a slow or expensive version.

To stop sending, set LANGSMITH_TRACING=false. The key can stay in .env; will_send_traces becomes False. It's one line.

In a bigger app: the Support Copilot

The Support Copilot (a supervisor, a RAG agent, a ticket agent and a responder) uses the same switch, set from its settings at startup:

def setup_tracing() -> bool:
    if not settings.langsmith_api_key:
        return False
    os.environ["LANGSMITH_API_KEY"] = settings.langsmith_api_key
    os.environ["LANGSMITH_TRACING"] = "true"
    os.environ["LANGSMITH_PROJECT"] = settings.langsmith_project
    return True

There is no tracing code inside the agents. Every graph run gets a config with the tag support-copilot and the customer's email as metadata, so when a customer says the bot was wrong, one search shows every trace for that customer:

def config_for(thread_id: str, customer_email: str = "") -> dict:
    """thread_id for the checkpointer; tags and metadata so a trace can be found later (by customer, by app)."""
    return {"configurable": {"thread_id": thread_id}, "tags": ["support-copilot"],
            "metadata": {"customer_email": customer_email}}

Two steps in that app are plain Python, so they get @traceable: the knowledge-base search becomes a kb_search step (run_type="retriever"), and the MCP tool call becomes an mcp_call step (run_type="tool"), with process_inputs dropping the self argument so the trace shows only the tool name and its arguments. Offline, its show_trace.py script prints the same kind of tree: for "How long does standard shipping take?" the run takes about two and a half seconds, and the RAG agent alone takes 2,135 ms. For "Where is my order 1043?" the supervisor routes to the ticket agent instead, which takes 3,377 ms because it calls the MCP tools. The route decides the path, and the slow step stands out. The same project also runs a 20-case golden set against four evaluators; that part is in LangSmith Datasets and Experiments.

Common mistakes

  • Setting the key but not the switch. Both LANGSMITH_TRACING=true and a key are needed. Print the status instead of guessing.
  • Printing or committing the key. Check whether it is set, never its value, and keep .env out of git.
  • No tags or metadata. Without a version tag and a user id, a busy project is a wall of identical traces.
  • Catching a tool error and forgetting it. The researcher caught the error, so the run "succeeded". Look for failed tool runs in the tree, not only failed requests.
  • Plain Python steps missing from the tree. Wrap them with @traceable, or a slow search looks like a slow model.

Quick recap

PieceJob
LANGSMITH_TRACING + LANGSMITH_API_KEYBoth set: traces are sent to LANGSMITH_PROJECT
run_configRun name, tags (app, version) and metadata (user, version)
@traceablePuts your own functions into the trace tree
Trace treeEach step with its time, tokens and errors
FiltersTag v1.4.0 plus metadata.user_id finds one user's runs on one version

For the ideas behind spans, redaction and sampling, see Observability and Tracing for LLM Apps.

Try it yourself

Raise the delay in 04_local_trace_tree.py to 1.0 second and add a delay to the writer too. Run it and check which step slowest_step picks. Then tag a run with an extra tag, such as run_config("user-42", "1.3.0", tags=["beta"]), and filter on it in LangSmith.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 99 of 207

Previous
Building a Claims Assistant: RAG, an Eval Harness With a Gate, and OpenTelemetry Tracing
Next post
LangSmith Datasets and Experiments: Upload a Golden Set, Run Two Prompt Versions With evaluate(), and Read the Score Diff

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

From ML Metrics to LLM Evals: Same Ruler, New Targets

Precision and recall don't disappear when you build with LLMs; they move. A spam filter at 0.75/0.75, precision@3 and recall@3 on six help-desk documents, exact match vs a key-fact check on two written answers, and the rubric that replaces a single label.

Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval

A friendlier prompt looked better on three questions and broke on others. An eval catches that: a fixed set of cases, a grader, a pass rate and a threshold. A tiny Python eval scores two prompt versions on the same six questions: v1 passes 83% and ships, v2 passes 50% and is blocked.

Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split

The answer key for a support bot: 24 cases in one JSONL file, from 12 past tickets, 8 edge cases and 4 attacks. A Pydantic schema catches 4 problems in a broken file, a stats table finds that payments and account have no hard case, and a seeded split gives the same 16 dev and 8 test cases every time.

Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model

When a RAG answer is wrong, check the retriever first. Score two retrievers on 24 graded queries with Recall@5, MRR and nDCG@5: overall there's no clear winner (0.757 vs 0.819, 0.854 vs 0.826, 0.769 vs 0.782), but the paraphrase slice drops to about 0.5 for both, and one query scores zero everywhere.

On this page

  • A flight data recorder for agents
  • The app we trace
  • Two settings decide whether anything is sent
  • Tags and metadata on every run
  • @traceable for your own functions
  • How a run becomes a trace
  • Read a trace tree on your own machine
  • Turn tracing on and read it in LangSmith
  • Filter by tag and by user
  • In a bigger app: the Support Copilot
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.