Module: Raif::Concerns::Llms::OpenAiResponses::ResponseToolCalls

Extended by:
ActiveSupport::Concern
Included in:
Llms::OpenAiResponses
Defined in:
app/models/raif/concerns/llms/open_ai_responses/response_tool_calls.rb

Instance Method Summary collapse

Instance Method Details

#extract_response_tool_calls(resp) ⇒ Object



6
7
8
9
10
11
12
13
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
# File 'app/models/raif/concerns/llms/open_ai_responses/response_tool_calls.rb', line 6

def extract_response_tool_calls(resp)
  return if resp["output"].blank?

  tool_calls = []
  preceding_reasoning = []
  resp["output"].each do |output_item|
    if output_item["type"] == "reasoning"
      preceding_reasoning << output_item if output_item["encrypted_content"].present?
      next
    end

    unless output_item["type"] == "function_call"
      # OpenAI rejects a replayed reasoning item without the item that followed it.
      # Only function calls are replayed, so reasoning that led to anything else is dropped.
      preceding_reasoning = []
      next
    end

    tool_call = {
      "provider_tool_call_id" => output_item["call_id"],
      "name" => output_item["name"],
      "arguments" => begin
        JSON.parse(output_item["arguments"])
      rescue JSON::ParserError
        output_item["arguments"]
      end
    }
    if preceding_reasoning.any?
      # OpenAI pairs a reasoning item with the original item that followed it, so the call keeps its own id and status.
      tool_call["provider_metadata"] = {
        "reasoning_items" => preceding_reasoning,
        "item_id" => output_item["id"],
        "item_status" => output_item["status"]
      }.compact
    end
    preceding_reasoning = []

    tool_calls << tool_call
  end

  tool_calls.any? ? tool_calls : nil
end