Module: ActiveAgent::Providers::OpenAI::Chat::Transforms

Defined in:
lib/active_agent/providers/open_ai/chat/transforms.rb

Overview

Provides transformation methods for normalizing chat parameters to OpenAI gem’s native format

Handles message normalization, shorthand formats, instructions mapping, and response format conversion for the Chat Completions API.

Class Method Summary collapse

Class Method Details

.cleanup_serialized_request(hash, defaults, gem_object) ⇒ Hash

Cleans up serialized hash for API request

Removes default values, simplifies messages, and handles special cases like web_search_options (which requires empty hash to enable).

Parameters:

  • hash (Hash)

    serialized request hash

  • defaults (Hash)

    default values to remove

  • gem_object (Object)

    original gem object for checking values

Returns:

  • (Hash)

    cleaned request hash



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 423

def cleanup_serialized_request(hash, defaults, gem_object)
  # Remove default values that shouldn't be in the request body
  defaults.each do |key, value|
    hash.delete(key) if hash[key] == value
  end

  # Simplify messages for cleaner API requests
  hash[:messages] = simplify_messages(hash[:messages]) if hash[:messages]

  # Add web_search_options if present (defaults to empty hash to enable feature)
  if gem_object.instance_variable_get(:@data)[:web_search_options]
    hash[:web_search_options] ||= {}
  end

  hash
end

.content_to_array(content) ⇒ Array<Hash>

Converts content to array format for merging

Parameters:

  • content (String, Array, nil)

Returns:

  • (Array<Hash>)

    content parts with type and text keys



240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 240

def content_to_array(content)
  case content
  when String
    [ { type: "text", text: content } ]
  when Array
    content.map { |part| part.is_a?(String) ? { type: "text", text: part } : part }
  when nil
    []
  else
    [ content ]
  end
end

.create_message_param(role, content, extra_params = {}) ⇒ OpenAI::Models::Chat::ChatCompletionMessageParam

Creates the appropriate gem message param class for the given role

Parameters:

  • role (String)

    message role (developer, system, user, assistant, tool, function)

  • content (String, Array, Hash, nil)
  • extra_params (Hash) (defaults to: {})

    additional parameters (tool_call_id, name, etc.)

Returns:

  • (OpenAI::Models::Chat::ChatCompletionMessageParam)

Raises:

  • (ArgumentError)

    when role is unknown



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 154

def create_message_param(role, content, extra_params = {})
  params = { role: role }
  params[:content] = normalize_content(content) if content
  params.merge!(extra_params)

  case role.to_s
  when "developer"
    ::OpenAI::Models::Chat::ChatCompletionDeveloperMessageParam.new(**params)
  when "system"
    ::OpenAI::Models::Chat::ChatCompletionSystemMessageParam.new(**params)
  when "user"
    ::OpenAI::Models::Chat::ChatCompletionUserMessageParam.new(**params)
  when "assistant"
    ::OpenAI::Models::Chat::ChatCompletionAssistantMessageParam.new(**params)
  when "tool"
    ::OpenAI::Models::Chat::ChatCompletionToolMessageParam.new(**params)
  when "function"
    ::OpenAI::Models::Chat::ChatCompletionFunctionMessageParam.new(**params)
  else
    raise ArgumentError, "Unknown message role: #{role}"
  end
end

.gem_to_hash(gem_object) ⇒ Hash

Converts gem model object to hash via JSON round-trip

Parameters:

  • gem_object (Object)

Returns:

  • (Hash)

    with symbolized keys



20
21
22
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 20

def gem_to_hash(gem_object)
  JSON.parse(gem_object.to_json, symbolize_names: true)
end

.merge_content(content1, content2) ⇒ Array

Merges two content values for consecutive same-role messages

Preserves multiple text parts and mixed content as array structure rather than concatenating strings.

Parameters:

  • content1 (String, Array, nil)
  • content2 (String, Array, nil)

Returns:

  • (Array)

    merged content parts



224
225
226
227
228
229
230
231
232
233
234
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 224

def merge_content(content1, content2)
  # Convert to arrays for consistent handling
  arr1 = content_to_array(content1)
  arr2 = content_to_array(content2)

  merged = arr1 + arr2

  # Keep as array of content parts - don't simplify to string
  # This preserves multiple text parts and mixed content
  merged
end

.normalize_content(content) ⇒ String, ...

Normalizes message content to Chat API format

Parameters:

  • content (String, Array, Hash, nil)

Returns:

  • (String, Array, nil)

Raises:

  • (ArgumentError)

    when content type is invalid



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 182

def normalize_content(content)
  case content
  when String
    content
  when Array
    content.map { |part| normalize_content_part(part) }
  when Hash
    # Single content part as hash - wrap in array
    [ normalize_content_part(content) ]
  when nil
    nil
  else
    raise ArgumentError, "Cannot normalize #{content.class} to content"
  end
end

.normalize_content_part(part) ⇒ Hash

Normalizes a single content part

Converts strings to proper content part format with type and text keys.

Parameters:

  • part (Hash, String)

Returns:

  • (Hash)

    content part with symbolized keys

Raises:

  • (ArgumentError)

    when part type is invalid



205
206
207
208
209
210
211
212
213
214
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 205

def normalize_content_part(part)
  case part
  when Hash
    part.deep_symbolize_keys
  when String
    { type: "text", text: part }
  else
    raise ArgumentError, "Cannot normalize #{part.class} to content part"
  end
end

.normalize_instructions(instructions) ⇒ Array<Hash>

Normalizes instructions to developer message format

Converts instructions into developer messages with proper content structure. Multiple instructions become content parts in a single developer message rather than separate messages.

Parameters:

  • instructions (Array<String>, String)

Returns:

  • (Array<Hash>)

    developer messages



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 398

def normalize_instructions(instructions)
  instructions_array = Array(instructions)

  # Convert multiple instructions into content parts for a single developer message
  if instructions_array.size > 1
    content_parts = instructions_array.map do |instruction|
      { type: "text", text: instruction }
    end
    [ { role: "developer", content: content_parts } ]
  else
    instructions_array.map do |instruction|
      { role: "developer", content: instruction }
    end
  end
end

.normalize_message(message) ⇒ OpenAI::Models::Chat::ChatCompletionMessageParam

Normalizes a single message to proper gem message param class

Handles shorthand formats:

  • ‘“text”` → user message

  • ‘“…”` → user message

  • ‘“system”, text: “…”` → system message

  • ‘“url”` → user message with image content part

  • ‘“…”, image: “url”` → user message with text and image parts

Parameters:

  • message (String, Hash, OpenAI::Models::Chat::ChatCompletionMessageParam)

Returns:

  • (OpenAI::Models::Chat::ChatCompletionMessageParam)


106
107
108
109
110
111
112
113
114
115
116
117
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/active_agent/providers/open_ai/chat/transforms.rb', line 106

def normalize_message(message)
  case message
  when String
    create_message_param("user", message)
  when ::OpenAI::Models::Chat::ChatCompletionMessageParam
    # Already a gem message param - pass through
    message
  when Hash
    msg_hash = message.deep_symbolize_keys
    role = msg_hash[:role]&.to_s || "user"

    # Handle shorthand formats
    content = if msg_hash.key?(:content)
      # Standard format with explicit content
      msg_hash[:content]
    elsif msg_hash.key?(:text) && msg_hash.key?(:image)
      # Shorthand with both text and image: { text: "...", image: "url" }
      [
        { type: "text", text: msg_hash[:text] },
        { type: "image_url", image_url: { url: msg_hash[:image] } }
      ]
    elsif msg_hash.key?(:image)
      # Shorthand with only image: { image: "url" }
      # Text comes from adjacent prompt arguments
      [ { type: "image_url", image_url: { url: msg_hash[:image] } } ]
    elsif msg_hash.key?(:text)
      # Shorthand: { text: "..." } or { role: "...", text: "..." }
      msg_hash[:text]
    else
      # No content specified
      nil
    end

    # Create appropriate message param based on role and content
    extra_params = msg_hash.except(:role, :content, :text, :image)
    create_message_param(role, content, extra_params)
  else
    raise ArgumentError, "Cannot normalize #{message.class} to message"
  end
end

.normalize_messages(messages) ⇒ Array<OpenAI::Models::Chat::ChatCompletionMessageParam>?

Normalizes messages to OpenAI Chat API format using gem message classes

Handles various input formats:

  • ‘“text”` → UserMessageParam

  • ‘[“user”, content: “…”]` → array of message params

  • Merges consecutive same-role messages into single message

Parameters:

  • messages (Array, String, Hash, nil)

Returns:

  • (Array<OpenAI::Models::Chat::ChatCompletionMessageParam>, nil)


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 65

def normalize_messages(messages)
  case messages
  when String
    [ create_message_param("user", messages) ]
  when Hash
    [ normalize_message(messages) ]
  when Array
    grouped = []

    messages.each do |msg|
      normalized = normalize_message(msg)

      # Don't merge tool messages - each needs its own tool_call_id
      if grouped.empty? || grouped.last.role != normalized.role || normalized.role.to_s == "tool"
        grouped << normalized
      else
        # Merge consecutive same-role messages
        merged_content = merge_content(grouped.last.content, normalized.content)
        grouped[-1] = create_message_param(grouped.last.role, merged_content)
      end
    end

    grouped
  when nil
    nil
  else
    raise ArgumentError, "Cannot normalize #{messages.class} to messages array"
  end
end

.normalize_params(params) ⇒ Hash

Normalizes all request parameters for OpenAI Chat API

Handles instructions mapping to developer messages, message normalization, tools normalization, and response_format conversion. This is the main entry point for parameter transformation.

Parameters:

  • params (Hash)

Returns:

  • (Hash)

    normalized parameters



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 32

def normalize_params(params)
  params = params.dup

  # Map common format 'instructions' to developer messages
  if params.key?(:instructions)
    instructions_messages = normalize_instructions(params.delete(:instructions))
    params[:messages] = instructions_messages + Array(params[:messages] || [])
  end

  # Normalize messages for gem compatibility
  params[:messages] = normalize_messages(params[:messages]) if params[:messages]

  # Normalize tools from common format to Chat API format
  params[:tools] = normalize_tools(params[:tools]) if params[:tools]

  # Normalize tool_choice from common format
  params[:tool_choice] = normalize_tool_choice(params[:tool_choice]) if params[:tool_choice]

  # Normalize response_format if present
  params[:response_format] = normalize_response_format(params[:response_format]) if params[:response_format]

  params
end

.normalize_response_format(format) ⇒ Hash

Normalizes response_format to OpenAI Chat API format

Parameters:

  • format (Hash, Symbol, String)

Returns:

  • (Hash)

    normalized response format



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 287

def normalize_response_format(format)
  case format
  when Hash
    format_hash = format.deep_symbolize_keys

    if format_hash[:type] == "json_schema" || format_hash[:type] == :json_schema
      # json_schema format
      {
        type: "json_schema",
        json_schema: {
          name: format_hash[:name] || format_hash[:json_schema]&.dig(:name),
          schema: format_hash[:schema] || format_hash[:json_schema]&.dig(:schema),
          strict: format_hash[:strict] || format_hash[:json_schema]&.dig(:strict)
        }.compact
      }
    elsif format_hash[:type]
      # Other type formats (json_object, text, etc.)
      { type: format_hash[:type].to_s }
    else
      # Pass through (already properly structured or complex)
      format_hash
    end
  when Symbol, String
    # Simple string type
    { type: format.to_s }
  else
    format
  end
end

.normalize_tool_choice(tool_choice) ⇒ String, ...

Normalizes tool_choice from common format to OpenAI Chat API format.

Accepts:

  • “auto” (common) → “auto” (passthrough)

  • “required” (common) → “required” (passthrough)

  • ‘“…”` (common) → `“function”, function: {name: “…”}`

  • Already nested format → passthrough

Parameters:

  • tool_choice (String, Hash, Symbol)

Returns:

  • (String, Hash, Symbol)


363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 363

def normalize_tool_choice(tool_choice)
  case tool_choice
  when "auto", :auto, "required", :required
    # Passthrough - Chat API accepts these directly
    tool_choice.to_s
  when Hash
    tool_choice_hash = tool_choice.deep_symbolize_keys

    # Already in nested format with type and function keys
    if tool_choice_hash[:type] == "function" && tool_choice_hash[:function]
      tool_choice_hash
    # Common format with just name - convert to nested format
    elsif tool_choice_hash[:name]
      {
        type: "function",
        function: {
          name: tool_choice_hash[:name]
        }
      }
    else
      tool_choice_hash
    end
  else
    tool_choice
  end
end

.normalize_tools(tools) ⇒ Array<Hash>

Normalizes tools from common format to OpenAI Chat API format.

Accepts tools in multiple formats:

  • Common format: ‘“…”, description: “…”, parameters: {…}`

  • Common format alt: ‘“…”, description: “…”, input_schema: {…}`

  • Nested format: ‘“function”, function: {name: “…”, parameters: {…}}`

Always outputs nested Chat API format: ‘“function”, function: {…}`

Parameters:

  • tools (Array<Hash>)

Returns:

  • (Array<Hash>)


328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 328

def normalize_tools(tools)
  return tools unless tools.is_a?(Array)

  tools.map do |tool|
    tool_hash = tool.is_a?(Hash) ? tool.deep_symbolize_keys : tool

    # Already in nested format - return as is
    if tool_hash[:type] == "function" && tool_hash[:function]
      tool_hash
    # Common format - convert to nested format
    elsif tool_hash[:name]
      {
        type: "function",
        function: {
          name: tool_hash[:name],
          description: tool_hash[:description],
          parameters: tool_hash[:parameters] || tool_hash[:input_schema]
        }.compact
      }
    else
      tool_hash
    end
  end
end

.simplify_messages(messages) ⇒ Array<Hash>

Simplifies messages for cleaner API requests

Converts gem message objects to hashes and simplifies content:

  • Single text content arrays → strings

  • Empty content arrays → removed

Parameters:

  • messages (Array)

Returns:

  • (Array<Hash>)


261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/active_agent/providers/open_ai/chat/transforms.rb', line 261

def simplify_messages(messages)
  return messages unless messages.is_a?(Array)

  messages.map do |msg|
    # Convert to hash if it's a gem object
    simplified = msg.is_a?(Hash) ? msg.dup : gem_to_hash(msg)

    # Simplify content if it's a single text part
    if simplified[:content].is_a?(Array) && simplified[:content].size == 1
      part = simplified[:content][0]
      if part.is_a?(Hash) && part[:type] == "text" && part.keys.sort == [ :text, :type ]
        simplified[:content] = part[:text]
      end
    end

    # Remove empty content arrays
    simplified.delete(:content) if simplified[:content] == []

    simplified
  end
end