Elffuss BraidHub

kikocis/Based-Agent public

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