> ## 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.

# 为跟踪添加元数据和标签

LangSmith 支持在跟踪中发送任意元数据和标签。

标签是可用于分类或标记跟踪的字符串。元数据是一个键值对字典，可用于存储关于跟踪的附加信息。

两者都可用于将附加信息与跟踪关联，例如执行环境、发起用户或内部关联 ID。有关标签和元数据的更多信息，请参阅[概念](/langsmith/observability-concepts#tags)页面。有关如何通过元数据和标签查询跟踪和运行的信息，请参阅[在应用程序中过滤跟踪](/langsmith/filter-traces-in-application)页面。

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

  client = openai.Client()
  messages = [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Hello!"}
  ]

      # 您可以在装饰函数时**静态**设置元数据和标签
      # 使用带有标签和元数据的 @traceable 装饰器
      # 确保设置了 LANGSMITH_TRACING 环境变量，以便 @traceable 正常工作
      @ls.traceable(
          run_type="llm",
          name="OpenAI Call Decorator",
          tags=["my-tag"],
          metadata={"my-key": "my-value"}
      )
      def call_openai(
          messages: list[dict], model: str = "gpt-5.4-mini"
      ) -> str:
          # 您也可以在父运行上动态设置元数据：
          rt = ls.get_current_run_tree()
          rt.metadata["some-conditional-key"] = "some-val"
          rt.tags.extend(["another-tag"])
          return client.chat.completions.create(
              model=model,
              messages=messages,
          ).choices[0].message.content

      call_openai(
          messages,
          # 在**调用时**添加，当调用函数时。
          # 通过 langsmith_extra 参数
          langsmith_extra={"tags": ["my-other-tag"], "metadata": {"my-other-key": "my-value"}}
      )

      # 或者您可以为给定范围内的运行动态设置默认元数据
      # tracing_context 本身不创建 span，但它会初始化
      # 为创建的子 span 初始化上下文。
      with ls.tracing_context(metadata={"default-key": "default-value"}):
          call_openai(messages)

      # 或者，您可以使用 trace 上下文管理器
      # 这会创建一个带有给定元数据和标签的新 span
      with ls.trace(
          name="OpenAI Call Trace",
          run_type="llm",
          inputs={"messages": messages},
          tags=["my-tag"],
          metadata={"my-key": "my-value"},
      ) as rt:
          chat_completion = client.chat.completions.create(
              model="gpt-5.4-mini",
              messages=messages,
          )
          rt.metadata["some-conditional-key"] = "some-val"
          rt.end(outputs={"output": chat_completion})

  # 您可以对包装后的客户端使用相同的技术
  patched_client = wrap_openai(
      client, tracing_extra={"metadata": {"my-key": "my-value"}, "tags": ["a-tag"]}
  )
  chat_completion = patched_client.chat.completions.create(
      model="gpt-5.4-mini",
      messages=messages,
      langsmith_extra={
          "tags": ["my-other-tag"],
          "metadata": {"my-other-key": "my-value"},
      },
  )
  ```

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

      const client = wrapOpenAI(new OpenAI());
      const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [
          { role: "system", content: "You are a helpful assistant." },
          { role: "user", content: "Hello!" },
      ];

      const traceableCallOpenAI = traceable(
          async (messages: OpenAI.Chat.ChatCompletionMessageParam[]) => {
              const completion = await client.chat.completions.create({
                  model: "gpt-5.4-mini",
                  messages,
              });
              const runTree = getCurrentRunTree();
              runTree.extra.metadata = {
                  ...runTree.extra.metadata,
                  someKey: "someValue",
              };
              runTree.tags = [...(runTree.tags ?? []), "runtime-tag"];
              return completion.choices[0].message.content;
          },
          {
              run_type: "llm",
              name: "OpenAI Call Traceable",
              tags: ["my-tag"],
              metadata: { "my-key": "my-value" },
          }
      );

  // 调用可跟踪函数
  await traceableCallOpenAI(messages);
  ```
</CodeGroup>

<Tip>
  **LangSmith 部署**：要在 Agent Server 部署中按调用动态添加元数据，我们建议在[工厂函数](/langsmith/graph-rebuild)中使用 `tracing_context`。有关示例，请参阅[在部署的代理中自定义跟踪](/langsmith/conditional-tracing#customize-tracing-in-deployed-agents)。
</Tip>

***

<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/add-metadata-tags.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
