> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 无需设置环境变量进行追踪

如其他指南所述，以下环境变量可用于配置追踪启用状态、API 端点、API 密钥和追踪项目：

* `LANGSMITH_TRACING`
* `LANGSMITH_API_KEY`
* `LANGSMITH_ENDPOINT`
* `LANGSMITH_PROJECT`

如果你需要使用自定义配置追踪运行，或者工作环境不支持典型的环境变量（例如 Cloudflare Workers），或者只是单纯不想依赖环境变量，LangSmith 允许你通过编程方式配置追踪。

<Warning>
  由于许多用户要求通过 `trace` 上下文管理器更精细地控制追踪，**我们在 Python SDK 版本 0.1.95** 中**更改了 `with trace` 的行为**，使其遵循 `LANGSMITH_TRACING` 环境变量。你可以在[发布说明](https://github.com/langchain-ai/langsmith-sdk/releases/tag/v0.1.95)中找到更多详细信息。在不设置环境变量的情况下启用/禁用追踪的推荐方法是使用 `with tracing_context` 上下文管理器，如下例所示。
</Warning>

* Python：在 Python 中推荐使用 `tracing_context` 上下文管理器。这适用于使用 `traceable` 注解的代码以及 `trace` 上下文管理器内的代码。
* TypeScript：你可以将客户端和 `tracingEnabled` 标志传递给 `traceable` 装饰器。

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import openai
  from langsmith import Client, tracing_context, traceable
  from langsmith.wrappers import wrap_openai

  langsmith_client = Client(
    api_key="YOUR_LANGSMITH_API_KEY",  # 可从密钥管理器获取
    api_url="https://api.smith.langchain.com",  # 针对自托管安装或欧盟区域适当更新
    workspace_id="YOUR_WORKSPACE_ID", # 对于作用域为多个工作空间的 API 密钥必须指定
  )

  client = wrap_openai(openai.Client())

  @traceable(run_type="tool", name="检索上下文")
  def my_tool(question: str) -> str:
    return "在今天早上的会议中，我们解决了所有世界冲突。"

  @traceable
  def chat_pipeline(question: str):
    context = my_tool(question)
    messages = [
        { "role": "system", "content": "你是一个乐于助人的助手。请仅根据给定的上下文回应用户的请求。" },
        { "role": "user", "content": f"问题：{question}\n上下文：{context}"}
    ]
    chat_completion = client.chat.completions.create(
        model="gpt-4.1-mini", messages=messages
    )
    return chat_completion.choices[0].message.content

  # 可设置为 False 以在此处禁用追踪，而无需更改代码结构
  with tracing_context(enabled=True):
    # 使用 langsmith_extra 传入自定义客户端
    chat_pipeline("你能总结一下今天早上的会议吗？", langsmith_extra={"client": langsmith_client})
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import { Client } from "langsmith";
  import { traceable } from "langsmith/traceable";
  import { wrapOpenAI } from "langsmith/wrappers";
  import { OpenAI } from "openai";

  const client = new Client({
      apiKey: "YOUR_API_KEY",  // 可从密钥管理器获取
      apiUrl: "https://api.smith.langchain.com",  // 针对自托管安装或欧盟区域适当更新
  });

  const openai = wrapOpenAI(new OpenAI());

  const tool = traceable((question: string) => {
      return "在今天早上的会议中，我们解决了所有世界冲突。";
  }, { name: "检索上下文", runType: "tool" });

  const pipeline = traceable(
      async (question: string) => {
          const context = await tool(question);

          const completion = await openai.chat.completions.create({
              model: "gpt-4.1-mini",
              messages: [
                  { role: "system" as const, content: "你是一个乐于助人的助手。请仅根据给定的上下文回应用户的请求。" },
                  { role: "user" as const, content: `问题：${question}\n上下文：${context}`}
              ]
          });

          return completion.choices[0].message.content;
      },
      { name: "聊天", client, tracingEnabled: true }
  );

  await pipeline("你能总结一下今天早上的会议吗？");
  ```
</CodeGroup>

如果你更喜欢视频教程，请查看 LangSmith 入门课程中的[替代追踪方式视频](https://academy.langchain.com/pages/intro-to-langsmith-preview)。

## 相关

如果你需要根据运行时条件（如客户端要求、数据敏感性或合规策略）动态启用或禁用追踪，请参考[条件追踪](/langsmith/conditional-tracing)中的示例。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\langsmith\trace-without-env-vars.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
