Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines678910111213141516171844 unmodified lines63646566676889 unmodified lines15815916016116216316474 unmodified lines2392402412422432442454 unmodified lines25025125225325425525625725821 unmodified lines28028128228328428528615 unmodified lines3023033043053063073086 unmodified lines3153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493 unmodified lines3533543553563573583593605 unmodified linesimport gradio as grimport httpximport timefrom typing import Generator, Any, Dict, List, Optional# -------------------- Configuration --------------------logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")# -------------------- External Model Call (with Caching and Retry) --------------------async def call_model(prompt: str, model: str = "gpt-4o", api_key: str = None, max_retries: int = 5) -> str:if api_key is None:api_key = os.getenv("OPENAI_API_KEY")if api_key is None:44 unmodified linesconverted.append({"role": "assistant", "content": f'{entry["agent"]}: {entry["message"]}'})return converted# -------------------- Shared Context --------------------class Context:def __init__(self, original_task: str, optimized_task: Optional[str] = None,89 unmodified lines)review = await call_model(prompt, model="gpt-4o", api_key=api_key)context.add_conversation_entry("Code Reviewer", f"Review:\n{review}")# If review is not "APPROVE", store the review comments.if "APPROVE" not in review.upper():structured_review = {"comments": []}for line in review.splitlines():74 unmodified linescontext = await self.agents[agent_name].generate_documentation(context, api_key)else:raise ValueError(f"Unknown agent: {agent_name}")# Push an update with the current conversation history.self.log_queue.put(("update", context.conversation_history))return context4 unmodified linesreturn "orchestrator"if not context.code:return "coder"# Instead of checking review_comments (which may be empty if reviewer approved),# check the conversation history for a Code Reviewer entry containing "APPROVE".if not any("APPROVE" in entry["message"].upper() for entry in context.conversation_history if entry["agent"].lower() == "code reviewer"):return "code_reviewer"if not context.test_cases:return "qa_tester"21 unmodified linescontext = await dispatcher.dispatch(next_agent, context, api_key, model="gpt-3.5-turbo-16k")else:context = await dispatcher.dispatch(next_agent, context, api_key)# Check approval by scanning the conversation history for a Code Reviewer entry that includes "APPROVE"if next_agent == "code_reviewer":approved = any("APPROVE" in entry["message"].upper()for entry in context.conversation_history15 unmodified lineslog_queue: queue.Queue) -> Generator[Any, None, None]:"""Runs the multi-agent conversation in a background thread and yields 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))6 unmodified linesmsg = log_queue.get(timeout=0.1)if isinstance(msg, tuple):if msg[0] in ("update", "result"):yield gr.update(value=convert_history(msg[1]), visible=True)else:# Optionally handle log messages here.passexcept queue.Empty:passtime.sleep(0.1)yield gr.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.update(value=[{"role": "assistant", "content": "Error: API key not provided."}])returnhuman_event = threading.Event()human_input_queue = queue.Queue()log_queue = queue.Queue()yield from process_conversation_generator(message, openai_api_key, human_event, human_input_queue, log_queue)# -------------------- Custom Gradio Blocks Interface --------------------with gr.Blocks() as demo:gr.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():with gr.Column(scale=8):3 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__":demo.launch(share=True)5 unmodified lines67891011121314151617181944 unmodified lines64656667686970717273747576777889 unmodified lines16816917017117217374 unmodified lines2482492502512522534 unmodified lines25825926026126226326426526621 unmodified lines28828929029129229315 unmodified lines3093103113123133143156 unmodified lines3223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703 unmodified lines3743753763773783793803813823833843853863875 unmodified linesimport gradio as grimport httpximport timeimport tempfilefrom typing import Generator, Any, Dict, List, Optional# -------------------- Configuration --------------------logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")# -------------------- External Model Call (with Caching and Retry) --------------------async def call_model(prompt: str, model: str = "gpt-4o", api_key: str = None, max_retries: int = 3) -> str:if api_key is None:api_key = os.getenv("OPENAI_API_KEY")if api_key is None:44 unmodified linesconverted.append({"role": "assistant", "content": f'{entry["agent"]}: {entry["message"]}'})return converteddef conversation_to_text(history: List[Dict[str, str]]) -> str:"""Convert the conversation history to a plain-text log."""lines = []for entry in history:lines.append(f"{entry['agent']}: {entry['message']}")return "\n".join(lines)# -------------------- Shared Context --------------------class Context:def __init__(self, original_task: str, optimized_task: Optional[str] = None,89 unmodified lines)review = await call_model(prompt, model="gpt-4o", api_key=api_key)context.add_conversation_entry("Code Reviewer", f"Review:\n{review}")if "APPROVE" not in review.upper():structured_review = {"comments": []}for line in review.splitlines():74 unmodified linescontext = await self.agents[agent_name].generate_documentation(context, api_key)else:raise ValueError(f"Unknown agent: {agent_name}")self.log_queue.put(("update", context.conversation_history))return context4 unmodified linesreturn "orchestrator"if not context.code:return "coder"if not any("APPROVE" in entry["message"].upper()for entry in context.conversation_historyif entry["agent"].lower() == "code reviewer"):return "code_reviewer"if not context.test_cases:return "qa_tester"21 unmodified linescontext = await dispatcher.dispatch(next_agent, context, api_key, model="gpt-3.5-turbo-16k")else:context = await dispatcher.dispatch(next_agent, context, api_key)if next_agent == "code_reviewer":approved = any("APPROVE" in entry["message"].upper()for entry in context.conversation_history15 unmodified lineslog_queue: queue.Queue) -> Generator[Any, None, None]:"""Runs the multi-agent conversation in a background thread and yields conversation history updatesas a tuple: (chat update, log state update)."""def run_conversation():asyncio.run(multi_agent_conversation(task_message, log_queue, api_key, human_event, human_input_queue))6 unmodified linesmsg = log_queue.get(timeout=0.1)if isinstance(msg, tuple):if msg[0] in ("update", "result"):chat_update = gr.update(value=convert_history(msg[1]), visible=True)log_text = conversation_to_text(msg[1])state_update = gr.update(value=log_text)yield (chat_update, state_update)else:# Optionally handle log messages.passexcept queue.Empty:passtime.sleep(0.1)yield (gr.update(visible=True), gr.update())# -------------------- 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.update(value=[{"role": "assistant", "content": "Error: API key not provided."}]), gr.update())returnhuman_event = threading.Event()human_input_queue = queue.Queue()log_queue = queue.Queue()yield from process_conversation_generator(message, openai_api_key, human_event, human_input_queue, log_queue)# -------------------- Download Log Function --------------------def download_log(log_text: str) -> str:"""Writes the log text to a temporary file and returns the file path."""with tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode="w", encoding="utf-8") as f:f.write(log_text)return f.name# -------------------- Custom Gradio Blocks Interface --------------------with gr.Blocks() as demo:gr.Markdown("## Multi-Agent Task Solver with Human-in-the-Loop")with gr.Row():# Chatbot displays conversation messages.chat_output = gr.Chatbot(label="Conversation", type="messages")# Hidden state to store the plain-text log.log_state = gr.State(value="")with gr.Row():with gr.Column(scale=8):3 unmodified linessend_button = gr.Button("Send")# The multi_agent_chat function now outputs two values: one for the chat and one for the log.send_button.click(fn=multi_agent_chat, inputs=[message_input, api_key_input], outputs=[chat_output, log_state])with gr.Row():download_button = gr.Button("Download Log")download_file = gr.File(label="Download your log file")download_button.click(fn=download_log, inputs=log_state, outputs=download_file)if __name__ == "__main__":demo.launch(share=True)
app.py+42-15