Langfuse 文档 中文 英文原文 ↗
文档 / Sessions

Sessions

与 LLM 应用的许多交互会跨越多个 traces 和 observations。Langfuse 中的 Sessions 是一种特殊的方式,用于将这些跨 trace 的 observations 归组在一起,并查看整个交互的简单会话回放(session replay)。通过在 observations 之间传播 sessionId 属性来开始使用。

mermaid
graph LR
    A(Session) -->|1:n, sessionId| B(Trace)

在跨多个 trace 的 observations 之间传播 sessionIdsessionId 可以是任何少于 200 字符的 US-ASCII 字符串,用于标识该 session。所有具有相同 sessionId 的 observations(包括它们所属的 traces)会被归组在一起。如果 session ID 超过 200 字符,它将被丢弃。

使用 @observe() 装饰器时:

python
from langfuse import observe, propagate_attributes

@observe()
def process_request():
    # Propagate session_id to all child observations
    with propagate_attributes(session_id="your-session-id"):
        # All nested observations automatically inherit session_id
        result = process_chat_message()

        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-chat-message"
) as root_span:
    # Propagate session_id to all child observations
    with propagate_attributes(session_id="chat-session-123"):
        # All observations created here automatically have session_id
        with root_span.start_as_current_observation(
            as_type="generation",
            name="generate-response",
            model="gpt-4o"
        ) as gen:
            # This generation automatically has session_id
            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 sessionId to all child observations
  await propagateAttributes(
    {
      sessionId: "session-123",
    },
    async () => {
      // All observations created here automatically have sessionId
      // ... your logic ...
    },
  );
});

使用 observe 包装器时:

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

const processChatMessage = observe(
  async (message: string) => {
    // Propagate sessionId to all child observations
    return await propagateAttributes({ sessionId: "session-123" }, async () => {
      // All nested observations automatically inherit sessionId
      const result = await processMessage(message);
      return result;
    });
  },
  { name: "process-chat-message" },
);

const result = await processChatMessage("Hello!");

更多细节参见 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 session_id to all observations including OpenAI generation
    with propagate_attributes(session_id="your-session-id"):
        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,
        )
python
from langfuse import get_client, propagate_attributes
from langfuse.langchain import CallbackHandler

langfuse = get_client()
handler = CallbackHandler()

with langfuse.start_as_current_observation(as_type="span", name="langchain-call"):
    # Propagate session_id to all observations
    with propagate_attributes(session_id="your-session-id"):
        # Pass handler to the chain invocation
        chain.invoke(
            {"animal": "dog"},
            config={"callbacks": [handler]},
        )

propagateAttributes() 与 CallbackHandler 一起使用:

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

const langfuseHandler = new CallbackHandler();

await startActiveObservation("langchain-call", async () => {
  // Propagate sessionId to all observations
  await propagateAttributes(
    {
      sessionId: "your-session-id",
    },
    async () => {
      // Pass handler to the chain invocation
      await chain.invoke(
        { input: "<user_input>" },
        { callbacks: [langfuseHandler] },
      );
    },
  );
});

Flowise 集成会自动将 Flowise 的 chatId 映射到 Langfuse 的 sessionId。需要 Flowise 1.4.10 或更高版本。

示例

使用公开的示例项目试用此功能。

跨多个 trace 的 session 示例

Session 视图

其他功能

相关资源

非官方中文翻译 · 图片/视频/代码均链接官方资源 · 版权归 Langfuse GmbH 所有 查看英文原文 ↗