Class: Aigen::Google::Chat

Inherits:
Object
  • Object
show all
Defined in:
lib/aigen/google/chat.rb

Overview

Chat manages stateful multi-turn conversations with the Gemini API. It maintains conversation history and automatically includes context in each API request for coherent, context-aware responses.

Examples:

Starting a new chat session

client = Aigen::Google::Client.new(api_key: "your-api-key")
chat = client.start_chat
response = chat.send_message("Hello!")
puts response["candidates"][0]["content"]["parts"][0]["text"]

Multi-turn conversation with context

chat = client.start_chat
chat.send_message("What is Ruby?")
chat.send_message("What are its main features?") # Uses context from first message
puts chat.history # View full conversation

Starting chat with existing history

history = [
  {role: "user", parts: [{text: "Hello"}]},
  {role: "model", parts: [{text: "Hi there!"}]}
]
chat = client.start_chat(history: history)
chat.send_message("How are you?") # Continues from existing context

Instance Method Summary collapse

Constructor Details

#initialize(client:, model: nil, history: []) ⇒ Chat

Initializes a new Chat instance.

Examples:

Create a new chat

chat = Chat.new(client: client, model: "gemini-pro")

Create chat with existing history

history = [{role: "user", parts: [{text: "Hello"}]}]
chat = Chat.new(client: client, history: history)

Parameters:

  • client (Aigen::Google::Client)

    the client instance for API requests

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

    the model to use (defaults to client’s default_model)

  • history (Array<Hash>) (defaults to: [])

    initial conversation history (defaults to empty array)



51
52
53
54
55
# File 'lib/aigen/google/chat.rb', line 51

def initialize(client:, model: nil, history: [])
  @client = client
  @model = model || @client.config.default_model
  @history = history.dup
end

Instance Method Details

#historyArray<Hash>

Note:

The returned array is frozen to prevent external modification. The history is managed internally by the Chat instance.

Returns the conversation history as an array of message hashes. Each message has a role (“user” or “model”) and parts array.

Returns:

  • (Array<Hash>)

    a frozen copy of the conversation history



35
36
37
# File 'lib/aigen/google/chat.rb', line 35

def history
  @history.dup.freeze
end

#send_message(message, **options) ⇒ Hash

Sends a message in the chat context and returns the model’s response. Automatically includes conversation history for context and updates history with both the user message and model response.

Accepts both simple String messages and Content objects for multimodal support.

Examples:

Send a simple text message

response = chat.send_message("What is the weather today?")
text = response["candidates"][0]["content"]["parts"][0]["text"]

Send multimodal content (text + image)

content = Aigen::Google::Content.new([
  {text: "What is in this image?"},
  {inline_data: {mime_type: "image/jpeg", data: base64_data}}
])
response = chat.send_message(content)

Send message with generation config

response = chat.send_message(
  "Tell me a story",
  generationConfig: {temperature: 0.9, maxOutputTokens: 1024}
)

Parameters:

  • message (String, Content)

    the message text or Content object to send

  • options (Hash)

    additional options to pass to the API (e.g., generationConfig)

Returns:

  • (Hash)

    the API response containing the model’s reply

Raises:



91
92
93
94
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
121
122
123
124
125
126
127
128
129
# File 'lib/aigen/google/chat.rb', line 91

def send_message(message, **options)
  # Validate message parameter
  raise ArgumentError, "message cannot be nil" if message.nil?
  raise ArgumentError, "message cannot be empty" if message.respond_to?(:empty?) && message.empty?

  # Build user message part
  # Handle both String (simple text) and Content objects (multimodal)
  user_message = if message.is_a?(Content)
    # Content object - use its to_h serialization and add role
    message.to_h.merge(role: "user")
  else
    # String - wrap in standard format
    {
      role: "user",
      parts: [{text: message}]
    }
  end

  # Build payload with full history + new message
  payload = {
    contents: @history + [user_message]
  }

  # Merge any additional generation config options
  payload.merge!(options) if options.any?

  # Make API request
  endpoint = "models/#{@model}:generateContent"
  response = @client.http_client.post(endpoint, payload)

  # Extract model response
  model_response = extract_model_message(response)

  # Update history with both user message and model response
  @history << user_message
  @history << model_response

  response
end

#send_message_stream(message, **options) {|chunk| ... } ⇒ nil, Enumerator

Note:

The conversation history is NOT updated until the entire stream completes. This ensures the history remains consistent even if streaming is interrupted.

Sends a message in the chat context with streaming response delivery. Automatically includes conversation history for context and updates history with the full accumulated response after streaming completes.

Examples:

Stream chat response with block

chat = client.start_chat
chat.send_message_stream("Tell me a joke") do |chunk|
  text = chunk["candidates"][0]["content"]["parts"][0]["text"]
  print text
end
# History now contains both user message and full accumulated response

Stream with Enumerator for lazy processing

chat = client.start_chat
stream = chat.send_message_stream("Count to 5")
stream.each { |chunk| puts chunk["candidates"][0]["content"]["parts"][0]["text"] }
puts chat.history.length # => 2 (user + model)

Parameters:

  • message (String)

    the message text to send

  • options (Hash)

    additional options to pass to the API (e.g., generationConfig)

Yield Parameters:

  • chunk (Hash)

    parsed JSON chunk from the streaming response (if block given)

Returns:

  • (nil)

    if block is given, returns nil after streaming completes

  • (Enumerator)

    if no block given, returns lazy Enumerator for progressive iteration

Raises:



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
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
# File 'lib/aigen/google/chat.rb', line 165

def send_message_stream(message, **options, &block)
  # Validate message parameter
  raise ArgumentError, "message cannot be nil" if message.nil?
  raise ArgumentError, "message cannot be empty" if message.respond_to?(:empty?) && message.empty?

  # Build user message part
  user_message = {
    role: "user",
    parts: [{text: message}]
  }

  # Build payload with full history + new message
  payload = {
    contents: @history + [user_message]
  }

  # Merge any additional generation config options
  payload.merge!(options) if options.any?

  # Make API request
  endpoint = "models/#{@model}:streamGenerateContent"

  # Accumulate full response text while streaming
  accumulated_text = ""

  # If block given, stream with block and accumulate
  if block_given?
    @client.http_client.post_stream(endpoint, payload) do |chunk|
      # Extract text from chunk
      text = extract_chunk_text(chunk)
      accumulated_text += text if text

      # Yield chunk to user's block
      block.call(chunk)
    end

    # After streaming completes, update history with full response
    update_history_after_stream(user_message, accumulated_text)
    nil
  else
    # Return Enumerator that accumulates and updates history when consumed
    Enumerator.new do |yielder|
      @client.http_client.post_stream(endpoint, payload) do |chunk|
        text = extract_chunk_text(chunk)
        accumulated_text += text if text
        yielder << chunk
      end

      # Update history after enumeration completes
      update_history_after_stream(user_message, accumulated_text)
    end
  end
end