Skip to content

Commit 06e07f4

Browse files
committed
fix: resolve duplicate traces for sessions
1 parent ff97409 commit 06e07f4

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

src/api/routers/chat.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,12 @@ def extract_langfuse_metadata(chat_request: ChatRequest, headers: dict) -> dict:
6464
if meta_key not in metadata:
6565
metadata[meta_key] = headers_lower[header_key]
6666

67+
# ALWAYS use chat_id as session_id for consistency
68+
# This ensures all messages in the same chat conversation are grouped
69+
# in the same Langfuse session, preventing duplicate sessions
70+
if "chat_id" in metadata:
71+
metadata["session_id"] = metadata["chat_id"]
72+
6773
return metadata
6874

6975

@@ -94,12 +100,20 @@ async def chat_completions(
94100
# Create trace name using chat_id if available
95101
trace_name = f"chat:{metadata.get('chat_id', 'unknown')}"
96102

103+
# Extract user_id and session_id separately for Langfuse trace attributes
104+
user_id = metadata.get("user_id")
105+
session_id = metadata.get("session_id")
106+
107+
# Create clean metadata dict for additional context (without duplicating trace attributes)
108+
# Remove user_id and session_id from metadata since they're passed as separate parameters
109+
clean_metadata = {k: v for k, v in metadata.items() if k not in ["user_id", "session_id"]}
110+
97111
# Update trace with metadata, user_id, and session_id
98112
langfuse_context.update_current_trace(
99113
name=trace_name,
100-
user_id=metadata.get("user_id"),
101-
session_id=metadata.get("session_id"),
102-
metadata=metadata,
114+
user_id=user_id,
115+
session_id=session_id,
116+
metadata=clean_metadata,
103117
input={
104118
"model": chat_request.model,
105119
"messages": [msg.model_dump() for msg in chat_request.messages],

0 commit comments

Comments
 (0)