Langfuse 文档 中文 英文原文 ↗
文档 / 标签(Tags)

标签(Tags)

标签(Tags)让你在 Langfuse 中对 observations 和 traces 进行分类和过滤。

标签是字符串(每个最多 200 字符),一个 observation 可以有多个标签。应用到一个 trace 中所有 observations 上的完整标签集合会自动聚合,并添加到 Langfuse 中的 trace 对象上。如果标签超过 200 字符,它将被丢弃。

由于 Langfuse 对 observations 使用不可变的数据模型,标签创建后无法在 UI 中添加或编辑。

将标签传播到 Observations

使用 propagate_attributes() 将标签应用到某个上下文内的一组 observations。

使用 @observe() 装饰器时:

python
from langfuse import observe, propagate_attributes

@observe()
def my_function():
    # Apply tags to all child observations
    with propagate_attributes(
        tags=["tag-1", "tag-2"]
    ):
        # All nested observations automatically have these tags
        result = process_data()
        return result

直接创建 observations 时:

python
from langfuse import get_client, propagate_attributes

langfuse = get_client()

with langfuse.start_as_current_observation(as_type="span", name="my-operation") as root_span:
    # Apply tags to all child observations
    with propagate_attributes(tags=["tag-1", "tag-2"]):
        # All observations created here automatically have these tags
        with root_span.start_as_current_observation(
            as_type="generation",
            name="llm-call",
            model="gpt-4o"
        ) as gen:
            # This generation automatically has the tags
            pass

使用上下文管理器时:

ts
import { startActiveObservation, propagateAttributes } from "@langfuse/tracing";

await startActiveObservation("context-manager", async (span) => {
  span.update({
    input: { query: "What is the capital of France?" },
  });

  // Apply tags to all child observations
  await propagateAttributes(
    {
      tags: ["tag-1", "tag-2"],
    },
    async () => {
      // All observations created here automatically have these tags
      // ... your logic ...
    }
  );
});

使用 observe 包装器时:

ts
import { observe, propagateAttributes } from "@langfuse/tracing";

const processData = observe(
  async (data: string) => {
    // Apply tags to all child observations
    return await propagateAttributes(
      { tags: ["tag-1", "tag-2"] },
      async () => {
        // All nested observations automatically have these tags
        const result = await performProcessing(data);
        return result;
      }
    );
  },
  { name: "process-data" }
);

const result = await processData("input");

更多细节参见 JS/TS SDK 文档

python
from langfuse import get_client, propagate_attributes
from langfuse.openai import openai

langfuse = get_client()

with langfuse.start_as_current_observation(as_type="span", name="openai-call"):
    # Apply tags to all observations including OpenAI generation
    with propagate_attributes(
        tags=["tag-1", "tag-2"]
    ):
        completion = openai.chat.completions.create(
            name="test-chat",
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a calculator."},
                {"role": "user", "content": "1 + 1 = "}
            ],
            temperature=0,
        )

或者,在没有外层 span 时使用 OpenAI:

python
from langfuse.openai import openai

completion = openai.chat.completions.create(
  name="test-chat",
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a calculator."},
    {"role": "user", "content": "1 + 1 = "}],
  temperature=0,
  metadata={"langfuse_tags": ["tag-1", "tag-2"]}
)
ts
import OpenAI from "openai";
import { observeOpenAI } from "@langfuse/openai";
import { startActiveObservation, propagateAttributes } from "@langfuse/tracing";

await startActiveObservation("openai-call", async () => {
  // Apply tags to all observations
  await propagateAttributes(
    {
      tags: ["tag-1", "tag-2"],
    },
    async () => {
      const res = await observeOpenAI(new OpenAI()).chat.completions.create({
        messages: [{ role: "system", content: "Tell me a story about a dog." }],
        model: "gpt-3.5-turbo",
        max_tokens: 300,
      });
    }
  );
});
python
from langfuse import get_client, propagate_attributes
from langfuse.langchain import CallbackHandler

langfuse = get_client()
langfuse_handler = CallbackHandler()

with langfuse.start_as_current_observation(as_type="span", name="langchain-call"):
    # Apply tags to all child observations
    with propagate_attributes(
        tags=["tag-1", "tag-2"]
    ):
        response = chain.invoke(
            {"topic": "cats"},
            config={"callbacks": [langfuse_handler]}
        )

或者,在链调用中使用 metadata:

python
from langfuse.langchain import CallbackHandler

handler = CallbackHandler()

chain.invoke(
    {"animal": "dog"},
    config={
        "callbacks": [handler],
        "metadata": {"langfuse_tags": ["tag-1", "tag-2"]},
    },
)
ts
import { startActiveObservation, propagateAttributes } from "@langfuse/tracing";
import { CallbackHandler } from "@langfuse/langchain";

const langfuseHandler = new CallbackHandler();

// Apply tags to all child observations
await propagateAttributes(
  {
    tags: ["tag-1", "tag-2"],
  },
  async () => {
    await chain.invoke(
      { input: "<user_input>" },
      { callbacks: [langfuseHandler] }
    );
  }
);

或者,使用 CallbackHandler 时,你可以将 tags 传给构造函数:

ts
const handler = new CallbackHandler({
  tags: ["tag-1", "tag-2"],
});

或者在链调用时通过 runnable 配置动态设置标签:

ts
const langfuseHandler = new CallbackHandler()
const tags = ["tag-1", "tag-2"];

// Pass config to the chain invocation to be parsed as Langfuse trace attributes
await chain.invoke({ input: "<user_input>" }, { callbacks: [langfuseHandler], tags: tags });
非官方中文翻译 · 图片/视频/代码均链接官方资源 · 版权归 Langfuse GmbH 所有 查看英文原文 ↗