Module: PlatformSdk::Observability::Langfuse::OpenAIAdapter

Defined in:
lib/platform_sdk/observability/langfuse/openai_adapter.rb

Overview

Fires llm_call.platform_sdk ActiveSupport::Notifications events with a payload extracted from a ruby-openai chat call. Apps that hit OpenAI's chat completions API directly (rather than via RubyLLM) call with_observability to get cost, tokens, model, input, and output captured in Langfuse:

PlatformSdk::Observability::Langfuse::OpenAIAdapter.with_observability(
parameters: { model: 'gpt-4o', messages: [...], ... },
context: 'amend_json'
) do
OpenAI::Client.new.chat(parameters: parameters)
end

The block runs the actual LLM call and its return value is forwarded back to the caller. On success a generation observation is recorded with model/usage from the response. On raise a failure observation is recorded and the exception is re-raised unchanged.

No hard dependency on the ruby-openai gem — this adapter only touches the plain-Hash response shape OpenAI's API returns.

Class Method Summary collapse

Class Method Details

.fire(parameters:, response:, context:, error: nil) ⇒ Object

Fire a single llm_call.platform_sdk notification. Useful when the caller has already invoked OpenAI and just wants to record the observation after the fact.



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/platform_sdk/observability/langfuse/openai_adapter.rb', line 46

def fire(parameters:, response:, context:, error: nil)
  payload = build_payload(parameters:, response:, context:, error:)
  return unless payload

  ActiveSupport::Notifications.instrument(LLM_CALL_EVENT, payload)
rescue StandardError => e
  OpenTelemetry.handle_error(
    message: "OpenAIAdapter.fire failed: #{e.class}: #{e.message[0, 200]}"
  )
  nil
end

.with_observability(parameters:, context:) ⇒ Object

Wrap an OpenAI::Client#chat call. Forwards the block's return value. On success: fires success notification with model/input/ output/usage extracted from parameters and the returned response. On raise: fires failure notification with error: set, re-raises.



34
35
36
37
38
39
40
41
# File 'lib/platform_sdk/observability/langfuse/openai_adapter.rb', line 34

def with_observability(parameters:, context:)
  response = yield
  fire(parameters:, response:, context:)
  response
rescue StandardError => e
  fire(parameters:, response: nil, context:, error: e)
  raise
end