11"""
2- MARS: Multi-Agent Reasoning System main orchestration
2+ MARS: Multi-Agent Reasoning System main orchestration with parallel execution
33"""
44
5+ import asyncio
56import logging
67from typing import Dict , Any , List , Tuple
78from datetime import datetime
9+ from concurrent .futures import ThreadPoolExecutor
810import optillm
911from optillm import conversation_logger
1012
@@ -36,7 +38,7 @@ def multi_agent_reasoning_system(
3638 request_id : str = None
3739) -> Tuple [str , int ]:
3840 """
39- Main MARS function implementing multi-agent mathematical reasoning
41+ Main MARS function implementing multi-agent mathematical reasoning with parallel execution
4042
4143 Args:
4244 system_prompt: System-level instructions
@@ -48,12 +50,31 @@ def multi_agent_reasoning_system(
4850 Returns:
4951 Tuple of (final_solution, total_reasoning_tokens)
5052 """
53+ return asyncio .run (_run_mars_parallel (
54+ system_prompt , initial_query , client , model , request_id
55+ ))
56+
57+ async def _run_mars_parallel (
58+ system_prompt : str ,
59+ initial_query : str ,
60+ client ,
61+ model : str ,
62+ request_id : str = None
63+ ) -> Tuple [str , int ]:
64+ """Async implementation of MARS with parallel execution"""
5165 logger .info (f"Starting MARS with model: { model } " )
5266
5367 # Initialize configuration
5468 config = DEFAULT_CONFIG .copy ()
5569 total_reasoning_tokens = 0
5670
71+ # Calculate optimal worker count for parallel execution
72+ max_workers = max (
73+ config ['num_agents' ], # For generation phase
74+ config ['num_agents' ] * min (2 , config ['verification_passes_required' ]) # For verification
75+ )
76+ logger .info (f"Using { max_workers } parallel workers" )
77+
5778 # Initialize workspace for collaboration
5879 workspace = MARSWorkspace (initial_query , config )
5980
@@ -66,37 +87,41 @@ def multi_agent_reasoning_system(
6687
6788 logger .info (f"Initialized { len (agents )} agents with diverse temperatures" )
6889
69- # Phase 2: Multi-Agent Exploration
70- logger .info ("Phase 1: Multi-Agent Exploration" )
71- exploration_tokens = _run_exploration_phase (agents , workspace , request_id )
72- total_reasoning_tokens += exploration_tokens
90+ # Create thread pool executor for parallel API calls
91+ with ThreadPoolExecutor (max_workers = max_workers ) as executor :
92+ # Phase 2: Multi-Agent Exploration (parallel)
93+ logger .info ("Phase 1: Multi-Agent Exploration" )
94+ exploration_tokens = await _run_exploration_phase_parallel (
95+ agents , workspace , request_id , executor
96+ )
97+ total_reasoning_tokens += exploration_tokens
7398
74- # Phase 3: Verification System
75- logger .info ("Phase 2: Verification System" )
76- verifier = MARSVerifier (agents , workspace , config )
77- verification_summary = verifier .verify_solutions (request_id )
99+ # Phase 3: Verification System (parallel)
100+ logger .info ("Phase 2: Verification System" )
101+ verifier = MARSVerifier (agents , workspace , config )
102+ verification_summary = await verifier .verify_solutions_parallel (request_id , executor )
78103
79- # Phase 4: Iterative Improvement (if needed)
80- iteration_count = 0
81- while workspace .should_continue_iteration () and iteration_count < config ['max_iterations' ]:
82- iteration_count += 1
83- logger .info (f"Phase 3: Iterative Improvement - Iteration { iteration_count } " )
104+ # Phase 4: Iterative Improvement (if needed)
105+ iteration_count = 0
106+ while workspace .should_continue_iteration () and iteration_count < config ['max_iterations' ]:
107+ iteration_count += 1
108+ logger .info (f"Phase 3: Iterative Improvement - Iteration { iteration_count } " )
84109
85- # Improve unverified solutions
86- improvement_summary = verifier .iterative_improvement (request_id )
87- total_reasoning_tokens += improvement_summary ['total_reasoning_tokens' ]
110+ # Improve unverified solutions (parallel)
111+ improvement_summary = await verifier .iterative_improvement_parallel (request_id , executor )
112+ total_reasoning_tokens += improvement_summary ['total_reasoning_tokens' ]
88113
89- # Re-verify improved solutions
90- verification_summary = verifier .verify_solutions (request_id )
114+ # Re-verify improved solutions (parallel)
115+ verification_summary = await verifier .verify_solutions_parallel (request_id , executor )
91116
92- # Check for early termination
93- if config ['early_termination' ] and workspace .has_consensus ():
94- logger .info ("Early termination: consensus reached" )
95- break
117+ # Check for early termination
118+ if config ['early_termination' ] and workspace .has_consensus ():
119+ logger .info ("Early termination: consensus reached" )
120+ break
96121
97- workspace .iteration_count = iteration_count
122+ workspace .iteration_count = iteration_count
98123
99- # Phase 5: Final Synthesis
124+ # Phase 5: Final Synthesis (sequential - needs all results)
100125 logger .info ("Phase 4: Final Synthesis" )
101126 final_solution , synthesis_tokens = _synthesize_final_solution (
102127 workspace , client , model , config , request_id
@@ -126,24 +151,50 @@ def multi_agent_reasoning_system(
126151 except :
127152 return error_response , 0
128153
129- def _run_exploration_phase (agents : List [MARSAgent ], workspace : MARSWorkspace , request_id : str = None ) -> int :
130- """Run the multi-agent exploration phase"""
131- total_tokens = 0
132-
133- # Generate solutions from all agents in parallel (conceptually)
134- for agent in agents :
154+ async def _run_exploration_phase_parallel (
155+ agents : List [MARSAgent ],
156+ workspace : MARSWorkspace ,
157+ request_id : str = None ,
158+ executor : ThreadPoolExecutor = None
159+ ) -> int :
160+ """Run the multi-agent exploration phase with parallel execution"""
161+
162+ async def generate_solution_async (agent : MARSAgent ):
163+ """Async wrapper for agent solution generation"""
164+ loop = asyncio .get_event_loop ()
135165 try :
136- agent_solution , reasoning_tokens = agent .generate_solution (
137- workspace .problem , request_id
166+ solution , tokens = await loop .run_in_executor (
167+ executor ,
168+ agent .generate_solution ,
169+ workspace .problem ,
170+ request_id
138171 )
139- workspace .add_solution (agent_solution )
140- total_tokens += reasoning_tokens
141-
172+ return agent .agent_id , solution , tokens , None
142173 except Exception as e :
143174 logger .error (f"Agent { agent .agent_id } failed during exploration: { str (e )} " )
175+ return agent .agent_id , None , 0 , e
176+
177+ # Run all agents in parallel
178+ tasks = [generate_solution_async (agent ) for agent in agents ]
179+ results = await asyncio .gather (* tasks , return_exceptions = True )
180+
181+ total_tokens = 0
182+ successful_solutions = 0
183+
184+ for result in results :
185+ if isinstance (result , Exception ):
186+ logger .error (f"Agent task failed: { str (result )} " )
144187 continue
145188
146- logger .info (f"Exploration phase complete: { len (workspace .solutions )} solutions generated" )
189+ agent_id , solution , tokens , error = result
190+ if error is None and solution is not None :
191+ workspace .add_solution (solution )
192+ total_tokens += tokens
193+ successful_solutions += 1
194+ else :
195+ logger .error (f"Agent { agent_id } generated no solution" )
196+
197+ logger .info (f"Exploration phase complete: { successful_solutions } solutions generated in parallel" )
147198 return total_tokens
148199
149200def _synthesize_final_solution (
0 commit comments