
Building an AI application is easier than ever with tools like LangChain, OpenAI, and LangGraph. However, making an AI application reliable in production introduces new challenges.
Have you ever encountered a situation where your AI chatbot returns incorrect answers, takes too long to respond, or generates unexpected output even though your code appears correct?
These problems can be difficult to investigate because AI applications involve multiple components, including prompts, language models, external APIs, vector databases, and retrieval pipelines.
Traditional debugging tools can help identify code errors, but they do not always provide enough information to understand why an AI model generated a particular response.
This is where LangSmith becomes useful.
LangSmith is an observability and evaluation platform designed to help developers trace AI application execution, debug failures, evaluate output quality, and monitor performance.
In this tutorial, you will learn how to use LangSmith with Node.js, LangChain.js, and OpenAI to debug and monitor an AI application step by step.
What Is LangSmith?
LangSmith is a platform for developing, debugging, evaluating, and monitoring applications powered by large language models (LLMs).
It integrates with LangChain and LangGraph and can also work with applications built using other frameworks or custom code.
With LangSmith, developers can inspect individual model calls, examine execution traces, identify errors, analyze latency, and evaluate the quality of AI-generated responses.
Key Features of LangSmith
1. Tracing
Tracing records the sequence of operations performed during an AI request. You can inspect model calls, tool executions, and other instrumented steps.
2. Debugging
Developers can investigate failed requests, unexpected model outputs, prompt issues, and problems in retrieval pipelines.
3. Performance Monitoring
LangSmith helps teams analyze execution times, errors, and other operational metrics.
4. Evaluation
You can evaluate AI outputs against defined criteria and compare application versions using test datasets.
5. Production Observability
Monitoring production traces helps identify recurring issues, changing usage patterns, and opportunities to improve AI application quality.
Why Do AI Applications Need LangSmith?
Consider an AI chatbot built using Node.js, LangChain, OpenAI, and a vector database.
A user asks:
"Explain how Redis caching works in Node.js."
The chatbot returns an irrelevant answer about React components.
Several things could have gone wrong:
The application retrieved irrelevant documents.
The prompt did not clearly explain the task.
The model received incomplete context.
The wrong model or configuration was used.
A previous step returned unexpected data.
Without tracing, you may need to add console statements throughout your code and manually inspect individual operations.
With LangSmith, you can examine the recorded execution steps and investigate where the problem occurred.
This makes debugging more systematic and helps developers improve AI application reliability.
Understanding Traces, Runs, and Projects
Before implementing LangSmith, it is important to understand three concepts.
1. Trace
A trace represents the execution of a request through an AI application.
For example, a RAG chatbot might perform these operations:
Receive the user's question.
Generate an embedding.
Retrieve relevant documents.
Construct a prompt.
Call an LLM.
Return the generated answer.
A trace helps you understand how these operations fit together.
2. Run
A run represents an individual operation within a trace.
Examples include:
Calling an OpenAI model.
Executing a retrieval function.
Running a chain.
Calling an external tool.
Executing a custom function that has been instrumented.
Each run can contain information such as its inputs, outputs, execution time, and errors, depending on the integration and configuration.
3. Project
A LangSmith project groups related traces so you can investigate the behavior of a particular application or environment.
For example, you might create separate projects for:
Development.
Staging.
Production.
Customer support chatbot.
AI document search.
Separating projects makes it easier to organize traces and investigate issues in the appropriate environment.
How LangSmith Works
A typical LangSmith observability workflow looks like this:
User Request → AI Application → Model and Tool Execution → LangSmith Tracing → Debugging and Evaluation → Application Improvements
When tracing is enabled, supported integrations can record execution details automatically.
You can then inspect traces in the LangSmith interface instead of relying exclusively on application logs.
For LangChain applications, enabling tracing generally requires configuring environment variables. You can learn more in the official LangSmith observability documentation.
Step 1: Create a LangSmith Account
First, open LangSmith and create an account or sign in.
After signing in:
Open the settings area.
Create an API key using the available key-management options.
Copy the key and store it securely.
Create or select a project for your AI application.
You will use the API key to authenticate your application's tracing requests.
Important: Never expose your LangSmith API key in frontend JavaScript, publish it in a public repository, or share it in screenshots.
Step 2: Create a Node.js Project
Let's build a simple AI application that answers user questions using OpenAI and LangChain.js.
Create a project directory:
mkdir langsmith-ai-monitoring
cd langsmith-ai-monitoringInitialize the project:
npm init -yInstall the required packages:
npm install @langchain/core @langchain/openai langsmith dotenvConfigure your package.json to use ES modules:
{
"type": "module",
"scripts": {
"start": "node index.js"
}
}If your existing package.json contains additional fields, keep them and update only the relevant configuration.
Step 3: Configure Environment Variables
Create a .env file in your project root.
Add the following variables:
OPENAI_API_KEY=your_openai_api_key
LANGSMITH_TRACING=true
LANGSMITH_API_KEY=your_langsmith_api_key
LANGSMITH_PROJECT=langsmith-ai-monitoringReplace the placeholder values with your actual API keys.
Here is what each variable does:
Variable | Purpose |
|---|---|
| Authenticates requests to the OpenAI API |
| Enables LangSmith tracing |
| Authenticates tracing requests |
| Selects the project for recorded traces |
The OpenAI API key and LangSmith API key serve different purposes.
The first allows your application to call the model provider. The second allows the application to send tracing data to LangSmith.
Add .env to your .gitignore file:
node_modules/
.envFor production deployments, configure environment variables through your hosting platform or a secrets manager rather than committing them to source control.
Step 4: Build a Simple AI Application
Create an index.js file.
Add the following code:
import "dotenv/config";
import { ChatOpenAI } from "@langchain/openai";
import { HumanMessage, SystemMessage } from "@langchain/core/messages";
const model = new ChatOpenAI({
model: "gpt-4.1-mini",
temperature: 0,
});
async function askAI(question) {
const response = await model.invoke([
new SystemMessage(
"You are a helpful programming assistant. " +
"Answer technical questions clearly and accurately."
),
new HumanMessage(question),
]);
return response.content;
}
try {
const answer = await askAI(
"What is Redis caching in Node.js?"
);
console.log("AI Response:", answer);
} catch (error) {
console.error("AI request failed:", error.message);
}This example uses a chat model to answer a programming question.
The temperature: 0 setting requests less variation in generation, although it does not guarantee identical outputs in every situation.
Because LangSmith tracing is enabled through environment variables, supported LangChain operations can be traced without manually creating a tracing callback for this example.
Run the application:
npm startThe terminal should display the generated answer.
Now open your LangSmith project and inspect the recorded trace.
You should be able to investigate the model invocation and its execution details, provided the request completed and tracing was successfully recorded.
Step 5: Inspect Traces in LangSmith
After running the application, open your LangSmith project.
Look for the trace corresponding to your request.
Depending on the integration and the information captured, the trace can help you inspect:
The input messages sent to the model.
The generated response.
The model used.
Execution duration.
Token usage and associated cost information when available.
Errors or failures.
The sequence of instrumented operations.
For example, imagine the AI application takes 4 seconds to answer a question.
The trace may help you determine whether the delay occurred during the model call or another operation in the application.
This is more useful than simply knowing that the overall request took 4 seconds.
Example: Debugging an Incorrect Response
Suppose your chatbot returns an answer unrelated to the user's question.
Use this debugging workflow:
Open the relevant trace.
Inspect the original user input.
Check the messages sent to the model.
Examine any retrieved documents or tool outputs.
Inspect the model's response.
Identify the step where the behavior first became incorrect.
Fix the issue and test the application again.
If the prompt is correct but the retrieved documents are irrelevant, changing the prompt alone may not solve the problem.
Tracing helps you investigate the actual execution path instead of guessing which component failed.
Step 6: Debug Errors in AI Applications
AI applications can fail for several reasons, including invalid API credentials, rate limits, network problems, malformed inputs, and unexpected model responses.
LangSmith helps you investigate failures when the relevant execution details are successfully recorded.
Let's modify the example to add more useful error handling.
async function askAI(question) {
try {
const response = await model.invoke([
new SystemMessage(
"You are a helpful programming assistant."
),
new HumanMessage(question),
]);
return response.content;
} catch (error) {
console.error("Model invocation failed:", {
message: error.message,
name: error.name,
});
throw error;
}
}This code logs the error name and message in your application logs and rethrows the error so the calling code can handle the failure.
The exception may also appear in the recorded trace if the failure occurs inside a traced operation and the trace is successfully submitted.
Common Errors to Investigate
Problem | What to Check |
|---|---|
Authentication failure | Verify the API key and permissions |
Rate-limit error | Review provider limits and implement backoff |
Slow response | Inspect model latency and other recorded operations |
Incorrect output | Examine prompts, inputs, and retrieved context |
Missing traces | Check tracing configuration and API credentials |
High model cost | Review model usage and request volume |
Note: Application logs and LangSmith traces complement each other. Application logs are useful for infrastructure-level diagnostics, while traces provide insight into the execution of AI workflows.
Step 7: Monitor AI Application Performance
Debugging helps you investigate individual failures. Monitoring helps you understand application behavior over time.
When working with AI applications, consider tracking the following metrics.
1. Latency
Latency measures how long an operation takes.
For example:
Retrieval: 100 milliseconds.
Prompt construction: 20 milliseconds.
Model invocation: 1.8 seconds.
Total request duration: 2 seconds.
These numbers are illustrative.
Inspecting execution durations can help you identify bottlenecks and determine which parts of your application need optimization.
2. Error Rate
Track how frequently requests fail.
A sudden increase in errors may indicate a provider outage, expired credentials, an application deployment issue, or a change in request patterns.
3. Token Usage and Cost
Model requests can consume input and output tokens.
Monitor token usage and available cost information to identify unexpectedly expensive requests.
Actual costs depend on the model, usage, provider pricing, and any applicable platform-specific charges.
4. Response Quality
A successful API call does not necessarily mean the AI produced a useful answer.
For example, a chatbot might return an answer that is grammatically correct but factually incorrect.
Quality evaluation helps identify these problems.
5. Tool and Retrieval Behavior
For applications using agents or RAG, inspect tool calls and retrieval operations.
An agent may repeatedly call the same tool, while a RAG system may retrieve irrelevant documents.
Understanding these behaviors can help you improve reliability and efficiency.
LangSmith's observability features can help analyze these areas through traces, monitoring views, and evaluations. Available metrics and features depend on the integration and configuration.
Step 8: Debug a RAG Application with LangSmith
Retrieval-Augmented Generation (RAG) combines document retrieval with an LLM to produce answers informed by external information.
A typical RAG application follows this workflow:
Receive a user question.
Convert the question into a search query or embedding.
Retrieve relevant documents from a data source or vector database.
Construct a prompt containing the retrieved context.
Send the prompt to an LLM.
Return the answer.
Consider a chatbot that searches technical documentation using ChromaDB.
A user asks:
"What is the purpose of Redis caching?"
However, the chatbot returns information about MongoDB indexes.
Several things could have gone wrong:
The vector search returned irrelevant documents.
The document chunks were poorly structured.
The retrieval query was not appropriate.
The retrieved context was not included correctly in the prompt.
The model ignored or misinterpreted the context.
How LangSmith Helps Debug RAG
With tracing enabled for the supported operations, inspect the relevant trace and investigate:
Retrieval step: Were the expected documents returned?
Prompt step: Did the final prompt contain the correct context?
Model step: Did the model receive the intended messages?
Output step: Did the final answer accurately reflect the available information?
This workflow helps separate retrieval problems from generation problems.
For example, if the correct document never appears in the retrieval results, you should investigate the embedding model, chunking strategy, similarity settings, or search filters before changing the generation prompt.
Step 9: Evaluate AI Responses with LangSmith
Tracing helps explain what happened during a request. Evaluation helps measure whether your AI application produces acceptable results.
LangSmith supports evaluation workflows using datasets and evaluators.
You can use these features to compare prompts, models, and application versions against representative test cases.
Example Evaluation Dataset
Suppose you are building a programming assistant.
You could create test cases like these:
Question | Expected Behavior |
|---|---|
What is Node.js? | Explain the JavaScript runtime |
What is Redis used for? | Describe common Redis use cases |
What is an API? | Explain how applications communicate |
What is semantic search? | Explain meaning-based information retrieval |
For each test case, define what a satisfactory response should contain.
You can then evaluate responses using criteria such as:
Correctness.
Relevance.
Helpfulness.
Completeness.
Adherence to instructions.
Depending on your evaluation setup, you can use code-based checks, reference-based comparisons, or model-based evaluators.
Why Evaluation Matters
Imagine you change your system prompt to improve the answer to one question.
The new prompt might improve that response but make other answers worse.
Running the same evaluation dataset against the old and new versions helps you compare the results systematically.
This is especially useful before deploying changes to production.
For more information, see the official LangSmith evaluation documentation.
Step 10: Monitor Production AI Applications
Once an AI application is deployed, its behavior may change as user traffic, prompts, data, and external dependencies evolve.
A production monitoring workflow should include:
Enable tracing in the appropriate environment.
Organize traces into suitable projects.
Inspect latency, errors, and usage patterns.
Evaluate output quality against defined criteria.
Investigate recurring failures.
Turn useful production examples into regression tests.
Verify improvements before releasing changes.
LangSmith supports production observability features, including trace analysis and online evaluations.
Depending on your configuration and plan, you can also use monitoring dashboards and alerting integrations to identify issues that need attention.
Example: Detecting a Quality Problem
Suppose users begin reporting that your AI assistant provides incomplete answers.
A practical investigation could look like this:
Find representative traces associated with the problem.
Compare them with traces from successful requests.
Check whether the model received sufficient context.
Review changes to prompts, retrieval logic, or model configuration.
Create evaluation examples representing the failures.
Test a proposed fix against the evaluation dataset.
Deploy the change only after verifying its impact.
This approach turns production failures into opportunities for continuous improvement.
Step 11: Best Practices for Using LangSmith
Follow these practices to make your AI applications easier to debug and maintain.
1. Enable Tracing Early
Enable tracing during development so you can understand how your application behaves before it reaches production.
2. Use Separate Projects
Organize traces by application or environment where appropriate.
This helps keep development experiments separate from production traffic.
3. Create Evaluation Datasets
Build a collection of representative questions and expected behaviors.
Use the dataset to test changes to prompts, models, and retrieval logic.
4. Monitor Latency and Cost
Measure performance and usage so you can identify slow operations and unexpectedly expensive requests.
5. Protect Sensitive Information
Traces can contain user messages, prompts, retrieved documents, tool inputs, and model outputs.
Before enabling tracing in production:
Review the data captured by your integrations.
Avoid sending unnecessary personal or confidential information.
Apply appropriate access controls.
Configure redaction or filtering where supported.
Review retention and data-handling requirements.
Do not assume that enabling tracing automatically removes sensitive information.
6. Use Structured Error Handling
Log meaningful error information in your application and preserve the original exception when appropriate.
Avoid logging API keys, authorization headers, or sensitive request bodies.
7. Test Changes Before Deployment
Evaluate new prompts and model configurations against representative examples before releasing them.
8. Investigate Recurring Failures
Look for patterns rather than treating every failed request as an isolated incident.
Repeated errors may indicate a systemic problem with retrieval, configuration, or an external dependency.
LangSmith vs. Traditional Logging
Traditional logging and AI observability solve related but different problems.
Feature | Traditional Logging | LangSmith |
|---|---|---|
Application error messages | Yes | Can capture errors in traced operations |
Model input and output inspection | Requires application instrumentation | Supported through tracing integrations |
AI execution traces | Requires custom implementation or tracing tools | Core capability |
Retrieval and tool execution analysis | Requires suitable instrumentation | Supported for traced operations |
AI output evaluation | Usually requires additional tooling | Provides evaluation workflows |
Performance analysis | Depends on logging and monitoring setup | Provides AI-focused trace analysis and monitoring features |
These tools work best together.
Traditional logs remain important for server health, infrastructure issues, and application-level events. LangSmith adds visibility into AI execution and helps evaluate model behavior.
Common Challenges When Using LangSmith
Traces Are Not Appearing
Check that tracing is enabled, the API key is valid, and the application is using the intended project.
Also verify that your installed integration supports the operations you expect to trace.
AI Responses Are Still Incorrect
Tracing shows what happened, but it does not automatically guarantee correct answers.
Investigate the prompt, retrieved context, model configuration, and application logic. Use evaluation datasets to measure improvements.
Application Latency Is High
Inspect the execution trace to identify slow operations.
Possible causes include model latency, sequential external API calls, slow retrieval, or unnecessary repeated operations.
Sensitive Information Appears in Traces
Review your tracing configuration and the data captured by the application.
Implement appropriate redaction, filtering, access controls, and retention practices before using tracing with sensitive production workloads.
Conclusion
LangSmith is a valuable tool for developers building AI-powered applications with LangChain, LangGraph, OpenAI, and other supported technologies.
It helps you understand how an AI application executes, investigate failures, analyze performance, and evaluate output quality.
In this tutorial, you learned how to:
Understand LangSmith and its core concepts.
Configure tracing in a Node.js application.
Connect LangSmith with LangChain.js and OpenAI.
Inspect traces and investigate errors.
Monitor latency, token usage, and application behavior.
Debug retrieval problems in RAG applications.
Evaluate AI responses using datasets.
Apply best practices for production monitoring.
If you are building AI chatbots, RAG systems, or autonomous agents, consider adding observability and evaluation early in development.
The goal is not just to make an AI application work. It is to understand its behavior, measure its quality, and improve its reliability over time.
Frequently Asked Questions (FAQs)
1. What is LangSmith used for?
LangSmith is used to trace, debug, evaluate, and monitor AI applications. It helps developers inspect execution steps, investigate failures, and measure application quality.
2. Is LangSmith only for LangChain applications?
No. Although it integrates with LangChain and LangGraph, LangSmith also supports other AI frameworks and custom applications through its SDKs and supported tracing integrations.
3. Is LangSmith free to use?
LangSmith offers a free tier, with additional capabilities and usage limits depending on the plan. Check the official LangSmith website for current product and plan information.
4. What is tracing in LangSmith?
Tracing records the execution of an AI request, including instrumented operations such as model calls, retrieval steps, and tool executions. It helps developers understand how a request was processed.
5. Can I use LangSmith with Node.js?
Yes. LangSmith supports JavaScript and TypeScript applications, including applications built with LangChain.js.
6. Can LangSmith help debug RAG applications?
Yes. Traces can help you inspect retrieval results, prompts, model calls, and generated answers, making it easier to identify whether a problem originates in retrieval or generation.
7. What is the difference between LangChain and LangSmith?
LangChain is a framework for building applications powered by language models. LangSmith provides tools for tracing, debugging, evaluating, and monitoring those applications.
8. Does LangSmith automatically fix AI hallucinations?
No. LangSmith helps developers investigate incorrect answers and evaluate potential improvements. Fixing hallucinations generally requires changes to prompts, retrieval, data quality, model configuration, or application logic.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


