Skip to content
Kward Search API index

Class: Kward::CodexImages

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/model/codex_images.rb

Overview

Codex subscription transport, separate from the chat Responses stream.

Constant Summary collapse

URL =
URI("https://chatgpt.com/backend-api/codex/images/generations")
MAX_IMAGE_BYTES =
20 * 1024 * 1024
MAX_RESPONSE_BYTES =
(MAX_IMAGE_BYTES + 2) / 3 * 4 + 65_536
PNG_HEADER =
"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR".b.freeze
Error =
Class.new(StandardError)

Class Method Summary collapse

Class Method Details

.generate(prompt, token:, account_id:, turn_id:, cancellation: nil) ⇒ Object



17
18
19
20
21
22
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
# File 'lib/kward/model/codex_images.rb', line 17

def self.generate(prompt, token:, account_id:, turn_id:, cancellation: nil)
  request = Http.apply_user_agent(Net::HTTP::Post.new(URL))
  request["Authorization"] = "Bearer #{token}"
  request["ChatGPT-Account-Id"] =  unless .to_s.empty?
  request["x-codex-image-turn-id"] = turn_id unless turn_id.to_s.empty?
  request["originator"] = "kward"
  request["Content-Type"] = "application/json"
  request["Accept"] = "application/json"
  request.body = JSON.generate(prompt: prompt, model: "gpt-image-2", background: "opaque", quality: "auto", size: "auto")

  body = +""
  cancellation&.raise_if_cancelled!
  Net::HTTP.start(URL.hostname, URL.port, use_ssl: true, open_timeout: 10, read_timeout: 180) do |http|
    http.max_retries = 0
    cancellation&.on_cancel { http.finish if http.started? }
    cancellation&.raise_if_cancelled!
    http.request(request) do |response|
      raise Error, error_message(response.code.to_i) unless response.is_a?(Net::HTTPSuccess)

      response.read_body do |chunk|
        cancellation&.raise_if_cancelled!
        raise Error, "Codex image exceeds the preview size limit." if body.bytesize + chunk.bytesize > MAX_RESPONSE_BYTES

        body << chunk
      end
    end
  end
  cancellation&.raise_if_cancelled!
  decode(body)
rescue IOError, SystemCallError, SocketError, Timeout::Error, OpenSSL::SSL::SSLError, Net::HTTPBadResponse
  cancellation&.raise_if_cancelled!
  raise Error, "The connection to Codex image generation was interrupted; it was not retried."
end

.valid_png?(bytes) ⇒ Boolean

Returns:

  • (Boolean)


66
67
68
69
70
71
# File 'lib/kward/model/codex_images.rb', line 66

def self.valid_png?(bytes)
  return false unless bytes.is_a?(String) && bytes.bytesize.between?(45, MAX_IMAGE_BYTES) && bytes.b.start_with?(PNG_HEADER)

  width, height = bytes.byteslice(16, 8).unpack("NN")
  width.between?(1, 8192) && height.between?(1, 8192) && bytes.end_with?("\x00\x00\x00\x00IEND\xaeB`\x82".b)
end