Spaces:
Sleeping
Sleeping
Update app.py
Browse files12 unmodified lines13141516171819324 unmodified lines3443453463473483493503513523533543553563573583593603613623634 unmodified lines36836937037137237337437537637737837938038138238338438538638738838939039139239339439512 unmodified lineslogging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")# -------------------- External Model Call (with Caching and Retry) --------------------@lru_cache(maxsize=128) # Cache up to 128 responsesasync def call_model(prompt: str, model: str = "gpt-4o", api_key: str = None, max_retries: int = 3) -> str:"""Sends a prompt to the OpenAI API endpoint, with caching and retries."""if api_key is None:324 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")feedback_queue = queue.Queue()def submit_feedback(input_text):feedback_queue.put(input_text)return ""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 --------------------4 unmodified linesif not openai_api_key:yield "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 --------------------12 unmodified lines13141516171819324 unmodified lines3443453463473483493503513523533543553563573583593603613623634 unmodified lines36836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942012 unmodified lineslogging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")# -------------------- External Model Call (with Caching and Retry) --------------------# Removed @lru_cache here, as it caused issues with async and Gradioasync def call_model(prompt: str, model: str = "gpt-4o", api_key: str = None, max_retries: int = 3) -> str:"""Sends a prompt to the OpenAI API endpoint, with caching and retries."""if api_key is None:324 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)with gr.Row():submit_button = gr.Button("Submit Feedback")def submit_feedback(input_text):# Put the feedback into the shared queuehuman_input_queue.put(input_text)return "" # Clear the input box after submissionsubmit_button.click(fn=submit_feedback, inputs=human_input, outputs=human_input)human_feedback_interface.load(None, [], []) # Keep interface alivereturn human_feedback_interface# -------------------- Chat Function for Gradio --------------------4 unmodified linesif not openai_api_key:yield "Error: API key not provided."returnhuman_in_the_loop_event = threading.Event()human_input_queue = queue.Queue() # Use a single queue for both requests and responses# Start the conversation in a separate threadconversation_thread = threading.Thread(target=lambda: asyncio.run(multi_agent_conversation(message, queue.Queue(), openai_api_key, human_in_the_loop_event, human_input_queue)))conversation_thread.start()log_queue = queue.Queue() # Local log queue for this chat instanceasyncio.run(multi_agent_conversation(message, log_queue, openai_api_key, human_in_the_loop_event, human_input_queue))while conversation_thread.is_alive() or not log_queue.empty() or human_in_the_loop_event.is_set():# Yield log messagestry:log_message = log_queue.get_nowait() # Non-blocking getif isinstance(log_message, tuple) and log_message[0] == "result":final_result_text = "\n=== Conversation ===\n"for entry in log_message[1]:final_result_text+= f"[{entry['agent']}]: {entry['message']}\n\n"yield final_result_textelse:yield log_messageexcept queue.Empty:pass# Handle human feedback requestsif human_in_the_loop_event.is_set():yield "Waiting for human feedback..."try:feedback_request = human_input_queue.get(timeout=0.1) # Get context for the request.human_interface = get_human_feedback(feedback_request) #Show context in the input boxyield gr.Textbox.update(visible=False), gr.update(visible=True) # Show the human feedback interface.human_in_the_loop_event.wait() # Wait until the event is clearedexcept queue.Empty:passawait asyncio.sleep(0.1) # Prevent busy-waitingconversation_thread.join()# -------------------- Launch the Chatbot --------------------
app.py+48-23