Class: Rager::Image::Providers::Replicate

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

Instance Method Summary collapse

Instance Method Details

#image(prompt, options) ⇒ Object



14
15
16
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
50
51
52
# File 'lib/rager/image/providers/replicate.rb', line 14

def image(prompt, options)
  api_key = options.api_key || ENV["REPLICATE_API_KEY"]
  raise Rager::Errors::CredentialsError.new("Replicate", env_var: ["REPLICATE_API_KEY"]) if api_key.nil?

  url = "https://api.replicate.com/v1/models/#{options.model}/predictions"

  headers = {
    "Authorization" => "Bearer #{api_key}",
    "Content-Type" => "application/json",
    "Prefer" => "wait"
  }

  body = {
    input: {
      prompt: prompt
    }
  }.tap do |b|
    b[:input][:output_format] = T.must(options.output_format).serialize if options.output_format
    b[:input][:seed] = options.seed if options.seed
  end

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

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

  raise Rager::Errors::HttpError.new(Rager.config.http_adapter, request.url, response.status, body: response_body) unless [200, 201].include?(response.status)

  parsed = JSON.parse(response_body)
  parsed.fetch("output").first
rescue JSON::ParserError, KeyError => e
  raise Rager::Errors::ParseError.new(response_body || "", details: e.message)
end