Class: Autoflux::OpenAI::Agent

Inherits:
Object
  • Object
show all
Defined in:
lib/autoflux/openai/agent.rb

Overview

The agent is design to use OpenAI as an agent

Constant Summary collapse

DEFAULT_NAME =
"openai"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model:, name: DEFAULT_NAME, client: Client.new, tools: [], memory: []) ⇒ Agent

Returns a new instance of Agent.



11
12
13
14
15
16
17
# File 'lib/autoflux/openai/agent.rb', line 11

def initialize(model:, name: DEFAULT_NAME, client: Client.new, tools: [], memory: [])
  @client = client
  @model = model
  @name = name
  @memory = memory
  @_tools = tools
end

Instance Attribute Details

#memoryObject (readonly)

Returns the value of attribute memory.



9
10
11
# File 'lib/autoflux/openai/agent.rb', line 9

def memory
  @memory
end

#modelObject (readonly)

Returns the value of attribute model.



9
10
11
# File 'lib/autoflux/openai/agent.rb', line 9

def model
  @model
end

#nameObject (readonly)

Returns the value of attribute name.



9
10
11
# File 'lib/autoflux/openai/agent.rb', line 9

def name
  @name
end

Instance Method Details

#call(prompt, **context) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/autoflux/openai/agent.rb', line 19

def call(prompt, **context)
  @memory << { role: :user, content: prompt }

  loop do
    res = complete
    @memory << res
    break res[:content] || "" unless res[:tool_calls]&.any?

    res[:tool_calls].each do |call|
      @memory << { role: :tool, content: use(call, **context).to_json, tool_call_id: call[:id] }
    end
  end
end

#tool(name) ⇒ Object



48
49
50
# File 'lib/autoflux/openai/agent.rb', line 48

def tool(name)
  @_tools.find { |tool| tool.name == name }
end

#toolsObject

rubocop:disable Metrics/MethodLength



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/autoflux/openai/agent.rb', line 33

def tools # rubocop:disable Metrics/MethodLength
  return unless @_tools.any?

  @tools ||= @_tools.map do |tool|
    {
      type: :function,
      function: {
        name: tool.name,
        description: tool.description,
        parameters: tool.parameters
      }
    }
  end
end

#use(call, **context) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/autoflux/openai/agent.rb', line 52

def use(call, **context)
  name = call.dig(:function, :name)
  params = JSON.parse(call.dig(:function, :arguments), symbolize_names: true)

  tool(name)&.call(params, **context) || { error: "tool not found: #{name}" }
rescue JSON::ParserError
  { error: "unable parse argument as JSON" }
end