Class: Genai::Chat

Inherits:
BaseChat show all
Defined in:
lib/genai/chat.rb

Instance Attribute Summary

Attributes inherited from BaseChat

#comprehensive_history, #config, #curated_history, #model

Instance Method Summary collapse

Methods inherited from BaseChat

#get_history, #record_history

Constructor Details

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

Returns a new instance of Chat.



105
106
107
108
# File 'lib/genai/chat.rb', line 105

def initialize(client:, model:, config: nil, history: [])
  @client = client
  super(model: model, config: config, history: history)
end

Instance Method Details

#send_message(message, config: nil) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/genai/chat.rb', line 110

def send_message(message, config: nil)
  input_content = case message
  when String
    { role: "user", parts: [{ text: message }] }
  when Array
    { role: "user", parts: message }
  when Hash
    message
  else
    raise ArgumentError, "Message must be a String, Array, or Hash"
  end

  model_instance = @client.model(@model)
  response = model_instance.generate_content(
    contents: @curated_history + [input_content],
    config: config || @config
  )

  model_output = if response[:candidates] && !response[:candidates].empty? && response[:candidates][0][:content]
    [response[:candidates][0][:content]]
  else
    []
  end

  automatic_function_calling_history = response[:automatic_function_calling_history] || []

  record_history(
    user_input: input_content,
    model_output: model_output,
    automatic_function_calling_history: automatic_function_calling_history,
    is_valid: ChatValidator.validate_response(response)
  )

  response
end

#send_message_stream(message, config: nil) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/genai/chat.rb', line 146

def send_message_stream(message, config: nil)
  input_content = case message
  when String
    { role: "user", parts: [{ text: message }] }
  when Array
    { role: "user", parts: message }
  when Hash
    message
  else
    raise ArgumentError, "Message must be a String, Array, or Hash"
  end


  send_message(message, config: config)
end