Class: Langfuse::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/langfuse/client.rb

Overview

Main client for Langfuse SDK

Provides a unified interface for interacting with the Langfuse API. Handles prompt fetching and returns the appropriate prompt client (TextPromptClient or ChatPromptClient) based on the prompt type.

rubocop:disable Metrics/ClassLength

Examples:

config = Langfuse::Config.new(
  public_key: "pk_...",
  secret_key: "sk_...",
  cache_ttl: 120
)
client = Langfuse::Client.new(config)
prompt = client.get_prompt("greeting")
compiled = prompt.compile(name: "Alice")

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Client

Initialize a new Langfuse client

Parameters:

  • config (Config)

    Configuration object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/langfuse/client.rb', line 27

def initialize(config)
  @config = config
  @config.validate!

  # Create cache if enabled
  cache = create_cache if cache_enabled?

  # Create API client with cache
  @api_client = ApiClient.new(
    public_key: config.public_key,
    secret_key: config.secret_key,
    base_url: config.base_url,
    timeout: config.timeout,
    logger: config.logger,
    cache: cache
  )

  # Initialize score client for batching score events
  @score_client = ScoreClient.new(api_client: @api_client, config: config)
end

Instance Attribute Details

#api_clientObject (readonly)

Returns the value of attribute api_client.



22
23
24
# File 'lib/langfuse/client.rb', line 22

def api_client
  @api_client
end

#configObject (readonly)

Returns the value of attribute config.



22
23
24
# File 'lib/langfuse/client.rb', line 22

def config
  @config
end

Instance Method Details

#compile_prompt(name, variables: {}, version: nil, label: nil, fallback: nil, type: nil) ⇒ String, Array<Hash>

Convenience method: fetch and compile a prompt in one call

This is a shorthand for calling get_prompt followed by compile. Returns the compiled prompt ready to use with your LLM.

Examples:

Compile a text prompt

text = client.compile_prompt("greeting", variables: { name: "Alice" })
# => "Hello Alice!"

Compile a chat prompt

messages = client.compile_prompt("support-bot", variables: { company: "Acme" })
# => [{ role: :system, content: "You are a support agent for Acme" }]

With fallback

text = client.compile_prompt(
  "greeting",
  variables: { name: "Alice" },
  fallback: "Hello {{name}}!",
  type: :text
)

Parameters:

  • name (String)

    The name of the prompt

  • variables (Hash) (defaults to: {})

    Variables to substitute in the prompt

  • version (Integer, nil) (defaults to: nil)

    Optional specific version number

  • label (String, nil) (defaults to: nil)

    Optional label (e.g., “production”, “latest”)

  • fallback (String, Array, nil) (defaults to: nil)

    Optional fallback prompt to use on error

  • type (Symbol, nil) (defaults to: nil)

    Required when fallback is provided (:text or :chat)

Returns:

  • (String, Array<Hash>)

    Compiled prompt (String for text, Array for chat)

Raises:

  • (ArgumentError)

    if both version and label are provided

  • (ArgumentError)

    if fallback is provided without type

  • (NotFoundError)

    if the prompt is not found and no fallback provided

  • (UnauthorizedError)

    if authentication fails and no fallback provided

  • (ApiError)

    for other API errors and no fallback provided



138
139
140
141
# File 'lib/langfuse/client.rb', line 138

def compile_prompt(name, variables: {}, version: nil, label: nil, fallback: nil, type: nil)
  prompt = get_prompt(name, version: version, label: label, fallback: fallback, type: type)
  prompt.compile(**variables)
end

#create_prompt(name:, prompt:, type:, config: {}, labels: [], tags: [], commit_message: nil) ⇒ TextPromptClient, ChatPromptClient

Create a new prompt (or new version if name already exists)

Creates a new prompt in Langfuse. If a prompt with the same name already exists, this creates a new version of that prompt.

rubocop:disable Metrics/ParameterLists

Examples:

Create a text prompt

prompt = client.create_prompt(
  name: "greeting",
  prompt: "Hello {{name}}!",
  type: :text,
  labels: ["production"],
  config: { model: "gpt-4o", temperature: 0.7 }
)

Create a chat prompt

prompt = client.create_prompt(
  name: "support-bot",
  prompt: [
    { role: "system", content: "You are a {{role}} assistant" },
    { role: "user", content: "{{question}}" }
  ],
  type: :chat,
  labels: ["staging"]
)

Parameters:

  • name (String)

    The prompt name (required)

  • prompt (String, Array<Hash>)

    The prompt content (required)

    • For text prompts: a string with {variable} placeholders

    • For chat prompts: array of message hashes with role and content

  • type (Symbol)

    Prompt type (:text or :chat) (required)

  • config (Hash) (defaults to: {})

    Optional configuration (model parameters, tools, etc.)

  • labels (Array<String>) (defaults to: [])

    Optional labels (e.g., [“production”])

  • tags (Array<String>) (defaults to: [])

    Optional tags for categorization

  • commit_message (String, nil) (defaults to: nil)

    Optional commit message

Returns:

Raises:

  • (ArgumentError)

    if required parameters are missing or invalid

  • (UnauthorizedError)

    if authentication fails

  • (ApiError)

    for other API errors



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/langfuse/client.rb', line 182

def create_prompt(name:, prompt:, type:, config: {}, labels: [], tags: [], commit_message: nil)
  validate_prompt_type!(type)
  validate_prompt_content!(prompt, type)

  prompt_data = api_client.create_prompt(
    name: name,
    prompt: normalize_prompt_content(prompt, type),
    type: type.to_s,
    config: config,
    labels: labels,
    tags: tags,
    commit_message: commit_message
  )

  build_prompt_client(prompt_data)
end

#create_score(name:, value:, trace_id: nil, observation_id: nil, comment: nil, metadata: nil, data_type: :numeric) ⇒ void

This method returns an undefined value.

Create a score event and queue it for batching

rubocop:disable Metrics/ParameterLists

Examples:

Numeric score

client.create_score(name: "quality", value: 0.85, trace_id: "abc123")

Boolean score

client.create_score(name: "passed", value: true, trace_id: "abc123", data_type: :boolean)

Categorical score

client.create_score(name: "category", value: "high", trace_id: "abc123", data_type: :categorical)

Parameters:

  • name (String)

    Score name (required)

  • value (Numeric, Integer, String)

    Score value (type depends on data_type)

  • trace_id (String, nil) (defaults to: nil)

    Trace ID to associate with the score

  • observation_id (String, nil) (defaults to: nil)

    Observation ID to associate with the score

  • comment (String, nil) (defaults to: nil)

    Optional comment

  • metadata (Hash, nil) (defaults to: nil)

    Optional metadata hash

  • data_type (Symbol) (defaults to: :numeric)

    Data type (:numeric, :boolean, :categorical)

Raises:

  • (ArgumentError)

    if validation fails



263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/langfuse/client.rb', line 263

def create_score(name:, value:, trace_id: nil, observation_id: nil, comment: nil, metadata: nil,
                 data_type: :numeric)
  @score_client.create(
    name: name,
    value: value,
    trace_id: trace_id,
    observation_id: observation_id,
    comment: comment,
    metadata: ,
    data_type: data_type
  )
end

#flush_scoresvoid

This method returns an undefined value.

Force flush all queued score events

Sends all queued score events to the API immediately.

Examples:

client.flush_scores


337
338
339
# File 'lib/langfuse/client.rb', line 337

def flush_scores
  @score_client.flush
end

#get_prompt(name, version: nil, label: nil, fallback: nil, type: nil) ⇒ TextPromptClient, ChatPromptClient

Fetch a prompt and return the appropriate client

Fetches the prompt from the Langfuse API and returns either a TextPromptClient or ChatPromptClient based on the prompt type.

Examples:

With fallback for graceful degradation

prompt = client.get_prompt("greeting", fallback: "Hello {{name}}!", type: :text)

Parameters:

  • name (String)

    The name of the prompt

  • version (Integer, nil) (defaults to: nil)

    Optional specific version number

  • label (String, nil) (defaults to: nil)

    Optional label (e.g., “production”, “latest”)

  • fallback (String, Array, nil) (defaults to: nil)

    Optional fallback prompt to use on error

  • type (Symbol, nil) (defaults to: nil)

    Required when fallback is provided (:text or :chat)

Returns:

Raises:

  • (ArgumentError)

    if both version and label are provided

  • (ArgumentError)

    if fallback is provided without type

  • (NotFoundError)

    if the prompt is not found and no fallback provided

  • (UnauthorizedError)

    if authentication fails and no fallback provided

  • (ApiError)

    for other API errors and no fallback provided



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/langfuse/client.rb', line 67

def get_prompt(name, version: nil, label: nil, fallback: nil, type: nil)
  # Validate fallback usage
  if fallback && !type
    raise ArgumentError, "type parameter is required when fallback is provided (use :text or :chat)"
  end

  # Try to fetch from API
  prompt_data = api_client.get_prompt(name, version: version, label: label)
  build_prompt_client(prompt_data)
rescue ApiError, NotFoundError, UnauthorizedError => e
  # If no fallback, re-raise the error
  raise e unless fallback

  # Log warning and return fallback
  config.logger.warn("Langfuse API error for prompt '#{name}': #{e.message}. Using fallback.")
  build_fallback_prompt_client(name, fallback, type)
end

#list_prompts(page: nil, limit: nil) ⇒ Array<Hash>

List all prompts in the Langfuse project

Fetches a list of all prompt names available in your project. Returns metadata only, not full prompt content.

Examples:

prompts = client.list_prompts
prompts.each do |prompt|
  puts "#{prompt['name']} (v#{prompt['version']})"
end

Parameters:

  • page (Integer, nil) (defaults to: nil)

    Optional page number for pagination

  • limit (Integer, nil) (defaults to: nil)

    Optional limit per page

Returns:

  • (Array<Hash>)

    Array of prompt metadata hashes

Raises:



101
102
103
# File 'lib/langfuse/client.rb', line 101

def list_prompts(page: nil, limit: nil)
  api_client.list_prompts(page: page, limit: limit)
end

#score_active_observation(name:, value:, comment: nil, metadata: nil, data_type: :numeric) ⇒ void

This method returns an undefined value.

Create a score for the currently active observation (from OTel span)

Extracts observation_id and trace_id from the active OpenTelemetry span.

Examples:

Langfuse.observe("operation") do |obs|
  client.score_active_observation(name: "accuracy", value: 0.92)
end

Parameters:

  • name (String)

    Score name (required)

  • value (Numeric, Integer, String)

    Score value

  • comment (String, nil) (defaults to: nil)

    Optional comment

  • metadata (Hash, nil) (defaults to: nil)

    Optional metadata hash

  • data_type (Symbol) (defaults to: :numeric)

    Data type (:numeric, :boolean, :categorical)

Raises:

  • (ArgumentError)

    if no active span or validation fails



293
294
295
296
297
298
299
300
301
# File 'lib/langfuse/client.rb', line 293

def score_active_observation(name:, value:, comment: nil, metadata: nil, data_type: :numeric)
  @score_client.score_active_observation(
    name: name,
    value: value,
    comment: comment,
    metadata: ,
    data_type: data_type
  )
end

#score_active_trace(name:, value:, comment: nil, metadata: nil, data_type: :numeric) ⇒ void

This method returns an undefined value.

Create a score for the currently active trace (from OTel span)

Extracts trace_id from the active OpenTelemetry span.

Examples:

Langfuse.observe("operation") do |obs|
  client.score_active_trace(name: "overall_quality", value: 5)
end

Parameters:

  • name (String)

    Score name (required)

  • value (Numeric, Integer, String)

    Score value

  • comment (String, nil) (defaults to: nil)

    Optional comment

  • metadata (Hash, nil) (defaults to: nil)

    Optional metadata hash

  • data_type (Symbol) (defaults to: :numeric)

    Data type (:numeric, :boolean, :categorical)

Raises:

  • (ArgumentError)

    if no active span or validation fails



319
320
321
322
323
324
325
326
327
# File 'lib/langfuse/client.rb', line 319

def score_active_trace(name:, value:, comment: nil, metadata: nil, data_type: :numeric)
  @score_client.score_active_trace(
    name: name,
    value: value,
    comment: comment,
    metadata: ,
    data_type: data_type
  )
end

#shutdownvoid

This method returns an undefined value.

Shutdown the client and flush any pending scores

Also shuts down the cache if it supports shutdown (e.g., SWR thread pool).



346
347
348
349
# File 'lib/langfuse/client.rb', line 346

def shutdown
  @score_client.shutdown
  @api_client.shutdown
end

#trace_url(trace_id) ⇒ String

Generate URL for viewing a trace in Langfuse UI

Examples:

url = client.trace_url("abc123...")
puts "View trace at: #{url}"

Parameters:

  • trace_id (String)

    The trace ID (hex-encoded, 32 characters)

Returns:

  • (String)

    URL to view the trace



238
239
240
# File 'lib/langfuse/client.rb', line 238

def trace_url(trace_id)
  "#{config.base_url}/traces/#{trace_id}"
end

#update_prompt(name:, version:, labels:) ⇒ TextPromptClient, ChatPromptClient

Update an existing prompt version’s metadata

Updates the labels of an existing prompt version. Note: The prompt content itself cannot be changed after creation.

Examples:

Update labels to promote to production

prompt = client.update_prompt(
  name: "greeting",
  version: 2,
  labels: ["production"]
)

Parameters:

  • name (String)

    The prompt name (required)

  • version (Integer)

    The version number to update (required)

  • labels (Array<String>)

    New labels (replaces existing). Required.

Returns:

Raises:



220
221
222
223
224
225
226
227
228
# File 'lib/langfuse/client.rb', line 220

def update_prompt(name:, version:, labels:)
  prompt_data = api_client.update_prompt(
    name: name,
    version: version,
    labels: labels
  )

  build_prompt_client(prompt_data)
end