Spaces:
Runtime error
Runtime error
File size: 39,898 Bytes
ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 0b88bc1 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 0b88bc1 ec19a5f 4f6b4f2 ec19a5f 0b88bc1 ec19a5f 4f6b4f2 ec19a5f 0b88bc1 ec19a5f 0b88bc1 ec19a5f 0b88bc1 ec19a5f 0b88bc1 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 0b88bc1 ec19a5f 0b88bc1 ec19a5f 0b88bc1 4f6b4f2 0b88bc1 ec19a5f 0b88bc1 ec19a5f 4f6b4f2 ec19a5f 0b88bc1 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 0b88bc1 ec19a5f 0b88bc1 ec19a5f 0b88bc1 ec19a5f 0b88bc1 ec19a5f 0b88bc1 ec19a5f 4f6b4f2 0b88bc1 ec19a5f 4f6b4f2 ec19a5f 0b88bc1 ec19a5f 0b88bc1 ec19a5f 0b88bc1 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 0b88bc1 4f6b4f2 ec19a5f 0b88bc1 ec19a5f 4f6b4f2 ec19a5f 0b88bc1 ec19a5f 0b88bc1 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 0b88bc1 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 8ba7ee2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 0b88bc1 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 8ba7ee2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 8ba7ee2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 8ba7ee2 ec19a5f 8ba7ee2 4f6b4f2 ec19a5f 8ba7ee2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 8ba7ee2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 8ba7ee2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f 4f6b4f2 ec19a5f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 | #!/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() |