Class: DeepAgents::ReactAgent

Inherits:
Object
  • Object
show all
Defined in:
lib/deepagents/graph.rb

Overview

ReactAgent class for implementing the React pattern

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tools, instructions, model, state_schema = nil) ⇒ ReactAgent

Returns a new instance of ReactAgent.



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/deepagents/graph.rb', line 12

def initialize(tools, instructions, model, state_schema = nil)
  @tools = tools
  @instructions = instructions
  @model = model
  @state = DeepAgentState.new
  @tool_registry = ToolRegistry.new
  
  # Register tools
  tools.each do |tool|
    @tool_registry.register(tool)
  end
end

Instance Attribute Details

#instructionsObject (readonly)

Returns the value of attribute instructions.



10
11
12
# File 'lib/deepagents/graph.rb', line 10

def instructions
  @instructions
end

#modelObject (readonly)

Returns the value of attribute model.



10
11
12
# File 'lib/deepagents/graph.rb', line 10

def model
  @model
end

#stateObject (readonly)

Returns the value of attribute state.



10
11
12
# File 'lib/deepagents/graph.rb', line 10

def state
  @state
end

#toolsObject (readonly)

Returns the value of attribute tools.



10
11
12
# File 'lib/deepagents/graph.rb', line 10

def tools
  @tools
end

Instance Method Details

#run(max_iterations = 10) ⇒ Object



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
# File 'lib/deepagents/graph.rb', line 25

def run(max_iterations = 10)
  iterations = 0
  messages = []
  
  while iterations < max_iterations
    iterations += 1
    
    prompt = build_prompt(messages)
    response = @model.generate(prompt, @tools)
    
    if response[:tool_calls] && !response[:tool_calls].empty?
      tool_call = response[:tool_calls].first
      tool_name = tool_call[:name]
      tool_args = tool_call[:arguments]
      
      begin
        tool = @tool_registry.get(tool_name)
        result = execute_tool(tool, tool_args)
        
        messages << { role: "assistant", content: "I'll use the #{tool_name} tool." }
        messages << { role: "system", content: "Tool result: #{result}" }
      rescue => e
        messages << { role: "system", content: "Error: #{e.message}" }
      end
    else
      messages << { role: "assistant", content: response[:content] }
      break
    end
  end
  
  if iterations >= max_iterations
    raise MaxIterationsError.new(max_iterations)
  end
  
  # Return the final response
  messages.last[:content]
end