LangfuseLangfuse Python SDK 4.15.4 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
38 small wins to finish your pathNext lesson

Trace IDs and work in another service

create_trace_id(seed=...) turns your own id, such as a ticket number, into the same Langfuse trace id every time. trace_context attaches work to an existing trace.

The traces so far got random ids. Two problems follow. Code that finds the trace for ticket 1042 later, to add a customer's rating, needs its id. And when a second service does part of the work, its observations should join the same trace rather than start a new one.

Exampletrace_ids.py, after the setup lines and from desk import answer
trace_id = langfuse.create_trace_id(seed="ticket-1042")
print(trace_id)
print(langfuse.create_trace_id(seed="ticket-1042") == trace_id)

with langfuse.start_as_current_observation(name="support-ticket", trace_context={"trace_id": trace_id}):
    answer("Where is my order A17?")
    print(langfuse.get_current_trace_id())
    parent = langfuse.get_current_observation_id()

Trace ids are 32 lowercase hex characters and observation ids 16, following the W3C Trace Context standard. create_trace_id with a seed hashes it into that shape, so the same ticket number always gives the same trace id.

Exampletrace_ids.py, continued
with langfuse.start_as_current_observation(
    name="billing-service", trace_context={"trace_id": trace_id, "parent_span_id": parent}
):
    pass

langfuse.flush()
local_langfuse.tree()
Example
python trace_ids.py

The printed id is the same on every run, on every machine. trace_context made support-ticket use it, and the second block, standing in for a billing service that received the two ids, attached itself under the same observation. In a real system those ids travel with the request, usually as an HTTP header.

You can set a trace id but not an observation id. The documentation also describes propagate_attributes(..., as_baggage=True), which copies the user id and other attributes into the headers of every outgoing HTTP request. Only use it for values that are safe to send to every service you call.

Try it yourself
  • Print create_trace_id() twice without a seed.
  • Pass trace_context={"trace_id": "1042"} and read the warning.
  • Leave out parent_span_id in the billing block and print the tree.

You understood something today that you didn't yesterday.