14 def image_gen(prompt, options)
15 api_key = options.api_key || ENV["REPLICATE_API_KEY"]
16 raise Rager::Errors::CredentialsError.new("Replicate", env_var: ["REPLICATE_API_KEY"]) if api_key.nil?
17
18 body = {
19 input: {
20 prompt: prompt
21 }
22 }.tap do |b|
23 b[:input][:output_format] = T.must(options.output_format).serialize if options.output_format
24 b[:input][:seed] = options.seed if options.seed
25 end
26
27 request = Rager::Http::Request.new(
28 url: "https://api.replicate.com/v1/models/#{options.model}/predictions",
29 verb: Rager::Http::Verb::Post,
30 headers: {
31 "Authorization" => "Bearer #{api_key}",
32 "Content-Type" => "application/json",
33 "Prefer" => "wait"
34 },
35 body: body.to_json,
36 timeout: options.timeout || Rager.config.timeout
37 )
38
39 response = Rager.config.http_adapter.make_request(request)
40 response_body = T.cast(T.must(response.body), String)
41
42 raise Rager::Errors::HttpError.new(Rager.config.http_adapter, request.url, response.status, body: response_body) unless [200, 201].include?(response.status)
43
44 parsed = JSON.parse(response_body)
45 parsed.fetch("output").first
46 rescue JSON::ParserError, KeyError => e
47 raise Rager::Errors::ParseError.new(response_body || "", details: e.message)
48 end