LLM Observability Challenges That LangSmith Solves
LLM outputs are stochastic, token usage fluctuates with prompt length, retrieval quality varies across different embedding models, and hallucinations appear inconsistently across similar queries. Traditional application monitoring tools such as Sentry capture HTTP errors and stack traces but cannot determine whether a generated response is faithful to the retrieved context, relevant to the user question, or contains fabricated details.
Consider a customer support assistant that answers shipping questions. Without specialized observability, a developer cannot easily answer why one query returned a correct 3-5 business day estimate while an almost identical query invented a nonexistent weekend delivery option. LangSmith solves this by capturing the complete execution graph of every chain, agent, retriever, and LLM call.
Each trace records exact inputs and outputs at every step, per-step latency, token counts for prompts and completions, embedding vectors when applicable, and arbitrary metadata. This trace data supports two distinct workflows: interactive debugging of single failures and aggregate quality measurement across hundreds or thousands of runs. In practice, teams using these traces reduce the time spent reproducing LLM bugs from hours to minutes.
The platform delivers three tightly integrated capabilities: automatic tracing of LangChain components, versioned datasets paired with evaluators, and production monitoring with feedback loops. When added to a Next.js 14 or 15 application built with LangChain.js v0.3, the initial setup cost is under 40 lines of code yet provides immediate visibility into retrieval relevance, answer grounding, and cost per query.
Project Setup and Environment Configuration
Begin with a Next.js application running on Node 20 or 22. If starting fresh, run npx create-next-app@latest langsmith-demo --typescript --tailwind --eslint. Navigate into the project and install the LangSmith and LangChain dependencies:
npm install langchain@0.3.0 @langchain/openai@0.3.0 langsmith@0.2.0
npm install -D @types/node
Create a .env.local file with the following variables. The tracing flag activates automatic instrumentation for all LangChain runnables:
LANGCHAIN_TRACING_V2=true
LANGCHAIN_ENDPOINT=https://api.smith.langchain.com
LANGCHAIN_API_KEY=lsv2_pt_your_key_here
LANGCHAIN_PROJECT=production-support-assistant
OPENAI_API_KEY=sk-your-openai-key
For local development, create a utility file lib/langsmith.ts that validates environment variables and exports a configured client:
import { Client } from "langsmith";
if (!process.env.LANGCHAIN_API_KEY) {
console.warn("LangSmith API key not set. Tracing disabled.");
}
export const langsmithClient = new Client({
apiKey: process.env.LANGCHAIN_API_KEY,
});
export function isTracingEnabled(): boolean {
return process.env.LANGCHAIN_TRACING_V2 === "true";
}
In next.config.mjs, enable server components and ensure environment variables are not stripped. Restart the development server with npm run dev. Any subsequent LangChain invocation on the server route or server action will automatically appear in the LangSmith project dashboard. No additional middleware is required for basic tracing, though you may add a custom tracer for non-LangChain OpenAI calls.
Instrumenting a Simple Chain and Inspecting Traces
Create a support assistant route at app/api/support/route.ts. The following chain uses a prompt template and GPT-4o-mini:
import { ChatOpenAI } from "@langchain/openai";
import { PromptTemplate } from "@langchain/core/prompts";
import { RunnableSequence } from "@langchain/core/runnables";
import { isTracingEnabled } from "@/lib/langsmith";
const model = new ChatOpenAI({
modelName: "gpt-4o-mini-2024-07-18",
temperature: 0,
maxTokens: 512,
});
const prompt = PromptTemplate.fromTemplate(
`You are a helpful support agent. Answer strictly using the provided context.
Context: {context}
Question: {question}
Answer:`
);
const chain = RunnableSequence.from([prompt, model]);
export async function POST(req: Request) {
const { question } = await req.json();
const context = `We ship all orders within 2 business days via UPS or FedEx.
Standard delivery takes 3-5 business days. Express options are available.`;
const config = isTracingEnabled()
? {
metadata: {
userId: "demo-user-123",
tenant: "acme",
feature: "shipping"
},
tags: ["support", "faq"]
}
: {};
const result = await chain.invoke({
context,
question,
}, config);
return Response.json({
answer: result.content,
traceUrl: isTracingEnabled()
? "Check LangSmith dashboard for latest trace"
: null
});
}
Send a POST request using curl or a frontend form: {"question": "What is your shipping timeline?"}. Open the LangSmith dashboard, locate the project, and click the most recent trace. The trace tree displays the PromptTemplate run, the ChatOpenAI call with exact prompt sent, token counts (typically 80 prompt tokens and 45 completion tokens for this example), latency (usually 400-900 ms), and the final output. Expand the metadata panel to verify custom tags and values. This granular visibility eliminates guesswork when diagnosing why certain queries produce incomplete answers.
Handling Streaming Responses While Preserving Traces
Production applications often stream tokens to reduce perceived latency. LangSmith supports streaming through the same tracing infrastructure. Modify the route to stream using LangChain's .stream() method:
export async function POST(req: Request) {
const { question } = await req.json();
const context = `We ship within 2 business days...`; // same as before
const stream = await chain.stream({
context,
question,
}, {
metadata: { streaming: true, userId: "demo-user-123" }
});
const encoder = new TextEncoder();
const readable = new ReadableStream({
async start(controller) {
for await (const chunk of stream) {
controller.enqueue(encoder.encode(chunk.content || ""));
}
controller.close();
},
});
return new Response(readable, {
headers: { "Content-Type": "text/event-stream" },
});
}
In the LangSmith UI the streamed run appears as a single trace with a "streaming" flag. The platform reconstructs the full output for evaluator use while preserving the incremental token timing data. This allows measurement of both time-to-first-token and total completion time, critical metrics for user experience in customer-facing assistants.
Building and Versioning Evaluation Datasets
Static datasets prevent regression when prompts or retrieval logic change. Use the LangSmith SDK to create and populate a dataset. Add this script in scripts/create-dataset.ts:
import { Client } from "langsmith";
const client = new Client();
async function main() {
const dataset = await client.createDataset("shipping-faqs-v1", {
description: "50 representative shipping and delivery questions with reference answers",
metadata: { domain: "ecommerce", version: "1.0" },
});
const examples = [
{
inputs: {
question: "How long does standard shipping take?",
context: "Standard delivery is 3-5 business days via UPS."
},
outputs: {
expected_answer: "Standard shipping takes 3-5 business days."
}
},
{
inputs: {
question: "Do you ship internationally?",
context: "We currently ship only within the United States."
},
outputs: {
expected_answer: "We currently ship only within the United States."
}
}
// Add at least 30 more examples covering edge cases such as holidays, returns, and tracking issues
];
await client.createExamples({
datasetId: dataset.id,
examples: examples,
});
console.log(`Dataset created with ${examples.length} examples`);
}
main();
Run the script with ts-node scripts/create-dataset.ts. In the LangSmith UI, the dataset supports manual editing, addition of reference outputs, and tagging of individual examples. Create a second dataset for regression testing after prompt changes. The platform tracks lineage so you can compare experiment results across dataset versions.
Running Automated Evaluations with Built-in Metrics
LangSmith evaluators score chain outputs without manual review. Key metrics for RAG systems include:
- faithfulness: Determines whether every claim in the answer is directly supported by the retrieved context. The evaluator uses an LLM judge to check for contradictions or unsubstantiated statements.
- answer_relevancy: Measures how directly the response addresses the original question rather than providing tangential information.
- context_precision: Assesses whether the most relevant chunks appear earlier in the prompt, reducing the impact of noise in long contexts.
- context_recall: Checks whether all information required to answer the question was present in the retrieved documents.
Execute evaluations with the following script that can run in CI or on-demand:
import { evaluate } from "langsmith/evaluation";
import { loadEvaluator } from "langsmith/evaluation";
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({ modelName: "gpt-4o-2024-08-06", temperature: 0 });
async function runEval() {
const faithfulness = await loadEvaluator("faithfulness", { llm });
const relevancy = await loadEvaluator("labeled_criteria", {
criteria: "relevancy",
llm,
});
const results = await evaluate(
async (input) => {
return await chain.invoke(input);
},
{
data: "shipping-faqs-v1",
evaluators: [faithfulness, relevancy],
experimentPrefix: "prompt-v2-gpt4o-mini",
maxConcurrency: 4,
}
);
console.dir(results, { depth: null });
}
runEval();
Each experiment receives a unique identifier and appears in the UI with summary statistics, per-example scores, and diff views against previous runs. A faithfulness score below 0.8 on more than 15% of examples signals that the prompt needs tightening or retrieval quality must improve. Because evaluators call an LLM, a 40-example run with two criteria typically consumes 120,000-180,000 tokens.
Tracing and Evaluating Full RAG Pipelines
Real applications combine retrieval with generation. The following expanded RAG implementation demonstrates nested tracing:
import { OpenAIEmbeddings } from "@langchain/openai";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
import { ContextualCompressionRetriever } from "langchain/retrievers/contextual_compression";
import { LLMChainExtractor } from "langchain/retrievers/document_compressors";
const embeddings = new OpenAIEmbeddings({ modelName: "text-embedding-3-small" });
const vectorStore = await MemoryVectorStore.fromTexts(
[
"Standard shipping via UPS takes 3-5 business days for domestic orders.",
"Express shipping guarantees delivery in 1-2 business days for an additional fee.",
"We do not ship to P.O. boxes or internationally at this time."
],
[{ source: "policy" }, { source: "policy" }, { source: "policy" }],
embeddings
);
const baseRetriever = vectorStore.asRetriever({ k: 6 });
const compressor = LLMChainExtractor.fromLLM(model);
const retriever = new ContextualCompressionRetriever({
baseRetriever,
compressor,
});
const ragChain = RunnableSequence.from([
{
context: retriever,
question: (input: { question: string }) => input.question,
},
prompt,
model,
]);
// Invocation automatically creates nested runs: Retriever → Compressor → LLM calls
In LangSmith each retrieval step shows the documents returned, their similarity scores, and which documents survived compression. The trace makes it obvious when irrelevant chunks are included or when the compressor removes critical information. Apply the same evaluators to the complete RAG chain to obtain end-to-end quality scores rather than isolated component metrics.
Creating Custom Evaluators for Domain Requirements
Generic metrics miss product-specific needs such as "includes a tracking link" or "maintains professional tone". Define a custom evaluator using criteria or a full prompt:
import { RunEvaluator } from "langsmith/evaluation";
const trackingLinkEvaluator: RunEvaluator = async ({ run, example }) => {
const output = run.outputs?.output || "";
const hasTracking = /https?:\/\/.*(ups|fedex|usps|tracking).*/i.test(output);
return {
key: "contains_tracking_link",
score: hasTracking ? 1 : 0,
comment: hasTracking
? "Contains valid tracking link"
: "Missing tracking information",
};
};
// Register in evaluate call
evaluators: [faithfulness, trackingLinkEvaluator]
For more sophisticated checks, supply a custom LLM prompt that returns JSON. The prompt can include few-shot examples of good and bad outputs. These custom scores appear in the same experiment tables, allowing a blended quality score that weights faithfulness at 0.5, relevancy at 0.3, and business rules at 0.2.
Production Monitoring, User Feedback, and Alerting
After launch, reduce tracing volume to 10% of traffic using a simple random sampler or header-based routing for premium users. Log explicit user feedback with the same run identifier returned from the API:
const response = await fetch("/api/support", { method: "POST", body: JSON.stringify(payload) });
const data = await response.json();
// Later, when user clicks thumbs-up or provides comment
await langsmithClient.createFeedback(data.runId, "user_feedback", {
score: 1,
comment: "Answer was accurate and included tracking link",
metadata: { source: "web" },
});
The dashboard surfaces negative feedback traces first, enabling rapid iteration. Configure alerts for key metrics: average faithfulness under 0.82, P95 latency above 3200 ms, or token usage spikes. Webhooks deliver these notifications to Slack or email, closing the loop between production behavior and engineering action.
Integrating LangSmith with CI/CD Pipelines
Prevent quality regressions by adding an evaluation step to GitHub Actions. The complete workflow file .github/workflows/eval.yml looks like this:
name: LLM Quality Evaluation
on:
pull_request:
branches: [main]
paths:
- "app/api/support/**"
- "prompts/**"
jobs:
evaluate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
- run: npm ci
- name: Run evaluation
run: npm run evaluate:ci
env:
LANGCHAIN_API_KEY: ${{ secrets.LANGCHAIN_API_KEY }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
LANGCHAIN_TRACING_V2: "true"
- name: Check results
run: node scripts/check-eval-thresholds.js
The threshold script parses the experiment results and fails the build if any critical metric falls below the defined bar. This practice turns previously subjective prompt engineering into an objective part of the release process.
Sampling Strategies and Cost Control Techniques
Tracing every request incurs both monetary cost and slight latency (typically 15-40 ms added network round-trip). Implement tiered sampling:
function shouldTrace(userTier: string, random = Math.random()): boolean {
if (userTier === "enterprise") return random < 0.25;
if (userTier === "pro") return random < 0.10;
return random < 0.03;
}
Additional controls include trace filtering by tags, retention policies (keep traces 30 days for production, 90 days for evaluation projects), and selective disabling of embedding logging. Monitor the LangSmith usage dashboard weekly to keep evaluation spend under 8% of total LLM cost. Many teams discover that switching simpler queries to cheaper models after evaluation saves 55-75% on inference while maintaining aggregate quality scores above 0.88.
Debugging Multi-Step Agents and Tool Use
Agents that use tools create deep trace trees. LangSmith visualizes the sequence of tool calls, intermediate thoughts, and final answers. Add an agent example using LangGraph or LangChain's agent executor and observe how each tool run appears as a child run. This makes it trivial to spot when an agent calls an expensive tool unnecessarily or enters a loop. Combine agent traces with custom evaluators that penalize excessive steps or tool costs.
Comparing LangSmith with Alternative Approaches
OpenTelemetry excels at infrastructure and microservice tracing but requires significant custom instrumentation to capture semantic LLM quality. Helicone offers lightweight proxy-based logging and caching but provides fewer built-in evaluators and no native dataset workflow. LangSmith differentiates itself through seamless integration with the LangChain ecosystem, experiment comparison UI, and first-class support for feedback annotation. The primary trade-off is reliance on a third-party service; however, self-hosted alternatives currently lag in evaluator accuracy and UI speed. Teams often combine LangSmith for LLM-specific insights with OpenTelemetry for overall system observability.
Security, Compliance, and Operational Considerations
When tracing production traffic, redact PII before sending to LangSmith using the anonymization filters or middleware that strips email addresses and API keys. Enable SOC 2 compliant settings in the LangSmith organization settings if handling customer data. Set strict retention policies and use the export API to pull trace data into internal analytics warehouses for long-term trend analysis. Regularly audit which metadata fields are attached to traces to avoid accidental leakage of sensitive business logic.
Common Pitfalls and Production Best Practices
Common mistakes include tracing too much data, causing both cost and noise, and over-reliance on a single evaluator without calibration. Mitigate by starting with 5% sampling, reviewing 20 traces manually each week, and adjusting evaluator prompts based on disagreements with human judgment. Keep chains modular so trace trees remain readable. Version every prompt and retrieval configuration, linking experiments to Git commits. Treat evaluation scores as directional signals rather than absolute truth; a drop in context_recall from 0.91 to 0.76 is meaningful, while a 0.02 fluctuation usually is not. Combine LangSmith data with traditional application metrics to build a complete picture of system health.
Following these patterns consistently, engineering teams achieve measurable improvements in answer quality, faster debugging cycles, and data-driven prompt iteration without guesswork. The combination of rich execution traces, version-controlled datasets, automated evaluators, and production feedback loops transforms opaque LLM systems into observable, testable, and continuously improving applications.
