How to set trace_id when using langchain.CallbackHandler in Langfuse v3.99.0? #16167
Describe your questionHow can I set the trace_id parameter using the langfuse.create_trace_id function? from langfuse import get_client
langfuse = get_client()
trace_id_msg = langfuse.create_trace_id(seed=f"{idConversacion}-{current_time.isoformat()}")
response_text = await ChatbotViewSet._full_chain.ainvoke({
"pregunta_usuario": pregunta_usuario},
config={"callbacks": [langfuse_handler],
"metadata": {
"langfuse_trace_name" : "FullChain ChatBot",
"langfuse_user_id": idUser,
"langfuse_session_id": idConversation,
"langfuse_trace_id" : trace_id_msg
}
}
)I've tried using "langfuse_trace_id" but it is not working :( Langfuse Cloud or Self-Hosted?Self-Hosted If Self-Hosted3.99.0 If Langfuse CloudNo response SDK and integration versionsNo response Pre-Submission Checklist
|
Replies: 1 comment
|
There is no from langfuse import get_client, Langfuse
from langfuse.langchain import CallbackHandler
langfuse = get_client()
# Generate deterministic trace ID from external system
external_request_id = "req_12345"
predefined_trace_id = Langfuse.create_trace_id(seed=external_request_id)
langfuse_handler = CallbackHandler()
# Use the predefined trace ID with trace_context
with langfuse.start_as_current_observation(
as_type="span",
name="langchain-request",
trace_context={"trace_id": predefined_trace_id}
) as span:
span.update(input={"person": "Ada Lovelace"})
with propagate_attributes(
user_id="user_123",
):
# LangChain execution will be part of this trace
response = chain.invoke(
{"person": "Ada Lovelace"},
config={"callbacks": [langfuse_handler]}
)
span.update(output={"response": response})
print(f"Trace ID: {predefined_trace_id}") # Use this for scoring later
print(f"Trace ID: {langfuse_handler.last_trace_id}") # Care needed in concurrent environments where handler is reusedNote that You can also pass import uuid
from langfuse.langchain import CallbackHandler
trace_id = str(uuid.uuid4()).replace("-", "")
handler = CallbackHandler(trace_context={"trace_id": trace_id})Keep in mind this approach comes from a community discussion rather than the reference docs, and reusing a single shared handler instance across concurrent requests means you cannot set a per-request trace ID that way (2). For your 📚 Sources:
Have another question? Just tag @inkeep. |
There is no
langfuse_trace_idmetadata field — metadata only supportslangfuse_user_id,langfuse_session_id, andlangfuse_tagsfor setting trace attributes dynamically (1). To use a custom trace ID, wrap the LangChain execution in a span that sets the predefined trace ID viatrace_context(1):