> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/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="Retrieve Context")
  def my_tool(question: str) -> str:
    return "During this morning's meeting, we solved all world conflict."

  @traceable
  def chat_pipeline(question: str):
    context = my_tool(question)
    messages = [
        { "role": "system", "content": "You are a helpful assistant. Please respond to the user's request only based on the given context." },
        { "role": "user", "content": f"Question: {question}\nContext: {context}"}
    ]
    chat_completion = client.chat.completions.create(
        model="gpt-5.4-mini", messages=messages
    )
    return chat_completion.choices[0].message.content

  # 可以设置为False以在不改变代码结构的情况下禁用追踪
  with tracing_context(enabled=True):
    # 使用 langsmith_extra 传递自定义客户端
    chat_pipeline("Can you summarize this morning's meetings?", 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 "During this morning's meeting, we solved all world conflict.";
  }, { name: "Retrieve Context", runType: "tool" });

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

          const completion = await openai.chat.completions.create({
              model: "gpt-5.4-mini",
              messages: [
                  { role: "system" as const, content: "You are a helpful assistant. Please respond to the user's request only based on the given context." },
                  { role: "user" as const, content: `Question: ${question}\nContext: ${context}`}
              ]
          });

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

  await pipeline("Can you summarize this morning's meetings?");
  ```
</CodeGroup>

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

## 相关内容

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

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到Claude、VSCode等，通过MCP获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在GitHub上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/langsmith/trace-without-env-vars.mdx)或[提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
