Class: Rasti::AI::OpenAI::Assistant

Inherits:
Object
  • Object
show all
Defined in:
lib/rasti/ai/open_ai/assistant.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client: nil, json_schema: nil, state: nil, model: nil, tools: [], mcp_servers: {}, logger: nil) ⇒ Assistant

Returns a new instance of Assistant.



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
# File 'lib/rasti/ai/open_ai/assistant.rb', line 8

def initialize(client:nil, json_schema:nil, state:nil, model:nil, tools:[], mcp_servers:{}, logger:nil)
  @client = client || Client.new
  @json_schema = json_schema
  @state = state || AssistantState.new
  @model = model
  @tools = {}
  @serialized_tools = []
  @logger = logger || Rasti::AI.logger

  tools.each do |tool|
    serialization = serialize_tool tool
    @tools[serialization[:function][:name]] = tool
    @serialized_tools << serialization
  end

  mcp_servers.each do |name, mcp|
    mcp.list_tools.each do |tool|
      serialization = wrap_tool_serialization tool.merge('name' => "#{name}_#{tool['name']}")
      @tools["#{name}_#{tool['name']}"] = ->(args) do
        mcp.call_tool tool['name'], args
      end
      @serialized_tools << serialization
    end
  end
end

Instance Attribute Details

#stateObject (readonly)

Returns the value of attribute state.



6
7
8
# File 'lib/rasti/ai/open_ai/assistant.rb', line 6

def state
  @state
end

Instance Method Details

#call(prompt) ⇒ Object



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
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/rasti/ai/open_ai/assistant.rb', line 34

def call(prompt)
  messages << {
    role: Roles::USER,
    content: prompt
  }

  loop do
    response = client.chat_completions messages: messages,
                                       model: model,
                                       tools: serialized_tools,
                                       response_format: response_format

    choice = response['choices'][0]['message']

    if choice['tool_calls']
      messages << {
        role: Roles::ASSISTANT,
        tool_calls: choice['tool_calls']
      }

      choice['tool_calls'].each do |tool_call|
        name = tool_call['function']['name']
        args = JSON.parse tool_call['function']['arguments']

        result = call_tool name, args

        messages << {
          role: Roles::TOOL,
          tool_call_id: tool_call['id'],
          content: result
        }
      end
    else
      messages << {
        role: Roles::ASSISTANT,
        content: choice['content']
      }

      return choice['content']
    end
  end
end