Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

LangChain LangSmith — Observability

LangChain LangSmith——Observability and Debugging

In previous tutorials, we have used LangChain to build a RAG Agent, an intelligent customer service bot, and a multi-tool personal assistant.

But as Agents become more complex, a new problem arises:When the AI answers incorrectly, a tool call fails, or the response slows down, how should we locate the problem?

For example, if a RAG Agent does not answer the user's question correctly, it may be because the model did not call the retrieval tool, the retrieval results are irrelevant, or the model did not correctly understand the material.

Simply looking at the final answer usually cannot quickly determine at which step the problem occurred.

This is where LangSmith comes in.

LangSmith is an observability, debugging, and evaluation platform for AI applications provided by LangChain, capable of tracing an Agent's model calls, tool executions, inputs and outputs, latency, and partial Token usage.

This chapter is based on LangChain 1.x and introduces basic usage of LangSmith, automatic tracing, custom Traces, project management, performance analysis, trace sampling, and data privacy.


I. What is LangSmith?

LangSmith helps developers understand the actual runtime behavior of AI applications.

For example, a user asks:

帮我查一下 Python 入门课程。

The Agent may go through the following process:

用户问题

    ↓

Agent 开始执行

    ↓

调用 DeepSeek 模型

    ↓

模型选择 search_course 工具

    ↓

执行 search_course("Python")

    ↓

工具返回课程资料

    ↓

再次调用 DeepSeek

    ↓

生成最终回答

    ↓

Agent 执行完成

Without a tracing tool, developers can usually only rely on print() and program logs to view part of the process.

After enabling LangSmith, you can view the call relationships, execution times, and recordable inputs and outputs of these operations in the console.

Main Features of LangSmith

Function Description Typical use
Tracing Trace the execution of models and tools Troubleshoot erroneous calls
Observability Observe latency, call volume, and errors Performance analysis
Token Usage Record available Token usage data Cost analysis
Debugging View historical inputs, outputs, and execution steps Problem localization
Evaluation Evaluate application effectiveness with test datasets Model version comparison
Feedback Collect and analyze feedback Continuously improve the Agent

**Note:** LangSmith displays execution traces that the application is able to record; it does not mean it can read the model's undisclosed internal reasoning process.


II. Several Important Concepts

Before using LangSmith, you need to understand a few basic terms.

Concept Description
Trace A complete trace record of a request
Run / Span An operation in the execution process, such as a model call or tool execution
Project A project for grouping and managing Traces
Metadata Additional information such as environment and version
Tags Tags for filtering trace records
Dataset A test dataset for evaluation

For example, a Trace of an intelligent customer service might contain multiple child Runs:

Trace:客服问题处理

    |

    ├── Run:Agent

    |

    ├── Run:ChatDeepSeek

    |

    ├── Run:search_knowledge

    |

    └── Run:ChatDeepSeek

Through this execution structure, you can see how much time each step took and where the problem might have occurred.


III. Registering for LangSmith

First, visit the official LangSmith website:

https://smith.langchain.com/

After logging in, create or obtain an API Key in the relevant Workspace settings.

The API Key is used to let the local Python program send trace data to the corresponding LangSmith workspace.

**Note:** The LangSmith API Key and the DeepSeek API Key are two independent credentials and cannot replace each other.


IV. Installing Dependencies

If LangChain is already installed, you can additionally install the LangSmith SDK:

pip install -U langsmith

To run the complete Agent example in this article, it is recommended to install:

pip install -U langchain langchain-deepseek langsmith python-dotenv

Where:

package Purpose
langchain Create Agents and Tools
langchain-deepseek Call the DeepSeek model
langsmith LangSmith SDK and Custom Tracing
python-dotenv Load environment variables

LangChain itself has LangSmith tracing integration. For general automatic Agent tracing, after setting the environment variables, you usually do not need to manually write tracing code for each tool.


V. Configuring LangSmith Environment Variables

Create a .env File:

Example: .env

Enable LangSmith tracing

LANGSMITH_TRACING

=

true

LangSmith API Key

LANGSMITH_API_KEY

=your_langsmith_api_key

Tracing project name

LANGSMITH_PROJECT

=runoob-agent-demo

DeepSeek model key

DEEPSEEK_API_KEY

=your_deepseek_api_key

Main environment variables:

Environment Variables Purpose Example
LANGSMITH_TRACING Whether to enable tracing true
LANGSMITH_API_KEY LangSmith API credentials API Key
LANGSMITH_PROJECT Tracing project name runoob-agent-demo
LANGSMITH_ENDPOINT LangSmith API address Configure according to deployment region
LANGSMITH_WORKSPACE_ID Specify the workspace Workspace ID

where LANGSMITH_ENDPOINT It can usually be omitted, using the default service address.

If your account's region is not the default US region, you need to configure the corresponding regional Endpoint according to the official LangSmith documentation.

When the API Key is associated with multiple Workspaces, or when using credentials that require an explicitly specified Workspace, you should configure LANGSMITH_WORKSPACE_ID。

**Version note:** Older tutorials may use LANGCHAIN_TRACING_V2、LANGCHAIN_API_KEY and LANGCHAIN_PROJECT. In new projects, it is recommended to uniformly use the LANGSMITH prefix to avoid confusion.


6. Automatic Tracing of Agents

LangSmith's most convenient feature is automatic tracing.

After configuring environment variables, when you normally create and call LangChain Agents, traceable components such as models and tools will typically record execution information automatically.

Below we create a simple course-query Agent.

Complete example: Automatic tracing

Example

from

dotenv

import

load_dotenv

from

langchain.

agents

import

create_agent

from

langchain.

tools

import

tool

from

langchain_deepseek

import

ChatDeepSeek

load_dotenv

(

)

@

tool

def

search_course

(

keyword

:

str

)

str

:

   

"""Query mock programming courses."""

   

print

(

f

"[Tool execution] search_course: {keyword}"

)

    courses

=

{

       

"Python"

:

"Python Basics, Python Functions, Python Object-Oriented"

,

       

"Java"

:

"Java Fundamentals, Java Object-Oriented"

   

}

   

return

courses.

get

(

keyword

,

"No matching mock course materials found"

)

agent

=

create_agent

(

    model

=

ChatDeepSeek

(

model

=

"deepseek-chat"

,

temperature

=

0

)

,

    tools

=

[

search_course

]

,

    system_prompt

=

"You are a programming learning assistant. When users query courses, call search_course first. All course materials are demo data."

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Please use the tool to query what Python courses are available."

}

]

}

)

print

(

"Final answer: "

,

result

[

"messages"

]

[

1

]

.

content

)

print

(

"Execution complete. Please view the Trace in the LangSmith project."

)

Run:

python trace_agent.py

If configured correctly, LangSmith will receive the tracing data for this Agent execution.

Open in the console:

runoob-agent-demo

and you can view the related execution records.

Whether the Trace actually appears depends on the API Key, workspace configuration, network connection, and whether the tracing data was successfully uploaded.


7. Viewing Agent Execution Traces

In LangSmith, select the corresponding Project, then open a Trace.

You can typically see the following information:

1. Execution timeline

For example:

Agent

  ├── ChatDeepSeek

  │     └── 请求 search_course

  ├── search_course

  │     └── 返回模拟课程

  └── ChatDeepSeek

        └── 生成最终回答

This lets you determine which tools the model actually called, rather than inferring from the final answer alone.

2. Inputs and outputs

You can inspect the messages the model received, tool arguments, and the content the model returned.

For example:

Tool:search_course



Input:

{"keyword": "Python"}



Output:

"Python 入门、Python 函数、Python 面向对象"

If the tool arguments are incorrect, you can further inspect the model's tool-selection logic and Prompt.

3. Execution duration

You can analyze where the time was mainly spent:

For example, if an Agent takes 8 seconds in total, with 6 seconds coming from the model request, you should prioritize inspecting the model call rather than blindly optimizing Python string handling.

4. Error information

If a traced step throws an exception, LangSmith can record the corresponding error information.

The completeness of the error details depends on the SDK, exception handling, and the actual runtime environment.


8. Token Usage and Cost Analysis

LangSmith can display available model Token usage and cost information, helping developers analyze Agent call costs.

For example, an Agent request may include:

Step Input Tokens Output Tokens
First model call 400 80
Second model call 650 120
Total 1050 200

The above figures are for demonstration only and do not represent real model consumption.

Note that Token usage and cost are not the same concept.

Even if the model API provides accurate Token counts, if LangSmith has not yet recognized the model's price, it may not be able to calculate costs correctly.

**Recommendation:** Formal cost accounting should be based on the actual billing records of the model provider, combined with LangSmith analysis of the cost structure of each request.


9. Viewing Actual Tool Call Counts

Besides using the LangSmith UI, you can also check in code whether the Agent actually called tools.

Example: Printing tool call records

Example

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Please query Python courses."

}

]

}

)

for

msg

in

result

[

"messages"

]

:

   

if

msg.

type

==

"ai"

and

getattr

(

msg

,

"tool_calls"

,

[

]

)

:

       

for

call

in

msg.

tool_calls

:

           

print

(

"Model requested tool:"

,

call

[

"name"

]

)

           

print

(

"Call arguments:"

,

call

[

"args"

]

)

   

elif

msg.

type

==

"tool"

:

       

print

(

"Actual tools:"

,

msg.

name

)

       

print

(

"Returned content:"

,

str

(

msg.

content

)

[

:

200

]

)

This is suitable for local debugging.

LangSmith can further correlate each model and tool call visually, making it easier to view the complete execution flow.


10. Manually Tracing Functions with @traceable

Besides automatically tracing LangChain Agents, you can also use LangSmith's @traceable decorator to create independent tracing records for ordinary Python functions.

For example, suppose we want to trace:

用户问题预处理

        ↓

    调用 Agent

        ↓

    格式化最终结果

You can mark an entire business function as a Trace node.

Example: Tracing a business function

Example

from

langsmith

import

traceable

@

traceable

(

name

=

"process_user_query"

,

run_type

=

"chain"

)

def

process_user_query

(

query:

str

)

dict

:

   

"""Preprocess the user question and call the Agent."""

    cleaned

=

query.

strip

(

)

    result

=

agent.

invoke

(

{

       

"messages"

:

[

{

"role"

:

"user"

,

"content"

: cleaned

}

]

   

}

)

   

return

{

       

"query"

: cleaned

,

       

"answer"

: result

[

"messages"

]

[

1

]

.

content

   

}

result

=

process_user_query

(

" query Python courses "

)

print

(

result

[

"answer"

]

)

If tracing succeeds, you can see in LangSmith:

process_user_query

    |

    └── Agent

         |

         ├── ChatDeepSeek

         ├── search_course

         └── ChatDeepSeek

@traceable It is well suited for tracing your own business functions, such as input cleaning, permission checks, RAG queries, and result transformation.

**Note:** When tracing ordinary Python functions, only explicitly traced functions and their sub-calls that support context propagation will form the corresponding observable execution structure. Not all third-party code automatically becomes an independent Trace node.


11. Adding Tags and Metadata to Traces

In real projects, you may need to distinguish different environments, model versions, and business scenarios.

For example:

开发环境:development

生产环境:production



业务类型:course-search

模型:deepseek-chat

版本:v1.0

You can use when calling the Agent config to add Tags and Metadata.

Example

Example

result

=

agent.

invoke

(

   

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Please query introductory Java courses."

}

]

}

,

    config

=

{

       

"run_name"

:

"runoob_course_query"

,

       

"tags"

:

[

"development"

,

"course-search"

]

,

       

"metadata"

:

{

           

"app_version"

:

"1.0.0"

,

           

"environment"

:

"development"

,

           

"feature"

:

"course_search"

       

}

   

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

This lets you filter tracing records by different tags in LangSmith.

For example, to view separately:

environment = production

or:

feature = course_search

**Note:** Metadata should not contain passwords, API Keys, access tokens, or unnecessary user privacy information.


12. Setting Projects for Different Environments

In real projects, it is recommended to separate development and production environments.

For example:

runoob-agent-dev

runoob-agent-staging

runoob-agent-production

You can set the default project via an environment variable:

LANGSMITH_PROJECT=runoob-agent-dev

You can also dynamically specify a Project for a single call.

Example: tracing_context

Example

import

langsmith

as

ls

with

ls.

tracing_context

(

    project_name

=

"runoob-agent-test"

,

    enabled

=

True

)

:

    result

=

agent.

invoke

(

{

       

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Introduce introductory Python courses."

}

]

   

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

This call will attempt to record to the specified project.

tracing_context() It is also suitable for use in code blocks where tracing needs to be temporarily enabled or disabled.


13. How to Disable LangSmith Tracing?

If you do not want your application to upload tracing information, you can set in an environment variable:

LANGSMITH_TRACING=false

or disable tracing for a specific code block:

Example

import

langsmith

as

ls

with

ls.

tracing_context

(

enabled

=

False

)

:

    result

=

agent.

invoke

(

{

       

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Hello" (Chinese)

}

]

   

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

This only disables LangSmith tracing for the specified scope and does not affect the Agent's normal model calls.

Note that other independent application logs, monitoring tools, or provider logs will not automatically stop recording just because LangSmith is disabled.


14. Setting Sampling Rate in Production

During development, you can enable full tracing to facilitate troubleshooting.

But in high-traffic production systems, recording all requests may incur additional data storage, transmission, and processing costs.

The LangSmith SDK provides tracing sampling configuration.

For example:

Example: Sampling configuration

LANGSMITH_TRACING

=

true

LANGSMITH_API_KEY

=your_langsmith_api_key

LANGSMITH_PROJECT

=runoob-agent-production

Apply a 10% sampling rate to traces that match the SDK sampling mechanism

LANGSMITH_TRACING_SAMPLING_RATE

=

0.1

The sampling rate typically uses a value between 0 and 1:

Settings Meaning
1.0 Sample all
0.5 Sample about 50%
0.1 Sample about 10%
0.01 Sample about 1%
0 No sampling

The exact effective scope depends on the implementation of the LangSmith SDK and the tracing client.

Sampling is suitable for controlling the volume of recorded normal requests, but it does not guarantee that all important errors will be sampled.

For critical exceptions, it is recommended to combine server-side error logs, alerts, and other monitoring systems rather than relying entirely on random sampling.


15. Protecting User Privacy and Sensitive Data

LangSmith can record model requests and tool inputs/outputs. This information may contain user chat content, internal documents, and other business data.

Therefore, data protection should be carefully considered in production environments.

Hiding inputs and outputs

If you do not want raw inputs and outputs recorded in tracing content, you can set:

LANGSMITH_HIDE_INPUTS=true

LANGSMITH_HIDE_OUTPUTS=true

This can reduce exposure of raw content to the tracing system.

But the trade-off is that developers can no longer directly view the hidden inputs or outputs in LangSmith.

Production security recommendations

**Important:** Hiding inputs and outputs in LangSmith does not mean the data is no longer sent to the underlying model provider. The model call itself still needs to be evaluated separately according to the actual provider's data processing policies.


16. How Does LangSmith Differ from Ordinary Logs?

Ordinary Python logs can also record tool execution information, for example:

print("开始调用模型")

print("调用 search_course")

print("执行完成")

But when an Agent undergoes complex multi-turn model calls, manual logs are usually hard to clearly show the complete call relationships.

Capability Ordinary Python logs LangSmith
Record text messages Supported Supported
Call relationship visualization Needs to be implemented yourself Provides a tracing UI
Model and tool steps Manual recording Supports automatic tracing
Call duration Manual measurement Provides relevant metrics
Token usage Needs to be obtained yourself Can display available data
Test set evaluation Develop yourself Provides an evaluation workflow

In real projects, LangSmith does not necessarily need to replace the existing logging system.

A more common approach is:

应用日志 → 记录业务错误、HTTP 请求和安全事件



LangSmith → 追踪模型、工具和 Agent 执行



监控平台 → 监控服务器、数据库和系统资源

The three complement each other.


17. Evaluating Agents with LangSmith

LangSmith can be used not only for debugging but also provides datasets and evaluation features.

For example, when developing a course-query Agent, you can prepare the following test questions:

Test question Expected behavior
What introductory Python courses are available? Call the course search tool
What basic Java courses are available? Query Java courses
What is the price of a course not in the knowledge base? Do not fabricate a price
Query a nonexistent course State that there are no results

These questions can serve as a test set to compare the effects of different models, Prompts, and tool implementations.

Evaluation methods can include:

Note that LLM-as-a-Judge scores can also be wrong and cannot be directly equated with true accuracy.

It is recommended to combine rule-based tests with manual sampling.


18. How to Analyze Problems in a RAG Agent?

Suppose a user asks:

Python 的装饰器有什么作用?

The Agent's final answer is wrong.

In LangSmith, you can troubleshoot in the following order:

  1. Whether the model actually called the knowledge base retrieval tool.
  2. Whether the retrieval tool received the correct query arguments.
  3. Whether the documents returned by the vector database contain knowledge about decorators.
  4. Whether the tool results were completely passed to the model.
  5. Whether the model's final answer correctly used the retrieved materials.
  6. Whether there were exceptions, timeouts, or context truncation.

For example:

用户问题:Python 装饰器有什么作用?

             ↓

模型调用 search_knowledge

             ↓

检索参数:Python 装饰器

             ↓

返回资料:Python 列表、Python 字典

             ↓

模型生成错误回答

In this case, the problem may lie mainly in knowledge base retrieval rather than the model's generation capability.

Conversely, if the retrieval results already contain accurate decorator descriptions but the model still answers incorrectly, you need to check the Prompt, context handling, or model performance.

This is the value of observability: helping developers locate which stage the problem occurred in, rather than immediately swapping models at the first error.


19. Frequently Asked Questions

1. Must LangSmith be used together with LangChain?

Not necessarily. The LangSmith SDK can trace custom Python functions and application logic in other frameworks, but it is usually more convenient when used with LangChain.

2. Does LangSmith modify the Agent's answers?

General tracing configuration is used to record execution information and is not responsible for changing model business logic. However, tracing itself may introduce some runtime overhead.

3. Why does no Trace appear in the console?

You should check LANGSMITH_TRACING, API Key, Project, Workspace, regional Endpoint, and network connection.

4. Why do I need a LangSmith Key when a DeepSeek Key is already configured?

The DeepSeek Key is used to call the model, while the LangSmith Key is used to upload and manage tracing data.

5. Can LANGCHAIN_TRACING_V2 still be used?

It belongs to the old configuration naming. The new tutorial recommends uniformly adopting LANGSMITH_TRACING.

6. Can LangSmith see all of the model's internal thinking?

No. It displays the execution data actually returned by the application and model API and recorded, which is not the same as the model's hidden reasoning process.

7. Why are Token and cost not displayed completely?

This may be because the model API does not provide complete usage information, or the current model's price mapping and billing data are incomplete.

8. What is the difference between @traceable and automatic tracing?

Automatic tracing is suitable for LangChain models and tool calls; @traceable can establish tracing nodes for custom Python functions.

9. How to distinguish development and production environments?

You can use different LANGSMITH_PROJECT values and mark environments with Tags and Metadata.

10. How to temporarily disable tracing?

You can set LANGSMITH_TRACING=false, or use tracing_context(enabled=False).

11. What does setting the sampling rate to 0.1 mean?

It means that under the corresponding SDK sampling mechanism, about 10% of traces are sampled, rather than guaranteeing that exactly one out of every ten consecutive requests is recorded.

12. Does LangSmith record user input?

After tracing is enabled, inputs/outputs and tool arguments may be recorded by default. Sensitive applications should configure masking or hiding and evaluate data protection requirements.

13. Can a historical Trace be directly used as an Agent replay execution?

A Trace is, first of all, a historical execution record. Re-running an Agent is a different operation and may produce new model results or real tool side effects.

14. Can LangSmith be used to evaluate RAG?

Yes. It can evaluate whether the retrieval tool was called, whether answers are grounded, and the Q&A performance of different versions.


Summary

LangSmith is an important observability tool in LangChain Agent development.

This chapter introduces:

The most commonly used LangSmith configuration:

LANGSMITH_TRACING=true

LANGSMITH_API_KEY=your_langsmith_api_key

LANGSMITH_PROJECT=my-agent-project

After configuration, execute normally:

result = agent.invoke({

    "messages": [{"role": "user", "content": "查询 Python 课程"}]

})

Then visit LangSmith console to view execution traces.

**Core principle:** When developing an Agent, you should not only care whether the final answer is correct, but also be able to explain which tools the application actually called, at which step it failed, and how many resources it consumed. LangSmith's role is to make these execution processes observable, analyzable, and evaluable.