Class: Geminize::Models::ContentRequest

Inherits:
Object
  • Object
show all
Defined in:
lib/geminize/models/content_request.rb,
lib/geminize/models/content_request_safety.rb,
lib/geminize/models/content_request_extensions.rb

Overview

Extends ContentRequest with function calling and JSON mode support

Constant Summary collapse

SUPPORTED_IMAGE_MIME_TYPES =

Supported image MIME types

[
  "image/jpeg",
  "image/png",
  "image/gif",
  "image/webp"
].freeze
MAX_IMAGE_SIZE_BYTES =

Maximum image size in bytes (10MB) Gemini API has limits on image sizes to prevent abuse and ensure performance

10 * 1024 * 1024

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(prompt, model_name = nil, params = {}) ⇒ ContentRequest

Initialize a new content generation request

Parameters:

  • prompt (String)

    The input prompt text

  • model_name (String) (defaults to: nil)

    The model name to use

  • params (Hash) (defaults to: {})

    Additional parameters

Options Hash (params):

  • :temperature (Float)

    Controls randomness (0.0-1.0)

  • :max_tokens (Integer)

    Maximum tokens to generate

  • :top_p (Float)

    Top-p value for nucleus sampling (0.0-1.0)

  • :top_k (Integer)

    Top-k value for sampling

  • :stop_sequences (Array<String>)

    Stop sequences to end generation

  • :system_instruction (String)

    System instruction to guide model behavior



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/geminize/models/content_request.rb', line 62

def initialize(prompt, model_name = nil, params = {})
  # Validate prompt first, before even trying to use it
  validate_prompt!(prompt)

  @prompt = prompt
  @model_name = model_name || Geminize.configuration.default_model
  @temperature = params[:temperature]
  @max_tokens = params[:max_tokens]
  @top_p = params[:top_p]
  @top_k = params[:top_k]
  @stop_sequences = params[:stop_sequences]
  @system_instruction = params[:system_instruction]

  # Initialize content parts with the prompt as the first text part
  @content_parts = []
  add_text(prompt)

  validate!
end

Instance Attribute Details

#content_partsArray<Hash> (readonly)

Returns Content parts for multimodal input.

Returns:

  • (Array<Hash>)

    Content parts for multimodal input



38
39
40
# File 'lib/geminize/models/content_request.rb', line 38

def content_parts
  @content_parts
end

#max_tokensInteger

Returns Maximum tokens to generate.

Returns:

  • (Integer)

    Maximum tokens to generate



23
24
25
# File 'lib/geminize/models/content_request.rb', line 23

def max_tokens
  @max_tokens
end

#model_nameString (readonly)

Returns The model name to use.

Returns:

  • (String)

    The model name to use



17
18
19
# File 'lib/geminize/models/content_request.rb', line 17

def model_name
  @model_name
end

#promptString (readonly)

Gemini API generation parameters

Returns:

  • (String)

    The input prompt text



14
15
16
# File 'lib/geminize/models/content_request.rb', line 14

def prompt
  @prompt
end

#response_mime_typeString?

Returns The MIME type for the response format.

Returns:

  • (String, nil)

    The MIME type for the response format



16
17
18
# File 'lib/geminize/models/content_request_extensions.rb', line 16

def response_mime_type
  @response_mime_type
end

#safety_settingsArray<Geminize::Models::SafetySetting> (readonly)

Returns The safety settings for this request.

Returns:



8
9
10
# File 'lib/geminize/models/content_request_safety.rb', line 8

def safety_settings
  @safety_settings
end

#stop_sequencesArray<String>

Returns Stop sequences to end generation.

Returns:

  • (Array<String>)

    Stop sequences to end generation



32
33
34
# File 'lib/geminize/models/content_request.rb', line 32

def stop_sequences
  @stop_sequences
end

#system_instructionString?

Returns System instruction to guide model behavior.

Returns:

  • (String, nil)

    System instruction to guide model behavior



35
36
37
# File 'lib/geminize/models/content_request.rb', line 35

def system_instruction
  @system_instruction
end

#temperatureFloat

Returns Temperature (controls randomness).

Returns:

  • (Float)

    Temperature (controls randomness)



20
21
22
# File 'lib/geminize/models/content_request.rb', line 20

def temperature
  @temperature
end

#tool_configGeminize::Models::ToolConfig? (readonly)

Returns The tool configuration.

Returns:



13
14
15
# File 'lib/geminize/models/content_request_extensions.rb', line 13

def tool_config
  @tool_config
end

#toolsArray<Geminize::Models::Tool> (readonly)

Returns The tools for this request.

Returns:



10
11
12
# File 'lib/geminize/models/content_request_extensions.rb', line 10

def tools
  @tools
end

#top_kInteger

Returns Top-k value for sampling.

Returns:

  • (Integer)

    Top-k value for sampling



29
30
31
# File 'lib/geminize/models/content_request.rb', line 29

def top_k
  @top_k
end

#top_pFloat

Returns Top-p value for nucleus sampling.

Returns:

  • (Float)

    Top-p value for nucleus sampling



26
27
28
# File 'lib/geminize/models/content_request.rb', line 26

def top_p
  @top_p
end

Instance Method Details

#add_function(name, description, parameters) ⇒ self

Add a function to the request

Parameters:

  • name (String)

    The name of the function

  • description (String)

    A description of what the function does

  • parameters (Hash)

    JSON schema for function parameters

Returns:

  • (self)

    The request object for chaining

Raises:



24
25
26
27
28
29
30
31
32
# File 'lib/geminize/models/content_request_extensions.rb', line 24

def add_function(name, description, parameters)
  @tools ||= []

  function_declaration = FunctionDeclaration.new(name, description, parameters)
  tool = Tool.new(function_declaration)

  @tools << tool
  self
end

#add_image_from_bytes(image_bytes, mime_type) ⇒ self

Add an image to the request from raw bytes

Parameters:

  • image_bytes (String)

    Raw binary image data

  • mime_type (String)

    The MIME type of the image

Returns:

  • (self)

    The request object for chaining

Raises:



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/geminize/models/content_request.rb', line 127

def add_image_from_bytes(image_bytes, mime_type)
  validate_image_bytes!(image_bytes)
  validate_mime_type!(mime_type)

  # Encode the image as base64
  base64_data = Base64.strict_encode64(image_bytes)

  @content_parts << {
    type: "image",
    mime_type: mime_type,
    data: base64_data
  }

  self
end

#add_image_from_file(file_path) ⇒ self

Add an image to the request from a file path

Parameters:

  • file_path (String)

    Path to the image file

Returns:

  • (self)

    The request object for chaining

Raises:



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/geminize/models/content_request.rb', line 95

def add_image_from_file(file_path)
  unless File.exist?(file_path)
    raise Geminize::ValidationError.new(
      "Image file not found: #{file_path}",
      "INVALID_ARGUMENT"
    )
  end

  unless File.file?(file_path)
    raise Geminize::ValidationError.new(
      "Path is not a file: #{file_path}",
      "INVALID_ARGUMENT"
    )
  end

  begin
    image_data = File.binread(file_path)
    mime_type = detect_mime_type(file_path)
    add_image_from_bytes(image_data, mime_type)
  rescue => e
    raise Geminize::ValidationError.new(
      "Error reading image file: #{e.message}",
      "INVALID_ARGUMENT"
    )
  end
end

#add_image_from_url(url) ⇒ self

Add an image to the request from a URL

Parameters:

  • url (String)

    URL of the image

Returns:

  • (self)

    The request object for chaining

Raises:



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/geminize/models/content_request.rb', line 147

def add_image_from_url(url)
  validate_url!(url)

  begin
    # Use Net::HTTP to fetch the image instead of URI.open
    uri = URI.parse(url)
    response = Net::HTTP.get_response(uri)

    # Check for HTTP errors
    unless response.is_a?(Net::HTTPSuccess)
      raise OpenURI::HTTPError.new(response.message, response)
    end

    # Read the response body
    image_data = response.body

    # Try to detect MIME type from URL extension or Content-Type header
    content_type = response["Content-Type"]

    # If Content-Type header exists and is a supported image type, use it
    mime_type = if content_type && SUPPORTED_IMAGE_MIME_TYPES.include?(content_type)
      content_type
    else
      # Otherwise try to detect from URL
      detect_mime_type_from_url(url) || "image/jpeg"
    end

    add_image_from_bytes(image_data, mime_type)
  rescue OpenURI::HTTPError => e
    raise Geminize::ValidationError.new(
      "Error fetching image from URL: HTTP error #{e.message}",
      "INVALID_ARGUMENT"
    )
  rescue => e
    raise Geminize::ValidationError.new(
      "Error fetching image from URL: #{e.message}",
      "INVALID_ARGUMENT"
    )
  end
end

#add_safety_setting(category, threshold) ⇒ self

Add a safety setting to the request

Parameters:

  • category (String)

    The harm category this setting applies to

  • threshold (String)

    The threshold level for filtering

Returns:

  • (self)

    The request object for chaining

Raises:



15
16
17
18
19
20
21
22
# File 'lib/geminize/models/content_request_safety.rb', line 15

def add_safety_setting(category, threshold)
  @safety_settings ||= []

  safety_setting = SafetySetting.new(category, threshold)
  @safety_settings << safety_setting

  self
end

#add_text(text) ⇒ self

Add text content to the request

Parameters:

  • text (String)

    The text to add

Returns:

  • (self)

    The request object for chaining



85
86
87
88
89
# File 'lib/geminize/models/content_request.rb', line 85

def add_text(text)
  Validators.validate_not_empty!(text, "Text content")
  @content_parts << {type: "text", text: text}
  self
end

#block_all_harmful_contentself

Block all harmful content (most conservative setting)

Returns:

  • (self)

    The request object for chaining



40
41
42
# File 'lib/geminize/models/content_request_safety.rb', line 40

def block_all_harmful_content
  set_default_safety_settings("BLOCK_LOW_AND_ABOVE")
end

#block_only_high_risk_contentself

Block only high-risk content (least conservative setting)

Returns:

  • (self)

    The request object for chaining



46
47
48
# File 'lib/geminize/models/content_request_safety.rb', line 46

def block_only_high_risk_content
  set_default_safety_settings("BLOCK_ONLY_HIGH")
end

#disable_json_modeself

Disable JSON mode and return to regular text output

Returns:

  • (self)

    The request object for chaining



60
61
62
63
# File 'lib/geminize/models/content_request_extensions.rb', line 60

def disable_json_mode
  @response_mime_type = nil
  self
end

#enable_code_executionself

Enable code execution for the request

Returns:

  • (self)

    The request object for chaining



36
37
38
39
40
# File 'lib/geminize/models/content_request_extensions.rb', line 36

def enable_code_execution
  @tools ||= []
  @tools << Tool.new(nil, true)
  self
end

#enable_json_modeself

Enable JSON mode for structured output

Returns:

  • (self)

    The request object for chaining



53
54
55
56
# File 'lib/geminize/models/content_request_extensions.rb', line 53

def enable_json_mode
  @response_mime_type = "application/json"
  self
end

#multimodal?Boolean

Check if this request has multimodal content

Returns:

  • (Boolean)

    True if the request contains multiple content types



190
191
192
193
194
195
# File 'lib/geminize/models/content_request.rb', line 190

def multimodal?
  return false if @content_parts.empty?

  # Check if we have any non-text parts or multiple text parts
  @content_parts.any? { |part| part[:type] != "text" } || @content_parts.count > 1
end

#original_validate!Object

Validate method for safety settings - should only be called if not overridden by content_request_extensions.rb If that file's validate! is called, it should also call validate_safety_settings! Original validate! method includes validation for tools and JSON mode



148
149
150
151
152
153
154
155
156
157
# File 'lib/geminize/models/content_request_extensions.rb', line 148

def validate!
  validate_temperature!
  validate_max_tokens!
  validate_top_p!
  validate_top_k!
  validate_stop_sequences!
  validate_content_parts!
  validate_system_instruction!
  true
end

#remove_safety_settingsself

Remove all safety settings (use with caution)

Returns:

  • (self)

    The request object for chaining



52
53
54
55
# File 'lib/geminize/models/content_request_safety.rb', line 52

def remove_safety_settings
  @safety_settings = []
  self
end

#safety_original_to_hashHash

Convert the request to a hash suitable for the API Get the base to_hash method - this will use the one defined in content_request_extensions.rb if available

Returns:

  • (Hash)

    The request as a hash



58
59
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
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/geminize/models/content_request_safety.rb', line 58

def to_hash
  # Map content_parts to the structure the API expects
  api_parts = @content_parts.map do |part|
    if part[:type] == "text"
      {text: part[:text]}
    elsif part[:type] == "image"
      {
        inlineData: {
          mimeType: part[:mime_type],
          data: part[:data]
        }
      }
    else
      # Handle potential future types or raise error
      nil # Or raise an error for unknown part types
    end
  end.compact # Remove any nil parts from unknown types

  request = {
    contents: [
      {
        parts: api_parts # Use the correctly formatted parts
      }
    ],
    generationConfig: generation_config
  }.compact

  # Add system_instruction if provided
  if @system_instruction
    request[:systemInstruction] = {
      parts: [
        {
          text: @system_instruction
        }
      ]
    }
  end

  request
end

#set_default_safety_settings(threshold) ⇒ self

Set default safety settings for all harm categories

Parameters:

  • threshold (String)

    The threshold level to apply to all categories

Returns:

  • (self)

    The request object for chaining

Raises:



28
29
30
31
32
33
34
35
36
# File 'lib/geminize/models/content_request_safety.rb', line 28

def set_default_safety_settings(threshold)
  @safety_settings = []

  SafetySetting::HARM_CATEGORIES.each do |category|
    add_safety_setting(category, threshold)
  end

  self
end

#set_tool_config(execution_mode = "AUTO") ⇒ self

Set the tool config for function execution

Parameters:

  • execution_mode (String) (defaults to: "AUTO")

    The execution mode for functions ("AUTO", "MANUAL", or "NONE")

Returns:

  • (self)

    The request object for chaining

Raises:



46
47
48
49
# File 'lib/geminize/models/content_request_extensions.rb', line 46

def set_tool_config(execution_mode = "AUTO")
  @tool_config = ToolConfig.new(execution_mode)
  self
end

#to_hHash

Alias for to_hash for consistency with Ruby conventions

Returns:

  • (Hash)

    The request as a hash



256
257
258
# File 'lib/geminize/models/content_request.rb', line 256

def to_h
  to_hash
end

#to_hashHash

Override the to_hash method to include additional function calling features

Returns:

  • (Hash)

    The request as a hash



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/geminize/models/content_request.rb', line 213

def to_hash
  # Map content_parts to the structure the API expects
  api_parts = @content_parts.map do |part|
    if part[:type] == "text"
      {text: part[:text]}
    elsif part[:type] == "image"
      {
        inlineData: {
          mimeType: part[:mime_type],
          data: part[:data]
        }
      }
    else
      # Handle potential future types or raise error
      nil # Or raise an error for unknown part types
    end
  end.compact # Remove any nil parts from unknown types

  request = {
    contents: [
      {
        parts: api_parts # Use the correctly formatted parts
      }
    ],
    generationConfig: generation_config
  }.compact

  # Add system_instruction if provided
  if @system_instruction
    request[:systemInstruction] = {
      parts: [
        {
          text: @system_instruction
        }
      ]
    }
  end

  request
end

#validate!Object

Validate method for safety settings - should only be called if not overridden by content_request_extensions.rb If that file's validate! is called, it should also call validate_safety_settings!



200
201
202
203
204
205
206
207
208
209
# File 'lib/geminize/models/content_request.rb', line 200

def validate!
  validate_temperature!
  validate_max_tokens!
  validate_top_p!
  validate_top_k!
  validate_stop_sequences!
  validate_content_parts!
  validate_system_instruction!
  true
end