Class: GenAI::Chat::Base

Inherits:
Base
  • Object
show all
Defined in:
lib/gen_ai/chat/base.rb

Direct Known Subclasses

Anthropic, Gemini, GooglePalm, OpenAI

Constant Summary collapse

USER_ROLE =
'user'
ASSISTANT_ROLE =
'assistant'

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Dependency

#depends_on

Constructor Details

#initialize(provider:, token:, options: {}) ⇒ Base

Returns a new instance of Base.



11
12
13
14
15
# File 'lib/gen_ai/chat/base.rb', line 11

def initialize(provider:, token:, options: {})
  @history = []
  @default_options = {}
  @model = GenAI::Language.new(provider, token, options: options)
end

Instance Attribute Details

#default_optionsObject (readonly)

Returns the value of attribute default_options.



9
10
11
# File 'lib/gen_ai/chat/base.rb', line 9

def default_options
  @default_options
end

#historyObject (readonly)

Returns the value of attribute history.



9
10
11
# File 'lib/gen_ai/chat/base.rb', line 9

def history
  @history
end

Instance Method Details

#message(message, options = {}, &block) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/gen_ai/chat/base.rb', line 21

def message(message, options = {}, &block)
  if @history.size == 1 && @history.first[:role] != 'system'
    append_to_message(message)
  else
    append_to_history({ role: USER_ROLE, content: message })
  end

  response = @model.chat(@history.dup, default_options.merge(options).compact, &block)
  append_to_history({ role: ASSISTANT_ROLE, content: response.value })
  response
end

#start(history: [], context: nil, examples: []) ⇒ Object



17
18
19
# File 'lib/gen_ai/chat/base.rb', line 17

def start(history: [], context: nil, examples: [])
  @history = build_history(history.map(&:deep_symbolize_keys), context, examples.map(&:deep_symbolize_keys))
end