Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions autogpt_platform/backend/backend/copilot/baseline/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from typing import Any

import orjson
from langfuse import propagate_attributes
Comment thread
majdyz marked this conversation as resolved.

from backend.copilot.model import (
ChatMessage,
Expand Down Expand Up @@ -198,6 +199,20 @@ async def stream_chat_completion_baseline(

yield StreamStart(messageId=message_id, sessionId=session_id)

# Propagate user/session context to Langfuse so all LLM calls within
# this request are grouped under a single trace with proper attribution.
_trace_ctx: Any = None
try:
_trace_ctx = propagate_attributes(
user_id=user_id,
session_id=session_id,
trace_name="copilot-baseline",
tags=["baseline"],
)
_trace_ctx.__enter__()
except Exception:
logger.warning("[Baseline] Langfuse trace context setup failed")

assistant_text = ""
text_block_id = str(uuid.uuid4())
text_started = False
Expand Down Expand Up @@ -385,6 +400,13 @@ async def stream_chat_completion_baseline(
yield StreamError(errorText=error_msg, code="baseline_error")
# Still persist whatever we got
finally:
# Close Langfuse trace context
if _trace_ctx is not None:
try:
_trace_ctx.__exit__(None, None, None)
except Exception:
logger.warning("[Baseline] Langfuse trace context teardown failed")

# Persist assistant response
if assistant_text:
session.messages.append(
Expand Down
6 changes: 4 additions & 2 deletions autogpt_platform/backend/backend/copilot/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@
import logging
from typing import Any

import openai
from langfuse import get_client
from langfuse.openai import (
AsyncOpenAI as LangfuseAsyncOpenAI, # pyright: ignore[reportPrivateImportUsage]
)

from backend.data.db_accessors import understanding_db
from backend.data.understanding import format_understanding_for_prompt
Expand All @@ -26,7 +28,7 @@

config = ChatConfig()
settings = Settings()
client = openai.AsyncOpenAI(api_key=config.api_key, base_url=config.base_url)
client = LangfuseAsyncOpenAI(api_key=config.api_key, base_url=config.base_url)


langfuse = get_client()
Expand Down