How to Trace Your Local AI Agent with Langfuse

Your agent failed. Now find out why.

A local agent gives a wrong answer, and the log shows nothing useful. The model ran, a tool ran, and something in between went sideways, with no record of what the model actually saw or sent. Print statements cover one run. They fall apart once an agent loops through five tool calls and two retries.

That is the gap tracing fills. Langfuse is an open-source observability platform for LLM apps and agents, built on OpenTelemetry. It records every model call, tool call, and retrieval step as a trace tree, with latency, token counts, and cost on each step. The current release is v4, the Python SDK is at v5, and the project is MIT-licensed with more than 37,000 GitHub stars. You can run it all on your own machine with Docker Compose, so prompts and completions never leave your network.

Prerequisites

  • Docker and Docker Compose v2 installed
  • Python 3.10 or newer
  • Ollama running locally with a model pulled (ollama pull llama3.1)

Step 1: Run Langfuse with Docker Compose

The official repository ships a Compose file with six containers: the web UI and API, a background worker, Postgres, ClickHouse, Redis, and MinIO for blob storage. Clone it and start the stack:

git clone --depth=1 https://github.com/langfuse/langfuse.git
cd langfuse
docker compose up -d

Give ClickHouse 30 to 60 seconds to initialize on first boot, then open http://localhost:3000. Create an account, create a project, and copy the API keys from Settings → API Keys: a public key (pk-lf-...) and a secret key (sk-lf-...). The secret key is a password, so keep it out of git. The Compose file ships placeholder secrets marked # CHANGEME; replace them before the instance is reachable from your network. Check the stack with docker compose ps.




The Langfuse home dashboard on a self-hosted instance, tracking traces from local Ollama models. Source: JB Software Solutions


Step 2: Build a small tool-calling agent

Tracing is only interesting with a real agent to watch, so build a minimal one first. This loop calls a local model through Ollama's OpenAI-compatible endpoint, runs any tool calls, and repeats until the model answers directly:

import json
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:11434/v1",
    api_key="ollama",  # required by the client, ignored by Ollama
)

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
            },
        },
    }
]

def get_weather(city: str) -> str:
    return f"The weather in {city} is 21C and sunny."

def run_agent(user_input: str) -> str:
    messages = [{"role": "user", "content": user_input}]
    for _ in range(5):
        response = client.chat.completions.create(
            model="llama3.1",
            messages=messages,
            tools=TOOLS,
        )
        message = response.choices[0].message
        messages.append(message)
        if not message.tool_calls:
            return message.content or ""
        for call in message.tool_calls:
            args = json.loads(call.function.arguments)
            result = get_weather(**args)
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": result,
            })
    return "I ran out of steps."

if __name__ == "__main__":
    print(run_agent("What is the weather like in Seoul?"))

Run it once to confirm it works, then break the tool on purpose by raising an exception inside get_weather. The traceback tells you the tool failed, but not what arguments the model sent, what the prompt looked like, or how many retries happened first. That missing context is what tracing adds.

Step 3: Instrument the agent with the Python SDK

Install the SDK and point it at your local instance. The base URL routes traces to your server instead of Langfuse Cloud:

pip install langfuse openai
export LANGFUSE_PUBLIC_KEY=pk-lf-...
export LANGFUSE_SECRET_KEY=sk-lf-...
export LANGFUSE_BASE_URL=http://localhost:3000

The SDK is built on OpenTelemetry, with three ways to create observations: the @observe() decorator, a context manager, and manual observations. The decorator is the shortest path: it wraps a function and captures its input, output, timing, and errors automatically. The OpenAI integration is a drop-in replacement, so changing one import turns every chat call into a generation observation.

Three changes carry the whole integration: the import, the decorator, and a flush() at the end:

import json
from langfuse import observe, get_client, propagate_attributes
from langfuse.openai import OpenAI

client = OpenAI(
    base_url="http://localhost:11434/v1",
    api_key="ollama",  # required by the client, ignored by Ollama
)

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
            },
        },
    }
]

def get_weather(city: str) -> str:
    return f"The weather in {city} is 21C and sunny."

@observe(name="agent-run")
def run_agent(user_input: str) -> str:
    messages = [{"role": "user", "content": user_input}]
    for _ in range(5):
        response = client.chat.completions.create(
            model="llama3.1",
            messages=messages,
            tools=TOOLS,
        )
        message = response.choices[0].message
        messages.append(message)
        if not message.tool_calls:
            return message.content or ""
        for call in message.tool_calls:
            args = json.loads(call.function.arguments)
            result = get_weather(**args)
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": result,
            })
    return "I ran out of steps."

if __name__ == "__main__":
    propagate_attributes(session_id="demo-session", user_id="demo-user")
    print(run_agent("What is the weather like in Seoul?"))
    get_client().flush()

Two details matter. First, propagate_attributes() attaches the session and user to every observation in the run, so you can group traces by conversation later. Call it early, before the observed function runs. Second, the SDK sends events asynchronously in the background, and a short script can exit before the last traces leave, so flush() at the end is not optional. The same pattern covers agents built with LangChain and multi-agent crews: native integrations for LangChain, LlamaIndex, LiteLLM, and the OpenAI Agents SDK put framework calls in the same trace tree.

Step 4: Read a trace in the dashboard

Run the script, then open the Traces page. Each run appears as one trace named agent-run:

agent-run
├── llm-call (generation, 1.2s, 342 tokens)
├── tool-get_weather (span, 0.03s)
├── llm-call (generation, 0.9s, 210 tokens)


A Langfuse trace tree breaks an agent run into LLM calls and tool spans, with latency and cost per step. Source: ClickHouse blog


Click a generation to see the exact messages sent to the model and the reply, including the tool call and its parsed arguments. Click a span to see what the tool received and returned. The home dashboard rolls the numbers up: total traces, latency over time, and cost per model. Local models show $0.00, since there is no per-token bill for a model on your own hardware, so the cost panel doubles as a token-usage panel.

Step 5: Debug with it

Three checks cover most agent failures:

  • Wrong tool arguments. Open the generation before a failed tool span and read the arguments the model sent. If it keeps passing a country where a city belongs, fix the tool description, not the model.
  • Prompt bloat. Watch input tokens per generation across runs. A history that grows without a cap shows up here first, long before latency complaints do.
  • Slow steps. Sort the tree by latency. The retrieval or tool span that dominates a run is usually the cheapest thing to fix.

Once the basics work, attach scores to traces: a thumbs up or down from a user, or a numeric score from a script. They accumulate in the dashboard, so you can tell whether a prompt change helped or made things worse.

Troubleshooting

  • No traces appear. The usual cause is a missing flush() in a short script. Next, check the three environment variables: a wrong LANGFUSE_BASE_URL sends traces nowhere, and a wrong key pair gets rejected.
  • First start is slow. ClickHouse takes 30 to 60 seconds to initialize. Wait, then run docker compose ps and confirm all six containers are healthy.
  • Port 3000 is taken. Another service owns the port. Stop it, or map Langfuse to a different host port in the Compose file.
  • SDK and server versions disagree. Python SDK v5 needs a server at v4.59.0 or newer. On an older server, use Python SDK v4, which works from v3.63.0 up.

What to do next

Start with one agent and one project. Then wire in the rest: LangChain or LlamaIndex callbacks for framework agents, LiteLLM routing if several models share one gateway, and datasets with LLM-as-a-judge scores to compare prompt versions. The point is not the dashboard. It is that every agent decision leaves a record you can open and read, on hardware you own.

Comments

Popular posts from this blog

Open-Source AI Weekly: Bonsai, GigaChat 4 Lead

Claude Claims Proof of Riemann Hypothesis After 167 Years

How to Build an AI Agent with LangGraph in 30 Minutes