Class: Promptcraft::Command::RechatConversationCommand

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/promptcraft/command/rechat_conversation_command.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers

#deep_stringify_keys, #deep_symbolize_keys

Constructor Details

#initialize(system_prompt:, conversation:, llm:) ⇒ RechatConversationCommand

Returns a new instance of RechatConversationCommand.



4
5
6
7
8
# File 'lib/promptcraft/command/rechat_conversation_command.rb', line 4

def initialize(system_prompt:, conversation:, llm:)
  @system_prompt = system_prompt
  @conversation = conversation
  @llm = llm
end

Instance Attribute Details

#conversationObject

Returns the value of attribute conversation.



10
11
12
# File 'lib/promptcraft/command/rechat_conversation_command.rb', line 10

def conversation
  @conversation
end

#llmObject

Returns the value of attribute llm.



10
11
12
# File 'lib/promptcraft/command/rechat_conversation_command.rb', line 10

def llm
  @llm
end

#system_promptObject

Returns the value of attribute system_prompt.



10
11
12
# File 'lib/promptcraft/command/rechat_conversation_command.rb', line 10

def system_prompt
  @system_prompt
end

#updated_conversationObject (readonly)

Returns the value of attribute updated_conversation.



11
12
13
# File 'lib/promptcraft/command/rechat_conversation_command.rb', line 11

def updated_conversation
  @updated_conversation
end

Instance Method Details

#executeObject

At each point in @conversation messages where the assistant has replied, or not yet replied, then ask the LLM to re-chat the preceding messages and generate a new response.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/promptcraft/command/rechat_conversation_command.rb', line 15

def execute
  @updated_conversation = Promptcraft::Conversation.new(system_prompt:, llm:)

  conversation.messages.each do |message|
    message = deep_symbolize_keys(message)
    role = message[:role]
    if role == "assistant"
      messages = @updated_conversation.to_messages
      response_message = Promptcraft::Command::LlmChatCommand.new(messages: messages, llm: @llm).execute
      @updated_conversation.messages << response_message
    else
      @updated_conversation.messages << message
    end
  end

  # if last message is from user, then ask the LLM to generate a response
  unless @updated_conversation.messages.last&.dig(:role) == "assistant"
    messages = @updated_conversation.to_messages
    response_message = Promptcraft::Command::LlmChatCommand.new(messages: messages, llm: @llm).execute
    @updated_conversation.messages << response_message
  end
end