세션

세션 (Sessions)

LLM 애플리케이션과의 많은 상호작용은 여러 trace에 걸쳐 이어져요. Langfuse의 Sessions는 trace들을 묶어 전체 상호작용의 간단한 세션 재생(session replay)을 볼 수 있게 해줘요.

출처: 문서

본문

LLM 애플리케이션과의 많은 상호작용은 여러 trace에 걸쳐 이어져요. Langfuse의 Sessions는 trace들을 묶고 전체 상호작용의 간단한 세션 재생을 볼 수 있게 해줘요.

공개 example 프로젝트로 이 기능을 시험해 볼 수 있어요.

여러 trace에 걸친 세션 예시

Session view

세션 뷰에서 다음을 할 수 있어요:

  • 대화를 디버깅하거나 분석하기 위해 전체 상호작용을 재생해요.
  • 세션을 공개 링크로 게시해 다른 사람과 공유해요 (예시).
  • 나중에 쉽게 찾도록 세션을 북마크해요.
  • Langfuse UI에서 점수를 추가해 세션에 주석을 달아 human-in-the-loop 평가를 기록해요.

세션 설정 (Set up sessions)

observation에 sessionId 속성을 전파해서 시작하세요. sessionId는 세션을 식별하는 데 쓰는 200자 미만의 US-ASCII 문자열이에요. 같은 sessionId를 가진 모든 observation은 이를 감싼 trace와 함께 그룹화돼요. session ID가 200자를 넘으면 버려져요.

Python SDK

@observe() 데코레이터 사용 시:

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

observation을 직접 생성할 때:

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

JS/TS SDK

컨텍스트 매니저 사용 시:

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 래퍼 사용 시:

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 docs를 참고하세요.

OpenAI (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,
        )

Langchain (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]},
        )

Langchain (JS/TS)

CallbackHandler와 함께 propagateAttributes() 사용:

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 통합은 Flowise chatId를 Langfuse sessionId에 자동으로 매핑해요. Flowise 1.4.10 이상이 필요해요.

속성 전파(Attribute Propagation)에 대한 참고 — 우리는 Attribute Propagation을 사용해 trace의 모든 observation에 sessionId를 전파해요. sessionId가 있는 모든 observation을 사용해 sessionId-레벨 메트릭을 만듭니다. Attribute Propagation 사용 시 다음을 고려하세요:

  • 값은 200자 이하의 문자열이어야 해요.
  • 모든 observation이 적용되도록 trace 초기에 호출하세요. 그래야 Langfuse의 모든 메트릭이 정확해요.
  • 잘못된 값은 경고와 함께 버려져요. 자세히: Python SDK | TypeScript SDK

기타 기능 (Other features)

  • 사용자 피드백 폼, 모더레이션 검사, 대화 레벨 QA 파이프라인 등에서 SDK 또는 API로 프로그래밍 방식으로 세션 레벨 점수를 추가해요. Scores via API/SDK를 참고하세요.
  • Langfuse에서 세션을 평가하는 방법은 Evaluating sessions/conversations 문서를 참고하세요.
  • 여러 서비스의 작업을 (trace를 묶는 대신) 단일 trace로 묶어야 한다면 Trace IDs & Distributed Tracing을 참고하세요.

GitHub Discussions

더 알아보기 (Learn more)