Class: Geminize::Models::ContentRequest
- Inherits:
-
Object
- Object
- Geminize::Models::ContentRequest
- 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
-
#content_parts ⇒ Array<Hash>
readonly
Content parts for multimodal input.
-
#max_tokens ⇒ Integer
Maximum tokens to generate.
-
#model_name ⇒ String
readonly
The model name to use.
-
#prompt ⇒ String
readonly
Gemini API generation parameters.
-
#response_mime_type ⇒ String?
The MIME type for the response format.
-
#safety_settings ⇒ Array<Geminize::Models::SafetySetting>
readonly
The safety settings for this request.
-
#stop_sequences ⇒ Array<String>
Stop sequences to end generation.
-
#system_instruction ⇒ String?
System instruction to guide model behavior.
-
#temperature ⇒ Float
Temperature (controls randomness).
-
#tool_config ⇒ Geminize::Models::ToolConfig?
readonly
The tool configuration.
-
#tools ⇒ Array<Geminize::Models::Tool>
readonly
The tools for this request.
-
#top_k ⇒ Integer
Top-k value for sampling.
-
#top_p ⇒ Float
Top-p value for nucleus sampling.
Instance Method Summary collapse
-
#add_function(name, description, parameters) ⇒ self
Add a function to the request.
-
#add_image_from_bytes(image_bytes, mime_type) ⇒ self
Add an image to the request from raw bytes.
-
#add_image_from_file(file_path) ⇒ self
Add an image to the request from a file path.
-
#add_image_from_url(url) ⇒ self
Add an image to the request from a URL.
-
#add_safety_setting(category, threshold) ⇒ self
Add a safety setting to the request.
-
#add_text(text) ⇒ self
Add text content to the request.
-
#block_all_harmful_content ⇒ self
Block all harmful content (most conservative setting).
-
#block_only_high_risk_content ⇒ self
Block only high-risk content (least conservative setting).
-
#disable_json_mode ⇒ self
Disable JSON mode and return to regular text output.
-
#enable_code_execution ⇒ self
Enable code execution for the request.
-
#enable_json_mode ⇒ self
Enable JSON mode for structured output.
-
#initialize(prompt, model_name = nil, params = {}) ⇒ ContentRequest
constructor
Initialize a new content generation request.
-
#multimodal? ⇒ Boolean
Check if this request has multimodal content.
-
#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.
-
#remove_safety_settings ⇒ self
Remove all safety settings (use with caution).
-
#safety_original_to_hash ⇒ Hash
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.
-
#set_default_safety_settings(threshold) ⇒ self
Set default safety settings for all harm categories.
-
#set_tool_config(execution_mode = "AUTO") ⇒ self
Set the tool config for function execution.
-
#to_h ⇒ Hash
Alias for to_hash for consistency with Ruby conventions.
-
#to_hash ⇒ Hash
Override the to_hash method to include additional function calling features.
-
#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!.
Constructor Details
#initialize(prompt, model_name = nil, params = {}) ⇒ ContentRequest
Initialize a new content generation request
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_parts ⇒ Array<Hash> (readonly)
Returns Content parts for multimodal input.
38 39 40 |
# File 'lib/geminize/models/content_request.rb', line 38 def content_parts @content_parts end |
#max_tokens ⇒ Integer
Returns Maximum tokens to generate.
23 24 25 |
# File 'lib/geminize/models/content_request.rb', line 23 def max_tokens @max_tokens end |
#model_name ⇒ String (readonly)
Returns The model name to use.
17 18 19 |
# File 'lib/geminize/models/content_request.rb', line 17 def model_name @model_name end |
#prompt ⇒ String (readonly)
Gemini API generation parameters
14 15 16 |
# File 'lib/geminize/models/content_request.rb', line 14 def prompt @prompt end |
#response_mime_type ⇒ String?
Returns 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_settings ⇒ Array<Geminize::Models::SafetySetting> (readonly)
Returns The safety settings for this request.
8 9 10 |
# File 'lib/geminize/models/content_request_safety.rb', line 8 def safety_settings @safety_settings end |
#stop_sequences ⇒ Array<String>
Returns Stop sequences to end generation.
32 33 34 |
# File 'lib/geminize/models/content_request.rb', line 32 def stop_sequences @stop_sequences end |
#system_instruction ⇒ String?
Returns System instruction to guide model behavior.
35 36 37 |
# File 'lib/geminize/models/content_request.rb', line 35 def system_instruction @system_instruction end |
#temperature ⇒ Float
Returns Temperature (controls randomness).
20 21 22 |
# File 'lib/geminize/models/content_request.rb', line 20 def temperature @temperature end |
#tool_config ⇒ Geminize::Models::ToolConfig? (readonly)
Returns The tool configuration.
13 14 15 |
# File 'lib/geminize/models/content_request_extensions.rb', line 13 def tool_config @tool_config end |
#tools ⇒ Array<Geminize::Models::Tool> (readonly)
Returns The tools for this request.
10 11 12 |
# File 'lib/geminize/models/content_request_extensions.rb', line 10 def tools @tools end |
#top_k ⇒ Integer
Returns Top-k value for sampling.
29 30 31 |
# File 'lib/geminize/models/content_request.rb', line 29 def top_k @top_k end |
#top_p ⇒ Float
Returns 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
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
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
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.}", "INVALID_ARGUMENT" ) end end |
#add_image_from_url(url) ⇒ self
Add an image to the request from a URL
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., 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.}", "INVALID_ARGUMENT" ) rescue => e raise Geminize::ValidationError.new( "Error fetching image from URL: #{e.}", "INVALID_ARGUMENT" ) end end |
#add_safety_setting(category, threshold) ⇒ self
Add a safety setting to the request
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
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_content ⇒ self
Block all harmful content (most conservative setting)
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_content ⇒ self
Block only high-risk content (least conservative setting)
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_mode ⇒ self
Disable JSON mode and return to regular text output
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_execution ⇒ self
Enable code execution for the request
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_mode ⇒ self
Enable JSON mode for structured output
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
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_settings ⇒ self
Remove all safety settings (use with caution)
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_hash ⇒ Hash
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
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
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
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_h ⇒ Hash
Alias for to_hash for consistency with Ruby conventions
256 257 258 |
# File 'lib/geminize/models/content_request.rb', line 256 def to_h to_hash end |
#to_hash ⇒ Hash
Override the to_hash method to include additional function calling features
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 |