跳到主要内容
LangSmith 与流行的开源 LLM 应用程序构建框架 LangChain(Python 和 JavaScript)无缝集成。

安装

安装 Python 和 JS 的核心库以及 OpenAI 集成(我们将在下面的代码片段中使用 OpenAI 集成)。 有关可用包的完整列表,请参阅 LangChain 文档
pip install langchain_openai langchain_core

快速开始

1. 配置您的环境

export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=<your-api-key>
# This example uses OpenAI, but you can use any LLM provider of choice
export OPENAI_API_KEY=<your-openai-api-key>
# For LangSmith API keys linked to multiple workspaces, set the LANGSMITH_WORKSPACE_ID environment variable to specify which workspace to use.
export LANGSMITH_WORKSPACE_ID=<your-workspace-id>
如果您正在将 LangChain.js 与 LangSmith 一起使用,并且不在无服务器环境中,我们还建议明确设置以下内容以减少延迟:export LANGCHAIN_CALLBACKS_BACKGROUND=true如果您在无服务器环境中,我们建议设置相反的值,以允许追踪在函数结束前完成:export LANGCHAIN_CALLBACKS_BACKGROUND=false

2. 记录追踪

将追踪记录到 LangSmith 无需额外代码。只需像往常一样运行您的 LangChain 代码。
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant. Please respond to the user's request only based on the given context."),
    ("user", "Question: {question}\nContext: {context}")
])

model = ChatOpenAI(model="gpt-4o-mini")
output_parser = StrOutputParser()
chain = prompt | model | output_parser

question = "Can you summarize this morning's meetings?"
context = "During this morning's meeting, we solved all world conflict."

chain.invoke({"question": question, "context": context})

3. 查看您的追踪

默认情况下,追踪将记录到名为 default 的项目。使用上述代码记录的追踪示例已公开,可在此处查看。

选择性追踪

上一节展示了如何通过设置一个环境变量来追踪应用程序中 LangChain runnable 的所有调用。虽然这是一种方便的入门方式,但您可能只想追踪特定调用或应用程序的特定部分。 在 Python 中有两种方法:手动传入 LangChainTracer 实例作为回调,或使用 tracing_context 上下文管理器 在 JS/TS 中,您可以传入一个 LangChainTracer 实例作为回调。
# You can opt-in to specific invocations..
import langsmith as ls

with ls.tracing_context(enabled=True):
    chain.invoke({"question": "Am I using a callback?", "context": "I'm using a callback"})

# This will NOT be traced (assuming LANGSMITH_TRACING is not set)
chain.invoke({"question": "Am I being traced?", "context": "I'm not being traced"})

# This would not be traced, even if LANGSMITH_TRACING=true
with ls.tracing_context(enabled=False):
    chain.invoke({"question": "Am I being traced?", "context": "I'm not being traced"})

记录到特定项目

静态

正如在追踪概念指南中提到的,LangSmith 使用“项目”概念来对追踪进行分组。如果未指定,追踪器项目将设置为默认值。您可以设置 LANGSMITH_PROJECT 环境变量,为整个应用程序运行配置自定义项目名称。这应在执行应用程序之前完成。
export LANGSMITH_PROJECT=my-project
LANGSMITH_PROJECT 标志仅在 JS SDK 版本 >= 0.2.16 中受支持,如果您使用的是旧版本,请使用 LANGCHAIN_PROJECT

动态

这主要基于上一节,允许您为特定的 LangChainTracer 实例设置项目名称,或将其作为参数传递给 Python 中的 tracing_context 上下文管理器。
# You can set the project name using the project_name parameter.
import langsmith as ls

with ls.tracing_context(project_name="My Project", enabled=True):
    chain.invoke({"question": "Am I using a context manager?", "context": "I'm using a context manager"})

向追踪添加元数据和标签

您可以通过在 RunnableConfig 中提供任意元数据和标签来注释您的追踪。这对于将附加信息(例如执行环境或发起用户)与追踪关联起来非常有用。有关如何通过元数据和标签查询追踪和运行的信息,请参阅本指南
当您将元数据或标签附加到 runnable(无论是通过 RunnableConfig 还是在运行时通过调用参数)时,它们将被该 runnable 的所有子 runnable 继承。
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful AI."),
    ("user", "{input}")
])

# The tag "model-tag" and metadata {"model-key": "model-value"} will be attached to the ChatOpenAI run only
chat_model = ChatOpenAI().with_config({"tags": ["model-tag"], "metadata": {"model-key": "model-value"}})
output_parser = StrOutputParser()

# Tags and metadata can be configured with RunnableConfig
chain = (prompt | chat_model | output_parser).with_config({"tags": ["config-tag"], "metadata": {"config-key": "config-value"}})

# Tags and metadata can also be passed at runtime
chain.invoke({"input": "What is the meaning of life?"}, {"tags": ["invoke-tag"], "metadata": {"invoke-key": "invoke-value"}})

自定义运行名称

您可以通过在 Config 中提供,来在调用或流式传输 LangChain 代码时自定义给定运行的名称。此名称用于在 LangSmith 中标识运行,并可用于过滤和分组运行。该名称也用作 LangSmith UI 中运行的标题。可以通过在构造时在 RunnableConfig 对象中设置 run_name,或者在 JS/TS 中通过调用参数传递 run_name 来完成。
# When tracing within LangChain, run names default to the class name of the traced object (e.g., 'ChatOpenAI').
configured_chain = chain.with_config({"run_name": "MyCustomChain"})
configured_chain.invoke({"input": "What is the meaning of life?"})

# You can also configure the run name at invocation time, like below
chain.invoke({"input": "What is the meaning of life?"}, {"run_name": "MyCustomChain"})
run_name 参数仅更改您调用的 runnable(例如,链、函数)的名称。它不会自动重命名在调用像 ChatOpenAI (gpt-4o-mini) 这样的 LLM 对象时自动创建的嵌套运行。在该示例中,封闭的运行将以 MyCustomChain 的形式出现在 LangSmith 中,而嵌套的 LLM 运行仍显示模型的默认名称。要为 LLM 运行提供更具意义的名称,您可以:
  • 将模型包装在另一个 runnable 中,并为该步骤分配一个 run_name
  • 使用追踪装饰器或辅助函数(例如,Python 中的 @traceable,或 JS/TS 中 langsmithtraceable)围绕模型调用创建自定义运行。

自定义运行 ID

您可以通过在 Config 中提供,来在调用或流式传输 LangChain 代码时自定义给定运行的 ID。此 ID 用于在 LangSmith 中唯一标识运行,并可用于查询特定运行。该 ID 对于跨不同系统链接运行或实现自定义跟踪逻辑非常有用。可以通过在构造时在 RunnableConfig 对象中设置 run_id,或者在调用参数中传递 run_id 来完成。
此功能目前不直接支持 LLM 对象。
import uuid

my_uuid = uuid.uuid4()

# You can configure the run ID at invocation time:
chain.invoke({"input": "What is the meaning of life?"}, {"run_id": my_uuid})
请注意,如果您在追踪的**根**(即顶层运行)执行此操作,则该运行 ID 将用作 trace_id

访问 LangChain 调用的运行(span)ID

当您调用 LangChain 对象时,可以手动指定调用的运行 ID。此运行 ID 可用于在 LangSmith 中查询运行。 在 JS/TS 中,您可以使用 RunCollectorCallbackHandler 实例访问运行 ID。
import uuid

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant. Please respond to the user's request only based on the given context."),
    ("user", "Question: {question}\n\nContext: {context}")
])
model = ChatOpenAI(model="gpt-4o-mini")
output_parser = StrOutputParser()

chain = prompt | model | output_parser

question = "Can you summarize this morning's meetings?"
context = "During this morning's meeting, we solved all world conflict."
my_uuid = uuid.uuid4()
result = chain.invoke({"question": question, "context": context}, {"run_id": my_uuid})
print(my_uuid)

确保在退出前提交所有追踪

在 LangChain Python 中,LangSmith 的追踪是在后台线程中完成的,以避免阻塞您的生产应用程序。这意味着您的进程可能会在所有追踪成功发布到 LangSmith 之前结束。这在无服务器环境中尤其普遍,在无服务器环境中,一旦您的链或代理完成,您的 VM 可能会立即终止。 您可以通过将 LANGCHAIN_CALLBACKS_BACKGROUND 环境变量设置为 "false" 来使回调同步。 对于两种语言,LangChain 都公开了在退出应用程序之前等待追踪提交的方法。下面是一个示例:
from langchain_openai import ChatOpenAI
from langchain_core.tracers.langchain import wait_for_all_tracers

llm = ChatOpenAI()

try:
  llm.invoke("Hello, World!")
finally:
  wait_for_all_tracers()

在不设置环境变量的情况下进行追踪

如其他指南所述,以下环境变量允许您配置追踪启用、API 端点、API 密钥和追踪项目
  • LANGSMITH_TRACING
  • LANGSMITH_API_KEY
  • LANGSMITH_ENDPOINT
  • LANGSMITH_PROJECT
然而,在某些环境中,无法设置环境变量。在这些情况下,您可以以编程方式设置追踪配置。 这主要基于上一节
import langsmith as ls

# You can create a client instance with an api key and api url
client = ls.Client(
    api_key="YOUR_API_KEY",  # This can be retrieved from a secrets manager
    api_url="https://api.smith.langchain.com",  # Update appropriately for self-hosted installations or the EU region
)

# You can pass the client and project_name to the tracing_context
with ls.tracing_context(client=client, project_name="test-no-env", enabled=True):
    chain.invoke({"question": "Am I using a callback?", "context": "I'm using a callback"})

使用 LangChain 进行分布式追踪 (Python)

LangSmith 支持使用 LangChain Python 进行分布式追踪。这允许您将不同服务和应用程序中的运行(span)链接起来。其原理与 LangSmith SDK 的分布式追踪指南类似。
import langsmith
from langchain_core.runnables import chain
from langsmith.run_helpers import get_current_run_tree

# -- This code should be in a separate file or service --
@chain
def child_chain(inputs):
    return inputs["test"] + 1

def child_wrapper(x, headers):
    with langsmith.tracing_context(parent=headers):
        child_chain.invoke({"test": x})

# -- This code should be in a separate file or service --
@chain
def parent_chain(inputs):
    rt = get_current_run_tree()
    headers = rt.to_headers()
    # ... make a request to another service with the headers
    # The headers should be passed to the other service, eventually to the child_wrapper function

parent_chain.invoke({"test": 1})

LangChain (Python) 和 LangSmith SDK 之间的互操作性

如果您的应用程序一部分使用 LangChain,另一部分使用 LangSmith SDK(请参阅本指南),您仍然可以无缝地追踪整个应用程序。 LangChain 对象在 traceable 函数中调用时将被追踪,并作为 traceable 函数的子运行绑定。
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langsmith import traceable

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant. Please respond to the user's request only based on the given context."),
    ("user", "Question: {question}\nContext: {context}")
])

model = ChatOpenAI(model="gpt-4o-mini")
output_parser = StrOutputParser()
chain = prompt | model | output_parser

# The above chain will be traced as a child run of the traceable function
@traceable(
    tags=["openai", "chat"],
    metadata={"foo": "bar"}
)
def invoke_runnnable(question, context):
    result = chain.invoke({"question": question, "context": context})
    return "The response is: " + result

invoke_runnnable("Can you summarize this morning's meetings?", "During this morning's meeting, we solved all world conflict.")
这将生成以下追踪树:

LangChain.JS 和 LangSmith SDK 之间的互操作性

追踪 traceable 内的 LangChain 对象 (仅限 JS)

langchain@0.2.x 开始,LangChain 对象在 @traceable 函数内部使用时会自动追踪,并继承 traceable 函数的客户端、标签、元数据和项目名称。 对于低于 0.2.x 的旧版本 LangChain,您需要手动传递由 @traceable 中找到的追踪上下文创建的 LangChainTracer 实例。
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";
import { getLangchainCallbacks } from "langsmith/langchain";

const prompt = ChatPromptTemplate.fromMessages([
  [
    "system",
    "You are a helpful assistant. Please respond to the user's request only based on the given context.",
  ],
  ["user", "Question: {question}\nContext: {context}"],
]);

const model = new ChatOpenAI({ modelName: "gpt-4o-mini" });
const outputParser = new StringOutputParser();
const chain = prompt.pipe(model).pipe(outputParser);

const main = traceable(
  async (input: { question: string; context: string }) => {
    const callbacks = await getLangchainCallbacks();
    const response = await chain.invoke(input, { callbacks });
    return response;
  },
  { name: "main" }
);

通过 traceable / RunTree API 追踪 LangChain 子运行 (仅限 JS)

我们正在努力改进 traceable 和 LangChain 之间的互操作性。在结合使用 LangChain 和 traceable 时存在以下限制:
  1. 修改从 RunnableLambda 上下文的 getCurrentRunTree() 获取的 RunTree 将导致无操作。
  2. 不建议通过 getCurrentRunTree() 遍历从 RunnableLambda 获取的 RunTree,因为它可能不包含所有 RunTree 节点。
  3. 不同的子运行可能具有相同的 execution_orderchild_execution_order 值。因此,在极端情况下,某些运行可能会因 start_time 而以不同的顺序结束。
在某些使用场景中,您可能希望将 traceable 函数作为 RunnableSequence 的一部分运行,或者通过 RunTree API 命令式地追踪 LangChain 运行的子运行。从 LangSmith 0.1.39 和 @langchain/core 0.2.18 开始,您可以直接在 RunnableLambda 中调用 traceable 包装的函数。
import { traceable } from "langsmith/traceable";
import { RunnableLambda } from "@langchain/core/runnables";
import { RunnableConfig } from "@langchain/core/runnables";

const tracedChild = traceable((input: string) => `Child Run: ${input}`, {
  name: "Child Run",
});

const parrot = new RunnableLambda({
  func: async (input: { text: string }, config?: RunnableConfig) => {
    return await tracedChild(input.text);
  },
});
追踪树 或者,您可以使用 RunTree.fromRunnableConfig 将 LangChain 的 RunnableConfig 转换为等效的 RunTree 对象,或者将 RunnableConfig 作为 traceable 包装函数的第一个参数传递。
import { traceable } from "langsmith/traceable";
import { RunnableLambda } from "@langchain/core/runnables";
import { RunnableConfig } from "@langchain/core/runnables";

const tracedChild = traceable((input: string) => `Child Run: ${input}`, {
  name: "Child Run",
});

const parrot = new RunnableLambda({
  func: async (input: { text: string }, config?: RunnableConfig) => {
    // Pass the config to existing traceable function
    await tracedChild(config, input.text);
    return input.text;
  },
});
如果您更喜欢视频教程,请查看 LangSmith 简介课程中的追踪替代方法视频
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.