# config/initializers/langchain_vertex_patch.rb

# Force Gemini to return only one tool call per turn by truncating the parts array.
# Gemini does not support parallel tool calls and langchainrb 0.19.5 doesn't handle this.
module Langchain
  module LLM
    class GoogleGeminiResponse < BaseResponse
      def tool_calls
        parts = raw_response.dig("candidates", 0, "content", "parts")
        return [] if parts.nil?
        return [] unless parts.first&.key?("functionCall")

        # Only return the first tool call — Gemini can't handle parallel responses
        [parts.first]
      end
    end
  end
end

# Fix build_tool_config to emit mode: "ANY" without allowed_function_names,
# which tells Gemini to pick any single function sequentially.
module Langchain
  class Assistant
    module LLM
      module Adapters
        class GoogleGemini < Base
          private

          def build_tool_config(choice)
            case choice
            when "auto"
              { function_calling_config: { mode: "AUTO" } }
            when "none"
              { function_calling_config: { mode: "NONE" } }
            else
              { function_calling_config: { mode: "AUTO" } }
            end
          end
        end
      end
    end
  end
end
