-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathcli.py
More file actions
1598 lines (1384 loc) · 76.6 KB
/
Copy pathcli.py
File metadata and controls
1598 lines (1384 loc) · 76.6 KB
1
2
3
4
5
6
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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
178
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
248
249
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import os
import json
import asyncio
import sys
import click
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.markdown import Markdown
from rich.syntax import Syntax
from rich.theme import Theme
from rich.text import Text
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.prompt import Prompt, Confirm
from dotenv import load_dotenv
from src.workflow.cache import workflow_cache
import functools
import shlex
import platform
import atexit
import logging
import signal
from config.global_variables import agents_dir
from src.workflow.polish_task import polish_agent
import traceback
logging.basicConfig(level=logging.INFO)
load_dotenv()
from src.interface.agent import *
from src.service.server import Server
if platform.system() == "Windows":
import collections
collections.Callable = collections.abc.Callable
from pyreadline import Readline
readline = Readline()
else:
import readline
custom_theme = Theme({
"info": "dim cyan",
"warning": "magenta",
"danger": "bold red",
"success": "bold green",
"command": "bold yellow",
"highlight": "bold cyan",
"agent_name": "bold blue",
"agent_nick_name": "bold magenta",
"agent_desc": "green",
"agent_type": "magenta",
"tool_name": "bold blue",
"tool_desc": "green",
"user_msg": "bold white on blue",
"assistant_msg": "bold black on green",
"step_title": "bold magenta",
"step_desc": "green",
"step_note": "magenta",
})
# Create Rich console object for beautified output
console = Console(theme=custom_theme)
_pending_line = ''
def direct_print(text):
global _pending_line
if not text:
return
text_to_print = str(text)
# Handle special characters (< and >)
if '<' in text_to_print or '>' in text_to_print:
parts = []
i = 0
while i < len(text_to_print):
if text_to_print[i] == '<':
end_pos = text_to_print.find('>', i)
if end_pos > i:
parts.append(text_to_print[i:end_pos+1])
i = end_pos + 1
else:
parts.append(text_to_print[i])
i += 1
else:
parts.append(text_to_print[i])
i += 1
text_to_print = ''.join(parts)
_pending_line += text_to_print
while '\n' in _pending_line:
pos = _pending_line.find('\n')
line = _pending_line[:pos+1]
sys.stdout.write(line)
sys.stdout.flush()
_pending_line = _pending_line[pos+1:]
def flush_pending():
global _pending_line
if _pending_line:
sys.stdout.write(_pending_line)
sys.stdout.flush()
_pending_line = ''
def stream_print(text, **kwargs):
"""Stream print text, ensuring immediate display. Automatically detects and renders Markdown format."""
if kwargs.get("end", "\n") == "" and not kwargs.get("highlight", True):
if text:
sys.stdout.write(str(text))
sys.stdout.flush()
else:
if isinstance(text, str) and _is_likely_markdown(text):
try:
plain_text = Text.from_markup(text).plain
if plain_text.strip():
md = Markdown(plain_text)
console.print(md, **kwargs)
else:
console.print(text, **kwargs)
except Exception:
console.print(text, **kwargs)
else:
console.print(text, **kwargs)
sys.stdout.flush()
def show_agent_config(config):
stream_print(Panel.fit(
f"[agent_name]Name:[/agent_name] {config.get('agent_name', '')}\n"
f"[agent_nick_name]NickName:[/agent_nick_name] {config.get('nick_name', '')}\n"
f"[agent_desc]Description:[/agent_desc] {config.get('description', '')}\n"
f"[tool_name]Tools:[/tool_name] {', '.join([t.get('name', '') for t in config.get('selected_tools', [])])}\n"
f"[highlight]Prompt:[/highlight]\n{config.get('prompt', '')}",
title="Current Configuration",
border_style="blue"
))
async def edit_agent_option(_agent: Agent, edit_option:list[str], original_config, modified_config, server: Server):
all_edit_option = {
'NickName': 'Modify NickName',
'Description': 'Modify Description',
'Tool': 'Modify Tool List',
'Prompt': 'Modify Prompt',
'Preview': 'Preview Changes',
'Save': 'Save and Exit',
'Exit': 'Only Exit'
}
choices = []
console.print("\nSelect content to modify:")
edit_option += ['Preview', 'Save', 'Exit']
for index, option in enumerate(edit_option):
console.print(f"{index + 1} - {all_edit_option[option]}")
choices.append(str(index + 1))
choice = Prompt.ask(
"Enter option",
choices=choices,
show_choices=False
)
choice_option = edit_option[int(choice)-1]
if choice_option == 'NickName':
new_name = Prompt.ask(
"Enter new NickName",
default=modified_config.get('nick_name', ''),
show_default=True
)
modified_config['nick_name'] = new_name
return False
elif choice_option == 'Description':
new_desc = Prompt.ask(
"Enter new description",
default=modified_config.get('description', ''),
show_default=True
)
modified_config['description'] = new_desc
return False
elif choice_option == 'Tool':
async def use_ai_generate_prompt():
if Confirm.ask("Whether to automatically update prompt?"):
repeat = True
while repeat:
polish_content = await polish_agent(_agent=_agent, part_to_edit='tool', tools=modified_config.get('selected_tools'))
stream_print(f"polished description: \n {polish_content['agent_description']}\n\n")
stream_print(f"polished prompt: \n {polish_content['prompt']}")
if not Confirm.ask("Do we need to regenerate the prompt?"):
repeat = False
if Confirm.ask("Confirm saving changes?"):
modified_config['description'] = polish_content['agent_description']
modified_config['prompt'] = polish_content['prompt']
else:
stream_print(f"[warning]The tool list may not match the prompt[/warning]")
else:
stream_print(f"[warning]The tool list may not match the prompt[/warning]")
stream_print("[green]Fetching tool list...")
default_tool_name = []
default_tool_desc = {}
async for tool_json in server._list_default_tools():
try:
default_tool = json.loads(tool_json)
default_tool_name.append(default_tool.get('name'))
default_tool_desc[default_tool.get('name')] = default_tool.get('description')
except:
stream_print(f"[danger]Parsing error: {tool_json}[/danger]")
stream_print("[success]Fetched tools!")
table = Table(title=f"Tool list for agent [highlight]{modified_config.get('nick_name')}[/highlight]", show_header=True, header_style="bold magenta", border_style="cyan")
table.add_column("Number", style="tool_desc")
table.add_column("Name", style="tool_desc")
table.add_column("Description", style="tool_desc")
current_tools = modified_config.get('selected_tools')
agent_tool_names = []
for num,tool in enumerate(current_tools):
table.add_row(str(num), tool['name'], tool['description'])
agent_tool_names.append(tool['name'])
stream_print(table)
_stop = False
while not _stop:
edit_tools_option = ["add tool","delete tool","view default tool list"]
for i, part_option in enumerate(edit_tools_option):
console.print(f"{i + 1} - {part_option}")
choice_tools_option_idx = Prompt.ask(
"Enter part number to select operation",
choices=[str(i + 1) for i in range(len(edit_tools_option))],
show_choices=False
)
if choice_tools_option_idx == '1':
new_tools = Prompt.ask(
"Enter tool list to add (comma-separated)",
show_default=True
)
change_successful = False
for t in new_tools.split(','):
if t.strip() not in agent_tool_names:
if t.strip() in default_tool_name:
modified_config['selected_tools'].append({"name": t.strip(), "description": default_tool_desc[t.strip()]})
change_successful = True
else:
stream_print(f"[danger]Error occurred during add:\n {t.strip()} does not exist in the default tool list[/danger]")
else:
stream_print(f"[warning]{t.strip()} already exists[/warning]")
if change_successful:
await use_ai_generate_prompt()
_stop = True
elif choice_tools_option_idx == '2':
del_tools = Prompt.ask(
"Enter tool list to delete (comma-separated)",
show_default=True
)
change_successful = False
for t in del_tools.split(','):
if t.strip() in agent_tool_names:
for i,original_tool in enumerate(modified_config.get('selected_tools')):
if original_tool["name"] == t.strip():
modified_config['selected_tools'].pop(i)
change_successful = True
break
else:
stream_print(
f"[danger]Error occurred during delete:\n {t.strip()} does not exist in the agent tool list[/danger]")
if change_successful:
await use_ai_generate_prompt()
_stop = True
elif choice_tools_option_idx == '3':
table = Table(title="Default Tool List", show_header=True, header_style="bold magenta", border_style="cyan")
table.add_column("Name", style="tool_name")
table.add_column("Description", style="tool_desc")
for tool_name in default_tool_name:
table.add_row(tool_name, default_tool_desc[tool_name])
stream_print(table)
return False
elif choice_option == 'Prompt':
console.print("Enter new prompt (type 'END' to finish):")
lines = []
while True:
line = Prompt.ask("> ", default="")
if line == "END":
break
lines.append(line)
modified_config['prompt'] = "\n".join(lines)
return False
elif choice_option == 'Preview':
show_agent_config(original_config)
stream_print(Panel.fit(
f"[agent_name]New Name:[/agent_name] {modified_config.get('agent_name', '')}\n"
f"[nick_name]New NickName:[/nick_name] {modified_config.get('nick_name', '')}\n"
f"[agent_desc]New Description:[/agent_desc] {modified_config.get('description', '')}\n"
f"[tool_name]New Tools:[/tool_name] {', '.join([t.get('name', '') for t in modified_config.get('selected_tools', [])])}\n"
f"[highlight]New Prompt:[/highlight]\n{modified_config.get('prompt', '')}",
title="Modified Configuration Preview",
border_style="yellow"
))
return False
elif choice_option == 'Save':
if Confirm.ask("Confirm saving changes and exit?"):
try:
agent_request = Agent(
user_id=original_config.get('user_id', ''),
nick_name=modified_config['nick_name'],
agent_name=modified_config['agent_name'],
description=modified_config['description'],
selected_tools=modified_config['selected_tools'],
prompt=modified_config['prompt'],
llm_type=original_config.get('llm_type', 'basic')
)
_agent.prompt = modified_config['prompt']
_agent.description = modified_config['description']
_agent.selected_tools = modified_config['selected_tools']
async for result in server._edit_agent(agent_request):
res = json.loads(result)
if res.get("result") == "success":
stream_print(Panel.fit("[success]Agent updated successfully![/success]", border_style="green"))
else:
stream_print(f"[danger]Update failed: {res.get('result', 'Unknown error')}[/danger]")
return True
except Exception as e:
stream_print(f"[danger]Error occurred during save: {str(e)}[/danger]")
return True
else:
stream_print("[warning]Modifications cancelled[/warning]")
return False
elif choice_option == 'Exit':
if Confirm.ask("Abandon any changes and exit?"):
return True
else:
return False
def _is_likely_markdown(text):
"""Use simple heuristics to determine if the text is likely Markdown."""
return any(marker in text for marker in ['\n#', '\n*', '\n-', '\n>', '```', '**', '__', '`', '[', '](', '
HISTORY_FILE = os.path.expanduser("~/.cooragent_history")
def _init_readline():
try:
readline.parse_and_bind(r'"\C-?": backward-kill-word')
readline.parse_and_bind(r'"\e[3~": delete-char')
readline.parse_and_bind('set editing-mode emacs')
readline.parse_and_bind('set horizontal-scroll-mode on')
readline.parse_and_bind('set bell-style none')
history_dir = os.path.dirname(HISTORY_FILE)
if not os.path.exists(history_dir):
os.makedirs(history_dir, exist_ok=True)
if not os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
pass
try:
readline.read_history_file(HISTORY_FILE)
except:
pass
readline.set_history_length(1000)
atexit.register(_save_history)
except Exception as e:
console.print(f"[warning]Failed to initialize command history: {str(e)}[/warning]")
def _save_history():
"""Safely save command history"""
try:
readline.write_history_file(HISTORY_FILE)
except Exception as e:
console.print(f"[warning]Unable to save command history: {str(e)}[/warning]")
def print_banner():
banner = """
╔═══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ ██████╗ ██████╗ ██████╗ ██████╗ █████╗ ██████╗ ███████╗███╗ ██╗████████╗
║ ██╔════╝██╔═══██╗██╔═══██╗██╔══██╗██╔══██╗██╔════╝ ██╔════╝████╗ ██║╚══██╔══╝
║ ██║ ██║ ██║██║ ██║██████╔╝███████║██║ ███╗█████╗ ██╔██╗ ██║ ██║
║ ██║ ██║ ██║██║ ██║██╔══██╗██╔══██║██║ ██║██╔══╝ ██║╚██╗██║ ██║
║ ╚██████╗╚██████╔╝╚██████╔╝██║ ██║██║ ██║╚██████╔╝███████╗██║ ╚████║ ██║
║ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝
║ ║
╚═══════════════════════════════════════════════════════════════════════════════╝
"""
console.print(Panel(Text(banner, style="bold cyan"), border_style="green"))
console.print("Welcome to [highlight]CoorAgent[/highlight]! CoorAgent is an AI agent collaboration community. Here, you can create specific agents with a single sentence and collaborate with other agents to complete complex tasks. Agents can be combined freely, creating infinite possibilities. You can also publish your agents to the community and share them to anyone!\n", justify="center")
def async_command(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return asyncio.run(f(*args, **kwargs))
return wrapper
def handle_sigint(signal, frame):
console.print("[success]Goodbye![/]")
flush_pending() # Flush buffer before exiting
sys.exit(0)
def init_server(ctx):
"""global init function"""
if not ctx.obj.get('_initialized', False):
with console.status("[bold green]Initializing server...[/]", spinner="dots"):
_init_readline()
print_banner()
ctx.obj['server'] = Server()
ctx.obj['_initialized'] = True
console.print("[success]✓ Server initialized successfully[/]")
@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):
"""CoorAgent command-line tool"""
signal.signal(signal.SIGINT, handle_sigint)
ctx.ensure_object(dict)
init_server(ctx)
if ctx.invoked_subcommand is None:
console.print("Enter 'exit' to quit interactive mode\n")
should_exit = False
while not should_exit:
try:
command = input("\001\033[1;36m\002CoorAgent>\001\033[0m\002 ").strip()
if not command:
continue
if command.lower() in ('exit', 'quit'):
console.print("[success]Goodbye![/]")
should_exit = True
flush_pending() # Flush buffer before exiting
break
if command and not command.lower().startswith(('exit', 'quit')):
readline.add_history(command)
args = shlex.split(command)
with cli.make_context("cli", args, parent=ctx) as sub_ctx:
cli.invoke(sub_ctx)
except Exception as e:
console.print(f"[danger]Error: {str(e)}[/]")
return
@cli.command(name="run-l")
@click.pass_context
@click.option('--user-id', '-u', default="test", help='User ID')
@click.option('--task-type', '-t', required=True,
type=click.Choice([task_type.value for task_type in TaskType]),
help='Task type (options: agent_factory, agent_workflow)')
@click.option('--message', '-m', required=True, multiple=True, help='Message content (use multiple times for multiple messages)')
@click.option('--debug/--no-debug', default=False, help='Enable debug mode')
@click.option('--deep-thinking/--no-deep-thinking', default=True, help='Enable deep thinking mode')
@click.option('--search-before-planning/--no-search-before-planning', default=False, help='Enable search before planning')
@click.option('--agents', '-a', multiple=True, help='List of collaborating Agents (use multiple times to add multiple Agents)')
@async_command
async def run_launch(ctx, user_id, task_type, message, debug, deep_thinking, search_before_planning, agents,):
"""Run the agent workflow"""
server: Server = ctx.obj['server']
config_table = Table(title="Run Launch Configuration", show_header=True, header_style="bold magenta")
config_table.add_column("Parameter", style="cyan")
config_table.add_column("Value", style="green")
config_table.add_row("User ID", user_id)
config_table.add_row("Task Type", task_type)
config_table.add_row("Debug Mode", "✅ Enabled" if debug else "❌ Disabled")
config_table.add_row("Deep Thinking", "✅ Enabled" if deep_thinking else "❌ Disabled")
config_table.add_row("Search Before Planning", "✅ Enabled" if search_before_planning else "❌ Disabled")
console.print(config_table)
msg_table = Table(title="Message History", show_header=True, header_style="bold magenta")
msg_table.add_column("Role", style="cyan")
msg_table.add_column("Content", style="green")
for i, msg in enumerate(message):
role = "User" if i % 2 == 0 else "Assistant"
style = "user_msg" if i % 2 == 0 else "assistant_msg"
msg_table.add_row(role, Text(msg, style=style))
console.print(msg_table)
messages = []
for i, msg in enumerate(message):
role = "user" if i % 2 == 0 else "assistant"
messages.append({"role": role, "content": msg})
request = AgentRequest(
user_id=user_id,
lang="en",
task_type=task_type,
messages=messages,
debug=debug,
deep_thinking_mode=deep_thinking,
search_before_planning=search_before_planning,
coor_agents=list(agents),
workmode="launch",
)
console.print(Panel.fit("[highlight]Workflow execution started[/highlight]", title="CoorAgent", border_style="cyan"))
current_content = ""
json_buffer = ""
in_json_block = False
live_mode = True
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
transient=True,
refresh_per_second=2
) as progress:
task = progress.add_task("[green]Processing request...", total=None)
async for chunk in server._run_agent_workflow(request):
event_type = chunk.get("event")
data = chunk.get("data", {})
if event_type == "start_of_agent":
if current_content:
console.print(current_content, end="", highlight=False)
current_content = ""
if in_json_block and json_buffer:
try:
parsed_json = json.loads(json_buffer)
formatted_json = json.dumps(parsed_json, indent=2, ensure_ascii=False)
console.print("\n")
syntax = Syntax(formatted_json, "json", theme="monokai", line_numbers=False)
console.print(syntax)
except:
console.print(f"\n{json_buffer}")
json_buffer = ""
in_json_block = False
agent_name = data.get("agent_name", "")
if agent_name :
console.print("\n")
progress.update(task, description=f"[green]Starting execution: {agent_name}...")
console.print(f"[agent_name]>>> {agent_name} starting execution...[/agent_name]")
console.print("")
elif event_type == "end_of_agent":
# The pipeline needs to be flushed after the agent finishes
flush_pending()
if current_content:
console.print(current_content, end="", highlight=False)
current_content = ""
if in_json_block and json_buffer:
try:
parsed_json = json.loads(json_buffer)
formatted_json = json.dumps(parsed_json, indent=2, ensure_ascii=False)
console.print("\n")
syntax = Syntax(formatted_json, "json", theme="monokai", line_numbers=False)
console.print(syntax)
except:
console.print(f"\n{json_buffer}")
json_buffer = ""
in_json_block = False
agent_name = data.get("agent_name", "")
if agent_name:
console.print("\n")
progress.update(task, description=f"[green]Execution finished: {agent_name}...")
console.print(f"[agent_name]<<< {agent_name} execution finished[/agent_name]")
console.print("")
elif event_type == "messages":
delta = data.get("delta", {})
content = delta.get("content", "")
reasoning = delta.get("reasoning_content", "")
agent_name = data.get("agent_name", "")
if agent_name:
console.print("\n")
progress.update(task, description=f"[green]Executing: {agent_name}...")
progress.update(task, description=f"[agent_name]>>> {agent_name} executing...[/agent_name]")
console.print("")
if content and (content.strip().startswith("{") or in_json_block):
if not in_json_block:
in_json_block = True
json_buffer = ""
json_buffer += content
try:
parsed_json = json.loads(json_buffer)
formatted_json = json.dumps(parsed_json, indent=2, ensure_ascii=False)
if current_content:
console.print(current_content, end="", highlight=False)
current_content = ""
console.print("")
syntax = Syntax(formatted_json, "json", theme="monokai", line_numbers=False)
console.print(syntax)
json_buffer = ""
in_json_block = False
except:
pass
elif content:
if live_mode:
if not content:
continue
direct_print(content)
else:
current_content += content
if reasoning:
stream_print(f"\n[info]Thinking process: {reasoning}[/info]")
elif event_type == "new_agent_created":
new_agent_name = data.get("new_agent_name", "")
agent_obj = data.get("agent_obj", None)
console.print(f"[new_agent_name]>>> {new_agent_name} created successfully...")
console.print(f"[new_agent]>>> Configuration: ")
syntax = Syntax(agent_obj, "json", theme="monokai", line_numbers=False)
console.print(syntax)
elif event_type == "end_of_workflow":
if current_content:
console.print(current_content, end="", highlight=False)
current_content = ""
if in_json_block and json_buffer:
try:
parsed_json = json.loads(json_buffer)
formatted_json = json.dumps(parsed_json, indent=2, ensure_ascii=False)
console.print("\n")
syntax = Syntax(formatted_json, "json", theme="monokai", line_numbers=False)
console.print(syntax)
except:
console.print(f"\n{json_buffer}")
json_buffer = ""
in_json_block = False
console.print("")
progress.update(task, description="[success]Workflow execution finished!")
console.print(Panel.fit("[success]Workflow execution finished![/success]", title="CoorAgent", border_style="green"))
console.print(Panel.fit("[success]Workflow execution finished![/success]", title="CoorAgent", border_style="green"))
@cli.command(name="run-p")
@click.pass_context
@click.option('--user-id', '-u', default="test", help='User ID')
@click.option('--messages', '-m', default=[], multiple=True, help='Message content (use multiple times for multiple messages)')
@click.option('--workflow-id', '-w', default="", help='Workflow ID')
@async_command
async def run_production(ctx, user_id, messages, workflow_id):
"""Run the agent workflow"""
server: Server = ctx.obj['server']
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console
) as progress:
task = progress.add_task("[green]Fetching Workflow list...", total=None)
request = listAgentRequest(user_id=user_id, match=None)
table = Table(title=f"Workflow list for user [highlight]{user_id}[/highlight]", show_header=True, header_style="bold magenta", border_style="cyan")
table.add_column("ID", style="tool_desc")
table.add_column("Workflow ID", style="tool_desc")
table.add_column("Lap", style="tool_desc")
table.add_column("Version", style="tool_desc")
table.add_column("Graph", style="tool_desc")
table.add_column("Planning Steps", style="agent_nick_name")
count = 0
workflow_list = server._list_workflow(request)
for workflow in workflow_list:
try:
steps = workflow.get("planning_steps", [])
if workflow_id:
if workflow.get("workflow_id") == workflow_id:
table.add_row(str(count), workflow.get("workflow_id", ""), str(workflow.get("lap", "")), str(workflow.get("version", "")), json.dumps(workflow.get("graph", ""), indent=2, ensure_ascii=False), json.dumps(steps, indent=2, ensure_ascii=False))
count += 1
break
else:
table.add_row(str(count), workflow.get("workflow_id", ""), str(workflow.get("lap", "")), str(workflow.get("version", "")), json.dumps(workflow.get("graph", ""), indent=2, ensure_ascii=False), json.dumps(steps, indent=2, ensure_ascii=False))
count += 1
except Exception as e:
logging.error(f"Error parsing workflow: {traceback.format_exc()}")
stream_print(f"[danger]Parsing error: {workflow}[/danger]")
progress.update(task, description=f"[success]Fetched {count} workflow!")
if count == 0:
stream_print(Panel(f"No matching workflow found", title="Result", border_style="yellow"))
else:
stream_print(table)
option = ["Select workflow", "Exit"]
console.print("Select Command:")
for i, part_option in enumerate(option):
console.print(f"{i+1} - {part_option}")
part_choice_idx_str = Prompt.ask(
"Enter part number",
choices=[str(i+1) for i in range(len(option))],
show_choices=False
)
if part_choice_idx_str == "2":
return
if part_choice_idx_str == "1":
console.print("\n Select workflow by index to run:")
choice = Prompt.ask(
"Enter workflow ID",
choices=[str(i) for i in range(count)],
show_choices=True
)
workflow = workflow_list[int(choice)]
workflow_id = workflow["workflow_id"]
input_messages = []
if messages:
for i, msg in enumerate(messages):
role = "user" if i % 2 == 0 else "assistant"
input_messages.append({"role": role, "content": msg})
else:
input_messages = workflow["user_input_messages"]
request = AgentRequest(
user_id=user_id,
lang="en",
task_type="agent_workflow",
messages=input_messages,
debug=False,
deep_thinking_mode=True,
search_before_planning=False,
coor_agents=[],
workmode="production",
workflow_id=workflow_id
)
console.print(Panel.fit("[highlight]Workflow execution started[/highlight]", title="CoorAgent", border_style="cyan"))
current_content = ""
json_buffer = ""
in_json_block = False
live_mode = True
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
transient=True,
refresh_per_second=2
) as progress:
task = progress.add_task("[green]Processing request...", total=None)
async for chunk in server._run_agent_workflow(request):
event_type = chunk.get("event")
data = chunk.get("data", {})
if event_type == "start_of_agent":
if current_content:
console.print(current_content, end="", highlight=False)
current_content = ""
if in_json_block and json_buffer:
try:
parsed_json = json.loads(json_buffer)
formatted_json = json.dumps(parsed_json, indent=2, ensure_ascii=False)
console.print("\n")
syntax = Syntax(formatted_json, "json", theme="monokai", line_numbers=False)
console.print(syntax)
except:
console.print(f"\n{json_buffer}")
json_buffer = ""
in_json_block = False
agent_name = data.get("agent_name", "")
if agent_name :
console.print("\n")
progress.update(task, description=f"[green]Starting execution: {agent_name}...")
console.print(f"[agent_name]>>> {agent_name} starting execution...[/agent_name]")
console.print("")
elif event_type == "end_of_agent":
if current_content:
console.print(current_content, end="", highlight=False)
current_content = ""
if in_json_block and json_buffer:
try:
parsed_json = json.loads(json_buffer)
formatted_json = json.dumps(parsed_json, indent=2, ensure_ascii=False)
console.print("\n")
syntax = Syntax(formatted_json, "json", theme="monokai", line_numbers=False)
console.print(syntax)
except:
console.print(f"\n{json_buffer}")
json_buffer = ""
in_json_block = False
agent_name = data.get("agent_name", "")
if agent_name:
console.print("\n")
progress.update(task, description=f"[green]Execution finished: {agent_name}...")
console.print(f"[agent_name]<<< {agent_name} execution finished[/agent_name]")
console.print("")
elif event_type == "messages":
delta = data.get("delta", {})
content = delta.get("content", "")
reasoning = delta.get("reasoning_content", "")
agent_name = data.get("agent_name", "")
if agent_name:
console.print("\n")
progress.update(task, description=f"[green]Executing: {agent_name}...")
progress.update(task, description=f"[agent_name]>>> {agent_name} executing...[/agent_name]")
console.print("")
if content and (content.strip().startswith("{") or in_json_block):
if not in_json_block:
in_json_block = True
json_buffer = ""
json_buffer += content
try:
parsed_json = json.loads(json_buffer)
formatted_json = json.dumps(parsed_json, indent=2, ensure_ascii=False)
if current_content:
console.print(current_content, end="", highlight=False)
current_content = ""
console.print("")
syntax = Syntax(formatted_json, "json", theme="monokai", line_numbers=False)
console.print(syntax)
json_buffer = ""
in_json_block = False
except:
pass
elif content:
if live_mode:
if not content:
continue
direct_print(content)
else:
current_content += content
if reasoning:
stream_print(f"\n[info]Thinking process: {reasoning}[/info]")
elif event_type == "new_agent_created":
new_agent_name = data.get("new_agent_name", "")
agent_obj = data.get("agent_obj", None)
console.print(f"[new_agent_name]>>> {new_agent_name} created successfully...")
console.print(f"[new_agent]>>> Configuration: ")
syntax = Syntax(agent_obj, "json", theme="monokai", line_numbers=False)
console.print(syntax)
elif event_type == "end_of_workflow":
if current_content:
console.print(current_content, end="", highlight=False)
current_content = ""
if in_json_block and json_buffer:
try:
parsed_json = json.loads(json_buffer)
formatted_json = json.dumps(parsed_json, indent=2, ensure_ascii=False)
console.print("\n")
syntax = Syntax(formatted_json, "json", theme="monokai", line_numbers=False)
console.print(syntax)
except:
console.print(f"\n{json_buffer}")
json_buffer = ""
in_json_block = False
console.print("")
progress.update(task, description="[success]Workflow execution finished!")
console.print(Panel.fit("[success]Workflow execution finished![/success]", title="CoorAgent", border_style="green"))
console.print(Panel.fit("[success]Workflow execution finished![/success]", title="CoorAgent", border_style="green"))
@cli.command()
@click.pass_context
@click.option('--user-id', '-u', default="test", help='User ID')
@click.option('--match', '-m', default="", help='Match string')
@async_command
async def list_agents(ctx, user_id, match):
"""List user's Agents"""
server = ctx.obj['server']
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console
) as progress:
task = progress.add_task("[green]Fetching Agent list...", total=None)
request = listAgentRequest(user_id=user_id, match=match)
table = Table(title=f"Agent list for user [highlight]{user_id}[/highlight]", show_header=True, header_style="bold magenta", border_style="cyan")
table.add_column("Name", style="agent_name")
table.add_column("NickName", style="agent_nick_name")
table.add_column("Description", style="agent_desc")
table.add_column("Tools", style="agent_type")
count = 0
async for agent_json in server._list_agents(request):
try:
agent = json.loads(agent_json)
tools = []
for tool in agent.get("selected_tools", []):
tools.append(tool.get("name", ""))
table.add_row(agent.get("agent_name", ""), agent.get("nick_name", ""), agent.get("description", ""), ', '.join(tools))
count += 1
except:
stream_print(f"[danger]Parsing error: {agent_json}[/danger]")
progress.update(task, description=f"[success]Fetched {count} Agents!")
if count == 0:
stream_print(Panel(f"No matching Agents found", title="Result", border_style="yellow"))
else:
stream_print(table)
@cli.command()
@click.pass_context
@async_command
async def list_default_agents(ctx):
"""List default Agents"""
server = ctx.obj['server']
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console
) as progress:
task = progress.add_task("[green]Fetching default Agent list...", total=None)
table = Table(title="Default Agent List", show_header=True, header_style="bold magenta", border_style="cyan")
table.add_column("Name", style="agent_name")
table.add_column("NickName", style="agent_nick_name")
table.add_column("Description", style="agent_desc")
count = 0
async for agent_json in server._list_default_agents():
try:
agent = json.loads(agent_json)
table.add_row(agent.get("agent_name", ""),agent.get("nick_name", ""), agent.get("description", ""))
count += 1
except:
stream_print(f"[danger]Parsing error: {agent_json}[/danger]")
progress.update(task, description=f"[success]Fetched {count} default Agents!")
stream_print(table)
@cli.command()
@click.pass_context
@async_command
async def list_default_tools(ctx):
"""List default tools"""
server = ctx.obj['server']
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console
) as progress:
task = progress.add_task("[green]Fetching default tool list...", total=None)
table = Table(title="Default Tool List", show_header=True, header_style="bold magenta", border_style="cyan")
table.add_column("Name", style="tool_name")
table.add_column("Description", style="tool_desc")
count = 0
async for tool_json in server._list_default_tools():
try:
tool = json.loads(tool_json)
table.add_row(tool.get("name", ""), tool.get("description", ""))
count += 1