Class: RailsAi::Providers::OpenAIAdapter

Inherits:
Base
  • Object
show all
Defined in:
lib/rails_ai/providers/openai_adapter.rb

Constant Summary collapse

OPENAI_API_BASE =
"https://api.openai.com/v1"

Instance Method Summary collapse

Constructor Details

#initializeOpenAIAdapter



12
13
14
15
# File 'lib/rails_ai/providers/openai_adapter.rb', line 12

def initialize
  @api_key = ENV.fetch("OPENAI_API_KEY")
  super
end

Instance Method Details

#analyze_image!(image:, prompt:, model: "gpt-4o", **opts) ⇒ Object

Multimodal analysis - GPT-4 Vision and other vision models



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/rails_ai/providers/openai_adapter.rb', line 270

def analyze_image!(image:, prompt:, model: "gpt-4o", **opts)
  return "[stubbed] Image analysis: #{prompt}" if RailsAi.config.stub_responses
  
  # Prepare image for vision models
  image_data = prepare_image_for_vision(image)
  
  messages = [
    {
      role: "user",
      content: [
        {
          type: "text",
          text: prompt
        },
        {
          type: "image_url",
          image_url: {
            url: image_data
          }
        }
      ]
    }
  ]
  
  response = make_request(
    "chat/completions",
    {
      model: model,
      messages: messages,
      max_tokens: opts[:max_tokens] || RailsAi.config.token_limit,
      temperature: opts[:temperature] || 0.7,
      **opts.except(:max_tokens, :temperature)
    }
  )
  
  response.dig("choices", 0, "message", "content")
end

#analyze_video!(video:, prompt:, model: "gpt-4o", **opts) ⇒ Object



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/rails_ai/providers/openai_adapter.rb', line 308

def analyze_video!(video:, prompt:, model: "gpt-4o", **opts)
  return "[stubbed] Video analysis: #{prompt}" if RailsAi.config.stub_responses
  
  # For video analysis, we'll extract frames and analyze them
  # This is a simplified implementation
  video_data = prepare_video_for_vision(video)
  
  messages = [
    {
      role: "user",
      content: [
        {
          type: "text",
          text: "#{prompt}\n\nAnalyze this video content:"
        },
        {
          type: "image_url",
          image_url: {
            url: video_data
          }
        }
      ]
    }
  ]
  
  response = make_request(
    "chat/completions",
    {
      model: model,
      messages: messages,
      max_tokens: opts[:max_tokens] || RailsAi.config.token_limit,
      temperature: opts[:temperature] || 0.7,
      **opts.except(:max_tokens, :temperature)
    }
  )
  
  response.dig("choices", 0, "message", "content")
end

#chat!(messages:, model:, **opts) ⇒ Object

Text-based operations



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rails_ai/providers/openai_adapter.rb', line 18

def chat!(messages:, model:, **opts)
  return "(stubbed) #{messages.last[:content]}" if RailsAi.config.stub_responses
  
  response = make_request(
    "chat/completions",
    {
      model: model,
      messages: messages,
      max_tokens: opts[:max_tokens] || RailsAi.config.token_limit,
      temperature: opts[:temperature] || 0.7,
      top_p: opts[:top_p] || 1.0,
      frequency_penalty: opts[:frequency_penalty] || 0.0,
      presence_penalty: opts[:presence_penalty] || 0.0,
      **opts.except(:max_tokens, :temperature, :top_p, :frequency_penalty, :presence_penalty)
    }
  )
  
  response.dig("choices", 0, "message", "content")
end

#create_variation!(image:, size: "1024x1024", **opts) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/rails_ai/providers/openai_adapter.rb', line 147

def create_variation!(image:, size: "1024x1024", **opts)
  return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" if RailsAi.config.stub_responses
  
  form_data = {
    image: prepare_image_file(image),
    size: size,
    n: opts[:n] || 1,
    response_format: opts[:response_format] || "url",
    **opts.except(:n, :response_format)
  }
  
  response = make_form_request("images/variations", form_data)
  
  image_data = response.dig("data", 0, "url") || response.dig("data", 0, "b64_json")
  if image_data
    if image_data.start_with?("http")
      convert_url_to_base64(image_data)
    else
      "data:image/png;base64,#{image_data}"
    end
  else
    raise "Image variation failed: No image data in response"
  end
end

#edit_image!(image:, prompt:, mask: nil, size: "1024x1024", **opts) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/rails_ai/providers/openai_adapter.rb', line 118

def edit_image!(image:, prompt:, mask: nil, size: "1024x1024", **opts)
  return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" if RailsAi.config.stub_responses
  
  # Prepare form data for image editing
  form_data = {
    image: prepare_image_file(image),
    prompt: prompt,
    size: size,
    n: opts[:n] || 1,
    response_format: opts[:response_format] || "url",
    **opts.except(:n, :response_format)
  }
  
  form_data[:mask] = prepare_image_file(mask) if mask
  
  response = make_form_request("images/edits", form_data)
  
  image_data = response.dig("data", 0, "url") || response.dig("data", 0, "b64_json")
  if image_data
    if image_data.start_with?("http")
      convert_url_to_base64(image_data)
    else
      "data:image/png;base64,#{image_data}"
    end
  else
    raise "Image editing failed: No image data in response"
  end
end

#edit_video!(video:, prompt:, **opts) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/rails_ai/providers/openai_adapter.rb', line 200

def edit_video!(video:, prompt:, **opts)
  return "data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAB1tZGF0AQAAARxtYXNrAAAAAG1wNDEAAAAAIG1kYXQ=" if RailsAi.config.stub_responses
  
  form_data = {
    video: prepare_video_file(video),
    prompt: prompt,
    **opts
  }
  
  response = make_form_request("video/edits", form_data)
  
  video_data = response.dig("data", 0, "url") || response.dig("data", 0, "b64_json")
  if video_data
    if video_data.start_with?("http")
      convert_url_to_base64(video_data, "video/mp4")
    else
      "data:video/mp4;base64,#{video_data}"
    end
  else
    raise "Video editing failed: No video data in response"
  end
end

#embed!(texts:, model:, **opts) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/rails_ai/providers/openai_adapter.rb', line 60

def embed!(texts:, model:, **opts)
  return Array.new(texts.length) { [0.0] * 1536 } if RailsAi.config.stub_responses
  
  # Handle both single and batch embedding requests
  if texts.length == 1
    response = make_request(
      "embeddings",
      {
        model: model,
        input: texts.first,
        **opts
      }
    )
    [response.dig("data", 0, "embedding")]
  else
    response = make_request(
      "embeddings",
      {
        model: model,
        input: texts,
        **opts
      }
    )
    response.dig("data").map { |item| item["embedding"] }
  end
end

#generate_image!(prompt:, model: "dall-e-3", size: "1024x1024", quality: "standard", **opts) ⇒ Object

Image generation - DALL-E 3 and DALL-E 2



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/rails_ai/providers/openai_adapter.rb', line 88

def generate_image!(prompt:, model: "dall-e-3", size: "1024x1024", quality: "standard", **opts)
  return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" if RailsAi.config.stub_responses
  
  response = make_request(
    "images/generations",
    {
      model: model,
      prompt: prompt,
      size: size,
      quality: quality,
      n: opts[:n] || 1,
      response_format: opts[:response_format] || "url",
      **opts.except(:n, :response_format)
    }
  )
  
  # Return the first image URL or base64 data
  image_data = response.dig("data", 0, "url") || response.dig("data", 0, "b64_json")
  if image_data
    if image_data.start_with?("http")
      # Convert URL to base64 for consistency
      convert_url_to_base64(image_data)
    else
      "data:image/png;base64,#{image_data}"
    end
  else
    raise "Image generation failed: No image data in response"
  end
end

#generate_speech!(text:, model: "tts-1", voice: "alloy", **opts) ⇒ Object

Audio generation - TTS models



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/rails_ai/providers/openai_adapter.rb', line 224

def generate_speech!(text:, model: "tts-1", voice: "alloy", **opts)
  return "data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4Ljc2LjEwMAAAAAAAAAAAAAAA//tQxAADB8AhSmAhIIEVWWWU" if RailsAi.config.stub_responses
  
  response = make_request(
    "audio/speech",
    {
      model: model,
      input: text,
      voice: voice,
      response_format: opts[:response_format] || "mp3",
      speed: opts[:speed] || 1.0,
      **opts.except(:response_format, :speed)
    }
  )
  
  # TTS returns binary data, not JSON
  if response.is_a?(String)
    "data:audio/mp3;base64,#{Base64.strict_encode64(response)}"
  else
    raise "Speech generation failed: No audio data in response"
  end
end

#generate_video!(prompt:, model: "sora", duration: 5, **opts) ⇒ Object

Video generation - Sora and other video models



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/rails_ai/providers/openai_adapter.rb', line 173

def generate_video!(prompt:, model: "sora", duration: 5, **opts)
  return "data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAB1tZGF0AQAAARxtYXNrAAAAAG1wNDEAAAAAIG1kYXQ=" if RailsAi.config.stub_responses
  
  response = make_request(
    "video/generations",
    {
      model: model,
      prompt: prompt,
      duration: duration,
      size: opts[:size] || "1280x720",
      quality: opts[:quality] || "standard",
      **opts.except(:size, :quality)
    }
  )
  
  video_data = response.dig("data", 0, "url") || response.dig("data", 0, "b64_json")
  if video_data
    if video_data.start_with?("http")
      convert_url_to_base64(video_data, "video/mp4")
    else
      "data:video/mp4;base64,#{video_data}"
    end
  else
    raise "Video generation failed: No video data in response"
  end
end

#stream_chat!(messages:, model:, **opts, &on_token) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rails_ai/providers/openai_adapter.rb', line 38

def stream_chat!(messages:, model:, **opts, &on_token)
  return on_token.call("(stubbed stream)") if RailsAi.config.stub_responses
  
  make_streaming_request(
    "chat/completions",
    {
      model: model,
      messages: messages,
      max_tokens: opts[:max_tokens] || RailsAi.config.token_limit,
      temperature: opts[:temperature] || 0.7,
      top_p: opts[:top_p] || 1.0,
      frequency_penalty: opts[:frequency_penalty] || 0.0,
      presence_penalty: opts[:presence_penalty] || 0.0,
      stream: true,
      **opts.except(:max_tokens, :temperature, :top_p, :frequency_penalty, :presence_penalty, :stream)
    }
  ) do |chunk|
    text = chunk.dig("choices", 0, "delta", "content")
    on_token.call(text) if text
  end
end

#transcribe_audio!(audio:, model: "whisper-1", **opts) ⇒ Object



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/rails_ai/providers/openai_adapter.rb', line 247

def transcribe_audio!(audio:, model: "whisper-1", **opts)
  return "[stubbed transcription]" if RailsAi.config.stub_responses
  
  form_data = {
    file: prepare_audio_file(audio),
    model: model,
    language: opts[:language],
    prompt: opts[:prompt],
    response_format: opts[:response_format] || "json",
    temperature: opts[:temperature] || 0.0,
    **opts.except(:language, :prompt, :response_format, :temperature)
  }
  
  response = make_form_request("audio/transcriptions", form_data)
  
  if response.is_a?(String)
    response
  else
    response.dig("text")
  end
end