#!/usr/bin/env python3 """ LangGraph Agent Test Client A Gradio-based test client for the LangGraphAgent that: 1. Fetches random questions from the evaluation API 2. Executes the LangGraph agent with proper dictionary input format 3. Handles task_id and file_name information for file processing 4. Displays comprehensive execution information 5. Supports custom question testing 6. Tests against evaluation questions from questions_evaluated.py Usage: python langgraph_agent_test_client.py """ import gradio as gr import requests from agent import LangGraphAgent import traceback import time from contextlib import redirect_stdout, redirect_stderr import io import pandas as pd from questions_evaluated import questions import json import os from typing import Optional, Dict, Any, List import logging # Configure logging for real-time terminal output logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.StreamHandler(), # This ensures logs go to console ] ) logger = logging.getLogger(__name__) # Configuration DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" class AgentExecutionTracker: """Tracks and logs agent execution with detailed information""" def __init__(self): self.reset() def reset(self): """Reset tracking for new execution""" self.logs = [] self.start_time = "" self.end_time = "" self.question = "" self.task_id = "" self.file_name = "" self.agent_response = "" self.final_answer = "" self.captured_stdout = "" self.captured_stderr = "" def log(self, level: str, message: str): """Add a log entry with timestamp""" timestamp = time.strftime("%H:%M:%S") self.logs.append(f"[{timestamp}] {level}: {message}") def get_formatted_log(self): """Get comprehensive formatted execution log""" lines = [ "๐Ÿค– LANGGRAPH AGENT EXECUTION LOG", "=" * 60, f"๐Ÿ“ Question: {self.question}", f"๐Ÿ”ข Task ID: {self.task_id}", f"๐Ÿ“Ž File Name: {self.file_name if self.file_name else 'None'}", f"โฐ Started: {self.start_time}", f"โฑ๏ธ Ended: {self.end_time}", "", "๐Ÿ“‹ EXECUTION STEPS:", "-" * 40 ] # Add all log entries for log_entry in self.logs: lines.append(log_entry) # Add captured outputs if any if self.captured_stdout.strip(): lines.extend([ "", "๐Ÿ“ค CAPTURED STDOUT:", "-" * 30, self.captured_stdout, "-" * 30 ]) if self.captured_stderr.strip(): lines.extend([ "", "โš ๏ธ CAPTURED STDERR:", "-" * 30, self.captured_stderr, "-" * 30 ]) # Add final results lines.extend([ "", "๐ŸŽฏ RESULTS:", "-" * 20, f"Agent Response Length: {len(self.agent_response)} characters", ]) if self.final_answer: lines.append(f"Final Answer: {self.final_answer}") return "\n".join(lines) class LangGraphAgentTester: """Main tester class that handles LangGraph agent execution and API calls""" def __init__(self): self.agent = None self.tracker = AgentExecutionTracker() self.api_url = DEFAULT_API_URL def _initialize_agent(self): """Initialize the LangGraphAgent if not already done""" if self.agent is None: try: self.tracker.log("INIT", "Initializing LangGraphAgent...") self.agent = LangGraphAgent(tasks_api=self.api_url) self.tracker.log("INIT", "โœ… LangGraphAgent initialized successfully") return True except Exception as e: self.tracker.log("ERROR", f"Failed to initialize agent: {str(e)}") return False return True def fetch_random_question(self): """Fetch a random question from the evaluation API""" try: logger.info("๐ŸŒ FETCHING RANDOM QUESTION FROM API") logger.info(f"๐Ÿ“ก API Endpoint: {self.api_url}/random-question") self.tracker.log("API", "Fetching random question from evaluation API...") response = requests.get(f"{self.api_url}/random-question", timeout=15) response.raise_for_status() question_data = response.json() task_id = question_data.get("task_id", "Unknown") question_text = question_data.get("question", "No question available") file_name = question_data.get("file_name", "") logger.info(f"โœ… API Response received") logger.info(f"๐Ÿ”ข Task ID: {task_id}") logger.info(f"๐Ÿ“Ž File Name: {file_name if file_name else 'None'}") logger.info(f"๐Ÿ“ Question Length: {len(question_text)} characters") logger.info(f"๐Ÿ“„ Question Preview: {question_text[:100]}{'...' if len(question_text) > 100 else ''}") self.tracker.log("API", f"โœ… Successfully fetched question (Task ID: {task_id})") if file_name: self.tracker.log("API", f"๐Ÿ“Ž Question includes file: {file_name}") return question_data except requests.exceptions.Timeout: logger.error("โฐ REQUEST TIMEOUT - API may be slow or unavailable") self.tracker.log("ERROR", "Request timeout - API may be slow or unavailable") return None except requests.exceptions.ConnectionError: logger.error("๐Ÿ”Œ CONNECTION ERROR - Check internet connection") self.tracker.log("ERROR", "Connection error - Check internet connection") return None except requests.exceptions.HTTPError as e: logger.error(f"โŒ HTTP ERROR {e.response.status_code} - API may be unavailable") self.tracker.log("ERROR", f"HTTP error {e.response.status_code} - API may be unavailable") return None except Exception as e: logger.error(f"๐Ÿ’ฅ UNEXPECTED ERROR: {str(e)}") self.tracker.log("ERROR", f"Unexpected error fetching question: {str(e)}") return None def execute_agent(self, question_dict: Dict[str, Any]): """Execute the LangGraph agent with comprehensive tracking""" # Reset tracker for new execution self.tracker.reset() self.tracker.question = question_dict.get("question", "") self.tracker.task_id = question_dict.get("task_id", "") self.tracker.file_name = question_dict.get("file_name", "") self.tracker.start_time = time.strftime("%H:%M:%S") # Real-time console logging logger.info("๐Ÿš€ EXECUTING LANGGRAPH AGENT") logger.info("=" * 60) logger.info(f"โฐ Start Time: {self.tracker.start_time}") logger.info(f"๐Ÿ”ข Task ID: {self.tracker.task_id}") logger.info(f"๐Ÿ“Ž File Name: {self.tracker.file_name}") logger.info(f"๐Ÿ“ Question Length: {len(self.tracker.question)} characters") logger.info(f"๐Ÿ“„ Question: {self.tracker.question[:150]}{'...' if len(self.tracker.question) > 150 else self.tracker.question}") try: # Initialize agent if needed if not self._initialize_agent(): logger.error("โŒ AGENT INITIALIZATION FAILED") self.tracker.end_time = time.strftime("%H:%M:%S") return "Failed to initialize agent" logger.info("โœ… Agent initialized successfully") self.tracker.log("EXEC", "Starting LangGraph agent execution...") self.tracker.log("INPUT", f"Question: {self.tracker.question[:100]}{'...' if len(self.tracker.question) > 100 else ''}") self.tracker.log("INPUT", f"Task ID: {self.tracker.task_id}") if self.tracker.file_name: self.tracker.log("INPUT", f"File Name: {self.tracker.file_name}") file_url = f"{self.api_url}/files/{self.tracker.task_id}" self.tracker.log("FILE", f"Agent will fetch file from: {file_url}") logger.info(f"๐Ÿ“ฅ File URL: {file_url}") logger.info("๐Ÿ”„ Calling agent with question dictionary...") # Capture stdout and stderr during execution (but don't suppress console logging) stdout_buffer = io.StringIO() stderr_buffer = io.StringIO() with redirect_stdout(stdout_buffer), redirect_stderr(stderr_buffer): result = self.agent(question_dict) # Store captured outputs self.tracker.captured_stdout = stdout_buffer.getvalue() self.tracker.captured_stderr = stderr_buffer.getvalue() logger.info("โœ… AGENT EXECUTION COMPLETED") self.tracker.log("EXEC", "โœ… LangGraph agent execution completed successfully") # Handle non-string results from agent original_type = type(result).__name__ if isinstance(result, str): result_str = result logger.info(f"๐Ÿ“ค Agent returned string ({len(result_str)} characters)") logger.info(f"๐Ÿ“ค Agent returned string: {result_str}") self.tracker.log("RESPONSE", f"Agent returned string ({len(result_str)} characters)") else: result_str = str(result) logger.info(f"๐Ÿ“ค Agent returned {original_type}: {result}") self.tracker.log("RESPONSE", f"Agent returned {original_type}: {result}") self.tracker.log("RESPONSE", f"Converted to string ({len(result_str)} characters)") final_answer = result_str.split("FINAL ANSWER:")[-1].strip() self.tracker.final_answer = final_answer logger.info(f"๐ŸŽฏ Final Answer: {final_answer[:100]}{'...' if len(final_answer) > 100 else ''}") self.tracker.log("ANSWER", f"Extracted final answer: {final_answer[:50]}{'...' if len(final_answer) > 50 else ''}") # Extract final answer if present in string version # if "FINAL ANSWER:" in result_str: # final_answer = result_str.split("FINAL ANSWER:")[-1].strip() # self.tracker.final_answer = final_answer # logger.info(f"๐ŸŽฏ Final Answer: {final_answer[:100]}{'...' if len(final_answer) > 100 else ''}") # self.tracker.log("ANSWER", f"Extracted final answer: {final_answer[:50]}{'...' if len(final_answer) > 50 else ''}") # else: # # If no "FINAL ANSWER:" format and original was not a string, use the converted string # if not isinstance(result, str): # self.tracker.final_answer = result_str # logger.warning(f"โš ๏ธ No FINAL ANSWER format, using converted {original_type}") # self.tracker.log("ANSWER", f"No FINAL ANSWER format, using converted {original_type}: {result_str}") # else: # self.tracker.final_answer = "No explicit final answer found" # logger.warning("โš ๏ธ No explicit FINAL ANSWER format detected") # self.tracker.log("ANSWER", "No explicit FINAL ANSWER format detected") self.tracker.agent_response = result_str self.tracker.end_time = time.strftime("%H:%M:%S") logger.info(f"โฐ End Time: {self.tracker.end_time}") logger.info("๐Ÿ AGENT EXECUTION SUMMARY COMPLETE") logger.info("=" * 60) return result_str except Exception as e: error_msg = f"LangGraph agent execution failed: {str(e)}" logger.error(f"๐Ÿ’ฅ AGENT EXECUTION FAILED: {str(e)}") logger.error(f"๐Ÿ“œ Traceback: {traceback.format_exc()}") self.tracker.log("ERROR", error_msg) self.tracker.log("ERROR", f"Traceback: {traceback.format_exc()}") self.tracker.end_time = time.strftime("%H:%M:%S") return f"ERROR: {error_msg}" # Global tester instance tester = LangGraphAgentTester() def test_random_question(): """Handle random question testing""" logger.info("๐ŸŽฒ STARTING RANDOM QUESTION TEST") try: # Fetch random question question_data = tester.fetch_random_question() if not question_data: logger.error("โŒ Failed to fetch random question from API") return ( "โŒ Failed to fetch random question from API", "Please check your internet connection and try again.\nThe evaluation API might be temporarily unavailable.", "No response available" ) logger.info("๐Ÿ“Š Question data received, executing agent...") # Execute agent with the complete question dictionary agent_response = tester.execute_agent(question_data) # Format outputs question_text = question_data.get("question", "No question text available") task_id = question_data.get("task_id", "Unknown") file_name = question_data.get("file_name", "") logger.info(f"โœ… Random question test completed for Task ID: {task_id}") question_info = f"๐Ÿ“‹ Task ID: {task_id}\n๐Ÿ“Ž File: {file_name if file_name else 'None'}\n\n๐Ÿ“ Question:\n{question_text}" execution_log = tester.tracker.get_formatted_log() result_summary = f"๐Ÿค– Agent Response:\n{agent_response}\n\n" if tester.tracker.final_answer: result_summary += f"๐ŸŽฏ Final Answer: {tester.tracker.final_answer}" return question_info, execution_log, result_summary except Exception as e: error_msg = f"Unexpected error in random question test: {str(e)}\n{traceback.format_exc()}" logger.error(f"๐Ÿ’ฅ Random question test failed: {str(e)}") return f"โŒ Error: {error_msg}", "", "" def test_custom_question(custom_question: str, custom_task_id: str = "", custom_file_name: str = ""): """Handle custom question testing""" if not custom_question.strip(): logger.warning("โš ๏ธ Empty custom question provided") return "โŒ Please enter a question to test", "", "" logger.info("โœ๏ธ STARTING CUSTOM QUESTION TEST") logger.info(f"๐Ÿ“ Custom Question: {custom_question[:100]}{'...' if len(custom_question) > 100 else ''}") logger.info(f"๐Ÿ”ข Custom Task ID: {custom_task_id if custom_task_id.strip() else 'Not provided'}") logger.info(f"๐Ÿ“Ž Custom File Name: {custom_file_name if custom_file_name.strip() else 'Not provided'}") try: # Create question dictionary for LangGraph agent question_dict = { "question": custom_question.strip(), "task_id": custom_task_id.strip() if custom_task_id.strip() else "custom_test", "file_name": custom_file_name.strip() if custom_file_name.strip() else "" } # Execute agent with custom question agent_response = tester.execute_agent(question_dict) # Format outputs question_info = f"๐Ÿ“ Custom Question:\n{custom_question.strip()}" if custom_task_id.strip(): question_info += f"\n๐Ÿ”ข Custom Task ID: {custom_task_id.strip()}" if custom_file_name.strip(): question_info += f"\n๐Ÿ“Ž Custom File: {custom_file_name.strip()}" execution_log = tester.tracker.get_formatted_log() result_summary = f"๐Ÿค– Agent Response:\n{agent_response}\n\n" if tester.tracker.final_answer: result_summary += f"๐ŸŽฏ Final Answer: {tester.tracker.final_answer}" logger.info("โœ… Custom question test completed") return question_info, execution_log, result_summary except Exception as e: error_msg = f"Unexpected error in custom question test: {str(e)}\n{traceback.format_exc()}" return f"โŒ Error: {error_msg}", "", "" def get_evaluation_questions(): """Get list of evaluation questions for dropdown""" question_choices = [] for i, q in enumerate(questions): task_id = q.get("task_id", "Unknown") question_text = q.get("question", "No question") level = q.get("Level", "Unknown") file_name = q.get("file_name", "") # Truncate long questions for display display_text = question_text[:100] + "..." if len(question_text) > 100 else question_text file_indicator = " ๐Ÿ“Ž" if file_name else "" label = f"[Level {level}] {task_id[:8]}...{file_indicator} - {display_text}" question_choices.append((label, i)) return question_choices def normalize_answer(answer: str) -> str: """Normalize an answer for comparison by stripping whitespace and converting to lowercase""" if not answer or answer == "Not found" or answer.startswith("ERROR:"): return "" return str(answer).strip().lower() def test_evaluation_question(question_index): """Handle evaluation question testing""" if question_index is None: return "โŒ Please select a question to test", "", "", "" try: selected_question = questions[question_index] # Execute agent with the complete question dictionary agent_response = tester.execute_agent(selected_question) # Format outputs question_text = selected_question.get("question", "No question text") task_id = selected_question.get("task_id", "Unknown") level = selected_question.get("Level", "Unknown") file_name = selected_question.get("file_name", "") question_info = f"๐Ÿ“‹ Task ID: {task_id}\n๐Ÿ“Š Level: {level}\n๐Ÿ“Ž File: {file_name if file_name else 'None'}\n\n๐Ÿ“ Question:\n{question_text}" execution_log = tester.tracker.get_formatted_log() result_summary = f"๐Ÿค– Agent Response:\n{agent_response}\n\n" if tester.tracker.final_answer: result_summary += f"๐ŸŽฏ Final Answer: {tester.tracker.final_answer}" # Get the correct answer correct_answer = get_correct_answer(task_id) if correct_answer: correct_answer_display = f"โœ… **Correct Answer:**\n{correct_answer}\n\n๐Ÿ“‹ **Task ID:** {task_id}\n๐Ÿ“Š **Level:** {level}" else: correct_answer_display = f"โ“ **Correct Answer:**\nNot found in metadata\n\n๐Ÿ“‹ **Task ID:** {task_id}\n๐Ÿ“Š **Level:** {level}" return question_info, execution_log, result_summary, correct_answer_display except Exception as e: error_msg = f"Unexpected error in evaluation question test: {str(e)}\n{traceback.format_exc()}" return f"โŒ Error: {error_msg}", "", "", "" def test_all_evaluation_questions(): """Run all evaluation questions and return results""" try: results = [] total_questions = len(questions) progress_info = f"๐Ÿ”„ Running {total_questions} evaluation questions with LangGraph agent...\n\n" for i, question_data in enumerate(questions): logger.info(f"Processing question {i+1}/{total_questions}: {question_data.get('task_id', 'Unknown')[:8]}...") question_text = question_data.get("question", "No question text") task_id = question_data.get("task_id", "Unknown") level = question_data.get("Level", "Unknown") file_name = question_data.get("file_name", "") progress_info += f"Processing question {i+1}/{total_questions}: {task_id[:8]}...\n" try: # Execute agent with complete question dictionary agent_response = tester.execute_agent(question_data) # Extract final answer final_answer = tester.tracker.final_answer if tester.tracker.final_answer else "No answer extracted" # Get correct answer correct_answer = get_correct_answer(task_id) correct_answer_display = correct_answer if correct_answer else "Not found" # Determine if answer is correct agent_normalized = normalize_answer(final_answer) correct_normalized = normalize_answer(correct_answer_display) is_correct = agent_normalized == correct_normalized and agent_normalized != "" results.append({ "Task ID": task_id, "Level": level, "File": file_name if file_name else "None", "Question": question_text[:100] + "..." if len(question_text) > 100 else question_text, "Agent Answer": final_answer, "Correct Answer": correct_answer_display, "Response Length": len(agent_response), "Status": "Correct" if is_correct else "Incorrect", "Execution Status": "Success" }) except Exception as e: # Get correct answer even if agent failed correct_answer = get_correct_answer(task_id) correct_answer_display = correct_answer if correct_answer else "Not found" results.append({ "Task ID": task_id, "Level": level, "File": file_name if file_name else "None", "Question": question_text[:100] + "..." if len(question_text) > 100 else question_text, "Agent Answer": f"ERROR: {str(e)}", "Correct Answer": correct_answer_display, "Response Length": 0, "Status": "Failed", "Execution Status": "Failed" }) # Create DataFrame for results results_df = pd.DataFrame(results) # Summary statistics - now based on correct answers correct_answers_count = len([r for r in results if r["Status"] == "Correct"]) incorrect_answers_count = len([r for r in results if r["Status"] == "Incorrect"]) execution_failures_count = len([r for r in results if r["Status"] == "Failed"]) successful_executions_count = len([r for r in results if r["Execution Status"] == "Success"]) file_questions = len([r for r in results if r["File"] != "None"]) # Calculate accuracy rate (only for questions that executed successfully) accuracy_rate = (correct_answers_count / successful_executions_count * 100) if successful_executions_count > 0 else 0 overall_success_rate = (correct_answers_count / total_questions * 100) summary = f""" โœ… LANGGRAPH AGENT EVALUATION COMPLETE ๐Ÿ“Š Summary: - Total Questions: {total_questions} - Questions with Files: {file_questions} - Execution Successes: {successful_executions_count} - Execution Failures: {execution_failures_count} ๐ŸŽฏ Answer Accuracy: - Correct Answers: {correct_answers_count} - Incorrect Answers: {incorrect_answers_count} - Accuracy Rate (of successful executions): {accuracy_rate:.1f}% - Overall Success Rate: {overall_success_rate:.1f}% """ return summary, results_df, "All LangGraph evaluation questions processed!" except Exception as e: error_msg = f"Error running all evaluation questions: {str(e)}\n{traceback.format_exc()}" return f"โŒ Error: {error_msg}", pd.DataFrame(), "" def create_interface(): """Create the main Gradio interface""" # Custom CSS for better styling css = """ .gradio-container { max-width: 1200px !important; } .tab-nav { font-size: 16px !important; } """ with gr.Blocks( title="LangGraph Agent Test Client", css=css ) as interface: # Header gr.Markdown(""" # ๐Ÿงช LangGraph Agent Test Client **Interactive testing environment for the LangGraphAgent** This tool allows you to thoroughly test the LangGraph agent's capabilities with detailed execution tracking. The agent expects dictionary inputs with question, task_id, and file_name information for proper file handling. You can fetch random questions from the evaluation API, test with custom questions, or run specific evaluation questions. """) # Main tabs with gr.Tabs(): # Random Question Tab with gr.TabItem("๐ŸŽฒ Random Question Test", elem_id="random-tab"): gr.Markdown("### Fetch and test a random question from the evaluation API") gr.Markdown("Click the button below to fetch a random question and run the LangGraph agent on it.") random_btn = gr.Button( "๐ŸŽฒ Fetch Random Question & Execute LangGraph Agent", variant="primary", size="lg", scale=1 ) # Output sections with gr.Row(): with gr.Column(scale=1): question_display = gr.Textbox( label="๐Ÿ“‹ Question Information", lines=6, max_lines=10, interactive=False, show_copy_button=True ) with gr.Column(scale=1): result_display = gr.Textbox( label="๐ŸŽฏ Agent Response & Final Answer", lines=6, max_lines=10, interactive=False, show_copy_button=True ) execution_log_display = gr.Textbox( label="๐Ÿ” Detailed Execution Log", lines=20, max_lines=30, interactive=False, show_copy_button=True, placeholder="Execution log will appear here after running the agent..." ) # Wire up the random question functionality random_btn.click( fn=test_random_question, inputs=[], outputs=[question_display, execution_log_display, result_display] ) # Custom Question Tab with gr.TabItem("โœ๏ธ Custom Question Test", elem_id="custom-tab"): gr.Markdown("### Test the agent with your own custom question") gr.Markdown("Enter any question you'd like to test the agent with. Optionally provide task_id and file_name for file processing.") with gr.Row(): with gr.Column(scale=2): custom_input = gr.Textbox( label="๐Ÿ“ Your Question", lines=3, max_lines=5, placeholder="Enter your question here...\n\nExample: What is the square root of 144?", show_copy_button=True ) with gr.Column(scale=1): custom_task_id = gr.Textbox( label="๐Ÿ”ข Task ID (Optional)", lines=1, placeholder="Leave empty for custom test", show_copy_button=True ) custom_file_name = gr.Textbox( label="๐Ÿ“Ž File Name (Optional)", lines=1, placeholder="e.g., data.xlsx, image.png", show_copy_button=True ) custom_btn = gr.Button( "๐Ÿš€ Execute LangGraph Agent on Custom Question", variant="secondary", size="lg" ) # Output sections for custom questions with gr.Row(): with gr.Column(scale=1): custom_question_display = gr.Textbox( label="๐Ÿ“‹ Question Information", lines=4, max_lines=8, interactive=False, show_copy_button=True ) with gr.Column(scale=1): custom_result_display = gr.Textbox( label="๐ŸŽฏ Agent Response & Final Answer", lines=4, max_lines=8, interactive=False, show_copy_button=True ) custom_execution_log_display = gr.Textbox( label="๐Ÿ” Detailed Execution Log", lines=20, max_lines=30, interactive=False, show_copy_button=True, placeholder="Execution log will appear here after running the agent..." ) # Wire up the custom question functionality custom_btn.click( fn=test_custom_question, inputs=[custom_input, custom_task_id, custom_file_name], outputs=[custom_question_display, custom_execution_log_display, custom_result_display] ) # Evaluation Questions Tab with gr.TabItem("๐Ÿ“Š Evaluation Questions", elem_id="eval-tab"): gr.Markdown("### Test with specific evaluation questions") gr.Markdown(f"Select from {len(questions)} evaluation questions or run all of them. Questions with files are marked with ๐Ÿ“Ž.") with gr.Row(): with gr.Column(scale=2): question_dropdown = gr.Dropdown( choices=get_evaluation_questions(), label="๐Ÿ“ Select Evaluation Question", value=None ) with gr.Column(scale=1): eval_single_btn = gr.Button( "๐Ÿš€ Run Selected Question", variant="secondary", size="lg" ) eval_all_btn = gr.Button( "๐Ÿ”„ Run ALL Evaluation Questions", variant="primary", size="lg" ) gr.Markdown("โš ๏ธ **Warning**: Running all questions may take a long time, especially those with file processing!") # Single question results with gr.Row(): with gr.Column(scale=1): eval_question_display = gr.Textbox( label="๐Ÿ“‹ Question Information", lines=6, max_lines=10, interactive=False, show_copy_button=True ) with gr.Column(scale=1): eval_result_display = gr.Textbox( label="๐ŸŽฏ Agent Response & Final Answer", lines=6, max_lines=10, interactive=False, show_copy_button=True ) with gr.Column(scale=1): eval_correct_answer_display = gr.Textbox( label="โœ… Correct Answer", lines=6, max_lines=10, interactive=False, show_copy_button=True, placeholder="Correct answer will appear here..." ) eval_execution_log_display = gr.Textbox( label="๐Ÿ” Detailed Execution Log", lines=15, max_lines=25, interactive=False, show_copy_button=True, placeholder="Execution log will appear here after running a question..." ) # All questions results gr.Markdown("### ๐Ÿ“Š Batch Results") batch_summary_display = gr.Textbox( label="๐Ÿ“ˆ Batch Summary", lines=8, interactive=False, show_copy_button=True, placeholder="Summary will appear here after running all questions..." ) batch_results_display = gr.DataFrame( label="๐Ÿ“‹ Detailed Results Table", headers=["Task ID", "Level", "File", "Question", "Agent Answer", "Correct Answer", "Response Length", "Status", "Execution Status"], datatype=["str", "str", "str", "str", "str", "str", "number", "str", "str"], interactive=False, wrap=True ) batch_status_display = gr.Textbox( label="๐Ÿ”„ Status", lines=2, interactive=False, placeholder="Status updates will appear here..." ) # Wire up evaluation question functionality eval_single_btn.click( fn=test_evaluation_question, inputs=[question_dropdown], outputs=[eval_question_display, eval_execution_log_display, eval_result_display, eval_correct_answer_display] ) eval_all_btn.click( fn=test_all_evaluation_questions, inputs=[], outputs=[batch_summary_display, batch_results_display, batch_status_display] ) # Footer information gr.Markdown("---") gr.Markdown(""" ### ๐Ÿ“š Features & Information **๐Ÿ” LangGraph Agent Features:** - Uses LangGraph for complex reasoning workflows - Supports file processing (images, Excel, Python, audio) - Handles task_id and file_name for proper file retrieval - Connects to evaluation API for file downloads - Uses multiple tools: math operations, Wikipedia, ArXiv, web search, YouTube transcripts **๐Ÿ”ง Execution Tracking:** - Comprehensive step-by-step logging with timestamps - Capture of stdout/stderr during agent execution - Detailed error reporting and stack traces - File processing information and URLs - Performance timing information **๐ŸŽฏ Response Analysis:** - Full agent response display - Automatic final answer extraction - Response length and format analysis - File handling diagnostics **โšก Testing Capabilities:** - Random questions from the evaluation API endpoint - Custom question testing with optional file parameters - Individual evaluation question testing with file support - Batch processing of all evaluation questions - Copy-friendly logs for external analysis - Real-time execution monitoring """) gr.Markdown(f""" ### ๐Ÿš€ Quick Start Guide 1. **Random Questions**: Click "Fetch Random Question & Execute LangGraph Agent" to test with API questions 2. **Custom Questions**: Enter your own question with optional task_id and file_name parameters 3. **Evaluation Questions**: Select a specific evaluation question (๐Ÿ“Ž indicates file support) or run all 4. **Review Results**: Check execution logs for detailed insights into agent processing and file handling 5. **Batch Analysis**: Use "Run ALL" to get comprehensive performance metrics across all question types **API Endpoint**: `{DEFAULT_API_URL}` **Agent Type**: LangGraphAgent with tool integration **File Support**: Images, Excel, Python, Audio files via task_id **Evaluation Questions**: {len(questions)} loaded from questions_evaluated.py """) return interface def main(): """Main function to launch the test client""" print("๐Ÿš€ Starting LangGraph Agent Test Client...") print("๐Ÿ“ก API Endpoint:", DEFAULT_API_URL) print("๐Ÿค– Agent Type: LangGraphAgent") print(f"๐Ÿ“Š Evaluation Questions: {len(questions)} loaded") print("๐Ÿ“Ž File Support: Enabled via tasks API") print("-" * 50) # Create and launch interface interface = create_interface() interface.launch( debug=True, share=False, show_error=True, server_name="0.0.0.0", # Allow external connections server_port=7861 # Different port from smolagents version ) def load_metadata() -> Dict[str, str]: """Load metadata from metadata.jsonl and return a mapping of task_id to final answer""" metadata = {} try: with open('metadata.jsonl', 'r', encoding='utf-8') as f: for line in f: line = line.strip() if line: try: data = json.loads(line) task_id = data.get('task_id') final_answer = data.get('Final answer') if task_id and final_answer is not None: metadata[task_id] = str(final_answer) except json.JSONDecodeError as e: print(f"Warning: Could not parse JSON line: {line[:100]}...") continue except FileNotFoundError: print("Warning: metadata.jsonl file not found") except Exception as e: print(f"Warning: Error loading metadata: {e}") return metadata def get_correct_answer(task_id: str) -> Optional[str]: """Get the correct answer for a given task_id""" metadata = load_metadata() return metadata.get(task_id) if __name__ == "__main__": main()