Module: Geminize

Defined in:
lib/geminize.rb,
lib/geminize/chat.rb,
lib/geminize/client.rb,
lib/geminize/errors.rb,
lib/geminize/version.rb,
lib/geminize/embeddings.rb,
lib/geminize/model_info.rb,
lib/geminize/validators.rb,
lib/geminize/models/tool.rb,
lib/geminize/error_mapper.rb,
lib/geminize/error_parser.rb,
lib/geminize/models/model.rb,
lib/geminize/vector_utils.rb,
lib/geminize/configuration.rb,
lib/geminize/models/memory.rb,
lib/geminize/models/message.rb,
lib/geminize/request_builder.rb,
lib/geminize/text_generation.rb,
lib/geminize/models/model_list.rb,
lib/geminize/models/tool_config.rb,
lib/geminize/models/chat_request.rb,
lib/geminize/models/conversation.rb,
lib/geminize/conversation_service.rb,
lib/geminize/models/chat_response.rb,
lib/geminize/models/safety_setting.rb,
lib/geminize/models/content_request.rb,
lib/geminize/models/stream_response.rb,
lib/geminize/conversation_repository.rb,
lib/geminize/models/content_response.rb,
lib/geminize/middleware/error_handler.rb,
lib/geminize/models/embedding_request.rb,
lib/geminize/models/function_response.rb,
lib/geminize/models/embedding_response.rb,
lib/geminize/models/function_declaration.rb,
lib/geminize/models/content_request_safety.rb,
lib/geminize/models/content_request_extensions.rb,
lib/geminize/models/content_response_extensions.rb,
lib/geminize/models/code_execution/executable_code.rb,
lib/geminize/models/code_execution/code_execution_result.rb

Overview

Main module for the Geminize gem

Defined Under Namespace

Modules: Middleware, Models, RequestBuilder, Validators, VectorUtils Classes: AuthenticationError, BadRequestError, Chat, Client, Configuration, ConfigurationError, ContentBlockedError, ConversationRepository, ConversationService, Embeddings, Error, ErrorMapper, ErrorParser, FileConversationRepository, GeminizeError, InvalidModelError, InvalidStreamFormatError, MemoryConversationRepository, ModelInfo, NotFoundError, RateLimitError, RequestError, ResourceNotFoundError, ServerError, StreamingError, StreamingInterruptedError, StreamingTimeoutError, TextGeneration, ValidationError

Constant Summary collapse

VERSION =
"1.3.1"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.last_streaming_generatorGeminize::TextGeneration?

Track the last streaming generator for cancellation support

Returns:



75
76
77
# File 'lib/geminize.rb', line 75

def last_streaming_generator
  @last_streaming_generator
end

Class Method Details

.average_vectors(vectors) ⇒ Array<Float>

Average multiple vectors

Parameters:

  • vectors (Array<Array<Float>>)

    Array of vectors

Returns:

  • (Array<Float>)

    Average vector

Raises:



374
375
376
# File 'lib/geminize.rb', line 374

def average_vectors(vectors)
  VectorUtils.average_vectors(vectors)
end

.cancel_streamingBoolean

Cancel the current streaming operation, if any

Returns:

  • (Boolean)

    true if a streaming operation was cancelled, false if none was in progress



79
80
81
82
83
# File 'lib/geminize.rb', line 79

def cancel_streaming
  return false unless last_streaming_generator

  last_streaming_generator.cancel_streaming
end

.chat(message, chat = nil, model_name = nil, params = {}) ⇒ Hash

Send a message in an existing chat or create a new one

Examples:

Send a message with a system instruction

Geminize.chat("Tell me a joke", nil, nil, system_instruction: "You are a comedian. Be funny.")

Parameters:

  • message (String)

    The message to send

  • chat (Geminize::Chat, nil) (defaults to: nil)

    An existing chat or nil to create a new one

  • model_name (String, nil) (defaults to: nil)

    The model to use (optional)

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

    Additional generation 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

  • :client_options (Hash)

    Options to pass to the client

Returns:

  • (Hash)

    The chat response and updated chat instance

Raises:



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/geminize.rb', line 406

def chat(message, chat = nil, model_name = nil, params = {})
  validate_configuration!

  # Extract client options
  client_options = params.delete(:client_options) || {}

  # Extract system instruction for new chat creation
  system_instruction = params[:system_instruction]

  # Create or use existing chat
  chat_instance = chat || create_chat(nil, system_instruction, client_options)

  # Send the message
  response = chat_instance.send_message(
    message,
    model_name || configuration.default_model,
    params
  )

  {
    response: response,
    chat: chat_instance
  }
end

.configurationGeminize::Configuration



92
93
94
# File 'lib/geminize.rb', line 92

def configuration
  Configuration.instance
end

.configure {|config| ... } ⇒ Object

Configure the gem

Examples:

Geminize.configure do |config|
  config.api_key = "your-api-key"
  config.api_version = "v1beta"
  config.default_model = "gemini-2.0-flash"
end

Yields:

  • (config)

    Configuration object that can be modified



104
105
106
107
# File 'lib/geminize.rb', line 104

def configure
  yield(configuration) if block_given?
  configuration
end

.conversation_repositoryGeminize::ConversationRepository

Default conversation repository



59
60
61
# File 'lib/geminize.rb', line 59

def conversation_repository
  @conversation_repository ||= FileConversationRepository.new
end

.conversation_repository=(repository) ⇒ Object

Set the conversation repository

Parameters:



65
66
67
68
69
70
71
# File 'lib/geminize.rb', line 65

def conversation_repository=(repository)
  unless repository.is_a?(ConversationRepository)
    raise ArgumentError, "Expected a ConversationRepository, got #{repository.class}"
  end

  @conversation_repository = repository
end

.conversation_serviceGeminize::ConversationService

Default conversation service



87
88
89
# File 'lib/geminize.rb', line 87

def conversation_service
  @conversation_service ||= ConversationService.new
end

.cosine_similarity(vec1, vec2) ⇒ Float

Calculate cosine similarity between two vectors

Parameters:

  • vec1 (Array<Float>)

    First vector

  • vec2 (Array<Float>)

    Second vector

Returns:

  • (Float)

    Cosine similarity (-1 to 1)

Raises:



350
351
352
# File 'lib/geminize.rb', line 350

def cosine_similarity(vec1, vec2)
  VectorUtils.cosine_similarity(vec1, vec2)
end

.create_chat(title = nil, system_instruction = nil, client_options = {}) ⇒ Geminize::Chat

Create a new chat conversation

Examples:

Create a chat with a system instruction

chat = Geminize.create_chat("Pirate Chat", "You are a pirate named Captain Codebeard. Always respond in pirate language.")

Parameters:

  • title (String, nil) (defaults to: nil)

    Optional title for the conversation

  • system_instruction (String, nil) (defaults to: nil)

    Optional system instruction to guide model behavior

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

    Options to pass to the client

Returns:



385
386
387
388
# File 'lib/geminize.rb', line 385

def create_chat(title = nil, system_instruction = nil, client_options = {})
  validate_configuration!
  Chat.new_conversation(title, system_instruction)
end

.create_managed_conversation(title = nil, system_instruction = nil) ⇒ Hash

Create a managed conversation

Examples:

Create a managed conversation with a system instruction

Geminize.create_managed_conversation("Pirate Chat", "You are a pirate. Respond in pirate language.")

Parameters:

  • title (String, nil) (defaults to: nil)

    Optional title for the conversation

  • system_instruction (String, nil) (defaults to: nil)

    Optional system instruction to guide model behavior

Returns:

  • (Hash)

    The created conversation data including ID



464
465
466
467
# File 'lib/geminize.rb', line 464

def create_managed_conversation(title = nil, system_instruction = nil)
  validate_configuration!
  conversation_service.create_conversation(title, system_instruction)
end

.delete_conversation(id) ⇒ Boolean

Delete a conversation by ID

Parameters:

  • id (String)

    The ID of the conversation to delete

Returns:

  • (Boolean)

    True if the deletion was successful



448
449
450
# File 'lib/geminize.rb', line 448

def delete_conversation(id)
  conversation_repository.delete(id)
end

.euclidean_distance(vec1, vec2) ⇒ Float

Calculate Euclidean distance between two vectors

Parameters:

  • vec1 (Array<Float>)

    First vector

  • vec2 (Array<Float>)

    Second vector

Returns:

  • (Float)

    Euclidean distance

Raises:



359
360
361
# File 'lib/geminize.rb', line 359

def euclidean_distance(vec1, vec2)
  VectorUtils.euclidean_distance(vec1, vec2)
end

.generate_embedding(text, model_name = nil, params = {}) ⇒ Geminize::Models::EmbeddingResponse

Generate embeddings from text using the Gemini API

Examples:

Generate embeddings for a single text

Geminize.generate_embedding("This is a sample text")

Generate embeddings for multiple texts

Geminize.generate_embedding(["First text", "Second text", "Third text"])

Generate embeddings with specific dimensions

Geminize.generate_embedding("Sample text", "embedding-001", dimensions: 768)

Process large batches with custom batch size

Geminize.generate_embedding(large_text_array, nil, batch_size: 50)

Parameters:

  • text (String, Array<String>)

    The input text or array of texts

  • model_name (String, nil) (defaults to: nil)

    The model to use (optional)

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

    Additional generation parameters

Options Hash (params):

  • :dimensions (Integer)

    Desired dimensionality of the embeddings

  • :task_type (String)

    The embedding task type

  • :with_retries (Boolean)

    Enable retries for transient errors (default: true)

  • :max_retries (Integer)

    Maximum retry attempts (default: 3)

  • :retry_delay (Float)

    Initial delay between retries in seconds (default: 1.0)

  • :batch_size (Integer)

    Maximum number of texts to process in one batch (default: 100)

  • :client_options (Hash)

    Options to pass to the client

Returns:

Raises:



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/geminize.rb', line 313

def generate_embedding(text, model_name = nil, params = {})
  validate_configuration!

  # Extract special options
  with_retries = params.delete(:with_retries) != false # Default to true
  max_retries = params.delete(:max_retries) || 3
  retry_delay = params.delete(:retry_delay) || 1.0
  client_options = params.delete(:client_options) || {}

  # Create the embeddings generator
  generator = Embeddings.new(nil, client_options)

  # Create the embedding request - batch processing is handled in the generator
  if with_retries
    # Implement retry logic for embeddings
    retries = 0
    begin
      generator.generate_embedding(text, model_name || configuration.default_embedding_model, params)
    rescue Geminize::RateLimitError, Geminize::ServerError => e
      if retries < max_retries
        retries += 1
        sleep retry_delay * retries # Exponential backoff
        retry
      else
        raise e
      end
    end
  else
    generator.generate_embedding(text, model_name || configuration.default_embedding_model, params)
  end
end

.generate_json(prompt, model_name = nil, params = {}, with_retries: true, max_retries: 3, retry_delay: 1.0, client_options: nil) ⇒ Geminize::Models::ContentResponse

Generate JSON output from a prompt using the Gemini API

Examples:

Generate JSON output

response = Geminize.generate_json(
  "List 3 planets with their diameter",
  nil,
  system_instruction: "Return the information as a JSON array"
)
planets = response.json_response # Returns parsed JSON

Parameters:

  • prompt (String)

    The input prompt

  • model_name (String, nil) (defaults to: nil)

    The model to use, defaults to the configured default model

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

    Additional parameters for generation

  • with_retries (Boolean) (defaults to: true)

    Whether to retry the generation if it fails

  • max_retries (Integer) (defaults to: 3)

    Maximum number of retries

  • retry_delay (Float) (defaults to: 1.0)

    Delay between retries in seconds

  • client_options (Hash) (defaults to: nil)

    Options for the HTTP client

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

  • :json_schema (Hash)

    Schema for the JSON output (optional)

Returns:

Raises:



841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
# File 'lib/geminize.rb', line 841

def generate_json(prompt, model_name = nil, params = {}, with_retries: true, max_retries: 3, retry_delay: 1.0, client_options: nil)
  validate_configuration!

  # Initialize the generator
  client = client_options ? Client.new(client_options) : Client.new
  generator = TextGeneration.new(client)

  # Set up params with defaults
  generation_params = params.dup
  with_retries = generation_params.delete(:with_retries) != false if generation_params.key?(:with_retries)

  # Enhance the system instruction for JSON output
  generation_params[:system_instruction] ||= ""
  generation_params[:system_instruction] = "You must respond with valid JSON only, with no explanation or other text. " + generation_params[:system_instruction]

  # Create the request
  content_request = Models::ContentRequest.new(
    prompt,
    model_name || configuration.default_model,
    generation_params
  )

  # Enable JSON mode
  content_request.enable_json_mode

  # Generate the response
  if with_retries
    generator.generate_with_retries(content_request, max_retries, retry_delay)
  else
    generator.generate(content_request)
  end
end

.generate_text(prompt, model_name = nil, params = {}) ⇒ Geminize::Models::ContentResponse

Generate text from a prompt using the Gemini API

Examples:

Generate text with a system instruction

Geminize.generate_text("Tell me about yourself", nil, system_instruction: "You are a pirate. Respond in pirate language.")

Parameters:

  • prompt (String)

    The input prompt

  • model_name (String, nil) (defaults to: nil)

    The model to use (optional)

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

    Additional generation 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

  • :with_retries (Boolean)

    Enable retries for transient errors (default: true)

  • :max_retries (Integer)

    Maximum retry attempts (default: 3)

  • :retry_delay (Float)

    Initial delay between retries in seconds (default: 1.0)

  • :client_options (Hash)

    Options to pass to the client

Returns:

Raises:



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/geminize.rb', line 139

def generate_text(prompt, model_name = nil, params = {})
  validate_configuration!

  # Extract special options
  with_retries = params.delete(:with_retries) != false # Default to true
  max_retries = params.delete(:max_retries) || 3
  retry_delay = params.delete(:retry_delay) || 1.0
  client_options = params.delete(:client_options) || {}

  # Create the generator and content request
  generator = TextGeneration.new(nil, client_options)
  content_request = Models::ContentRequest.new(
    prompt,
    model_name || configuration.default_model,
    params
  )

  # Generate with or without retries
  if with_retries
    generator.generate_with_retries(content_request, max_retries, retry_delay)
  else
    generator.generate(content_request)
  end
end

.generate_text_multimodal(prompt, images, model_name = nil, params = {}) ⇒ Geminize::Models::ContentResponse

Generate content with both text and images using the Gemini API

Examples:

Generate with an image file

Geminize.generate_text_multimodal("Describe this image", [{source_type: 'file', data: 'path/to/image.jpg'}])

Generate with multiple images

Geminize.generate_text_multimodal("Compare these images", [
  {source_type: 'file', data: 'path/to/image1.jpg'},
  {source_type: 'url', data: 'https://example.com/image2.jpg'}
])

Parameters:

  • prompt (String)

    The input prompt text

  • images (Array<Hash>)

    Array of image data hashes

  • model_name (String, nil) (defaults to: nil)

    The model to use (optional)

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

    Additional generation parameters

Options Hash (images):

  • :source_type (Hash)

    Source type for image ('file', 'bytes', or 'url')

  • :data (String)

    File path, raw bytes, or URL depending on source_type

  • :mime_type (String)

    MIME type for the image (optional for file and url)

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

  • :with_retries (Boolean)

    Enable retries for transient errors (default: true)

  • :max_retries (Integer)

    Maximum retry attempts (default: 3)

  • :retry_delay (Float)

    Initial delay between retries in seconds (default: 1.0)

  • :client_options (Hash)

    Options to pass to the client

Returns:

Raises:



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/geminize.rb', line 190

def generate_text_multimodal(prompt, images, model_name = nil, params = {})
  validate_configuration!

  # Extract special options
  with_retries = params.delete(:with_retries) != false # Default to true
  max_retries = params.delete(:max_retries) || 3
  retry_delay = params.delete(:retry_delay) || 1.0
  client_options = params.delete(:client_options) || {}

  # Create the generator
  generator = TextGeneration.new(nil, client_options)

  # Create a content request first
  content_request = Models::ContentRequest.new(
    prompt,
    model_name || configuration.default_model,
    params
  )

  # Add each image to the request
  images.each do |image|
    case image[:source_type]
    when "file"
      content_request.add_image_from_file(image[:data])
    when "bytes"
      content_request.add_image_from_bytes(image[:data], image[:mime_type])
    when "url"
      content_request.add_image_from_url(image[:data])
    else
      raise Geminize::ValidationError.new(
        "Invalid image source type: #{image[:source_type]}. Must be 'file', 'bytes', or 'url'",
        "INVALID_ARGUMENT"
      )
    end
  end

  # Generate with or without retries
  if with_retries
    generator.generate_with_retries(content_request, max_retries, retry_delay)
  else
    generator.generate(content_request)
  end
end

.generate_text_permissive(prompt, model_name = nil, params = {}) ⇒ Geminize::Models::ContentResponse

Generate text with minimum safety (blocks only high-risk content)

Examples:

Generate text with minimum safety

Geminize.generate_text_permissive("Tell me about conflicts", nil, temperature: 0.7)

Parameters:

  • prompt (String)

    The input prompt

  • model_name (String, nil) (defaults to: nil)

    The model to use (optional)

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

    Additional generation parameters

Returns:

Raises:



695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# File 'lib/geminize.rb', line 695

def generate_text_permissive(prompt, model_name = nil, params = {})
  validate_configuration!

  # Extract special options
  with_retries = params.delete(:with_retries) != false # Default to true
  max_retries = params.delete(:max_retries) || 3
  retry_delay = params.delete(:retry_delay) || 1.0
  client_options = params.delete(:client_options) || {}

  # Create the generator and content request
  generator = TextGeneration.new(nil, client_options)
  content_request = Models::ContentRequest.new(
    prompt,
    model_name || configuration.default_model,
    params
  )

  # Set minimum safety (block only high risk)
  content_request.block_only_high_risk_content

  # Generate with or without retries
  if with_retries
    generator.generate_with_retries(content_request, max_retries, retry_delay)
  else
    generator.generate(content_request)
  end
end

.generate_text_safe(prompt, model_name = nil, params = {}) ⇒ Geminize::Models::ContentResponse

Generate text with maximum safety (blocks most potentially harmful content)

Examples:

Generate text with maximum safety

Geminize.generate_text_safe("Tell me about conflicts", nil, temperature: 0.7)

Parameters:

  • prompt (String)

    The input prompt

  • model_name (String, nil) (defaults to: nil)

    The model to use (optional)

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

    Additional generation parameters

Returns:

Raises:



659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
# File 'lib/geminize.rb', line 659

def generate_text_safe(prompt, model_name = nil, params = {})
  validate_configuration!

  # Extract special options
  with_retries = params.delete(:with_retries) != false # Default to true
  max_retries = params.delete(:max_retries) || 3
  retry_delay = params.delete(:retry_delay) || 1.0
  client_options = params.delete(:client_options) || {}

  # Create the generator and content request
  generator = TextGeneration.new(nil, client_options)
  content_request = Models::ContentRequest.new(
    prompt,
    model_name || configuration.default_model,
    params
  )

  # Set maximum safety (block low and above)
  content_request.block_all_harmful_content

  # Generate with or without retries
  if with_retries
    generator.generate_with_retries(content_request, max_retries, retry_delay)
  else
    generator.generate(content_request)
  end
end

.generate_text_stream(prompt, model_name = nil, params = {}) {|chunk| ... }

This method returns an undefined value.

Generate streaming text from a prompt using the Gemini API

Examples:

Stream text with a system instruction

Geminize.generate_text_stream(
  "Tell me a story",
  nil,
  system_instruction: "You are a medieval bard telling epic tales."
) do |chunk|
  print chunk
end

Parameters:

  • prompt (String)

    The input prompt

  • model_name (String, nil) (defaults to: nil)

    The model to use (optional)

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

    Additional generation 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

  • :stream_mode (Symbol)

    Mode for processing stream chunks (:raw, :incremental, or :delta)

  • :client_options (Hash)

    Options to pass to the client

Yields:

  • (chunk)

    Yields each chunk of the streaming response

Yield Parameters:

  • chunk (String, Hash)

    A chunk of the response

Raises:



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/geminize.rb', line 262

def generate_text_stream(prompt, model_name = nil, params = {}, &block)
  raise ArgumentError, "A block is required for streaming" unless block_given?

  validate_configuration!

  # Extract client options
  client_options = params.delete(:client_options) || {}

  # Create the generator
  generator = TextGeneration.new(nil, client_options)

  # Store the generator for potential cancellation
  self.last_streaming_generator = generator

  # Generate with streaming
  begin
    generator.generate_text_stream(prompt, model_name || configuration.default_model, params, &block)
  rescue => e
    # Ensure all errors are wrapped in a GeminizeError
    if e.is_a?(GeminizeError)
      raise
    else
      raise GeminizeError.new("Error during text generation streaming: #{e.message}")
    end
  ensure
    # Clear the reference to allow garbage collection
    self.last_streaming_generator = nil if last_streaming_generator == generator
  end
end

.generate_with_code_execution(prompt, model_name = nil, params = {}, with_retries: true, max_retries: 3, retry_delay: 1.0, client_options: nil) ⇒ Geminize::Models::ContentResponse

Generate text with code execution capabilities

Examples:

Generate text with code execution

Geminize.generate_with_code_execution(
  "What is the sum of the first 50 prime numbers?",
  nil,
  { temperature: 0.2 }
)

Parameters:

  • prompt (String)

    The input prompt

  • model_name (String, nil) (defaults to: nil)

    The model to use, defaults to the configured default model

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

    Additional parameters for generation

  • with_retries (Boolean) (defaults to: true)

    Whether to retry the generation if it fails

  • max_retries (Integer) (defaults to: 3)

    Maximum number of retries

  • retry_delay (Float) (defaults to: 1.0)

    Delay between retries in seconds

  • client_options (Hash) (defaults to: nil)

    Options for the HTTP client

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

Returns:

Raises:



968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
# File 'lib/geminize.rb', line 968

def generate_with_code_execution(prompt, model_name = nil, params = {}, with_retries: true, max_retries: 3, retry_delay: 1.0, client_options: nil)
  validate_configuration!

  # Initialize the generator
  client = client_options ? Client.new(client_options) : Client.new
  generator = TextGeneration.new(client)

  # Set up params with defaults
  generation_params = params.dup
  with_retries = generation_params.delete(:with_retries) != false if generation_params.key?(:with_retries)

  # Enhance the system instruction to ensure code execution is effective
  generation_params[:system_instruction] ||= ""
  generation_params[:system_instruction] = "You are a helpful assistant with the ability to generate and execute Python code. When appropriate, use code to solve problems or complete tasks. " + generation_params[:system_instruction]

  # Create the request
  content_request = Models::ContentRequest.new(
    prompt,
    model_name || configuration.default_model,
    generation_params
  )

  # Enable code execution
  content_request.enable_code_execution

  # Generate the response
  if with_retries
    generator.generate_with_retries(content_request, max_retries, retry_delay)
  else
    generator.generate(content_request)
  end
end

.generate_with_functions(prompt, functions, model_name = nil, params = {}, with_retries: true, max_retries: 3, retry_delay: 1.0, client_options: nil) ⇒ Geminize::Models::ContentResponse

Generate text with function calling capabilities

Examples:

Generate text with a function call

Geminize.generate_with_functions(
  "What's the weather in New York?",
  [
    {
      name: "get_weather",
      description: "Get the current weather in a location",
      parameters: {
        type: "object",
        properties: {
          location: {
            type: "string",
            description: "The city and state, e.g. New York, NY"
          },
          unit: {
            type: "string",
            enum: ["celsius", "fahrenheit"],
            description: "The unit of temperature"
          }
        },
        required: ["location"]
      }
    }
  ]
)

Parameters:

  • prompt (String)

    The input prompt

  • functions (Array<Hash>)

    Array of function definitions

  • model_name (String, nil) (defaults to: nil)

    The model to use, defaults to the configured default model

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

    Additional parameters for generation

  • with_retries (Boolean) (defaults to: true)

    Whether to retry the generation if it fails

  • max_retries (Integer) (defaults to: 3)

    Maximum number of retries

  • retry_delay (Float) (defaults to: 1.0)

    Delay between retries in seconds

  • client_options (Hash) (defaults to: nil)

    Options for the HTTP client

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

  • :tool_execution_mode (String)

    Tool execution mode ("AUTO", "MANUAL", or "NONE")

Returns:

Raises:



766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
# File 'lib/geminize.rb', line 766

def generate_with_functions(prompt, functions, model_name = nil, params = {}, with_retries: true, max_retries: 3, retry_delay: 1.0, client_options: nil)
  validate_configuration!

  # Initialize the generator
  client = client_options ? Client.new(client_options) : Client.new
  generator = TextGeneration.new(client)

  # Parse functions
  if functions.nil? || !functions.is_a?(Array) || functions.empty?
    raise Geminize::ValidationError.new(
      "Functions must be a non-empty array",
      "INVALID_ARGUMENT"
    )
  end

  # Set up params with defaults
  generation_params = params.dup
  tool_execution_mode = generation_params.delete(:tool_execution_mode) || "AUTO"
  with_retries = generation_params.delete(:with_retries) != false if generation_params.key?(:with_retries)

  # Enhance the system instruction to ensure function calling
  generation_params[:system_instruction] ||= ""
  generation_params[:system_instruction] = "You are a helpful assistant. When you encounter a question that you can answer by calling a function, you must always use the provided function. Always respond using the function call format, not with your own text. " + generation_params[:system_instruction]

  # Create the request
  content_request = Models::ContentRequest.new(
    prompt,
    model_name || configuration.default_model,
    generation_params
  )

  # Add functions to the request
  functions.each do |function|
    content_request.add_function(
      function[:name],
      function[:description],
      function[:parameters]
    )
  end

  # Set the tool config
  content_request.set_tool_config(tool_execution_mode)

  # Generate the response
  if with_retries
    generator.generate_with_retries(content_request, max_retries, retry_delay)
  else
    generator.generate(content_request)
  end
end

.generate_with_safety_settings(prompt, safety_settings, model_name = nil, params = {}) ⇒ Geminize::Models::ContentResponse

Generate text with custom safety settings

Examples:

Generate text with specific safety settings

Geminize.generate_with_safety_settings(
  "Tell me a scary story",
  [
    {category: "HARM_CATEGORY_DANGEROUS_CONTENT", threshold: "BLOCK_MEDIUM_AND_ABOVE"},
    {category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_LOW_AND_ABOVE"}
  ]
)

Parameters:

  • prompt (String)

    The input prompt

  • safety_settings (Array<Hash>)

    Array of safety setting definitions

  • model_name (String, nil) (defaults to: nil)

    The model to use (optional)

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

    Additional generation 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

  • :with_retries (Boolean)

    Enable retries for transient errors (default: true)

  • :max_retries (Integer)

    Maximum retry attempts (default: 3)

  • :retry_delay (Float)

    Initial delay between retries in seconds (default: 1.0)

  • :client_options (Hash)

    Options to pass to the client

Returns:

Raises:



618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
# File 'lib/geminize.rb', line 618

def generate_with_safety_settings(prompt, safety_settings, model_name = nil, params = {})
  validate_configuration!

  # Extract special options
  with_retries = params.delete(:with_retries) != false # Default to true
  max_retries = params.delete(:max_retries) || 3
  retry_delay = params.delete(:retry_delay) || 1.0
  client_options = params.delete(:client_options) || {}

  # Create the generator and content request
  generator = TextGeneration.new(nil, client_options)
  content_request = Models::ContentRequest.new(
    prompt,
    model_name || configuration.default_model,
    params
  )

  # Add safety settings to the request
  safety_settings.each do |setting|
    content_request.add_safety_setting(
      setting[:category],
      setting[:threshold]
    )
  end

  # Generate with or without retries
  if with_retries
    generator.generate_with_retries(content_request, max_retries, retry_delay)
  else
    generator.generate(content_request)
  end
end

.get_chat_models(force_refresh: false, client_options: {}) ⇒ Geminize::Models::ModelList

Get models that support chat generation

Parameters:

  • force_refresh (Boolean) (defaults to: false)

    Force a refresh from the API instead of using cache

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

    Options to pass to the client

Returns:

Raises:



566
567
568
569
# File 'lib/geminize.rb', line 566

def get_chat_models(force_refresh: false, client_options: {})
  models = list_all_models(force_refresh: force_refresh, client_options: client_options)
  models.chat_models
end

.get_content_generation_models(force_refresh: false, client_options: {}) ⇒ Geminize::Models::ModelList

Get models that support content generation

Parameters:

  • force_refresh (Boolean) (defaults to: false)

    Force a refresh from the API instead of using cache

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

    Options to pass to the client

Returns:

Raises:



546
547
548
549
# File 'lib/geminize.rb', line 546

def get_content_generation_models(force_refresh: false, client_options: {})
  models = list_all_models(force_refresh: force_refresh, client_options: client_options)
  models.content_generation_models
end

.get_embedding_models(force_refresh: false, client_options: {}) ⇒ Geminize::Models::ModelList

Get models that support embedding generation

Parameters:

  • force_refresh (Boolean) (defaults to: false)

    Force a refresh from the API instead of using cache

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

    Options to pass to the client

Returns:

Raises:



556
557
558
559
# File 'lib/geminize.rb', line 556

def get_embedding_models(force_refresh: false, client_options: {})
  models = list_all_models(force_refresh: force_refresh, client_options: client_options)
  models.embedding_models
end

.get_model(model_name, force_refresh: false, client_options: {}) ⇒ Geminize::Models::Model

Get information about a specific model

Parameters:

  • model_name (String)

    The model name to retrieve (can be "models/gemini-2.0-flash" or just "gemini-2.0-flash")

  • force_refresh (Boolean) (defaults to: false)

    Force a refresh from the API instead of using cache

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

    Options to pass to the client

Returns:

Raises:



523
524
525
526
527
# File 'lib/geminize.rb', line 523

def get_model(model_name, force_refresh: false, client_options: {})
  validate_configuration!
  model_info = ModelInfo.new(nil, client_options)
  model_info.get_model(model_name, force_refresh: force_refresh)
end

.get_models_by_method(method, force_refresh: false, client_options: {}) ⇒ Geminize::Models::ModelList

Get models that support a specific generation method

Parameters:

  • method (String)

    The generation method (e.g., "generateContent", "embedContent")

  • force_refresh (Boolean) (defaults to: false)

    Force a refresh from the API instead of using cache

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

    Options to pass to the client

Returns:

Raises:



535
536
537
538
539
# File 'lib/geminize.rb', line 535

def get_models_by_method(method, force_refresh: false, client_options: {})
  validate_configuration!
  model_info = ModelInfo.new(nil, client_options)
  model_info.get_models_by_method(method, force_refresh: force_refresh)
end

.get_streaming_models(force_refresh: false, client_options: {}) ⇒ Geminize::Models::ModelList

Get models that support streaming generation

Parameters:

  • force_refresh (Boolean) (defaults to: false)

    Force a refresh from the API instead of using cache

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

    Options to pass to the client

Returns:

Raises:



576
577
578
579
# File 'lib/geminize.rb', line 576

def get_streaming_models(force_refresh: false, client_options: {})
  models = list_all_models(force_refresh: force_refresh, client_options: client_options)
  models.streaming_models
end

.list_all_models(force_refresh: false, client_options: {}) ⇒ Geminize::Models::ModelList

Get all available models, handling pagination automatically

Parameters:

  • force_refresh (Boolean) (defaults to: false)

    Force a refresh from the API instead of using cache

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

    Options to pass to the client

Returns:

Raises:



511
512
513
514
515
# File 'lib/geminize.rb', line 511

def list_all_models(force_refresh: false, client_options: {})
  validate_configuration!
  model_info = ModelInfo.new(nil, client_options)
  model_info.list_all_models(force_refresh: force_refresh)
end

.list_conversationsArray<Hash>

List all saved conversations

Returns:

  • (Array<Hash>)

    Array of conversation metadata



454
455
456
# File 'lib/geminize.rb', line 454

def list_conversations
  conversation_repository.list
end

.list_models(page_size: nil, page_token: nil, force_refresh: false, client_options: {}) ⇒ Geminize::Models::ModelList

List available models from the Gemini API

Parameters:

  • page_size (Integer, nil) (defaults to: nil)

    Number of models to return per page (max 1000)

  • page_token (String, nil) (defaults to: nil)

    Token for retrieving a specific page

  • force_refresh (Boolean) (defaults to: false)

    Force a refresh from the API instead of using cache

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

    Options to pass to the client

Returns:

Raises:



500
501
502
503
504
# File 'lib/geminize.rb', line 500

def list_models(page_size: nil, page_token: nil, force_refresh: false, client_options: {})
  validate_configuration!
  model_info = ModelInfo.new(nil, client_options)
  model_info.list_models(page_size: page_size, page_token: page_token, force_refresh: force_refresh)
end

.load_conversation(id) ⇒ Geminize::Models::Conversation?

Load a conversation by ID

Parameters:

  • id (String)

    The ID of the conversation to load

Returns:



441
442
443
# File 'lib/geminize.rb', line 441

def load_conversation(id)
  conversation_repository.load(id)
end

.normalize_vector(vec) ⇒ Array<Float>

Normalize a vector to unit length

Parameters:

  • vec (Array<Float>)

    Vector to normalize

Returns:

  • (Array<Float>)

    Normalized vector



366
367
368
# File 'lib/geminize.rb', line 366

def normalize_vector(vec)
  VectorUtils.normalize(vec)
end

.process_function_call(response, model_name = nil, with_retries: true, max_retries: 3, retry_delay: 1.0, client_options: nil) {|function_name, args| ... } ⇒ Geminize::Models::ContentResponse

Process a function call by executing a provided block and returning the result to Gemini

Examples:

Process a function call

response = Geminize.generate_with_functions("What's the weather in New York?", [...])
if response.has_function_call?
  final_response = Geminize.process_function_call(response) do |function_name, args|
    if function_name == "get_weather"
      # Call a real weather API here
      { temperature: 72, conditions: "sunny" }
    end
  end
  puts final_response.text
end

Parameters:

  • response (Geminize::Models::ContentResponse)

    The response containing a function call

  • model_name (String, nil) (defaults to: nil)

    The model to use for the followup, defaults to the configured default model

  • with_retries (Boolean) (defaults to: true)

    Whether to retry the generation if it fails

  • max_retries (Integer) (defaults to: 3)

    Maximum number of retries

  • retry_delay (Float) (defaults to: 1.0)

    Delay between retries in seconds

  • client_options (Hash) (defaults to: nil)

    Options for the HTTP client

Yields:

  • (function_name, args)

    Block to execute the function

Yield Parameters:

  • function_name (String)

    The name of the function to execute

  • args (Hash)

    The arguments to pass to the function

Yield Returns:

  • (Hash, Array, String, Numeric, Boolean, nil)

    The result of the function

Returns:

Raises:



898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
# File 'lib/geminize.rb', line 898

def process_function_call(response, model_name = nil, with_retries: true, max_retries: 3, retry_delay: 1.0, client_options: nil)
  validate_configuration!

  # Ensure a block is provided
  unless block_given?
    raise Geminize::ValidationError.new(
      "A block must be provided to process the function call",
      "INVALID_ARGUMENT"
    )
  end

  # Ensure the response has a function call
  unless response.has_function_call?
    raise Geminize::ValidationError.new(
      "The response does not contain a function call",
      "INVALID_ARGUMENT"
    )
  end

  # Extract function call information
  function_call = response.function_call
  function_name = function_call.name
  function_args = function_call.response

  # Call the provided block with the function information
  result = yield(function_name, function_args)

  # Create a function response
  Models::FunctionResponse.new(function_name, result)

  # Initialize the generator
  client = client_options ? Client.new(client_options) : Client.new
  generator = TextGeneration.new(client)

  # Create a request with the function result
  content_request = Models::ContentRequest.new(
    "Function #{function_name} returned: #{result.inspect}",
    model_name || configuration.default_model
  )

  # Generate the response
  if with_retries
    generator.generate_with_retries(content_request, max_retries, retry_delay)
  else
    generator.generate(content_request)
  end
end

.reset_configuration!Object

Reset the configuration to defaults



110
111
112
# File 'lib/geminize.rb', line 110

def reset_configuration!
  configuration.reset!
end

.save_conversation(conversation) ⇒ Boolean

Save a conversation

Parameters:

Returns:

  • (Boolean)

    True if the save was successful



434
435
436
# File 'lib/geminize.rb', line 434

def save_conversation(conversation)
  conversation_repository.save(conversation)
end

.send_message_in_conversation(conversation_id, message, model_name = nil, params = {}) ⇒ Hash

Send a message in a managed conversation

Examples:

Send a message with a system instruction

Geminize.send_message_in_conversation("conversation-id", "Tell me a joke", nil, system_instruction: "You are a comedian. Be funny.")

Parameters:

  • conversation_id (String)

    The ID of the conversation

  • message (String)

    The message to send

  • model_name (String, nil) (defaults to: nil)

    The model to use (optional)

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

    Additional generation 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 for this specific message

Returns:

  • (Hash)

    The response data



483
484
485
486
487
488
489
490
491
# File 'lib/geminize.rb', line 483

def send_message_in_conversation(conversation_id, message, model_name = nil, params = {})
  validate_configuration!
  conversation_service.send_message(
    conversation_id,
    message,
    model_name || configuration.default_model,
    params
  )
end

.update_conversation_system_instruction(id, system_instruction) ⇒ Models::Conversation

Update a conversation's system instruction

Examples:

Update a conversation's system instruction

Geminize.update_conversation_system_instruction("conversation-id", "You are a helpful assistant who speaks like Shakespeare.")

Parameters:

  • id (String)

    The ID of the conversation to update

  • system_instruction (String)

    The new system instruction

Returns:

Raises:



588
589
590
591
# File 'lib/geminize.rb', line 588

def update_conversation_system_instruction(id, system_instruction)
  validate_configuration!
  conversation_service.update_conversation_system_instruction(id, system_instruction)
end

.validate_configuration!Boolean

Validates the configuration

Returns:

  • (Boolean)

Raises:



117
118
119
# File 'lib/geminize.rb', line 117

def validate_configuration!
  configuration.validate!
end