Spaces:
Sleeping
Sleeping
Download langgraph_agent_test_client.py from DiegoSanC/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 39.9 kB
-
https://huggingface.co/spaces/DiegoSanC/Final_Assignment_Template/resolve/main/langgraph_agent_test_client.py
- Command line
-
hf download hf://spaces/DiegoSanC/Final_Assignment_Template/langgraph_agent_test_client.py
-
curl -L -o langgraph_agent_test_client.py https://huggingface.co/spaces/DiegoSanC/Final_Assignment_Template/resolve/main/langgraph_agent_test_client.py
39.9 kB
| #!/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() |