Class: Langchain::Assistant

Inherits:
Object
  • Object
show all
Defined in:
lib/langchainrb_overrides/assistant.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id: nil, **kwargs) ⇒ Assistant

rubocop:disable Style/ArgumentsForwarding



11
12
13
14
# File 'lib/langchainrb_overrides/assistant.rb', line 11

def initialize(id: nil, **kwargs) # rubocop:disable Style/ArgumentsForwarding
  @id = id
  original_initialize(**kwargs) # rubocop:disable Style/ArgumentsForwarding
end

Instance Attribute Details

#idObject

Returns the value of attribute id.



7
8
9
# File 'lib/langchainrb_overrides/assistant.rb', line 7

def id
  @id
end

Class Method Details

.find_assistant(id) ⇒ Object



47
48
49
# File 'lib/langchainrb_overrides/assistant.rb', line 47

def find_assistant(id)
  ::Assistant.find(id)
end

.load(id) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/langchainrb_overrides/assistant.rb', line 51

def load(id)
  ar_assistant = find_assistant(id)

  tools = ar_assistant.tools.map { |tool_name| Object.const_get(tool_name).new }

  assistant = Langchain::Assistant.new(
    id: ar_assistant.id,
    llm: ar_assistant.llm,
    tools: tools,
    instructions: ar_assistant.instructions,
    tool_choice: ar_assistant.tool_choice
  )

  ar_assistant.messages.each do |ar_message|
    messages = assistant.add_message(
      role: ar_message.role,
      content: ar_message.content,
      tool_calls: ar_message.tool_calls,
      tool_call_id: ar_message.tool_call_id
    )
    messages.last.id = ar_message.id
  end

  assistant
end

Instance Method Details

#original_initializeObject



9
# File 'lib/langchainrb_overrides/assistant.rb', line 9

alias_method :original_initialize, :initialize

#saveObject



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
# File 'lib/langchainrb_overrides/assistant.rb', line 16

def save
  ::ActiveRecord::Base.transaction do
    ar_assistant = if id
      self.class.find_assistant(id)
    else
      ::Assistant.new
    end

    ar_assistant.update!(
      instructions: instructions,
      tool_choice: tool_choice,
      tools: tools.map(&:class).map(&:name)
    )

    messages.each do |message|
      ar_message = ar_assistant.messages.find_or_initialize_by(id: message.id)
      ar_message.update!(
        role: message.role,
        content: message.content,
        tool_calls: message.tool_calls,
        tool_call_id: message.tool_call_id
      )
      message.id = ar_message.id
    end

    @id = ar_assistant.id
    true
  end
end