Repository navigation
Expand file tree
/
Copy pathstreaming.rb
More file actions
64 lines (50 loc) · 1.85 KB
/
Copy pathstreaming.rb
File metadata and controls
64 lines (50 loc) · 1.85 KB
1
2
3
4
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# frozen_string_literal: true
# `Chat` and `Message` could be ActiveRecord models but we're using to use POROs for simplicity
Message = Struct.new(:role, :content)
class Chat
attr_reader :messages
def initialize
@messages = []
end
def history
messages.map do |message|
case message.role
when :user then L.user(message.content)
when :assistant then L.assistant(message.content)
end
end
end
end
# This is the main class that will be used to interact with the LLM
class Bot
# To be able to make LLM calls, we first include `L` at the top of our class
include L
attr_reader :chat
def initialize
@chat = ::Chat.new
end
llm(model: 'gpt-4o')
def talk(message)
chat.messages << Message.new(:user, message)
# We start with an empty assistant message which will be filled in by the model later
chat.messages << Message.new(:assistant, '')
# Use the `stream` method to stream chunks of the response
stream lambda { |content|
chat.messages.last.content += content if content
# Display the content in the console
puts content
}
# We always give the model the entire history of the conversation so that it can continue from where we left off
chat.history
end
end
bot = Bot.new
bot.talk('Hello, how are you?')
bot.chat.history
# => [{:role=>:user, :content=>"Hello, how are you?"}, {:role=>:assistant, :content=>"Hello! I'm here and ready to help. How can I assist you today?"}]
bot.talk("What's your name?")
bot.chat.history
# => [{:role=>:user, :content=>"Hello, how are you?"},
# {:role=>:assistant, :content=>"Hello! I'm here and ready to help. How can I assist you today?"},
# {:role=>:user, :content=>"What's your name?"},
# {:role=>:assistant, :content=>"I don't have a personal name, but you can call me Assistant or whatever you'd like. How can I help you today?"}]