Module: Swarm::Repl

Defined in:
lib/swarm/repl.rb

Class Method Summary collapse

Class Method Details

.pretty_print_messages(messages) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/swarm/repl.rb', line 41

def self.pretty_print_messages(messages)
  messages.each do |message|
    next unless message["role"] == "assistant"

    # Print agent name in blue
    print "\e[94m#{message["sender"]}\e[0m: "

    puts message["content"] if message["content"]

    tool_calls = message["tool_calls"] || []
    puts if tool_calls.length > 1
    tool_calls.each do |tool_call|
      func = tool_call["function"]
      name = func["name"]
      args = JSON.parse(func["arguments"] || "{}").map { |k, v| "#{k}=#{v}" }.join(", ")
      puts "\e[95m#{name}\e[0m(#{args})"
    end
  end
end

.process_and_print_streaming_response(response) ⇒ Object



7
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
33
34
35
36
37
38
39
# File 'lib/swarm/repl.rb', line 7

def self.process_and_print_streaming_response(response)
  content = ""
  last_sender = ""

  response.each do |chunk|
    if chunk["sender"]
      last_sender = chunk["sender"]
    end

    if chunk["content"]
      if content.empty? && last_sender
        print "\e[94m#{last_sender}:\e[0m "
        last_sender = ""
      end
      print chunk["content"]
      content += chunk["content"]
    end

    chunk["tool_calls"]&.each do |tool_call|
      func = tool_call["function"]
      name = func["name"]
      next unless name
      puts "\e[94m#{last_sender}: \e[95m#{name}\e[0m()"
    end

    if chunk["delim"] == "end" && !content.empty?
      puts
      content = ""
    end

    return chunk["response"] if chunk["response"]
  end
end

.run_demo_loop(starting_agent, context_variables = nil, stream = false, debug = false) ⇒ Object



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
# File 'lib/swarm/repl.rb', line 61

def self.run_demo_loop(
  starting_agent,
  context_variables = nil,
  stream = false,
  debug = false
)
  client = Swarm.new
  puts "Starting Swarm CLI \u{1F41D}"

  messages = []
  agent = starting_agent

  loop do
    print "\e[90mUser\e[0m: "
    user_input = gets.chomp
    messages << {"role" => "user", "content" => user_input}

    response = client.run(
      agent: agent,
      messages: messages,
      context_variables: context_variables || {},
      stream: stream,
      debug: debug
    )

    if stream
      response = process_and_print_streaming_response(response)
    else
      pretty_print_messages(response.messages)
    end

    messages.concat(response.messages)
    agent = response.agent
  end
end