Metadata
Traces and observations (see Langfuse Data Model) can be enriched with metadata to better understand your users, application, and experiments. Metadata can be added to traces in the form of arbitrary JSON.
The v3 SDK is currently in beta. Please check out the SDK v3 for more details.
When using the @observe()
decorator:
from langfuse import observe, get_client
langfuse = get_client()
@observe()
def process_data():
# Access the client and update the current trace metadata
# Add metadata to the trace level
langfuse.update_current_trace(
metadata={"source": "api", "version": "1.2.3"}
)
# Add metadata to the current span level
langfuse.update_current_span(
metadata={"processing_stage": "initial"}
)
# Process data...
return result
When creating spans directly:
from langfuse import Langfuse
langfuse = Langfuse()
# Add metadata at trace level
with langfuse.start_as_current_span(
name="process-request"
) as root_span:
# Add metadata to the trace
root_span.update_trace(metadata={"request_id": "req_12345"})
# Add metadata to the current span
root_span.update(metadata={"stage": "parsing"})
# Create a child span with metadata
with root_span.start_as_current_generation(
name="generate-response",
model="gpt-4o",
metadata={"temperature": 0.7, "max_tokens": 1000}
) as gen:
# Update metadata later if needed
gen.update(metadata={"completion_type": "creative"})
You can update metadata multiple times - new values are merged with existing ones up until the first level of the dictionary:
with langfuse.start_as_current_span(name="operation") as span:
# First update
span.update(metadata={"step": 1, "status": "started"})
# Later update - will be merged with previous metadata
span.update(metadata={"step": 2, "error": None})
# Final metadata will be {"step": 2, "status": "started", "error": null}