Module: Lammy::Chat

Defined in:
lib/lammy/chat.rb

Class Method Summary collapse

Class Method Details

.handle(klass, method_name, settings) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/lammy/chat.rb', line 5

def self.handle(klass, method_name, settings)
  # Unbind the original method
  original_method = klass.instance_method(method_name)

  # Redefine the method
  klass.define_method(method_name) do |*args, &block|
    # Initialize context
    @system_message = nil

    # `context` sets the system message and is available within the instance
    define_singleton_method(:context) do |message|
      @system_message = message
    end

    define_singleton_method(:stream) do |proc|
      @stream = proc
    end

    # Call the original method to get the user message
    user_message = original_method.bind(self).call(*args, &block)

    client = case settings[:model]
             when *OpenAI::MODELS
               OpenAI.new(settings)
             when *Claude::MODELS
               Claude.new(settings)
             else
               raise "Unsupported model: #{settings[:model]}"
             end

    client.chat(user_message, @system_message, @stream)
  end
end