Spaces:
Build error
Build error
Update app.py
Browse files23 unmodified lines242526272829599 unmodified lines62963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567623 unmodified linesCONFIDENCE_THRESHOLD = 3JSON_DIRECTORY = './evaluation'class GPUMemoryManager:def __init__(self):self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")599 unmodified linesself._record_task_completion(query, final_answer, execution_time)return final_answerdef create_gradio_interface():def process_query(query: str) -> str:try:g_designer = GDesigner()llm = DynamicLLM(g_designer)mas = MultiAgentSystem(g_designer)agent_specs = [{"base": llm.model_name, "role": "Analyst", "plugins": ["analysis"]},{"base": llm.model_name, "role": "Expert", "plugins": ["domain"]},{"base": llm.model_name, "role": "Critic", "plugins": ["evaluation"]}]response = mas.execute_query(query, agent_specs, initial_rounds=3)return responseexcept Exception as e:return f"Error processing query: {str(e)}"with gr.Blocks() as demo:gr.Markdown("# Multi-Agent LLM System")with gr.Row():input_text = gr.Textbox(label="Enter your query",placeholder="Type your question here...",lines=3)output_text = gr.Textbox(label="Response",lines=10)submit_btn = gr.Button("Submit")submit_btn.click(fn=process_query,inputs=input_text,outputs=output_text)return demoif __name__ == "__main__":try:23 unmodified lines24252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222599 unmodified lines82282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598623 unmodified linesCONFIDENCE_THRESHOLD = 3JSON_DIRECTORY = './evaluation'class ARCDataLoader:"""Handles loading and processing of ARC task data."""JSON_directory='./evaluation'def __init__(self, base_path: str = JSON_directory):self.base_path = base_pathif not os.path.exists(base_path):raise ValueError(f"Base path does not exist: {base_path}")if not os.access(base_path, os.R_OK):raise ValueError(f"No read permission for base path: {base_path}")def load_task(self, file_path: str) -> Optional[Dict]:"""Load a single ARC task from JSON file."""try:if not file_path.endswith('.json'):return Noneif not os.path.exists(file_path):print(f"File not found: {file_path}")return Noneif not os.access(file_path, os.R_OK):print(f"No read permission for file: {file_path}")return Nonewith open(file_path, 'r') as f:data = json.load(f)# Validate the expected structureif not isinstance(data, dict):print(f"Invalid data structure in {file_path}: not a dictionary")return Noneif 'train' not in data or 'test' not in data:print(f"Invalid data structure in {file_path}: missing train or test data")return None# Validate that train and test are listsif not isinstance(data['train'], list) or not isinstance(data['test'], list):print(f"Invalid data structure in {file_path}: train or test is not a list")return Nonereturn dataexcept json.JSONDecodeError:print(f"Invalid JSON format in file: {file_path}")return Noneexcept Exception as e:print(f"Unexpected error reading {file_path}: {str(e)}")return Nonedef load_all_tasks(self) -> List[Dict]:"""Load all ARC tasks from the evaluation directory."""tasks = []for filename in os.listdir(self.base_path):if not filename.endswith('.json'):continuefile_path = os.path.join(self.base_path, filename)task = self.load_task(file_path)if task is not None:tasks.append({'filename': filename,'data': task})if not tasks:print(f"Warning: No valid JSON files found in {self.base_path}")return tasksdef validate_task_format(self, task: Dict) -> bool:"""Validate that a task has the correct format."""try:for example in task['train'] + task['test']:if not isinstance(example['input'], list) or not isinstance(example['output'], list):return Falseif not all(isinstance(row, list) for row in example['input'] + example['output']):return Falseif not all(isinstance(val, int) for row in example['input'] + example['output'] for val in row):return Falsereturn Trueexcept (KeyError, TypeError):return Falseclass ARCTaskConverter:"""Converts ARC tasks into format suitable for agent system."""def __init__(self):self.cached_descriptions = {}def grid_to_text(self, grid: List[List[int]]) -> str:"""Convert a grid to a text description."""rows = len(grid)cols = len(grid[0]) if rows > 0 else 0return f"Grid of size {rows}x{cols} with values:\n" + \"\n".join([" ".join(map(str, row)) for row in grid])def analyze_pattern(self, input_grid: List[List[int]], output_grid: List[List[int]]) -> str:"""Analyze the transformation pattern between input and output grids."""in_rows, in_cols = len(input_grid), len(input_grid[0]) if input_grid else 0out_rows, out_cols = len(output_grid), len(output_grid[0]) if output_grid else 0pattern = f"Transform {in_rows}x{in_cols} grid into {out_rows}x{out_cols} grid.\n"# Detect basic patternsif out_rows == in_rows * 3 and out_cols == in_cols * 3:pattern += "Pattern appears to involve 3x3 expansion of the input."elif all(all(val in [0, 1] for val in row) for row in input_grid):pattern += "Binary grid transformation task."return patterndef create_task_description(self, task: Dict) -> str:"""Create a natural language description of the ARC task."""train_pairs = task.get('train', [])test_pairs = task.get('test', [])# Create a description including both training and testing pairsdescription = "ARC reasoning task with the following examples:\n\n"for idx, pair in enumerate(train_pairs):input_desc = self.grid_to_text(pair['input'])output_desc = self.grid_to_text(pair['output'])pattern = self.analyze_pattern(pair['input'], pair['output'])description += f"Training Example {idx + 1}:\nInput:\n{input_desc}\n"description += f"Output:\n{output_desc}\nPattern: {pattern}\n\n"for idx, pair in enumerate(test_pairs):input_desc = self.grid_to_text(pair['input'])description += f"Test Example {idx + 1}:\nInput:\n{input_desc}\nExpected output needs to be inferred.\n\n"return descriptionclass ARCEvaluator:"""Evaluates agent system performance on ARC tasks."""def __init__(self, max_trials: int = 3):self.max_trials = max_trialsself.results = []def evaluate_output(self, predicted: List[List[int]], actual: List[List[int]]) -> bool:"""Check if predicted output matches actual output exactly."""if len(predicted) != len(actual) or any(len(pred_row) != len(act_row) for pred_row, act_row in zip(predicted, actual)):return Falsereturn all(all(p == a for p, a in zip(pred_row, act_row)) for pred_row, act_row in zip(predicted, actual))def record_result(self, task_id: str, success: bool, trials_used: int):"""Record the result of a task evaluation."""self.results.append({'task_id': task_id,'success': success,'trials_used': trials_used})def get_summary(self) -> Dict:"""Generate summary statistics of evaluation results."""total_tasks = len(self.results)successful_tasks = sum(1 for r in self.results if r['success'])avg_trials = sum(r['trials_used'] for r in self.results) / total_tasks if total_tasks > 0 else 0return {'total_tasks': total_tasks,'successful_tasks': successful_tasks,'success_rate': successful_tasks / total_tasks if total_tasks > 0 else 0,'average_trials': avg_trials}def load_grid_data(data: Dict) -> Tuple[List[Dict], List[Dict]]:"""Load grid transformation data from the provided dictionary.Args:data: Dictionary containing 'train' and 'test' dataReturns:Tuple of training and test data lists"""return data['train'], data['test']def process_grid_example(example: Dict) -> Tuple[torch.Tensor, torch.Tensor]:"""Convert a grid example into input and output tensors.Args:example: Dictionary containing 'input' and 'output' gridsReturns:Tuple of input and output tensors"""input_grid = torch.tensor(example['input'], dtype=torch.float32)output_grid = torch.tensor(example['output'], dtype=torch.float32)return input_grid, output_gridclass GPUMemoryManager:def __init__(self):self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")599 unmodified linesself._record_task_completion(query, final_answer, execution_time)return final_answerdef create_gradio_interface():# Initialize ARC componentsarc_loader = ARCDataLoader()arc_converter = ARCTaskConverter()arc_evaluator = ARCEvaluator()def process_query(task_json: str) -> str:try:# Parse the ARC task JSONtask = json.loads(task_json)if not arc_loader.validate_task_format(task):return "Error: Invalid ARC task format"# Convert ARC task to natural languagequery = arc_converter.create_task_description(task)g_designer = GDesigner()llm = DynamicLLM(g_designer)mas = MultiAgentSystem(g_designer)agent_specs = [{"base": llm.model_name, "role": "Pattern Analyst", "plugins": ["analysis"]},{"base": llm.model_name, "role": "Grid Transformation Expert", "plugins": ["domain"]},{"base": llm.model_name, "role": "Solution Validator", "plugins": ["evaluation"]}]response = mas.execute_query(query, agent_specs, initial_rounds=3)# Evaluate the response against test examplessuccess = Falsefor test_case in task['test']:# Extract predicted grid from response (assuming response contains grid in proper format)try:# You'll need to implement parse_grid_from_response based on your response formatpredicted_grid = parse_grid_from_response(response)success = arc_evaluator.evaluate_output(predicted_grid, test_case['output'])arc_evaluator.record_result(task_json[:20], success, 1) # Using first 20 chars as task_idexcept Exception as e:return f"Error parsing response grid: {str(e)}"# Add evaluation results to responseeval_summary = arc_evaluator.get_summary()response += f"\n\nEvaluation Results:\n"response += f"Success: {success}\n"response += f"Overall Success Rate: {eval_summary['success_rate']*100:.2f}%"return responseexcept Exception as e:return f"Error processing query: {str(e)}"def parse_grid_from_response(response: str) -> List[List[int]]:"""Parse the grid from the agent's response string."""try:# Look for grid pattern in the responsegrid_lines = []in_grid = Falsefor line in response.split('\n'):# Start collecting grid when we see a row patternif '[' in line and ']' in line and any(c.isdigit() for c in line):in_grid = True# Clean the line and extract numbersclean_line = line.strip().strip('[]').replace(',', ' ')row = [int(x) for x in clean_line.split() if x.isdigit()]if row:grid_lines.append(row)# Stop if we've found the grid and hit a non-grid lineelif in_grid and line.strip() and '[' not in line:break# Validate grid formatif not grid_lines:raise ValueError("No valid grid found in response")# Ensure all rows have same lengthwidth = len(grid_lines[0])if not all(len(row) == width for row in grid_lines):raise ValueError("Inconsistent grid row lengths")# Ensure all values are 0, 3, or 8 (based on training data)valid_values = {0, 3, 8}if not all(all(val in valid_values for val in row) for row in grid_lines):raise ValueError("Invalid grid values found")return grid_linesexcept Exception as e:print(f"Error parsing grid: {str(e)}")return Nonedef process_query(task_json: str) -> str:try:arc_loader = ARCDataLoader()arc_converter = ARCTaskConverter()arc_evaluator = ARCEvaluator()# Parse the ARC task JSONtask = json.loads(task_json)if not arc_loader.validate_task_format(task):return "Error: Invalid ARC task format"# Convert ARC task to natural languagequery = arc_converter.create_task_description(task)g_designer = GDesigner()llm = DynamicLLM(g_designer)mas = MultiAgentSystem(g_designer)# Add grid-specific context to agent specsagent_specs = [{"base": llm.model_name,"role": "Pattern Analyst","plugins": ["analysis"],"output_format": "grid"},{"base": llm.model_name,"role": "Grid Transformation Expert","plugins": ["domain"],"output_format": "grid"},{"base": llm.model_name,"role": "Solution Validator","plugins": ["evaluation"],"output_format": "grid"}]response = mas.execute_query(query, agent_specs, initial_rounds=3)# Evaluate the response against test examplessuccess = Falsefor test_case in task['test']:predicted_grid = parse_grid_from_response(response)if predicted_grid is not None:success = arc_evaluator.evaluate_output(predicted_grid, test_case['output'])if success:break # Stop if we find a successful matcharc_evaluator.record_result(task_json[:20], success, 1)# Format the response with the grid and evaluation resultsformatted_response = f"Predicted Grid:\n"if predicted_grid:formatted_response += "\n".join([str(row) for row in predicted_grid])else:formatted_response += "Error: Could not generate valid grid"formatted_response += f"\n\nEvaluation Results:\n"formatted_response += f"Success: {success}\n"eval_summary = arc_evaluator.get_summary()formatted_response += f"Overall Success Rate: {eval_summary['success_rate']*100:.2f}%"return formatted_responseexcept Exception as e:return f"Error processing query: {str(e)}"if __name__ == "__main__":try:
app.py+334-24