Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines678910111213141516171819202113 unmodified lines3536373839404142434445464748495051521 unmodified line5455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923031 unmodified lines2622632642652662672684 unmodified lines2732742752762772782792802812822 unmodified lines2852862872882892902912922932942952962972982993003013023033043053063073083093103113123 unmodified lines3163173183193203213223233243253263273283293305 unmodified linesimport queueimport gradio as grimport httpxfrom typing import Generator, Any, Dict, List, Optional# -------------------- Configuration --------------------logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")# -------------------- External Model Call --------------------async def call_model(prompt: str, model: str = "gpt-4o", api_key: str = None) -> str:"""Sends a prompt to the OpenAI API endpoint."""if api_key is None:api_key = os.getenv("OPENAI_API_KEY")if api_key is None:13 unmodified linesresponse_json = response.json()return response_json["choices"][0]["message"]["content"]# -------------------- Agent Classes --------------------class PromptOptimizerAgent:async def optimize_prompt(self, user_prompt: str, api_key: str) -> str:"""Optimizes the user's initial prompt."""system_prompt = ("You are a prompt optimization expert. Improve the given user prompt. ""Be clear, specific, and complete. Maintain the user's original intent.""Return ONLY the revised prompt.")full_prompt = f"{system_prompt}\n\nUser's initial prompt:\n{user_prompt}"optimized = await call_model(full_prompt, model="gpt-4o", api_key=api_key)return optimizedclass OrchestratorAgent:def __init__(self, log_queue: queue.Queue, human_in_the_loop_event: threading.Event, human_input_queue: queue.Queue) -> None:1 unmodified lineself.human_in_the_loop_event = human_in_the_loop_eventself.human_input_queue = human_input_queueasync def generate_plan(self, task: str, api_key: str, human_feedback: Optional[str] = None) -> str:"""Generates a plan, potentially requesting human feedback."""if human_feedback: # Use human feedback if providedprompt = (f"You are a master planner. You previously generated a partial plan for the task: '{task}'.\n""You requested human feedback, and here's the feedback you received:\n"f"{human_feedback}\n\n""Now, complete or revise the plan, incorporating the human feedback. ""Output the plan as a numbered list.")plan = await call_model(prompt, model="gpt-4o", api_key=api_key)return planprompt = (f"You are a master planner. Given the task: '{task}', create a detailed, step-by-step plan. ""Break down the task into sub-tasks. Assign each sub-task to agents: Coder, Code Reviewer, Quality Assurance Tester, and Documentation Agent. ""Include steps for review and revision. Consider potential issues and error handling. ""Include instructions for documentation.\n\n""HOWEVER, if at ANY point you are unsure how to proceed, you can request human feedback. ""To do this, output ONLY the following phrase (and nothing else): 'REQUEST_HUMAN_FEEDBACK'\n""Followed by a newline and a clear and concise question for the human. Example:\n\nREQUEST_HUMAN_FEEDBACK\nShould the output be in JSON or XML format?""\n\nOutput the plan as a numbered list (or as much as you can before requesting feedback).")plan = await call_model(prompt, model="gpt-4o", api_key=api_key)if "REQUEST_HUMAN_FEEDBACK" in plan:self.log_queue.put("[Orchestrator]: Requesting human feedback...")question = plan.split("REQUEST_HUMAN_FEEDBACK\n", 1)[1].strip()self.log_queue.put(f"[Orchestrator]: Question for human: {question}")self.human_in_the_loop_event.set() # Signal the human input threadhuman_response = self.human_input_queue.get() # Wait for human inputself.human_in_the_loop_event.clear() # Reset the eventself.log_queue.put(f"[Orchestrator]: Received human feedback: {human_response}")return await self.generate_plan(task, api_key, human_response) # Recursive call with feedbackreturn planclass CoderAgent:async def generate_code(self, instructions: str, api_key: str, model: str = "gpt-4o") -> str:"""Generates code based on instructions."""prompt = ("You are a highly skilled coding agent. Output ONLY the code. ""Adhere to best practices. Include error handling.\n\n"f"Instructions:\n{instructions}")code = await call_model(prompt, model=model, api_key=api_key)return codeclass CodeReviewerAgent:async def review_code(self, code: str, task: str, api_key: str) -> str:"""Reviews code. Provides concise, actionable feedback or 'APPROVE'."""prompt = ("You are a meticulous code reviewer. Provide CONCISE feedback. ""Focus on correctness, efficiency, readability, error handling, security, and adherence to the task. ""Suggest improvements. If acceptable, respond with ONLY 'APPROVE'. ""Do NOT generate code.\n\n"f"Task: {task}\n\nCode:\n{code}")review = await call_model(prompt, model="gpt-4o", api_key=api_key)return reviewclass QualityAssuranceTesterAgent:async def generate_test_cases(self, code: str, task: str, api_key: str) -> str:"""Generates test cases."""prompt = ("You are a quality assurance testing agent. Generate test cases. ""Consider edge cases and error scenarios. Output in a clear format.\n\n"f"Task: {task}\n\nCode:\n{code}")test_cases = await call_model(prompt, model="gpt-4o", api_key=api_key)return test_casesasync def run_tests(self, code:str, test_cases:str, api_key:str) -> str:"""Runs tests and reports results."""prompt = ("Run the generated test cases. Compare actual vs expected output. ""State discrepancies. If all pass, output 'TESTS PASSED'.\n\n"f"Code:\n{code}\n\nTest Cases:\n{test_cases}")test_results = await call_model(prompt, model="gpt-4o", api_key=api_key)return test_resultsclass DocumentationAgent:async def generate_documentation(self, code: str, api_key: str) -> str:"""Generates documentation, including a --help message."""prompt = ("Generate clear and concise documentation. ""Include a brief description, explanation, and a --help message.\n\n"f"Code:\n{code}")documentation = await call_model(prompt, model="gpt-4o", api_key=api_key)return documentation# -------------------- Multi-Agent Conversation --------------------async def multi_agent_conversation(task_message: str, log_queue: queue.Queue, api_key: str, human_in_the_loop_event: threading.Event, human_input_queue: queue.Queue) -> None:"""Conducts the multi-agent conversation."""conversation: List[Dict[str, str]] = []# Step 0: Optimize Promptlog_queue.put("[Prompt Optimizer]: Optimizing prompt...")prompt_optimizer = PromptOptimizerAgent()optimized_task = await prompt_optimizer.optimize_prompt(task_message, api_key=api_key)conversation.append({"agent": "Prompt Optimizer", "message": f"Optimized Task:\n{optimized_task}"})log_queue.put(f"[Prompt Optimizer]: Optimized task prompt:\n{optimized_task}")# Step 1: Generate Planlog_queue.put("[Orchestrator]: Generating plan...")orchestrator = OrchestratorAgent(log_queue, human_in_the_loop_event, human_input_queue)plan = await orchestrator.generate_plan(optimized_task, api_key=api_key)conversation.append({"agent": "Orchestrator", "message": f"Plan:\n{plan}"})log_queue.put(f"[Orchestrator]: Plan generated:\n{plan}")# Step 2: Generate Codecoder = CoderAgent()coder_instructions = f"Implement the task:\n{plan}"log_queue.put("[Coder]: Generating code...")code = await coder.generate_code(coder_instructions, api_key=api_key)conversation.append({"agent": "Coder", "message": f"Code:\n{code}"})log_queue.put(f"[Coder]: Code generated:\n{code}")# Step 3: Code Review and Revisionreviewer = CodeReviewerAgent()tester = QualityAssuranceTesterAgent()approval_keyword = "approve"revision_iteration = 0while True:log_queue.put(f"[Code Reviewer]: Reviewing code (Iteration {revision_iteration})...")review = await reviewer.review_code(code, optimized_task, api_key=api_key)conversation.append({"agent": "Code Reviewer", "message": f"Review (Iteration {revision_iteration}):\n{review}"})log_queue.put(f"[Code Reviewer]: Review (Iteration {revision_iteration}):\n{review}")if approval_keyword in review.lower():log_queue.put("[Code Reviewer]: Code approved.")breakrevision_iteration += 1if revision_iteration >= 5:log_queue.put("Unable to solve task satisfactorily.")sys.exit("Unable to solve task satisfactorily.")log_queue.put("[QA Tester]: Generating test cases...")test_cases = await tester.generate_test_cases(code, optimized_task, api_key=api_key)conversation.append({"agent": "QA Tester", "message": f"Test Cases:\n{test_cases}"})log_queue.put(f"[QA Tester]: Test Cases:\n{test_cases}")log_queue.put("[QA Tester]: Running tests...")test_results = await tester.run_tests(code, test_cases, api_key)conversation.append({"agent": "QA Tester", "message": f"Test Results:\n{test_results}"})log_queue.put(f"[QA Tester]: Test Results:\n{test_results}")log_queue.put(f"[Orchestrator]: Revising code (Iteration {revision_iteration})...")update_instructions = f"Revise:\nReview:\n{review}\nTests:\n{test_results}\nPlan:\n{plan}"revised_code = await coder.generate_code(update_instructions, api_key=api_key, model="gpt-3.5-turbo-16k")conversation.append({"agent": "Coder", "message": f"Revised Code (Iteration {revision_iteration}):\n{revised_code}"})log_queue.put(f"[Coder]: Revised (Iteration {revision_iteration}):\n{revised_code}")code = revised_code# Step 4: Generate Documentationdoc_agent = DocumentationAgent()log_queue.put("[Documentation Agent]: Generating documentation...")documentation = await doc_agent.generate_documentation(code, api_key=api_key)conversation.append({"agent": "Documentation Agent", "message": f"Documentation:\n{documentation}"})log_queue.put(f"[Documentation Agent]: Documentation generated:\n{documentation}")log_queue.put("Conversation complete.")log_queue.put(("result", conversation))# -------------------- Process Generator and Human Input --------------------def process_conversation_generator(task_message: str, api_key: str, human_in_the_loop_event: threading.Event, human_input_queue: queue.Queue) -> Generator[str, None, None]:31 unmodified lines"""Gets human input using a Gradio Textbox."""with gr.Blocks() as human_feedback_interface:with gr.Row():human_input = gr.Textbox(lines=4, placeholder=placeholder_text, label="Human Feedback")with gr.Row():submit_button = gr.Button("Submit Feedback")4 unmodified linesreturn ""submit_button.click(submit_feedback, inputs=human_input, outputs=human_input)human_feedback_interface.load(None, [], []) # This is needed to keep the interface alivereturn human_feedback_interface, feedback_queue# -------------------- Chat Function for Gradio --------------------def multi_agent_chat(message: str, history: List[Any], openai_api_key: str = None) -> Generator[str, None, None]:"""Chat function for Gradio."""if not openai_api_key:2 unmodified linesyield "Error: API key not provided."returnhuman_in_the_loop_event = threading.Event()human_input_queue = queue.Queue()yield from process_conversation_generator(message, openai_api_key, human_in_the_loop_event, human_input_queue)while human_in_the_loop_event.is_set():yield "Waiting for human feedback..."placeholder = "Please provide your feedback."human_interface, feedback_queue = get_human_feedback(placeholder)#This is a hacky but currently only working way to make this work with gradioyield gr.Textbox.update(visible=False), gr.update(visible=True)try:human_feedback = feedback_queue.get(timeout=300) # Wait for up to 5 minuteshuman_input_queue.put(human_feedback)human_in_the_loop_event.clear()yield gr.Textbox.update(visible=True), human_interface.close()yield from process_conversation_generator(message, openai_api_key, human_in_the_loop_event, human_input_queue)except queue.Empty:human_input_queue.put("No feedback provided.") #Timeouthuman_in_the_loop_event.clear()yield gr.Textbox.update(visible=True), human_interface.close()yield from process_conversation_generator(message, openai_api_key, human_in_the_loop_event, human_input_queue)# -------------------- Launch the Chatbot --------------------3 unmodified linesadditional_inputs=[gr.Textbox(label="OpenAI API Key (optional)", type="password", placeholder="Leave blank to use env variable")],title="Multi-Agent Task Solver with Human-in-the-Loop",description="""- Collaborative workflow with Human-in-the-Loop capability.- The Orchestrator can ask for human feedback if needed.- Enter a task, and the agents will work on it. You may be prompted for input.- Max 5 revision iterations.- Provide your OpenAI API Key below.""")#Need a dummy interface to make the human feedback interface updatedummy_iface = gr.Interface(lambda x:x, "textbox", "textbox")if __name__ == "__main__":5 unmodified lines678910111213141516171819202113 unmodified lines353637383940414243444546474849505152535455565758596061626364656667686970711 unmodified line73747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229331 unmodified lines3253263273283293303314 unmodified lines3363373383393403413423433443453463472 unmodified lines3503513523533543553563573583593603613623633643653663673683693703713723733743753763 unmodified lines3803813823833843853863873883893903913923933945 unmodified linesimport queueimport gradio as grimport httpxfrom typing import Generator, Any, Dict, List, Optional, Callablefrom functools import lru_cache# -------------------- Configuration --------------------logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")# -------------------- External Model Call (with Caching) --------------------@lru_cache(maxsize=128) # Cache up to 128 responsesasync def call_model(prompt: str, model: str = "gpt-4o", api_key: str = None) -> str:"""Sends a prompt to the OpenAI API endpoint, with caching."""if api_key is None:api_key = os.getenv("OPENAI_API_KEY")if api_key is None:13 unmodified linesresponse_json = response.json()return response_json["choices"][0]["message"]["content"]# -------------------- Shared Context --------------------class Context:def __init__(self, original_task: str, optimized_task: Optional[str] = None,plan: Optional[str] = None, code: Optional[str] = None,review_comments: Optional[List[Dict[str, str]]] = None,test_cases: Optional[str] = None, test_results: Optional[str] = None,documentation: Optional[str] = None, conversation_history: Optional[List[Dict[str, str]]] = None):self.original_task = original_taskself.optimized_task = optimized_taskself.plan = planself.code = codeself.review_comments = review_comments or []self.test_cases = test_casesself.test_results = test_resultsself.documentation = documentationself.conversation_history = conversation_history or []def add_conversation_entry(self, agent_name: str, message: str):self.conversation_history.append({"agent": agent_name, "message": message})# -------------------- Agent Classes --------------------class PromptOptimizerAgent:async def optimize_prompt(self, context: Context, api_key: str) -> Context:"""Optimizes the user's initial prompt."""system_prompt = "Improve the prompt. Be clear, specific, and complete. Keep original intent. Return ONLY the revised prompt."full_prompt = f"{system_prompt}\n\nUser's prompt:\n{context.original_task}"optimized = await call_model(full_prompt, model="gpt-4o", api_key=api_key)context.optimized_task = optimizedcontext.add_conversation_entry("Prompt Optimizer", f"Optimized Task:\n{optimized}")return contextclass OrchestratorAgent:def __init__(self, log_queue: queue.Queue, human_in_the_loop_event: threading.Event, human_input_queue: queue.Queue) -> None:1 unmodified lineself.human_in_the_loop_event = human_in_the_loop_eventself.human_input_queue = human_input_queueasync def generate_plan(self, context: Context, api_key: str, human_feedback: Optional[str] = None) -> Context:"""Generates a plan, potentially requesting human feedback."""if human_feedback:prompt = (f"You are a planner. Revise/complete the plan for '{context.original_task}' using feedback:\n"f"{human_feedback}\n\nCurrent Plan:\n{context.plan if context.plan else 'No plan yet.'}\n\n""Output the plan as a numbered list. If unsure, output 'REQUEST_HUMAN_FEEDBACK\\n[Question]'")plan = await call_model(prompt, model="gpt-4o", api_key=api_key)else:prompt = (f"You are a planner. Create a plan for: '{context.optimized_task}'. ""Break down the task. Assign sub-tasks to: Coder, Code Reviewer, Quality Assurance Tester, and Documentation Agent. ""Include review/revision steps. Consider error handling. Include documentation instructions.\n\n""If unsure, output 'REQUEST_HUMAN_FEEDBACK\\n[Question]'\n\nOutput the plan as a numbered list.")plan = await call_model(prompt, model="gpt-4o", api_key=api_key)if "REQUEST_HUMAN_FEEDBACK" in plan:self.log_queue.put("[Orchestrator]: Requesting human feedback...")question = plan.split("REQUEST_HUMAN_FEEDBACK\n", 1)[1].strip()self.log_queue.put(f"[Orchestrator]: Question for human: {question}")#Prepare detailed context for humanfeedback_request_context = (f"The orchestrator agent is requesting feedback on the following task:\n **{context.optimized_task}**\n\n"f"The current plan (if any):\n**{context.plan}**\n\n" if context.plan else "") + f"The specific question is:\n**{question}**"self.human_in_the_loop_event.set() # Signal the human input threadhuman_response = self.get_human_response(feedback_request_context) # Pass context to input functionself.human_in_the_loop_event.clear() # Reset the eventself.log_queue.put(f"[Orchestrator]: Received human feedback: {human_response}")context.add_conversation_entry("Orchestrator", f"Plan:\n{plan}\n\nHuman Feedback Requested. Question: {question}")return await self.generate_plan(context, api_key, human_response) # Recursive callcontext.plan = plancontext.add_conversation_entry("Orchestrator", f"Plan:\n{plan}")return contextdef get_human_response(self, feedback_request_context):"""Gets human input, using the Gradio queue and event."""self.human_input_queue.put(feedback_request_context) # Put the question into Gradiohuman_response = self.human_input_queue.get() # Get the responsereturn human_responseclass CoderAgent:async def generate_code(self, context: Context, api_key: str, model: str = "gpt-4o") -> Context:"""Generates code based on instructions."""prompt = ("You are a coding agent. Output ONLY the code. ""Adhere to best practices. Include error handling.\n\n"f"Instructions:\n{context.plan}")code = await call_model(prompt, model=model, api_key=api_key)context.code = codecontext.add_conversation_entry("Coder", f"Code:\n{code}")return contextclass CodeReviewerAgent:async def review_code(self, context: Context, api_key: str) -> Context:"""Reviews code. Provides concise, actionable feedback or 'APPROVE'."""prompt = ("You are a code reviewer. Provide CONCISE feedback. ""Focus on correctness, efficiency, readability, error handling, security, and adherence to the task. ""Suggest improvements. If acceptable, respond with ONLY 'APPROVE'. ""Do NOT generate code.\n\n"f"Task: {context.optimized_task}\n\nCode:\n{context.code}")review = await call_model(prompt, model="gpt-4o", api_key=api_key)context.add_conversation_entry("Code Reviewer", f"Review:\n{review}")# Structured Feedback (Example)if "APPROVE" not in review.upper():structured_review = {"comments": []}#In a real implementation you might use a more advanced parsing technique herefor line in review.splitlines():if line.strip(): #Simple examplestructured_review["comments"].append({"issue": line.strip(), "line_number": "N/A", "severity": "Medium"}) #Dummy datacontext.review_comments.append(structured_review)return contextclass QualityAssuranceTesterAgent:async def generate_test_cases(self, context: Context, api_key: str) -> Context:"""Generates test cases."""prompt = ("You are a testing agent. Generate test cases. ""Consider edge cases and error scenarios. Output in a clear format.\n\n"f"Task: {context.optimized_task}\n\nCode:\n{context.code}")test_cases = await call_model(prompt, model="gpt-4o", api_key=api_key)context.test_cases = test_casescontext.add_conversation_entry("QA Tester", f"Test Cases:\n{test_cases}")return contextasync def run_tests(self, context: Context, api_key: str) -> Context:"""Runs tests and reports results."""prompt = ("Run the test cases. Compare actual vs expected output. ""State discrepancies. If all pass, output 'TESTS PASSED'.\n\n"f"Code:\n{context.code}\n\nTest Cases:\n{context.test_cases}")test_results = await call_model(prompt, model="gpt-4o", api_key=api_key)context.test_results = test_resultscontext.add_conversation_entry("QA Tester", f"Test Results:\n{test_results}")return contextclass DocumentationAgent:async def generate_documentation(self, context: Context, api_key: str) -> Context:"""Generates documentation, including a --help message."""prompt = ("Generate clear and concise documentation. ""Include a brief description, explanation, and a --help message.\n\n"f"Code:\n{context.code}")documentation = await call_model(prompt, model="gpt-4o", api_key=api_key)context.documentation = documentationcontext.add_conversation_entry("Documentation Agent", f"Documentation:\n{documentation}")return context# -------------------- Agent Dispatcher (New) --------------------class AgentDispatcher:def __init__(self, log_queue: queue.Queue, human_in_the_loop_event: threading.Event, human_input_queue: queue.Queue):self.log_queue = log_queueself.human_in_the_loop_event = human_in_the_loop_eventself.human_input_queue = human_input_queueself.agents = {"prompt_optimizer": PromptOptimizerAgent(),"orchestrator": OrchestratorAgent(log_queue, human_in_the_loop_event, human_input_queue),"coder": CoderAgent(),"code_reviewer": CodeReviewerAgent(),"qa_tester": QualityAssuranceTesterAgent(),"documentation_agent": DocumentationAgent(),}async def dispatch(self, agent_name: str, context: Context, api_key: str, **kwargs) -> Context:"""Dispatches the task to the specified agent."""agent = self.agents.get(agent_name)if not agent:raise ValueError(f"Unknown agent: {agent_name}")self.log_queue.put(f"[{agent_name.replace('_', ' ').title()}]: Starting task...")if agent_name == "prompt_optimizer":context = await agent.optimize_prompt(context, api_key)elif agent_name == "orchestrator":context = await agent.generate_plan(context, api_key) #Removed human_feedbackelif agent_name == "coder":context = await agent.generate_code(context, api_key, **kwargs)elif agent_name == "code_reviewer":context = await agent.review_code(context, api_key)elif agent_name == "qa_tester":if kwargs.get("generate_tests", False):context = await agent.generate_test_cases(context, api_key)elif kwargs.get("run_tests", False):context = await agent.run_tests(context, api_key)elif agent_name == "documentation_agent":context = await agent.generate_documentation(context, api_key)else:raise ValueError(f"Unknown Agent Name: {agent_name}")return contextasync def determine_next_agent(self, context:Context, api_key:str) -> str:"""Determines the next agent to run based on the current context."""if not context.optimized_task:return "prompt_optimizer"if not context.plan:return "orchestrator"if not context.code:return "coder"if not context.review_comments or "APPROVE" not in [comment.get('issue',"").upper() for comment_list in context.review_comments for comment in comment_list.get("comments",[]) ]:return "code_reviewer"if not context.test_cases:return "qa_tester"if not context.test_results or "TESTS PASSED" not in context.test_results.upper() :return "qa_tester"if not context.documentation:return "documentation_agent"return "done" # All tasks are complete# -------------------- Multi-Agent Conversation (Refactored) --------------------async def multi_agent_conversation(task_message: str, log_queue: queue.Queue, api_key: str, human_in_the_loop_event: threading.Event, human_input_queue: queue.Queue) -> None:"""Conducts the multi-agent conversation using the AgentDispatcher."""context = Context(original_task=task_message)dispatcher = AgentDispatcher(log_queue, human_in_the_loop_event, human_input_queue)next_agent = await dispatcher.determine_next_agent(context, api_key)while next_agent != "done":if next_agent == "qa_tester":if not context.test_cases:context = await dispatcher.dispatch(next_agent, context, api_key, generate_tests=True)else:context = await dispatcher.dispatch(next_agent, context, api_key, run_tests=True)elif next_agent == "coder" and (context.review_comments or context.test_results):#Coder needs a different model after the first codingcontext = await dispatcher.dispatch(next_agent,context, api_key, model="gpt-3.5-turbo-16k")else:context = await dispatcher.dispatch(next_agent, context, api_key) # Call the agentnext_agent = await dispatcher.determine_next_agent(context, api_key)if next_agent == "code_reviewer" and context.review_comments and "APPROVE" in [comment.get('issue',"").upper() for comment_list in context.review_comments for comment in comment_list.get("comments",[]) ]:next_agent = await dispatcher.determine_next_agent(context, api_key)# Check for maximum revisionsif next_agent == "coder" and len([entry for entry in context.conversation_history if entry["agent"] == "Coder"]) > 5:log_queue.put("Maximum revision iterations reached. Exiting.")break;log_queue.put("Conversation complete.")log_queue.put(("result", context.conversation_history))# -------------------- Process Generator and Human Input --------------------def process_conversation_generator(task_message: str, api_key: str, human_in_the_loop_event: threading.Event, human_input_queue: queue.Queue) -> Generator[str, None, None]:31 unmodified lines"""Gets human input using a Gradio Textbox."""with gr.Blocks() as human_feedback_interface:with gr.Row():human_input = gr.Textbox(lines=4, label="Human Feedback", placeholder=placeholder_text) #Removed placeholderwith gr.Row():submit_button = gr.Button("Submit Feedback")4 unmodified linesreturn ""submit_button.click(submit_feedback, inputs=human_input, outputs=human_input)human_feedback_interface.load(None, [], []) # Keep interface alivereturn human_feedback_interface, feedback_queue# -------------------- Chat Function for Gradio --------------------def multi_agent_chat(message: str, history: List[Any], openai_api_key: str = None) -> Generator[str, None, None]:"""Chat function for Gradio."""if not openai_api_key:2 unmodified linesyield "Error: API key not provided."returnhuman_in_the_loop_event = threading.Event()human_input_queue = queue.Queue() #For receiving the feedback requestyield from process_conversation_generator(message, openai_api_key, human_in_the_loop_event, human_input_queue)while human_in_the_loop_event.is_set():yield "Waiting for human feedback..."try:feedback_request = human_input_queue.get(timeout=0.1) #Non-blocking, check for feedback requesthuman_interface, feedback_queue = get_human_feedback(feedback_request)#This is a hacky but currently only working way to make this work with gradioyield gr.Textbox.update(visible=False), gr.update(visible=True)human_feedback = feedback_queue.get(timeout=300) # Wait for up to 5 minuteshuman_input_queue.put(human_feedback) #Put feedback where Orchestrator can find it.human_in_the_loop_event.clear()yield gr.Textbox.update(visible=True), human_interface.close() #Hide human input boxyield from process_conversation_generator(message, openai_api_key, human_in_the_loop_event, human_input_queue)except queue.Empty: #If we get here, there was NO human feedback request, so skip.continue #Go back to the top of the while loop# -------------------- Launch the Chatbot --------------------3 unmodified linesadditional_inputs=[gr.Textbox(label="OpenAI API Key (optional)", type="password", placeholder="Leave blank to use env variable")],title="Multi-Agent Task Solver with Human-in-the-Loop",description="""- Collaborative workflow with Human-in-the-Loop.- Orchestrator can ask for human feedback.- Enter a task; agents will work on it. You may be prompted for input.- Max 5 revisions.- Provide API Key.""")#Need a dummy interface to prevent Gradio errorsdummy_iface = gr.Interface(lambda x:x, "textbox", "textbox")if __name__ == "__main__":
app.py+216-152