Workflow recipe
Add tracing and cost tracking to an LLM app
One trace per user action, with tokens, latency and cost for each model call, so slow and costly features stand out.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
To add LLM tracing, decide what one trace represents (a user action, not an API call), run Langfuse yourself or use its cloud service, instrument the feature with the Langfuse Python SDK, and make sure every model call carries token costs. Then filter the traces by feature and user to find the slow and expensive requests.
When an LLM feature is slow, expensive or wrong, the first question is “which requests?”. Tracing answers it: every user action becomes a trace, each model call inside it records its input, output, tokens and latency, and costs add up per feature and per user.
This recipe uses Langfuse, an open source LLM observability platform you can self-host or use as a cloud service. Its current Python SDK (v4, released March 2026) is built on OpenTelemetry. The example instruments a function that summarises support tickets with Claude; the same pattern works for any provider.
NotebookAbout 5 min
1. Decide what one trace should represent
A trace should match something a user did, not an individual API call. Write down, for each feature:
Feature: ticket summary Trace name: summarise-ticket
User action: agent clicks "Summarise" on a ticket
Model calls inside: 1 (summary)
Attributes: user_id (support agent), session_id (ticket id), featureWith this in place, “cost per summary” and “slowest feature” become simple filters instead of log archaeology.
TerminalAbout 10 min
2. Run Langfuse
To self-host for development, Langfuse’s repository includes a Docker Compose setup:
git clone https://github.com/langfuse/langfuse.git
cd langfuse
docker compose up -dOpen http://localhost:3000, create an account, an organisation and a project, then create API keys in the project settings. If you would rather not run it yourself, sign up for Langfuse Cloud and create a project there instead.
TerminalAbout 5 min
3. Install the SDK and set the keys
pip install langfuse anthropic
export LANGFUSE_PUBLIC_KEY=pk-lf-...
export LANGFUSE_SECRET_KEY=sk-lf-...
export LANGFUSE_BASE_URL=http://localhost:3000 # or your Langfuse Cloud URL
export ANTHROPIC_API_KEY=...Keep these in your application’s normal secret store in production, not in code.
EditorAbout 20 min
4. Instrument the feature: one trace, one generation per model call
@observe turns the function into a traced observation. Inside it, start_as_current_observation(as_type="generation") records the model call, and usage_details carries the token counts from the API response. propagate_attributes attaches the user and session to everything created inside the block.
import anthropic
from langfuse import get_client, observe, propagate_attributes
langfuse = get_client()
claude = anthropic.Anthropic()
MODEL = "claude-opus-5-5"
@observe(name="summarise-ticket")
def summarise_ticket(ticket_text: str, user_id: str, ticket_id: str) -> str:
with propagate_attributes(user_id=user_id, session_id=ticket_id):
prompt = f"Summarise this support ticket in three short bullet points:\n\n{ticket_text}"
with langfuse.start_as_current_observation(
as_type="generation", name="claude-summary", model=MODEL
) as generation:
resp = claude.messages.create(
model=MODEL,
max_tokens=2000,
messages=[{"role": "user", "content": prompt}],
)
text = "".join(block.text for block in resp.content if block.type == "text")
generation.update(
input=prompt,
output=text,
usage_details={
"input": resp.usage.input_tokens,
"output": resp.usage.output_tokens,
"cache_read_input_tokens": resp.usage.cache_read_input_tokens or 0,
},
)
return text
if __name__ == "__main__":
print(summarise_ticket("Customer cannot reset password; reset email never arrives.", "agent-42", "T-1001"))
langfuse.flush() # send buffered data before a short-lived script exitsLatency is measured automatically from the start and end of each observation. Long-running servers do not need flush(); scripts, serverless functions and CLI tools do, or the last traces may never be sent.
Langfuse UIAbout 10 min
5. Make sure costs are calculated
Langfuse calculates cost when the generation’s model value matches one of its model definitions and usage was sent. It ships definitions for common Anthropic, OpenAI and Google models, but very new model names may not be matched yet.
Open a trace and check the generation shows a cost. If it shows tokens but no cost, add a model definition in the project settings (Models) with a match pattern for your model name and its prices. For example, at the time of writing Anthropic lists Claude Opus 5.5 at $4 per million input tokens and $20 per million output tokens; check the provider’s pricing page for current numbers.
If your provider bills extra items (cached tokens, tool calls), you can also send cost_details yourself on the generation, alongside usage_details.
Langfuse UIAbout 10 min
6. Look at the numbers that matter
Run the feature a few dozen times with realistic inputs (or turn tracing on in a staging environment), then answer these in the UI:
- average and 95th-percentile latency for
summarise-ticket, - average cost per trace, and the most expensive traces (open them: they are usually unusually long inputs),
- cost per user, using the user filter,
- any traces with errors.
Write the baseline down. Every later change to prompts or models can then be judged on quality, cost and latency together.
Check it worked
Verification checklist
0 of 6 done
When it goes wrong
If no traces appear, check the three LANGFUSE_ variables in the process that runs the code (not just your shell), and that the base URL is reachable from it. Then check that short-lived scripts call flush().
If traces appear but have no user or session, the propagate_attributes block must wrap the calls that create the observations, as in the example.
If tokens show but costs are zero, the model name does not match a model definition. See step 5.
If traces contain personal data you should not store, you have two options: avoid sending input and output for sensitive features, or use Langfuse’s masking support to redact fields before they leave the application. Decide this before turning tracing on in production.
Variations
Arize Phoenix is another option built on OpenTelemetry, free to self-host under the source-available Elastic License 2.0, with automatic instrumentation for common LLM SDKs through the OpenInference packages. It is a good fit if you want to run traces and evals locally in one tool.
If you would rather not depend on one platform’s SDK, OpenLLMetry records model and framework calls as plain OpenTelemetry spans that any OTel backend can store, including Langfuse. Opik from Comet is an Apache 2.0 alternative to Langfuse with tracing, LLM-as-a-judge evals and a PyTest integration for CI.
If your application is in TypeScript, Langfuse’s TypeScript SDK follows the same model of traces and generations. For frameworks such as LangChain or the Vercel AI SDK, check Langfuse’s integration pages before instrumenting by hand; they record generations for you.
If you already run an error tracker such as Sentry, traces and errors answer different questions: traces show what each request cost and how long it took, errors show what broke. Triage production errors with an agent covers the second half.
If your agent is built with LangChain or LangGraph and you trace to LangSmith instead, the langchain-agent-tracing skill walks a coding agent through the instrumentation choices, projects, sampling and redaction. The checks in this recipe (one trace per request, cost per feature, personal data decided up front) apply the same way.
Related observability guides
Once traces are flowing, gate changes with a golden-set eval and read what agent observability adds when one request turns into many tool calls. Tracing an agent with OpenTelemetry covers the vendor-neutral route, and the LLM observability platforms comparison sets Langfuse against the alternatives. For keeping spend down, see LLM cost control. Browse more AI workflow examples.
Outcome and tools
- Outcome
- Every user-facing feature sends one trace per action to Langfuse, with tokens, latency and cost per model call, and a list of the slowest and costliest features.
- For
- Developers
- Agent Skills
Related
- Evaluate RAG answers with a golden dataset
Set up RAG evaluation with a golden dataset and promptfoo: score retrieval, correctness and grounding for every question, and fail CI when answer quality drops.
- LangSmith
LangChain's tracing and evaluation platform, usable from any code.
- Write your first LLM eval
Turn real outputs into a small test set, add code-based checks in promptfoo and run them in CI to catch regressions on every change.
- Trace an agent with OpenTelemetry
Instrument an agent loop with OpenTelemetry GenAI spans, one per model call and tool call, and send the traces to Langfuse or Arize Phoenix.
- Triage production errors with an agent
AI error triage with a coding agent: read errors over a read-only Sentry MCP connection, write a triage note, reproduce in a failing test, then fix behind it.