Spaces:
Sleeping
Sleeping
Update app.py
Browse files51 unmodified lines52535455555657581 unmodified line6061626363646512 unmodified lines787980828182838434 unmodified lines11912012112212312412512512612612712812913013113213213313413413513613783 unmodified lines22122222322422422522622711 unmodified lines23924024124224324424524632 unmodified lines2792802812802822832842852862871 unmodified line2892902912882922932902942952962972982962993002982993013023033043054 unmodified lines3103113123103113123133143133143153163173183193203213173183223233213243253263273283293303313283323333343355 unmodified lines3413423433403443453463474 unmodified lines35235335435135535635735851 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) Convert our internal conversation history (with 'agent' and 'message') into the Gradio messages format (with 'role' and 'content'). """ converted = []1 unmodified line if 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 converted
12 unmodified lines self.test_cases = test_cases self.test_results = test_results self.documentation = documentation # Initialize conversation history with the user's original task. # Initialize with the user's 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}") # Report update after planning self.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]: Requesting human feedback...") self.log_queue.put(f"[Orchestrator]: Question: {question}") 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 call waiting for human response human_response = self.human_input_queue.get() # Blocking waiting for human response self.human_event.clear() self.log_queue.put(f"[Orchestrator]: Received human feedback: {human_response}") self.log_queue.put(("[Orchestrator]", f"Received human feedback: {human_response}")) context.plan = (context.plan + "\n" + human_response) if context.plan else human_response else: 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...") 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 lines context = 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 context
async def determine_next_agent(self, context: Context, api_key: str) -> str:32 unmodified lines else: 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", [])) 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 line else: 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.") log_queue.put(("[System]", "Maximum revision iterations reached. Exiting.")) break log_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]: log_queue: queue.Queue) -> Generator[Any, None, None]: """ Runs the multi-agent conversation in a background thread and yields log messages to update the chat box without blocking the UI. Runs the multi-agent conversation in a background thread and yields only conversation history updates in 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 lines while 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 msg 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. pass except queue.Empty: pass if human_event.is_set(): yield "Waiting for human feedback..." time.sleep(0.1) yield "Conversation complete." # Final update if needed yield 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 "Error: API key not provided." yield gr.Chatbot.update(value=[{"role": "assistant", "content": "Error: API key not provided."}]) return human_event = threading.Event() human_input_queue = queue.Queue()5 unmodified lines gr.Markdown("## Multi-Agent Task Solver with Human-in-the-Loop") with gr.Row(): # Set type="messages" to match the expected format. # 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 lines send_button = gr.Button("Send") # Note: 'stream=True' has been removed. # 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