Spaces:
Sleeping
Sleeping
Update app.py
Browse files51 unmodified lines525354555657581 unmodified line6061626364656612 unmodified lines7980818283848534 unmodified lines12012112212312412512612712812913013113213313413513613783 unmodified lines22122222322422522622711 unmodified lines23924024124224324432 unmodified lines2772782792802812822831 unmodified line2852862872882892902912922932942952962972982993003013024 unmodified lines3073083093103113123133143153163173183193203213223233243253263273283293303315 unmodified lines3373383393403413423434 unmodified lines34834935035135235335451 unmodified lines# -------------------- Conversation History Conversion --------------------def convert_history(history: List[Dict[str, str]]) -> List[Dict[str, str]]:"""Convert our internal conversation history format (with 'agent' and 'message' keys)into the Gradio messages format (with 'role' and 'content')."""converted = []1 unmodified lineif entry["agent"].lower() == "user":converted.append({"role": "user", "content": entry["message"]})else:# You can customize the formatting below as desired.converted.append({"role": "assistant", "content": f'{entry["agent"]}: {entry["message"]}'})return converted12 unmodified linesself.test_cases = test_casesself.test_results = test_resultsself.documentation = documentation# Initialize conversation history with the user's original task.self.conversation_history = conversation_history or [{"agent": "User", "message": original_task}]def add_conversation_entry(self, agent_name: str, message: str):34 unmodified lines)plan = await call_model(prompt, model="gpt-4o", api_key=api_key)context.add_conversation_entry("Orchestrator", f"Plan:\n{plan}")if "REQUEST_HUMAN_FEEDBACK" in plan:question = plan.split("REQUEST_HUMAN_FEEDBACK\n", 1)[1].strip()self.log_queue.put("[Orchestrator]: Requesting human feedback...")self.log_queue.put(f"[Orchestrator]: Question: {question}")feedback_context = (f"Task: {context.optimized_task}\nCurrent Plan: {context.plan or 'None'}\nQuestion: {question}")self.human_event.set()self.human_input_queue.put(feedback_context)human_response = self.human_input_queue.get() # blocking call waiting for human responseself.human_event.clear()self.log_queue.put(f"[Orchestrator]: Received human feedback: {human_response}")context.plan = (context.plan + "\n" + human_response) if context.plan else human_responseelse:context.plan = plan83 unmodified lines}async def dispatch(self, agent_name: str, context: Context, api_key: str, **kwargs) -> Context:self.log_queue.put(f"[{agent_name.replace('_', ' ').title()}]: Starting task...")if agent_name == "prompt_optimizer":context = await self.agents[agent_name].optimize_prompt(context, api_key)elif agent_name == "orchestrator":11 unmodified linescontext = await self.agents[agent_name].generate_documentation(context, api_key)else:raise ValueError(f"Unknown agent: {agent_name}")return contextasync def determine_next_agent(self, context: Context, api_key: str) -> str:32 unmodified lineselse:context = await dispatcher.dispatch(next_agent, context, api_key)if next_agent == "code_reviewer":approved = any("APPROVE" in comment.get("issue", "").upper() for review in context.review_comments for comment in review.get("comments", []))if not approved:next_agent = "coder"else:1 unmodified lineelse:next_agent = await dispatcher.determine_next_agent(context, api_key)if next_agent == "coder" and coder_iterations > 5:log_queue.put("Maximum revision iterations reached. Exiting.")breaklog_queue.put("Conversation complete.")log_queue.put(("result", context.conversation_history))# -------------------- Process Conversation Generator --------------------def process_conversation_generator(task_message: str, api_key: str,human_event: threading.Event, human_input_queue: queue.Queue,log_queue: queue.Queue) -> Generator[str, None, None]:"""Runs the multi-agent conversation in a background thread and yields log messagesto update the chat box without blocking the UI."""def run_conversation():asyncio.run(multi_agent_conversation(task_message, log_queue, api_key, human_event, human_input_queue))4 unmodified lineswhile conversation_thread.is_alive() or not log_queue.empty():try:msg = log_queue.get(timeout=0.1)if isinstance(msg, tuple) and msg[0] == "result":# Convert conversation history to the required messages format.yield gr.Chatbot.update(value=convert_history(msg[1]))else:yield msgexcept queue.Empty:passif human_event.is_set():yield "Waiting for human feedback..."time.sleep(0.1)yield "Conversation complete."# -------------------- Multi-Agent Chat Function --------------------def multi_agent_chat(message: str, openai_api_key: str = None) -> Generator[Any, None, None]:if not openai_api_key:openai_api_key = os.getenv("OPENAI_API_KEY")if not openai_api_key:yield "Error: API key not provided."returnhuman_event = threading.Event()human_input_queue = queue.Queue()5 unmodified linesgr.Markdown("## Multi-Agent Task Solver with Human-in-the-Loop")with gr.Row():# Set type="messages" to match the expected format.chat_output = gr.Chatbot(label="Conversation", type="messages")with gr.Row():4 unmodified linessend_button = gr.Button("Send")# Note: 'stream=True' has been removed.send_button.click(fn=multi_agent_chat, inputs=[message_input, api_key_input], outputs=chat_output)if __name__ == "__main__":51 unmodified lines525354555657581 unmodified line60616263646512 unmodified lines7879808182838434 unmodified lines11912012112212312412512612712812913013113213313413513613783 unmodified lines22122222322422522622711 unmodified lines23924024124224324424524632 unmodified lines2792802812822832842852862871 unmodified line2892902912922932942952962972982993003013023033043054 unmodified lines3103113123133143153163173183193203213223233243253263273283293303313323333343355 unmodified lines3413423433443453463474 unmodified lines35235335435535635735851 unmodified lines# -------------------- Conversation History Conversion --------------------def convert_history(history: List[Dict[str, str]]) -> List[Dict[str, str]]:"""Convert our internal conversation history (with 'agent' and 'message')into the Gradio messages format (with 'role' and 'content')."""converted = []1 unmodified lineif entry["agent"].lower() == "user":converted.append({"role": "user", "content": entry["message"]})else:converted.append({"role": "assistant", "content": f'{entry["agent"]}: {entry["message"]}'})return converted12 unmodified linesself.test_cases = test_casesself.test_results = test_resultsself.documentation = documentation# Initialize with the user's taskself.conversation_history = conversation_history or [{"agent": "User", "message": original_task}]def add_conversation_entry(self, agent_name: str, message: str):34 unmodified lines)plan = await call_model(prompt, model="gpt-4o", api_key=api_key)context.add_conversation_entry("Orchestrator", f"Plan:\n{plan}")# Report update after planningself.log_queue.put(("update", context.conversation_history))if "REQUEST_HUMAN_FEEDBACK" in plan:question = plan.split("REQUEST_HUMAN_FEEDBACK\n", 1)[1].strip()self.log_queue.put(("[Orchestrator]", f"Requesting human feedback... Question: {question}"))feedback_context = (f"Task: {context.optimized_task}\nCurrent Plan: {context.plan or 'None'}\nQuestion: {question}")self.human_event.set()self.human_input_queue.put(feedback_context)human_response = self.human_input_queue.get() # Blocking waiting for human responseself.human_event.clear()self.log_queue.put(("[Orchestrator]", f"Received human feedback: {human_response}"))context.plan = (context.plan + "\n" + human_response) if context.plan else human_responseelse:context.plan = plan83 unmodified lines}async def dispatch(self, agent_name: str, context: Context, api_key: str, **kwargs) -> Context:self.log_queue.put((f"[{agent_name.replace('_', ' ').title()}]", "Starting task..."))if agent_name == "prompt_optimizer":context = await self.agents[agent_name].optimize_prompt(context, api_key)elif agent_name == "orchestrator":11 unmodified linescontext = await self.agents[agent_name].generate_documentation(context, api_key)else:raise ValueError(f"Unknown agent: {agent_name}")# After each dispatch, push an update with the current conversation history.self.log_queue.put(("update", context.conversation_history))return contextasync def determine_next_agent(self, context: Context, api_key: str) -> str:32 unmodified lineselse:context = await dispatcher.dispatch(next_agent, context, api_key)if next_agent == "code_reviewer":approved = any("APPROVE" in comment.get("issue", "").upper()for review in context.review_commentsfor comment in review.get("comments", []))if not approved:next_agent = "coder"else:1 unmodified lineelse:next_agent = await dispatcher.determine_next_agent(context, api_key)if next_agent == "coder" and coder_iterations > 5:log_queue.put(("[System]", "Maximum revision iterations reached. Exiting."))breaklog_queue.put(("result", context.conversation_history))# -------------------- Process Conversation Generator --------------------def process_conversation_generator(task_message: str, api_key: str,human_event: threading.Event, human_input_queue: queue.Queue,log_queue: queue.Queue) -> Generator[Any, None, None]:"""Runs the multi-agent conversation in a background thread and yields only conversation history updatesin the proper messages format."""def run_conversation():asyncio.run(multi_agent_conversation(task_message, log_queue, api_key, human_event, human_input_queue))4 unmodified lineswhile conversation_thread.is_alive() or not log_queue.empty():try:msg = log_queue.get(timeout=0.1)if isinstance(msg, tuple):if msg[0] in ("update", "result"):# Yield the updated conversation history in proper format.yield gr.Chatbot.update(value=convert_history(msg[1]), visible=True)else:# For log messages (e.g., "[Orchestrator]", ...), ignore or handle separately.passexcept queue.Empty:passtime.sleep(0.1)# Final update if neededyield gr.Chatbot.update(visible=True)# -------------------- Multi-Agent Chat Function --------------------def multi_agent_chat(message: str, openai_api_key: str = None) -> Generator[Any, None, None]:if not openai_api_key:openai_api_key = os.getenv("OPENAI_API_KEY")if not openai_api_key:yield gr.Chatbot.update(value=[{"role": "assistant", "content": "Error: API key not provided."}])returnhuman_event = threading.Event()human_input_queue = queue.Queue()5 unmodified linesgr.Markdown("## Multi-Agent Task Solver with Human-in-the-Loop")with gr.Row():# Use type="messages" so that the Chatbot expects a list of dicts with 'role' and 'content'.chat_output = gr.Chatbot(label="Conversation", type="messages")with gr.Row():4 unmodified linessend_button = gr.Button("Send")# Connect the button to our multi_agent_chat generator.send_button.click(fn=multi_agent_chat, inputs=[message_input, api_key_input], outputs=chat_output)if __name__ == "__main__":
app.py+29-25