Langfuse 文档 中文 英文原文 ↗
文档 / 元数据(Metadata)

元数据(Metadata)

Observations(参见 Langfuse 数据模型)可以通过元数据(metadata)进行丰富,帮助你更好地理解应用,并在 Langfuse 中关联 observations。

你可以在 Langfuse UI 和 API 中按元数据的键进行过滤。

传播的元数据

使用 propagate_attributes() 可以确保元数据自动应用于某个上下文内的所有 observations。传播的元数据是键值对,值限制为最多 200 字符的字符串。键仅限字母数字字符。如果元数据值超过 200 字符,它将被丢弃。

使用 @observe() 装饰器时:

python
from langfuse import observe, propagate_attributes

@observe()
def process_data():
    # Propagate metadata to all child observations
    with propagate_attributes(
        metadata={"source": "api", "region": "us-east-1", "user_tier": "premium"}
    ):
        # All nested observations automatically inherit this metadata
        result = perform_processing()
        return result

直接创建 observations 时:

python
from langfuse import get_client, propagate_attributes

langfuse = get_client()

with langfuse.start_as_current_observation(as_type="span", name="process-request") as root_span:
    # Propagate metadata to all child observations
    with propagate_attributes(metadata={"request_id": "req_12345", "region": "us-east-1"}):
        # All observations created here automatically have this metadata
        with root_span.start_as_current_observation(
            as_type="generation",
            name="generate-response",
            model="gpt-4o"
        ) as gen:
            # This generation automatically has the metadata
            pass

使用上下文管理器时:

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

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

  // Propagate metadata to all child observations
  await propagateAttributes(
    {
      metadata: { source: "api", region: "us-east-1", userTier: "premium" },
    },
    async () => {
      // All observations created here automatically have this metadata
      // ... your logic ...
    }
  );
});

使用 observe 包装器时:

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

const processData = observe(
  async (data: string) => {
    // Propagate metadata to all child observations
    return await propagateAttributes(
      { metadata: { source: "api", region: "us-east-1" } },
      async () => {
        // All nested observations automatically inherit this metadata
        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"):
    # Propagate metadata to all observations including OpenAI generation
    with propagate_attributes(
        metadata={"source": "api", "region": "us-east-1"}
    ):
        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,
        )
ts
import OpenAI from "openai";
import { observeOpenAI } from "@langfuse/openai";
import { startActiveObservation, propagateAttributes } from "@langfuse/tracing";

await startActiveObservation("openai-call", async () => {
  // Propagate metadata to all observations
  await propagateAttributes(
    {
      metadata: { source: "api", region: "us-east-1" },
    },
    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"):
    # Propagate metadata to all child observations
    with propagate_attributes(
        metadata={"foo": "bar", "baz": "qux"}
    ):
        response = chain.invoke(
            {"topic": "cats"},
            config={"callbacks": [langfuse_handler]}
        )
ts
import { startActiveObservation, propagateAttributes } from "@langfuse/tracing";
import { CallbackHandler } from "@langfuse/langchain";

const langfuseHandler = new CallbackHandler();

// Propagate metadata to all child observations
await propagateAttributes(
  {
    metadata: { key: "value" },
  },
  async () => {
    await chain.invoke(
      { input: "<user_input>" },
      { callbacks: [langfuseHandler] }
    );
  }
);

你可以通过 override 配置设置 metadata,更多细节参见 Flowise 集成文档

非传播的元数据

你也可以只为特定的 observations 添加元数据:

python
# Python SDK
from langfuse import get_client

langfuse = get_client()

with langfuse.start_as_current_observation(as_type="span", name="process-request") as root_span:
    # Add metadata to this specific observation only
    root_span.update(metadata={"stage": "parsing"})

    # ... or access span via the current context
    langfuse.update_current_span(metadata={"stage": "parsing"})
typescript
// TypeScript SDK
import {
  startActiveObservation,
  updateActiveObservation,
} from "@langfuse/tracing";

await startActiveObservation("process-request", async (span) => {
  // Add metadata to this specific observation only
  span.update({
    metadata: { stage: "parsing" },
  })

  // ... or access span via the current context
  updateActiveObservation({
    metadata: { stage: "parsing" },
  });
});
非官方中文翻译 · 图片/视频/代码均链接官方资源 · 版权归 Langfuse GmbH 所有 查看英文原文 ↗