Class: Paid::Tracing::Wrappers::PaidOpenAI::ImagesWrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/paid_ruby/tracing/wrappers/open_ai_wrapper.rb

Overview

A private wrapper for the OpenAI Images API.

Instance Method Summary collapse

Constructor Details

#initialize(openai_client:, tracer:) ⇒ ImagesWrapper

Returns a new instance of ImagesWrapper.



39
40
41
42
# File 'lib/paid_ruby/tracing/wrappers/open_ai_wrapper.rb', line 39

def initialize(openai_client:, tracer:)
  @openai_client = openai_client
  @tracer = tracer
end

Instance Method Details

#generate(parameters:) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/paid_ruby/tracing/wrappers/open_ai_wrapper.rb', line 44

def generate(parameters:)
  current_span = OpenTelemetry::Trace.current_span
  unless current_span.context.valid?
    Paid::Tracing::Logging.logger.warn("No active span found, calling OpenAI directly without tracing.")
    return @openai_client.images.generate(parameters: parameters)
  end

  external_customer_id = Paid::Tracing.get_external_customer_id_from_context
  token = Paid::Tracing.get_token_from_context
  model = parameters[:model] || "dall-e-3"
  span_name = "trace.images #{model}"

  @tracer.in_span(span_name) do |span|
    attributes = {
      "gen_ai.request.model" => model,
      "gen_ai.system" => "openai",
      "gen_ai.operation.name" => "image_generation"
    }
    attributes["external_customer_id"] = external_customer_id if external_customer_id
    attributes["token"] = token if token
    span.add_attributes(attributes)

    begin
      response = @openai_client.images.generate(parameters: parameters)
      span.add_attributes({
                            "gen_ai.image.count" => parameters[:n] || 1,
                            "gen_ai.image.size" => parameters[:size] || "1024x1024",
                            "gen_ai.image.quality" => parameters[:quality] || "standard"
                          })
      span.status = OpenTelemetry::Trace::Status.ok("Success")
      response
    rescue StandardError => e
      span.record_exception(e)
      span.status = OpenTelemetry::Trace::Status.error("Error: #{e.message}")
      raise e
    end
  end
end