Class: OpenAISwarm::Core

Inherits:
Object
  • Object
show all
Includes:
Util
Defined in:
lib/ruby-openai-swarm/core.rb

Constant Summary collapse

CTX_VARS_NAME =
'context_variables'

Instance Method Summary collapse

Methods included from Util

clean_message_tools, debug_print, function_to_json, latest_role_user_message, merge_chunk, merge_fields, message_template, request_tools_excluded, symbolize_keys_to_string

Constructor Details

#initialize(client = nil) ⇒ Core

Returns a new instance of Core.



13
14
15
16
# File 'lib/ruby-openai-swarm/core.rb', line 13

def initialize(client = nil)
  @client = client || OpenAI::Client.new
  @logger = OpenAISwarm::Logger.instance.logger
end

Instance Method Details

#get_chat_completion(agent_tracker, history, context_variables, model_override, stream, debug, metadata = nil) ⇒ Object

TODO(Grayson) def create_agent(name:, model:, instructions:, **options)

memory = Memory.new(@memory_fields)
Agent.new(
  name: name,
  model: model,
  instructions: instructions,
  memory: memory,
  functions: functions,
  **options
)

end



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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/ruby-openai-swarm/core.rb', line 31

def get_chat_completion(agent_tracker, history, context_variables, model_override, stream, debug,  = nil)
  agent = agent_tracker.current_agent
  context_variables = context_variables.dup
  instructions = agent.instructions.respond_to?(:call) ? agent.instructions.call(context_variables) : agent.instructions

  # Build a message history, including memories
  messages = [{ role: 'system', content: instructions }]
  messages << { role: 'system', content: agent.memory.prompt_content } unless agent&.memory&.prompt_content.nil?
  messages += history

  # Util.debug_print(debug, "Getting chat completion for...:", messages)

  tools = agent.functions.map { |f| Util.function_to_json(f) }
  # hide context_variables from model
  tools.each do |tool|
    params = tool[:function][:parameters]
    params[:properties].delete(CTX_VARS_NAME.to_sym)
    params[:required]&.delete(CTX_VARS_NAME.to_sym)
  end

  cleaned_messages = Util.clean_message_tools(messages, agent.noisy_tool_calls)

  create_params = {
    model: model_override || agent.model,
    messages: cleaned_messages,
    tools: Util.request_tools_excluded(tools, agent_tracker.tracking_agents_tool_name, agent.strategy.prevent_agent_reentry),
  }

  # Add metadata if provided
  # Add support for LiteLLM observability with Langfuse
  # See: https://docs.litellm.ai/docs/observability/langfuse_integration
  if  && .is_a?(Hash)
     = .deep_transform_values { |val| val.to_s.to_sym == :agent_name ? agent&.name : val }
    create_params[:metadata] = 
  end

  # TODO: https://platform.openai.com/docs/guides/function-calling/how-do-functions-differ-from-tools
  # create_params[:functions] = tools unless tools.empty?
  # create_params[:function_call] = agent.tool_choice if agent.tool_choice

  create_params[:temperature] = agent.temperature if agent.temperature
  create_params[:tool_choice] = agent.tool_choice if agent.tool_choice
  create_params[:parallel_tool_calls] = agent.parallel_tool_calls if tools.any?

  Util.debug_print(debug, "Getting chat completion for...:", create_params)
  log_message(:info, "Getting chat completion for...:", create_params)

  if stream
    return Enumerator.new do |yielder|
      yielder << { 'parameters' => create_params }

      @client.chat(parameters: create_params.merge(
        stream: proc do |chunk, _bytesize|
          yielder << { chunk: chunk }
        end
      ))
    end
  else
    response = @client.chat(parameters: create_params)
  end

  Util.debug_print(debug, "API Response:", response)
  response
rescue OpenAI::Error, Faraday::BadRequestError => e
  error_message = (e.response || {}).dig(:body) || e.inspect
  log_message(:error, "OpenAI API Error: #{error_message}")
  Util.debug_print(true, "OpenAI API Error:", error_message)
  raise
end

#handle_function_result(result, debug) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/ruby-openai-swarm/core.rb', line 101

def handle_function_result(result, debug)
  case result
  when Result
    result
  when Agent
    Result.new(
      value: JSON.generate({ assistant: result.name }),
      agent: result
    )
  else
    begin
      Result.new(value: result.to_s)
    rescue => e
      error_message = "Failed to cast response to string: #{result}. Make sure agent functions return a string or Result object. Error: #{e}"
      Util.debug_print(debug, error_message)
      raise TypeError, error_message
    end
  end
end

#handle_tool_calls(tool_calls, active_agent, context_variables, debug) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/ruby-openai-swarm/core.rb', line 121

def handle_tool_calls(tool_calls, active_agent, context_variables, debug)
  functions = active_agent.functions

  function_map = functions.map do |f|
    if f.is_a?(OpenAISwarm::FunctionDescriptor)
      [f.target_method.name, f.target_method]
    else
      [f.name, f]
    end
  end.to_h.transform_keys(&:to_s)

  partial_response = Response.new(
    messages: [],
    agent: nil,
    context_variables: {}
  )

  tool_calls.each do |tool_call|
    name = tool_call.dig('function', 'name')
    unless function_map.key?(name)
      Util.debug_print(debug, "Tool #{name} not found in function map.")
      log_message(:error, "Tool #{name} not found in function map.")
      partial_response.messages << {
        'role' => 'tool',
        'tool_call_id' => tool_call['id'],
        'tool_name' => name,
        'content' => "Error: Tool #{name} not found."
      }
      next
    end

    args = JSON.parse(tool_call.dig('function', 'arguments') || '{}')
    Util.debug_print(debug, "Processing tool call: #{name} with arguments #{args}")
    log_message(:info, "Processing tool call: #{name} with arguments #{args}")

    func = function_map[name]
    # pass context_variables to agent functions
    args[CTX_VARS_NAME] = context_variables if func.parameters.map(&:last).include?(CTX_VARS_NAME.to_sym)
    is_parameters = func.parameters.any?
    arguments = args.transform_keys(&:to_sym)

    raw_result = is_parameters ? func.call(**arguments) : func.call
    result = handle_function_result(raw_result, debug)

    partial_response.messages << {
      'role' => 'tool',
      'tool_call_id' => tool_call['id'],
      'tool_name' => name,
      'content' => result.value
    }

    partial_response.context_variables.merge!(result.context_variables)
    partial_response.agent = result.agent if result.agent
  end

  partial_response
end

#run(agent:, messages:, context_variables: {}, model_override: nil, stream: false, debug: false, max_turns: Float::INFINITY, execute_tools: true, metadata: nil) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/ruby-openai-swarm/core.rb', line 179

def run(agent:, messages:, context_variables: {}, model_override: nil, stream: false, debug: false, max_turns: Float::INFINITY, execute_tools: true, metadata: nil)
  agent_tracker = OpenAISwarm::Agents::ChangeTracker.new(agent)
  if stream
    return run_and_stream(
      agent: agent,
      messages: messages,
      context_variables: context_variables,
      model_override: model_override,
      debug: debug,
      max_turns: max_turns,
      execute_tools: execute_tools,
      metadata: 
    )
  end

  active_agent = agent
  context_variables = context_variables.dup
  history = messages.dup
  init_len = messages.length

  while history.length - init_len < max_turns && active_agent
    agent_tracker.update(active_agent)
    history = OpenAISwarm::Util.latest_role_user_message(history) if agent_tracker.switch_agent_reset_message?

    completion = get_chat_completion(
      agent_tracker,
      history,
      context_variables,
      model_override,
      stream,
      debug,
      
    )

    message = completion.dig('choices', 0, 'message') || {}
    Util.debug_print(debug, "Received completion:", message)
    log_message(:info, "Received completion:", message)

    message['sender'] = active_agent&.name
    history << message

    if !message['tool_calls'] || !execute_tools
      log_message(:info, "Ending turn.")
      break
    end

    partial_response = handle_tool_calls(
      message['tool_calls'],
      active_agent,
      context_variables,
      debug
    )

    if partial_response.agent
      agent_tool_name = message['tool_calls'].dig(0, 'function', 'name')
      agent_tracker.add_tracking_agents_tool_name(agent_tool_name)
    end

    history.concat(partial_response.messages)
    context_variables.merge!(partial_response.context_variables)
    active_agent = partial_response.agent if partial_response.agent
  end

  Response.new(
    messages: history[init_len..],
    agent: active_agent,
    context_variables: context_variables
  )
end

#run_and_stream(agent:, messages:, context_variables: {}, model_override: nil, debug: false, max_turns: Float::INFINITY, execute_tools: true, metadata: nil) {|'response' => Response.new(messages: history[init_len..], agent: active_agent, context_variables: context_variables)| ... } ⇒ Object

TODO(Grayson): a lot of copied code here that will be refactored

Yields:

  • ('response' => Response.new(messages: history[init_len..], agent: active_agent, context_variables: context_variables))


250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/ruby-openai-swarm/core.rb', line 250

def run_and_stream(agent:, messages:, context_variables: {}, model_override: nil, debug: false, max_turns: Float::INFINITY, execute_tools: true, metadata: nil)
  agent_tracker = OpenAISwarm::Agents::ChangeTracker.new(agent)
  active_agent = agent
  context_variables = context_variables.dup
  history = messages.dup
  init_len = messages.length

  while history.length - init_len < max_turns && active_agent
    agent_tracker.update(active_agent)
    history = OpenAISwarm::Util.latest_role_user_message(history) if agent_tracker.switch_agent_reset_message?

    message = OpenAISwarm::Util.message_template(agent.name)
    completion = get_chat_completion(
      agent_tracker,
      history,
      context_variables,
      model_override,
      true, # stream
      debug,
      
    )

    yield({ delim: "start" }) if block_given?
    completion.each do |stream|

      # TODO(Grayson): will refactor it
      if stream['parameters']
        yield({ 'parameters' => stream['parameters'], 'agent' => active_agent&.name }) if block_given?
      end
      next if stream.key?('parameters')

      chunk = stream[:chunk]
      if chunk['error']
        details = {
          'response' =>
             Response.new(
               messages: messages,
               agent: active_agent,
               context_variables: context_variables)
        }
        raise OpenAISwarm::Error.new(chunk['error'], details)
      end

      delta = chunk.dig('choices', 0, 'delta')
      if delta['role'] == "assistant"
        delta['sender'] = active_agent.name
      end

      yield({ 'delta' => delta })  if block_given?

      delta.delete('role')
      delta.delete('sender')
      Util.merge_chunk(message, delta)
    end
    yield({ delim: "end" }) if block_given?

    message['tool_calls'] = message['tool_calls'].values
    message['tool_calls'] = nil if message['tool_calls'].empty?
    Util.debug_print(debug, "Received completion:", message)
    log_message(:info, "Received completion:", message)

    history << message


    if !message['tool_calls'] || !execute_tools
      log_message(:info, "Ending turn.")
      break
    end

    # convert tool_calls to objects
    tool_calls = message['tool_calls'].map do |tool_call|
      OpenStruct.new(
        id: tool_call['id'],
        function: OpenStruct.new(
          arguments: tool_call['function']['arguments'],
          name: tool_call['function']['name']
        ),
        type: tool_call['type']
      )
    end

    partial_response = handle_tool_calls(
      tool_calls,
      active_agent,
      context_variables,
      debug
    )

    if partial_response.agent
      agent_tool_name = message['tool_calls'].dig(0, 'function', 'name')
      agent_tracker.add_tracking_agents_tool_name(agent_tool_name)
    end

    history.concat(partial_response.messages)
    context_variables.merge!(partial_response.context_variables)
    active_agent = partial_response.agent if partial_response.agent

    tool_call_messages = (Array.wrap(message) + partial_response.messages)
    yield(
      'tool_call_messages' => Response.new(
        messages: tool_call_messages,
        agent: active_agent,
        context_variables: context_variables)
    ) if block_given?
  end

  yield(
    'response' => Response.new(messages: history[init_len..],
                               agent: active_agent,
                               context_variables: context_variables)
  ) if block_given?
end