A trajectory, or trace, records how a request or operation moves across components as related spans. In an agent run, spans can capture model calls, tool calls, retrieved material, selected context, latency, token counts, and the final response. section 8.3.1 section 8.4.4
Unlike logs, which record discrete events, and metrics, which summarize numerical trends, traces preserve execution flow. Adding semantic context such as prompt versions, retrieval sources, and tool arguments helps explain why an AI system behaved as it did. section 8.3.1 section 8.3.2
Listing 8.5 Python example for observability and tracing with Langfuse
import uuid
from langchain.agents import create_agent
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langfuse import get_client
from langfuse.langchain import CallbackHandler
LANGUAGE_FACTS = {
"python": "Python was created by Guido van Rossum and first "
"released in 1991.",
}
@tool
def lookup_language(name: str) -> str: #1
"""Look up who created a programming language and when it was
first released."""
return LANGUAGE_FACTS.get(name.lower(), f"No record for {name}.")
langfuse_client = get_client() #2
langfuse_callback_handler = CallbackHandler()
llm = ChatOpenAI(model="gpt-4o", temperature=0) #3
agent = create_agent(
model=llm,
tools=[lookup_language],
system_prompt="Use the available tools to answer questions
about programming languages.",
)
trace_id = str(uuid.uuid4()) #4
question = "Who created the Python programming language, and in
which year was it first released?"
response = agent.invoke( #5
{"messages": [{"role": "user", "content": question}]},
config={"callbacks": [langfuse_callback_handler],
"run_id": trace_id},
)
print(response["messages"][-1].content)
langfuse_client.flush() #6
trace_url = langfuse_client.get_trace_url(trace_id=trace_id)
print(f"View the trace in Langfuse: {trace_url}")
A Python agent setup attaches a Langfuse callback handler to capture execution traces. section 8.4.4
























