Observable AI Pipelines: Langfuse, Tracing, Logging

Build production-grade observability for LLM apps. Implement Langfuse, structured logging, distributed tracing, and cost monitoring for AI pipelines.

0

When your LLM application hits production, visibility becomes critical. Without proper observability, you can’t see what’s happening inside your system. API calls become hard to trace. Agents’ decisions are unclear. Costs are difficult to predict. Token usage is hidden. RAG retrieval quality is hard to measure.

The problem isn’t the LLM. It’s the lack of observability. Most AI systems are built with the same debugging tools we used for CRUD APIs: basic logging, error traces, maybe some metrics. That approach doesn’t work for systems where behavior emerges from model outputs, retrieval chains, and agent loops.

I’ve spent the last year building production LLM applications in the UAE, and the difference between a maintainable system and an opaque one comes down to three things: structured observability for LLM calls, distributed tracing across your pipeline, and smart logging that captures context. This guide shows you how to implement all three.

Why Standard Monitoring Fails for AI Pipelines

Traditional observability tools track requests, errors, and latency. They work fine for deterministic systems. But LLM applications are different:

  • A successful HTTP response doesn’t mean the model returned useful output.
  • Latency spikes might be normal (long context windows, reasoning tokens) or problematic (retrieval delays).
  • Costs scale with token usage, not request count, and you need per-call visibility.
  • Agent failures happen silently: the agent picks the wrong tool, or the tool call fails mid-execution.
  • RAG systems fail in subtle ways: retrieval returns documents, but the wrong ones, and the LLM can’t fix it.

You need observability built for LLM workflows: tracing individual model calls, capturing prompt and completion data, measuring retrieval quality, and correlating everything across distributed services.

The Three Pillars of AI Pipeline Observability

1. LLM-Native Observability with Langfuse

Langfuse is purpose-built for this. It captures LLM calls, chains, agent traces, and scores them. Unlike generic APM tools, Langfuse understands the semantics of LLM workflows.

Here’s what you get:

  • Automatic tracing of OpenAI, Anthropic, and other provider calls.
  • Span-based traces for multi-step chains and agents.
  • Cost tracking per model, per user, per prompt.
  • Latency breakdowns: time to first token, total generation time, retrieval latency.
  • Prompt versioning and A/B testing infrastructure.
  • User session replay: see what your agent did, step by step.

Setting it up is straightforward. If you’re using OpenAI with Node.js:

import Langfuse from "langfuse";
import OpenAI from "openai";

const langfuse = new Langfuse({
  publicKey: process.env.LANGFUSE_PUBLIC_KEY,
  secretKey: process.env.LANGFUSE_SECRET_KEY,
  baseUrl: process.env.LANGFUSE_BASE_URL,
});

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const trace = langfuse.trace({
  name: "customer_support_agent",
  userId: "user_123",
  metadata: {
    environment: "production",
    version: "1.2.0",
  },
});

const span = trace.span({
  name: "generate_response",
  input: { query: "How do I reset my password?" },
});

const response = await openai.chat.completions.create({
  model: "gpt-4",
  messages: [
    { role: "system", content: "You are a helpful support agent." },
    { role: "user", content: "How do I reset my password?" },
  ],
});

span.end({
  output: response.choices[0].message.content,
  metadata: {
    inputTokens: response.usage.prompt_tokens,
    outputTokens: response.usage.completion_tokens,
  },
});

await langfuse.flush();

That’s the basic pattern. For complex agents with tool calls, you add nested spans:

const agentTrace = langfuse.trace({
  name: "customer_support_agent_full_run",
  userId: "user_123",
});

const thinkingSpan = agentTrace.span({
  name: "planning",
  input: { userQuery: "I want to close my account" },
});

// Agent decides to retrieve account info
const retrievalSpan = agentTrace.span({
  name: "retrieve_account_info",
  parentObservationId: thinkingSpan.id,
});

const accountData = await database.getAccount("user_123");

retrievalSpan.end({
  output: accountData,
});

// Agent makes decision based on retrieval
const decisionSpan = agentTrace.span({
  name: "generate_response",
  parentObservationId: thinkingSpan.id,
});

const finalResponse = await openai.chat.completions.create({
  model: "gpt-4",
  messages: [
    {
      role: "system",
      content: "You are a support agent. Help the user close their account.",
    },
    {
      role: "user",
      content: `User wants to close their account. Current balance: $${accountData.balance}. Pending orders: ${accountData.pendingOrders}.`,
    },
  ],
});

decisionSpan.end({
  output: finalResponse.choices[0].message.content,
});

In the Langfuse dashboard, you see the entire trace: every span, every LLM call, costs, latency, and the full chain of reasoning. When something goes wrong, you replay the exact execution.

2. Structured Logging for Context and Debugging

Langfuse captures LLM calls, but you also need application-level context. Structured logging lets you correlate application events with LLM traces.

The key is logging as JSON with consistent fields. Use a library like Pino (Node.js) or structlog (Python):

import pino from "pino";

const logger = pino({
  level: process.env.LOG_LEVEL || "info",
  transport: {
    target: "pino-pretty",
    options: {
      colorize: true,
    },
  },
});

const trace = langfuse.trace({
  name: "process_customer_query",
  userId: "user_456",
});

logger.info(
  {
    traceId: trace.id,
    userId: "user_456",
    queryType: "account_status",
    timestamp: new Date().toISOString(),
  },
  "Starting query processing"
);

const retrievalSpan = trace.span({
  name: "vector_search",
});

try {
  const results = await vectorDb.search(userQuery, { topK: 5 });
  logger.info(
    {
      traceId: trace.id,
      spanId: retrievalSpan.id,
      documentsRetrieved: results.length,
      averageScore: (results.reduce((s, r) => s + r.score, 0) / results.length).toFixed(2),
    },
    "Vector search completed"
  );
} catch (error) {
  logger.error(
    {
      traceId: trace.id,
      spanId: retrievalSpan.id,
      error: error.message,
      errorCode: error.code,
    },
    "Vector search failed"
  );
  throw error;
}

This pattern gives you several advantages:

  • Logs are queryable: filter by traceId to see all events for one request.
  • You can correlate application logs with Langfuse traces: same traceId in both systems.
  • Structured fields let you aggregate: count errors by type, measure retrieval score distributions, track latency percentiles.
  • Log aggregation tools (ELK, DataDog, Grafana Loki) can parse and visualize this automatically.

For Python, the pattern is similar with structlog:

import structlog
import logging

structlog.configure(
    processors=[
        structlog.stdlib.filter_by_level,
        structlog.stdlib.add_logger_name,
        structlog.stdlib.add_log_level,
        structlog.stdlib.PositionalArgumentsFormatter(),
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.StackInfoRenderer(),
        structlog.processors.format_exc_info,
        structlog.processors.UnicodeDecoder(),
        structlog.processors.JSONRenderer(),
    ],
    context_class=dict,
    logger_factory=structlog.stdlib.LoggerFactory(),
    cache_logger_on_first_use=True,
)

logger = structlog.get_logger()

logger.info(
    "vector_search_completed",
    trace_id=trace.id,
    span_id=retrieval_span.id,
    documents_retrieved=len(results),
    average_score=sum(r["score"] for r in results) / len(results),
)

3. Distributed Tracing with OpenTelemetry

When your AI pipeline spans multiple services (retrieval service, LLM gateway, database, vector store), you need distributed tracing. OpenTelemetry is the standard.

OpenTelemetry works by propagating a trace context across service boundaries. Each service adds its own spans, and they’re correlated by a common trace ID.

Here’s a minimal setup with Node.js:

import { NodeSDK } from "@opentelemetry/sdk-node";
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { Resource } from "@opentelemetry/resources";
import { SemanticResourceAttributes } from "@opentelemetry/semantic-conventions";

const sdk = new NodeSDK({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: "ai-pipeline-service",
    [SemanticResourceAttributes.SERVICE_VERSION]: "1.0.0",
  }),
  traceExporter: new OTLPTraceExporter({
    url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
  }),
  instrumentations: [getNodeAutoInstrumentations()],
});

sdk.start();

Once initialized, OpenTelemetry automatically instruments HTTP calls, database queries, and more. You can add custom spans:

import { trace } from "@opentelemetry/api";

const tracer = trace.getTracer("ai-pipeline");

const span = tracer.startSpan("rag_retrieval");

try {
  const documents = await retrieveDocuments(userQuery);
  span.addEvent("documents_retrieved", {
    count: documents.length,
  });
} catch (error) {
  span.recordException(error);
  span.setStatus({ code: SpanStatusCode.ERROR });
} finally {
  span.end();
}

The trace context is automatically propagated to downstream services. If your retrieval service also uses OpenTelemetry, it will create child spans under the same trace.

For visualization, you can use Jaeger (open source) or export to services like Datadog, New Relic, or Grafana Cloud. The traces show you the full request path, latency at each step, and where bottlenecks occur.

Putting It Together: A Production Example

Let’s build a complete example: a customer support agent that retrieves account data, queries an LLM, and logs everything.

import Langfuse from "langfuse";
import OpenAI from "openai";
import pino from "pino";
import { trace } from "@opentelemetry/api";

const langfuse = new Langfuse();
const openai = new OpenAI();
const logger = pino();
const tracer = trace.getTracer("support-agent");

async function handleSupportQuery(userId, query) {
  // Create top-level trace for this request
  const trace = langfuse.trace({
    name: "support_agent_full_flow",
    userId: userId,
    input: { query },
    metadata: {
      environment: "production",
    },
  });

  logger.info(
    { traceId: trace.id, userId, query },
    "Support query received"
  );

  // Distributed tracing span for the entire flow
  const otelSpan = tracer.startSpan("support_agent_flow");

  try {
    // Step 1: Retrieve account data
    const retrievalSpan = trace.span({
      name: "retrieve_account_data",
      input: { userId },
    });

    logger.info(
      { traceId: trace.id, spanId: retrievalSpan.id },
      "Retrieving account data"
    );

    const accountData = await retrieveAccountData(userId);

    retrievalSpan.end({
      output: accountData,
    });

    logger.info(
      {
        traceId: trace.id,
        spanId: retrievalSpan.id,
        accountStatus: accountData.status,
      },
      "Account data retrieved"
    );

    // Step 2: Vector search for relevant docs
    const searchSpan = trace.span({
      name: "vector_search",
      input: { query },
      parentObservationId: trace.id,
    });

    const relevantDocs = await vectorDb.search(query, { topK: 5 });

    searchSpan.end({
      output: {
        documentsFound: relevantDocs.length,
        topScore: relevantDocs[0]?.score,
      },
    });

    logger.info(
      {
        traceId: trace.id,
        spanId: searchSpan.id,
        docsFound: relevantDocs.length,
      },
      "Vector search completed"
    );

    // Step 3: Call LLM with context
    const llmSpan = trace.span({
      name: "generate_response",
      input: {
        query,
        contextDocs: relevantDocs.length,
        userStatus: accountData.status,
      },
    });

    const systemPrompt = `You are a helpful support agent. The user's account status is: ${accountData.status}. Recent orders: ${accountData.recentOrders}. Help them with their query.`;

    const messages = [
      { role: "system", content: systemPrompt },
      { role: "user", content: query },
      ...(relevantDocs.length > 0
        ? [
            {
              role: "user",
              content: `Relevant documentation: ${relevantDocs.map((d) => d.text).join("
")}`,
            },
          ]
        : []),
    ];

    const response = await openai.chat.completions.create({
      model: "gpt-4",
      messages,
      temperature: 0.7,
      max_tokens: 500,
    });

    const responseText = response.choices[0].message.content;

    llmSpan.end({
      output: responseText,
      metadata: {
        model: "gpt-4",
        inputTokens: response.usage.prompt_tokens,
        outputTokens: response.usage.completion_tokens,
        totalTokens: response.usage.total_tokens,
      },
    });

    logger.info(
      {
        traceId: trace.id,
        spanId: llmSpan.id,
        model: "gpt-4",
        inputTokens: response.usage.prompt_tokens,
        outputTokens: response.usage.completion_tokens,
      },
      "LLM response generated"
    );

    // End the trace
    trace.end({
      output: responseText,
      metadata: {
        totalSteps: 3,
        success: true,
      },
    });

    logger.info(
      { traceId: trace.id, success: true },
      "Support query completed"
    );

    otelSpan.end();

    return {
      response: responseText,
      traceId: trace.id,
    };
  } catch (error) {
    logger.error(
      { traceId: trace.id, error: error.message },
      "Support query failed"
    );

    trace.end({
      output: null,
      metadata: {
        error: error.message,
        success: false,
      },
    });

    otelSpan.recordException(error);
    otelSpan.end();

    throw error;
  }
}

This pattern gives you:

  • Full LLM visibility: every model call is captured in Langfuse.
  • Application context: every step is logged with the trace ID, so you can correlate logs and traces.
  • Distributed tracing: if any service makes HTTP calls or database queries, OpenTelemetry captures them.
  • Cost tracking: Langfuse knows the model, tokens used, and can calculate cost per request.
  • Debugging: when something goes wrong, you have the full context: what data was retrieved, what prompt was sent, what the model returned.

Key Metrics to Monitor

Once observability is in place, focus on these metrics:

  • Cost per request: Track total tokens (input and output) and calculate cost. Watch for unexpectedly high usage, which might indicate inefficient retrieval or prompt design.
  • Latency percentiles (p50, p95, p99): LLM calls are slow by nature, but identify outliers. If p99 latency spikes, it might be retrieval delays or model overload.
  • Retrieval quality: Log the relevance scores of retrieved documents. If top documents have low scores, your retrieval needs improvement.
  • LLM output quality: Use Langfuse’s scoring feature to mark responses as good or bad. Track the ratio over time.
  • Error rates by component: Separate errors in retrieval, LLM calls, and downstream services. Fix the highest-impact ones first.
  • Token usage by model: If you use multiple models, see which one is most expensive and whether you can optimize prompts or switch models.

Common Pitfalls and How to Avoid Them

Pitfall 1: Logging sensitive data. Prompts and completions might contain user PII or proprietary information. Redact or hash sensitive fields before logging. Langfuse lets you mask fields in the UI, but be careful at the application level too.

Pitfall 2: Forgetting trace context in async code. If you spawn background tasks or use async/await, make sure the trace ID is passed along. Otherwise, you lose correlation.

Pitfall 3: Observability overhead. Sending traces and logs to external services adds latency. Use sampling (e.g., log 10% of requests) and batch exports to minimize impact.

Pitfall 4: Not correlating traces with business events. Add user IDs, session IDs, and feature flags to traces. This lets you analyze observability by cohort: “How much slower are queries for users with feature X?”, “What’s the error rate for this new model?”

Getting Started

You don’t need to implement everything at once. Start small:

  1. Add Langfuse to your LLM calls. Spend a week exploring the dashboard, understanding costs and latency.
  2. Add structured logging with correlation IDs. Start logging key events (retrieval, LLM call, decision points).
  3. Once you’re comfortable with logs and LLM traces, add OpenTelemetry to trace across services.
  4. Set up dashboards and alerts for the metrics that matter most to your business.

The goal is straightforward: when your AI pipeline encounters an issue in production, you should be able to understand why within minutes. Observability is what transforms an opaque system into one you can understand, debug, and improve continuously.

What’s the difference between Langfuse and OpenTelemetry?

Langfuse is LLM-specific: it understands prompts, completions, tokens, and costs. OpenTelemetry is generic distributed tracing that works for any service. Use both: Langfuse for LLM calls and chains, OpenTelemetry for the broader infrastructure (databases, APIs, message queues).

Do I need all three (Langfuse, structured logging, and distributed tracing)?

Not immediately. Start with Langfuse for LLM visibility. Add structured logging when you have multiple services. Add distributed tracing when you need to correlate across service boundaries. Build incrementally based on your complexity.

How do I handle PII and sensitive data in traces?

Redact or hash sensitive fields at the application level before sending to external services. Langfuse supports field masking in the UI, but don’t rely on that alone. Consider using a local observability backend (Jaeger) for highly sensitive workloads, or implement encryption in transit.

What if tracing adds too much latency?

Use sampling: log or trace 10% or 1% of requests, not 100%. Batch exports so traces are sent asynchronously, not blocking your request. Both Langfuse and OpenTelemetry support sampling policies.

How do I correlate logs with Langfuse traces?

Use the same trace ID in both systems. When you create a Langfuse trace, get its ID and include it in all logs for that request. Log aggregation tools can then join logs and traces by trace ID.

Leave a Reply

Your email address will not be published. Required fields are marked *