Langfuse.Instrumentation (Langfuse v0.1.0)

View Source

Macros for automatic function tracing in Langfuse.

This module provides declarative instrumentation for tracing function calls without modifying function bodies. Use these macros to automatically capture inputs, outputs, timing, and errors.

Using @observe

The @observe attribute marks functions for automatic tracing:

defmodule MyApp.Pipeline do
  use Langfuse.Instrumentation

  @observe name: "fetch-data"
  def fetch_data(query) do
    # Function body - automatically traced
    {:ok, results}
  end

  @observe as_type: :generation, model: "gpt-4"
  def call_llm(messages) do
    # LLM call - traced as generation
    {:ok, response}
  end
end

Using with_trace/2

For ad-hoc tracing of code blocks:

with_trace "process-request", user_id: user.id do
  # Code block is traced
  process(request)
end

Options

  • :name - Custom name for the observation (defaults to function name)
  • :as_type - Observation type: :span (default) or :generation
  • :capture_input - Whether to capture function arguments (default: true)
  • :capture_output - Whether to capture return value (default: true)
  • :model - Model name (for generations)
  • :metadata - Static metadata to include

Summary

Functions

Enables instrumentation macros in the using module.

Traces a code block with a new trace and span.

Functions

__using__(opts)

(macro)

Enables instrumentation macros in the using module.

Example

defmodule MyApp.Service do
  use Langfuse.Instrumentation

  @observe name: "my-operation"
  def my_function(arg), do: process(arg)
end

with_trace(name, list)

(macro)

Traces a code block with a new trace and span.

Creates a trace with the given name and executes the block within a span. The span automatically captures the block's return value and timing.

Options

  • :user_id - User identifier for the trace
  • :session_id - Session identifier for the trace
  • :metadata - Additional metadata
  • :tags - Tags for categorization

Examples

result = with_trace "process-request" do
  fetch_and_process(data)
end

result = with_trace "user-action", user_id: current_user.id do
  perform_action(params)
end

with_trace(name, opts, list)

(macro)