-
Notifications
You must be signed in to change notification settings - Fork 600
Expand file tree
/
Copy pathorchestrator.py
More file actions
1208 lines (1056 loc) · 46.2 KB
/
orchestrator.py
File metadata and controls
1208 lines (1056 loc) · 46.2 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
# Copyright (c) 2025 MiroMind
# This source code is licensed under the Apache 2.0 License.
"""
Orchestrator module for coordinating agent task execution.
This module contains the main Orchestrator class that manages the execution of tasks
by coordinating between the main agent, sub-agents, and various tools.
"""
import asyncio
import gc
import logging
import time
import uuid
from collections import defaultdict
from datetime import date
from typing import Any, Dict, List, Optional
from miroflow_tools.manager import ToolManager
from omegaconf import DictConfig
from ..config.settings import expose_sub_agents_as_tools
from ..io.input_handler import process_input
from ..io.output_formatter import OutputFormatter
from ..llm.base_client import BaseClient
from ..logging.task_logger import TaskLog, get_utc_plus_8_time
from ..utils.parsing_utils import extract_llm_response_text
from ..utils.prompt_utils import (
generate_agent_specific_system_prompt,
generate_agent_summarize_prompt,
mcp_tags,
refusal_keywords,
)
from .answer_generator import AnswerGenerator
from .stream_handler import StreamHandler
from .tool_executor import ToolExecutor
logger = logging.getLogger(__name__)
# =============================================================================
# Constants
# =============================================================================
# Default timeout for LLM calls in seconds
DEFAULT_LLM_TIMEOUT = 600
# Safety limits for retry loops
DEFAULT_MAX_CONSECUTIVE_ROLLBACKS = 5
# Additional attempts beyond max_turns for total loop protection
EXTRA_ATTEMPTS_BUFFER = 200
def _list_tools(sub_agent_tool_managers: Dict[str, ToolManager]):
"""
Create a cached async function for fetching sub-agent tool definitions.
This factory function returns an async closure that lazily fetches and caches
tool definitions from all sub-agent tool managers. The cache ensures that
tool definitions are only fetched once per orchestrator instance.
Args:
sub_agent_tool_managers: Dictionary mapping sub-agent names to their ToolManager instances.
Returns:
An async function that returns a dictionary of tool definitions for each sub-agent.
"""
cache = None
async def wrapped():
nonlocal cache
if cache is None:
# Only fetch tool definitions if not already cached
result = {
name: await tool_manager.get_all_tool_definitions()
for name, tool_manager in sub_agent_tool_managers.items()
}
cache = result
return cache
return wrapped
class Orchestrator:
"""
Main orchestrator for coordinating agent task execution.
Manages the execution loop for main and sub-agents, coordinating
LLM calls, tool execution, streaming events, and context management.
"""
def __init__(
self,
main_agent_tool_manager: ToolManager,
sub_agent_tool_managers: Dict[str, ToolManager],
llm_client: BaseClient,
output_formatter: OutputFormatter,
cfg: DictConfig,
task_log: Optional["TaskLog"] = None,
stream_queue: Optional[Any] = None,
tool_definitions: Optional[List[Dict[str, Any]]] = None,
sub_agent_tool_definitions: Optional[Dict[str, List[Dict[str, Any]]]] = None,
):
"""
Initialize the orchestrator.
Args:
main_agent_tool_manager: Tool manager for main agent
sub_agent_tool_managers: Dictionary of tool managers for sub-agents
llm_client: The LLM client for API calls
output_formatter: Formatter for output processing
cfg: Configuration object
task_log: Logger for task execution
stream_queue: Optional async queue for streaming events
tool_definitions: Pre-fetched tool definitions (optional)
sub_agent_tool_definitions: Pre-fetched sub-agent tool definitions (optional)
"""
self.main_agent_tool_manager = main_agent_tool_manager
self.sub_agent_tool_managers = sub_agent_tool_managers
self.llm_client = llm_client
self.output_formatter = output_formatter
self.cfg = cfg
self.task_log = task_log
self.stream_queue = stream_queue
self.tool_definitions = tool_definitions
self.sub_agent_tool_definitions = sub_agent_tool_definitions
# Initialize sub-agent tool list function
self._list_sub_agent_tools = None
if sub_agent_tool_managers:
self._list_sub_agent_tools = _list_tools(sub_agent_tool_managers)
# Pass task_log to llm_client
if self.llm_client and task_log:
self.llm_client.task_log = task_log
# Track boxed answers extracted during main loop turns
self.intermediate_boxed_answers: List[str] = []
# Record used subtask / q / Query to detect duplicates
self.used_queries: Dict[str, Dict[str, int]] = {}
# Retry loop protection limits
self.MAX_CONSECUTIVE_ROLLBACKS = DEFAULT_MAX_CONSECUTIVE_ROLLBACKS
# Context management settings
self.context_compress_limit = cfg.agent.get("context_compress_limit", 0)
# Initialize helper components
self.stream = StreamHandler(stream_queue)
self.tool_executor = ToolExecutor(
main_agent_tool_manager=main_agent_tool_manager,
sub_agent_tool_managers=sub_agent_tool_managers,
output_formatter=output_formatter,
task_log=task_log,
stream_handler=self.stream,
max_consecutive_rollbacks=DEFAULT_MAX_CONSECUTIVE_ROLLBACKS,
)
self.answer_generator = AnswerGenerator(
llm_client=llm_client,
output_formatter=output_formatter,
task_log=task_log,
stream_handler=self.stream,
cfg=cfg,
intermediate_boxed_answers=self.intermediate_boxed_answers,
)
def _save_message_history(
self, system_prompt: str, message_history: List[Dict[str, Any]]
):
"""Save message history to task log."""
self.task_log.main_agent_message_history = {
"system_prompt": system_prompt,
"message_history": message_history,
}
self.task_log.save()
async def _handle_response_format_issues(
self,
assistant_response_text: str,
message_history: List[Dict[str, Any]],
turn_count: int,
consecutive_rollbacks: int,
total_attempts: int,
max_attempts: int,
agent_name: str,
) -> tuple:
"""
Handle MCP tag format errors and refusal keywords.
Args:
assistant_response_text: The LLM response text
message_history: Current message history
turn_count: Current turn count
consecutive_rollbacks: Current consecutive rollback count
total_attempts: Total attempts made
max_attempts: Maximum allowed attempts
agent_name: Name of the agent for logging
Returns:
Tuple of (should_continue, should_break, turn_count, consecutive_rollbacks, message_history)
"""
# Check for MCP tags in response (format error)
if any(mcp_tag in assistant_response_text for mcp_tag in mcp_tags):
if consecutive_rollbacks < self.MAX_CONSECUTIVE_ROLLBACKS - 1:
turn_count -= 1
consecutive_rollbacks += 1
if message_history[-1]["role"] == "assistant":
message_history.pop()
self.task_log.log_step(
"warning",
f"{agent_name} | Turn: {turn_count} | Rollback",
f"Tool call format incorrect - found MCP tags in response. "
f"Consecutive rollbacks: {consecutive_rollbacks}/{self.MAX_CONSECUTIVE_ROLLBACKS}, "
f"Total attempts: {total_attempts}/{max_attempts}",
)
return True, False, turn_count, consecutive_rollbacks, message_history
else:
self.task_log.log_step(
"warning",
f"{agent_name} | Turn: {turn_count} | End After Max Rollbacks",
f"Ending agent loop after {consecutive_rollbacks} consecutive MCP format errors",
)
return False, True, turn_count, consecutive_rollbacks, message_history
# Check for refusal keywords
if any(keyword in assistant_response_text for keyword in refusal_keywords):
matched_keywords = [
kw for kw in refusal_keywords if kw in assistant_response_text
]
if consecutive_rollbacks < self.MAX_CONSECUTIVE_ROLLBACKS - 1:
turn_count -= 1
consecutive_rollbacks += 1
if message_history[-1]["role"] == "assistant":
message_history.pop()
self.task_log.log_step(
"warning",
f"{agent_name} | Turn: {turn_count} | Rollback",
f"LLM refused to answer - found refusal keywords: {matched_keywords}. "
f"Consecutive rollbacks: {consecutive_rollbacks}/{self.MAX_CONSECUTIVE_ROLLBACKS}, "
f"Total attempts: {total_attempts}/{max_attempts}",
)
return True, False, turn_count, consecutive_rollbacks, message_history
else:
self.task_log.log_step(
"warning",
f"{agent_name} | Turn: {turn_count} | End After Max Rollbacks",
f"Ending agent loop after {consecutive_rollbacks} consecutive refusals with keywords: {matched_keywords}",
)
return False, True, turn_count, consecutive_rollbacks, message_history
# No format issues - normal end without tool calls
return False, True, turn_count, consecutive_rollbacks, message_history
async def _check_duplicate_query(
self,
tool_name: str,
arguments: dict,
cache_name: str,
consecutive_rollbacks: int,
turn_count: int,
total_attempts: int,
max_attempts: int,
message_history: List[Dict[str, Any]],
agent_name: str,
) -> tuple:
"""
Check for duplicate queries and handle rollback if needed.
Args:
tool_name: Name of the tool being called
arguments: Tool arguments
cache_name: Name of the query cache to use
consecutive_rollbacks: Current consecutive rollback count
turn_count: Current turn count
total_attempts: Total attempts made
max_attempts: Maximum allowed attempts
message_history: Current message history
agent_name: Name of the agent for logging
Returns:
Tuple of (is_duplicate, should_rollback, turn_count, consecutive_rollbacks, message_history)
"""
query_str = self.tool_executor.get_query_str_from_tool_call(
tool_name, arguments
)
if not query_str:
return False, False, turn_count, consecutive_rollbacks, message_history
self.used_queries.setdefault(cache_name, defaultdict(int))
count = self.used_queries[cache_name][query_str]
if count > 0:
if consecutive_rollbacks < self.MAX_CONSECUTIVE_ROLLBACKS - 1:
message_history.pop()
turn_count -= 1
consecutive_rollbacks += 1
self.task_log.log_step(
"warning",
f"{agent_name} | Turn: {turn_count} | Rollback",
f"Duplicate query detected - tool: {tool_name}, query: '{query_str}', "
f"previous count: {count}. Consecutive rollbacks: {consecutive_rollbacks}/"
f"{self.MAX_CONSECUTIVE_ROLLBACKS}, Total attempts: {total_attempts}/{max_attempts}",
)
return True, True, turn_count, consecutive_rollbacks, message_history
else:
self.task_log.log_step(
"warning",
f"{agent_name} | Turn: {turn_count} | Allow Duplicate",
f"Allowing duplicate query after {consecutive_rollbacks} rollbacks - "
f"tool: {tool_name}, query: '{query_str}', previous count: {count}",
)
return False, False, turn_count, consecutive_rollbacks, message_history
async def _record_query(self, cache_name: str, tool_name: str, arguments: dict):
"""Record a successful query execution."""
query_str = self.tool_executor.get_query_str_from_tool_call(
tool_name, arguments
)
if query_str:
self.used_queries.setdefault(cache_name, defaultdict(int))
self.used_queries[cache_name][query_str] += 1
async def run_sub_agent(
self,
sub_agent_name: str,
task_description: str,
):
"""
Run a sub-agent to handle a subtask.
Args:
sub_agent_name: Name of the sub-agent to run
task_description: Description of the subtask
Returns:
The final answer text from the sub-agent
"""
task_description += "\n\nPlease provide the answer and detailed supporting information of the subtask given to you."
self.task_log.log_step(
"info",
f"{sub_agent_name} | Task Description",
f"Subtask: {task_description}",
)
# Stream sub-agent start
display_name = sub_agent_name.replace("agent-", "")
sub_agent_id = await self.stream.start_agent(display_name)
await self.stream.start_llm(display_name)
# Start new sub-agent session
self.task_log.start_sub_agent_session(sub_agent_name, task_description)
# Initialize message history
message_history = [{"role": "user", "content": task_description}]
# Get sub-agent tool definitions
if not self.sub_agent_tool_definitions:
tool_definitions = await self._list_sub_agent_tools()
tool_definitions = tool_definitions.get(sub_agent_name, {})
else:
tool_definitions = self.sub_agent_tool_definitions[sub_agent_name]
if not tool_definitions:
self.task_log.log_step(
"warning",
f"{sub_agent_name} | No Tools",
"No tool definitions available.",
)
# Generate sub-agent system prompt
system_prompt = self.llm_client.generate_agent_system_prompt(
date=date.today(),
mcp_servers=tool_definitions,
) + generate_agent_specific_system_prompt(agent_type=sub_agent_name)
# Limit sub-agent turns
if self.cfg.agent.sub_agents:
max_turns = self.cfg.agent.sub_agents[sub_agent_name].max_turns
else:
max_turns = 0
turn_count = 0
total_attempts = 0
max_attempts = max_turns + EXTRA_ATTEMPTS_BUFFER
consecutive_rollbacks = 0
while turn_count < max_turns and total_attempts < max_attempts:
turn_count += 1
total_attempts += 1
if consecutive_rollbacks >= self.MAX_CONSECUTIVE_ROLLBACKS:
self.task_log.log_step(
"error",
f"{sub_agent_name} | Too Many Rollbacks",
f"Reached {consecutive_rollbacks} consecutive rollbacks, breaking loop.",
)
break
self.task_log.save()
# Reset 'last_call_tokens'
self.llm_client.last_call_tokens = {
"prompt_tokens": 0,
"completion_tokens": 0,
}
# LLM call using answer generator
(
assistant_response_text,
should_break,
tool_calls,
message_history,
) = await self.answer_generator.handle_llm_call(
system_prompt,
message_history,
tool_definitions,
turn_count,
f"{sub_agent_name} | Turn: {turn_count}",
agent_type=sub_agent_name,
)
if should_break:
self.task_log.log_step(
"info",
f"{sub_agent_name} | Turn: {turn_count} | LLM Call",
"should break is True, breaking the loop",
)
break
if assistant_response_text:
text_response = extract_llm_response_text(assistant_response_text)
if text_response:
await self.stream.tool_call("show_text", {"text": text_response})
else:
self.task_log.log_step(
"info",
f"{sub_agent_name} | Turn: {turn_count} | LLM Call",
"LLM call failed",
)
await asyncio.sleep(5)
continue
# Handle no tool calls case
if not tool_calls:
(
should_continue,
should_break_loop,
turn_count,
consecutive_rollbacks,
message_history,
) = await self._handle_response_format_issues(
assistant_response_text,
message_history,
turn_count,
consecutive_rollbacks,
total_attempts,
max_attempts,
sub_agent_name,
)
if should_continue:
continue
if should_break_loop:
if not any(
mcp_tag in assistant_response_text for mcp_tag in mcp_tags
) and not any(
keyword in assistant_response_text
for keyword in refusal_keywords
):
self.task_log.log_step(
"info",
f"{sub_agent_name} | Turn: {turn_count} | LLM Call",
f"No tool calls found in {sub_agent_name}, ending on turn {turn_count}",
)
break
# Execute tool calls
tool_calls_data = []
all_tool_results_content_with_id = []
should_rollback_turn = False
for call in tool_calls:
server_name = call["server_name"]
tool_name = call["tool_name"]
arguments = call["arguments"]
call_id = call["id"]
# Fix common parameter name mistakes
arguments = self.tool_executor.fix_tool_call_arguments(
tool_name, arguments
)
self.task_log.log_step(
"info",
f"{sub_agent_name} | Turn: {turn_count} | Tool Call",
f"Executing {tool_name} on {server_name}",
)
call_start_time = time.time()
try:
# Check for duplicate query
cache_name = sub_agent_id + "_" + tool_name
(
is_duplicate,
should_rollback,
turn_count,
consecutive_rollbacks,
message_history,
) = await self._check_duplicate_query(
tool_name,
arguments,
cache_name,
consecutive_rollbacks,
turn_count,
total_attempts,
max_attempts,
message_history,
sub_agent_name,
)
if should_rollback:
should_rollback_turn = True
break
# Send stream event
tool_call_id = await self.stream.tool_call(tool_name, arguments)
# Execute tool call
tool_result = await self.sub_agent_tool_managers[
sub_agent_name
].execute_tool_call(server_name, tool_name, arguments)
# Update query count if successful
if "error" not in tool_result:
await self._record_query(cache_name, tool_name, arguments)
# Post-process result
tool_result = self.tool_executor.post_process_tool_call_result(
tool_name, tool_result
)
result = (
tool_result.get("result")
if tool_result.get("result")
else tool_result.get("error")
)
# Check for errors that should trigger rollback
if self.tool_executor.should_rollback_result(
tool_name, result, tool_result
):
if consecutive_rollbacks < self.MAX_CONSECUTIVE_ROLLBACKS - 1:
message_history.pop()
turn_count -= 1
consecutive_rollbacks += 1
should_rollback_turn = True
self.task_log.log_step(
"warning",
f"{sub_agent_name} | Turn: {turn_count} | Rollback",
f"Tool result error - tool: {tool_name}, result: '{str(result)[:200]}'",
)
break
await self.stream.tool_call(
tool_name, {"result": result}, tool_call_id=tool_call_id
)
call_end_time = time.time()
call_duration_ms = int((call_end_time - call_start_time) * 1000)
self.task_log.log_step(
"info",
f"{sub_agent_name} | Turn: {turn_count} | Tool Call",
f"Tool {tool_name} completed in {call_duration_ms}ms",
)
tool_calls_data.append(
{
"server_name": server_name,
"tool_name": tool_name,
"arguments": arguments,
"result": tool_result,
"duration_ms": call_duration_ms,
"call_time": get_utc_plus_8_time(),
}
)
except Exception as e:
call_end_time = time.time()
call_duration_ms = int((call_end_time - call_start_time) * 1000)
tool_calls_data.append(
{
"server_name": server_name,
"tool_name": tool_name,
"arguments": arguments,
"error": str(e),
"duration_ms": call_duration_ms,
"call_time": get_utc_plus_8_time(),
}
)
tool_result = {
"error": f"Tool call failed: {str(e)}",
"server_name": server_name,
"tool_name": tool_name,
}
self.task_log.log_step(
"error",
f"{sub_agent_name} | Turn: {turn_count} | Tool Call",
f"Tool {tool_name} failed to execute: {str(e)}",
)
tool_result_for_llm = self.output_formatter.format_tool_result_for_user(
tool_result
)
all_tool_results_content_with_id.append((call_id, tool_result_for_llm))
if should_rollback_turn:
continue
# Reset consecutive rollbacks on successful execution
if consecutive_rollbacks > 0:
self.task_log.log_step(
"info",
f"{sub_agent_name} | Turn: {turn_count} | Recovery",
f"Successfully recovered after {consecutive_rollbacks} consecutive rollbacks",
)
consecutive_rollbacks = 0
# Update message history
message_history = self.llm_client.update_message_history(
message_history, all_tool_results_content_with_id
)
# Check context length
temp_summary_prompt = generate_agent_summarize_prompt(
task_description,
agent_type=sub_agent_name,
)
pass_length_check, message_history = self.llm_client.ensure_summary_context(
message_history, temp_summary_prompt
)
if not pass_length_check:
turn_count = max_turns
self.task_log.log_step(
"info",
f"{sub_agent_name} | Turn: {turn_count} | Context Limit Reached",
"Context limit reached, triggering summary",
)
break
# Log loop end
if turn_count >= max_turns:
self.task_log.log_step(
"info",
f"{sub_agent_name} | Max Turns Reached / Context Limit Reached",
f"Reached maximum turns ({max_turns}) or context limit reached",
)
else:
self.task_log.log_step(
"info",
f"{sub_agent_name} | Main Loop Completed",
f"Main loop completed after {turn_count} turns",
)
# Generate final summary
self.task_log.log_step(
"info",
f"{sub_agent_name} | Final Summary",
f"Generating {sub_agent_name} final summary",
)
summary_prompt = generate_agent_summarize_prompt(
task_description,
agent_type=sub_agent_name,
)
if message_history[-1]["role"] == "user":
message_history.pop()
message_history.append({"role": "user", "content": summary_prompt})
await self.stream.tool_call(
"Partial Summary", {}, tool_call_id=str(uuid.uuid4())
)
# Generate final answer
(
final_answer_text,
should_break,
tool_calls_info,
message_history,
) = await self.answer_generator.handle_llm_call(
system_prompt,
message_history,
tool_definitions,
turn_count + 1,
f"{sub_agent_name} | Final summary",
agent_type=sub_agent_name,
)
if final_answer_text:
self.task_log.log_step(
"info",
f"{sub_agent_name} | Final Answer",
"Final answer generated successfully",
)
else:
final_answer_text = (
f"No final answer generated by sub agent {sub_agent_name}."
)
self.task_log.log_step(
"error",
f"{sub_agent_name} | Final Answer",
"Unable to generate final answer",
)
# Save session history
self.task_log.sub_agent_message_history_sessions[
self.task_log.current_sub_agent_session_id
] = {"system_prompt": system_prompt, "message_history": message_history}
self.task_log.save()
self.task_log.end_sub_agent_session(sub_agent_name)
# Remove thinking content
final_answer_text = final_answer_text.split("<think>")[-1].strip()
final_answer_text = final_answer_text.split("</think>")[-1].strip()
# Stream sub-agent end
await self.stream.end_llm(display_name)
await self.stream.end_agent(display_name, sub_agent_id)
return final_answer_text
async def run_main_agent(
self,
task_description,
task_file_name=None,
task_id="default_task",
is_final_retry=False,
):
"""
Execute the main end-to-end task.
Args:
task_description: Description of the task to execute
task_file_name: Optional file associated with the task
task_id: Unique identifier for the task
Returns:
Tuple of (final_summary, final_boxed_answer, failure_experience_summary)
"""
workflow_id = await self.stream.start_workflow(task_description)
self.task_log.log_step("info", "Main Agent", f"Start task with id: {task_id}")
self.task_log.log_step(
"info", "Main Agent", f"Task description: {task_description}"
)
if task_file_name:
self.task_log.log_step(
"info", "Main Agent", f"Associated file: {task_file_name}"
)
# Process input
initial_user_content, processed_task_desc = process_input(
task_description, task_file_name
)
message_history = [{"role": "user", "content": initial_user_content}]
# Record initial user input
user_input = processed_task_desc
if task_file_name:
user_input += f"\n[Attached file: {task_file_name}]"
# Get tool definitions
if not self.tool_definitions:
tool_definitions = (
await self.main_agent_tool_manager.get_all_tool_definitions()
)
if self.cfg.agent.sub_agents is not None:
tool_definitions += expose_sub_agents_as_tools(
self.cfg.agent.sub_agents
)
else:
tool_definitions = self.tool_definitions
if not tool_definitions:
self.task_log.log_step(
"warning",
"Main Agent | Tool Definitions",
"Warning: No tool definitions found. LLM cannot use any tools.",
)
# Generate system prompt
system_prompt = self.llm_client.generate_agent_system_prompt(
date=date.today(),
mcp_servers=tool_definitions,
) + generate_agent_specific_system_prompt(agent_type="main")
system_prompt = system_prompt.strip()
# Main loop configuration
max_turns = self.cfg.agent.main_agent.max_turns
turn_count = 0
total_attempts = 0
max_attempts = max_turns + EXTRA_ATTEMPTS_BUFFER
consecutive_rollbacks = 0
self.current_agent_id = await self.stream.start_agent("main")
await self.stream.start_llm("main")
while turn_count < max_turns and total_attempts < max_attempts:
turn_count += 1
total_attempts += 1
if consecutive_rollbacks >= self.MAX_CONSECUTIVE_ROLLBACKS:
self.task_log.log_step(
"error",
"Main Agent | Too Many Rollbacks",
f"Reached {consecutive_rollbacks} consecutive rollbacks, breaking loop.",
)
break
self.task_log.save()
# LLM call
(
assistant_response_text,
should_break,
tool_calls,
message_history,
) = await self.answer_generator.handle_llm_call(
system_prompt,
message_history,
tool_definitions,
turn_count,
f"Main agent | Turn: {turn_count}",
agent_type="main",
)
# Process LLM response
if assistant_response_text:
text_response = extract_llm_response_text(assistant_response_text)
if text_response:
await self.stream.tool_call("show_text", {"text": text_response})
# Extract boxed content
boxed_content = self.output_formatter._extract_boxed_content(
assistant_response_text
)
if boxed_content:
self.intermediate_boxed_answers.append(boxed_content)
if should_break:
self.task_log.log_step(
"info",
f"Main Agent | Turn: {turn_count} | LLM Call",
"should break is True, breaking the loop",
)
break
else:
turn_count -= 1
self.task_log.log_step(
"warning",
f"Main Agent | Turn: {turn_count} | LLM Call",
"No valid response from LLM, retrying",
)
await asyncio.sleep(5)
continue
# Handle no tool calls case
if not tool_calls:
(
should_continue,
should_break_loop,
turn_count,
consecutive_rollbacks,
message_history,
) = await self._handle_response_format_issues(
assistant_response_text,
message_history,
turn_count,
consecutive_rollbacks,
total_attempts,
max_attempts,
"Main Agent",
)
if should_continue:
continue
if should_break_loop:
if not any(
mcp_tag in assistant_response_text for mcp_tag in mcp_tags
) and not any(
keyword in assistant_response_text
for keyword in refusal_keywords
):
self.task_log.log_step(
"info",
f"Main Agent | Turn: {turn_count} | LLM Call",
"LLM did not request tool usage, ending process.",
)
break
# Execute tool calls
tool_calls_data = []
all_tool_results_content_with_id = []
should_rollback_turn = False
main_agent_last_call_tokens = self.llm_client.last_call_tokens
for call in tool_calls:
server_name = call["server_name"]
tool_name = call["tool_name"]
arguments = call["arguments"]
call_id = call["id"]
# Fix common parameter name mistakes
arguments = self.tool_executor.fix_tool_call_arguments(
tool_name, arguments
)
call_start_time = time.time()
try:
if server_name.startswith("agent-") and self.cfg.agent.sub_agents:
# Sub-agent execution
cache_name = "main_" + tool_name
(
is_duplicate,
should_rollback,
turn_count,
consecutive_rollbacks,
message_history,
) = await self._check_duplicate_query(
tool_name,
arguments,
cache_name,
consecutive_rollbacks,
turn_count,
total_attempts,
max_attempts,
message_history,
"Main Agent",
)
if should_rollback:
should_rollback_turn = True
break
# Stream events
await self.stream.end_llm("main")
await self.stream.end_agent("main", self.current_agent_id)
# Execute sub-agent
sub_agent_result = await self.run_sub_agent(
server_name,
arguments["subtask"],
)
# Update query count
await self._record_query(cache_name, tool_name, arguments)
tool_result = {
"server_name": server_name,
"tool_name": tool_name,
"result": sub_agent_result,
}
self.current_agent_id = await self.stream.start_agent(
"main", display_name="Summarizing"
)
await self.stream.start_llm("main", display_name="Summarizing")
else:
# Regular tool execution
cache_name = "main_" + tool_name
(
is_duplicate,
should_rollback,
turn_count,
consecutive_rollbacks,
message_history,
) = await self._check_duplicate_query(
tool_name,
arguments,
cache_name,
consecutive_rollbacks,
turn_count,
total_attempts,
max_attempts,
message_history,
"Main Agent",
)
if should_rollback:
should_rollback_turn = True
break
# Send stream event
tool_call_id = await self.stream.tool_call(tool_name, arguments)
# Execute tool call
tool_result = (
await self.main_agent_tool_manager.execute_tool_call(
server_name=server_name,
tool_name=tool_name,