Class: Rager::Chat::Providers::Openai

Inherits:
Abstract
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/rager/chat/providers/openai.rb

Constant Summary collapse

OpenaiContentItem =
T.type_alias { T::Hash[String, T.any(String, T::Hash[String, String])] }
OpenaiMessages =
T.type_alias { T::Array[T::Hash[String, T.any(String, T::Array[OpenaiContentItem])]] }

Instance Method Summary collapse

Instance Method Details

#build_openai_messages(messages, system_prompt) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/rager/chat/providers/openai.rb', line 84

def build_openai_messages(messages, system_prompt)
  output = T.let([], OpenaiMessages)

  if system_prompt
    output << {"role" => "system", "content" => system_prompt}
  end

  messages.each do |message|
    role = message.role.is_a?(String) ? message.role : message.role.serialize
    content = message.content

    case content
    when String
      output << {"role" => role, "content" => content}
    when Array
      formatted_content = content.map { |item| format_content_item(item) }
      output << {"role" => role, "content" => formatted_content}
    end
  end

  output
end

#chat(messages, options) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
# File 'lib/rager/chat/providers/openai.rb', line 23

def chat(messages, options)
  api_key = options.api_key || ENV["OPENAI_API_KEY"]
  raise Rager::Errors::CredentialsError.new("OpenAI", env_var: ["OPENAI_API_KEY"]) if api_key.nil?

  base_url = options.url || ENV["OPENAI_URL"] || "https://api.openai.com/v1"
  url = "#{base_url}/chat/completions"

  headers = {
    "Content-Type" => "application/json"
  }.tap do |h|
    h["Authorization"] = "Bearer #{api_key}" if api_key
  end

  body = {
    model: options.model || "gpt-4.1",
    messages: build_openai_messages(messages, options.system_prompt)
  }.tap do |b|
    b[:n] = options.n if options.n
    b[:max_tokens] = options.max_tokens if options.max_tokens
    b[:temperature] = options.temperature if options.temperature
    b[:stream] = options.stream if options.stream
    b[:seed] = options.seed if options.seed

    if options.schema && options.schema_name
      b[:response_format] = {
        type: "json_schema",
        json_schema: {
          name: T.must(options.schema_name).downcase,
          strict: true,
          schema: Rager::Chat::Schema.dry_schema_to_json_schema(T.must(options.schema))
        }
      }
    end
  end

  request = Rager::Http::Request.new(
    verb: Rager::Http::Verb::Post,
    url: url,
    headers: headers,
    body: body.to_json,
    streaming: options.stream || false,
    timeout: options.timeout || Rager.config.timeout
  )

  response = Rager.config.http_adapter.make_request(request)
  response_body = T.must(response.body)

  raise Rager::Errors::HttpError.new(Rager.config.http_adapter, request.url, response.status, body: T.cast(response_body, String)) if response.status != 200

  case response_body
  when String then handle_non_stream_body(response_body)
  when Enumerator then handle_stream_body(response_body)
  end
end

#format_content_item(item) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/rager/chat/providers/openai.rb', line 108

def format_content_item(item)
  case item.type
  when Rager::Chat::MessageContentType::Text
    {"type" => "text", "text" => item.content}
  when Rager::Chat::MessageContentType::ImageUrl
    {"type" => "image_url", "image_url" => {"url" => item.content}}
  when Rager::Chat::MessageContentType::ImageBase64
    mime_type = case T.must(item.image_type)
    when Rager::Chat::MessageContentImageType::Jpeg then "image/jpeg"
    when Rager::Chat::MessageContentImageType::Png then "image/png"
    when Rager::Chat::MessageContentImageType::Webp then "image/webp"
    end
    {"type" => "image_url", "image_url" => {"url" => "data:#{mime_type};base64,#{item.content}"}}
  end
end

#handle_non_stream_body(body) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/rager/chat/providers/openai.rb', line 125

def handle_non_stream_body(body)
  response_data = JSON.parse(body)
  return [] unless response_data.key?("choices") && response_data["choices"].is_a?(Array)

  result = response_data["choices"].filter_map do |choice|
    text = choice.dig("message", "content").to_s
    text unless text.empty?
  end

  result.one? ? result.first : result
rescue JSON::ParserError
  raise Rager::Errors::ParseError.new(body, details: "OpenAI response body is not valid JSON")
end

#handle_stream_body(body) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/rager/chat/providers/openai.rb', line 140

def handle_stream_body(body)
  Enumerator.new do |yielder|
    buffer_parts = []
    body.each do |chunk|
      buffer_parts << chunk.force_encoding(Encoding::UTF_8)
      buffer = buffer_parts.join
      while (line = buffer.slice!(/.*\n/))
        process_stream_line(line, yielder)
      end
      buffer_parts = buffer.empty? ? [] : [buffer]
    end

    unless buffer_parts.empty?
      process_stream_line(buffer_parts.join, yielder)
    end
  end
end