Elffuss BraidHub

kikocis/Based-Agent public

96fe88dcefb1 路 2.6 KiBRawPermalink
1import json
2import time
3
4from swarm import Swarm
5
6
7def process_and_print_streaming_response(response):
8 content = ""
9 last_sender = ""
10
11 for chunk in response:
12 if "sender" in chunk:
13 last_sender = chunk["sender"]
14
15 if "content" in chunk and chunk["content"] is not None:
16 if not content and last_sender:
17 print(f"\033[94m{last_sender}:\033[0m", end=" ", flush=True)
18 last_sender = ""
19 print(chunk["content"], end="", flush=True)
20 content += chunk["content"]
21
22 if "tool_calls" in chunk and chunk["tool_calls"] is not None:
23 for tool_call in chunk["tool_calls"]:
24 f = tool_call["function"]
25 name = f["name"]
26 if not name:
27 continue
28 print(f"\033[94m{last_sender}: \033[95m{name}\033[0m()")
29
30 if "delim" in chunk and chunk["delim"] == "end" and content:
31 print() # End of response message
32 content = ""
33
34 if "response" in chunk:
35 return chunk["response"]
36
37
38def pretty_print_messages(messages) -> None:
39 for message in messages:
40 if message["role"] != "assistant":
41 continue
42
43 # print agent name in blue
44 print(f"\033[94m{message['sender']}\033[0m:", end=" ")
45
46 # print response, if any
47 if message["content"]:
48 print(message["content"])
49
50 # print tool calls in purple, if any
51 tool_calls = message.get("tool_calls") or []
52 if len(tool_calls) > 1:
53 print()
54 for tool_call in tool_calls:
55 f = tool_call["function"]
56 name, args = f["name"], f["arguments"]
57 arg_str = json.dumps(json.loads(args)).replace(":", "=")
58 print(f"\033[95m{name}\033[0m({arg_str[1:-1]})")
59
60
61def run_demo_loop(
62 starting_agent, context_variables=None, stream=False, debug=False
63) -> None:
64 client = Swarm()
65 print("Starting Swarm CLI 馃悵")
66
67 messages = []
68 agent = starting_agent
69
70 while True:
71 user_input = input("\033[90mUser\033[0m: ")
72 messages.append({"role": "user", "content": user_input})
73
74 response = client.run(
75 agent=agent,
76 messages=messages,
77 context_variables=context_variables or {},
78 stream=stream,
79 debug=debug,
80 )
81
82 if stream:
83 response = process_and_print_streaming_response(response)
84 else:
85 pretty_print_messages(response.messages)
86
87 messages.extend(response.messages)
88 agent = response.agent
89
90