File size: 9,595 Bytes
35f54b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Example GAIA Agent Implementation

This file shows how to implement a basic agent with external API integration.
You can use this as a starting point and customize it for your needs.
"""

import requests
import json
import re
from typing import Dict, List, Any
from agent_implementation import BaseGAIAAgent

class ExampleGAIAAgent(BaseGAIAAgent):
    """
    Example agent implementation with basic reasoning and external API support.
    
    This agent demonstrates:
    1. Basic question analysis
    2. Mathematical calculations
    3. Simple reasoning patterns
    4. Error handling
    """
    
    def __init__(self):
        super().__init__()
        self.calculation_patterns = [
            r'(\d+)\s*\+\s*(\d+)',
            r'(\d+)\s*-\s*(\d+)',
            r'(\d+)\s*\*\s*(\d+)',
            r'(\d+)\s*/\s*(\d+)',
            r'(\d+)\s*%\s*(\d+)'
        ]
    
    def generate_answer(self, question: Dict) -> str:
        """
        Generate an answer for a given question.
        
        This implementation includes:
        - Question type detection
        - Mathematical calculations
        - Basic reasoning
        - File content processing
        """
        task_id = question.get("task_id", "")
        question_text = question.get("question", "")
        
        # Download any associated files
        file_content = self.download_file(task_id)
        
        # Analyze the question type
        question_type = self.analyze_question_type(question_text)
        
        # Generate answer based on question type
        if question_type == "calculation":
            answer = self.handle_calculation(question_text)
        elif question_type == "temporal":
            answer = self.handle_temporal(question_text)
        elif question_type == "factual":
            answer = self.handle_factual(question_text, file_content)
        else:
            answer = self.handle_general(question_text, file_content)
        
        return answer
    
    def analyze_question_type(self, question: str) -> str:
        """Determine the type of question based on keywords and patterns."""
        question_lower = question.lower()
        
        # Check for mathematical operations
        if any(op in question_lower for op in ["calculate", "compute", "sum", "total", "percentage", "percent"]):
            return "calculation"
        
        # Check for temporal questions
        if any(word in question_lower for word in ["when", "date", "time", "year", "month", "day"]):
            return "temporal"
        
        # Check for factual questions
        if any(word in question_lower for word in ["what", "which", "who", "where"]):
            return "factual"
        
        return "general"
    
    def handle_calculation(self, question: str) -> str:
        """Handle mathematical calculation questions."""
        # Extract numbers and operations
        for pattern in self.calculation_patterns:
            match = re.search(pattern, question)
            if match:
                num1 = float(match.group(1))
                num2 = float(match.group(2))
                
                if '+' in pattern:
                    result = num1 + num2
                    operation = "addition"
                elif '-' in pattern:
                    result = num1 - num2
                    operation = "subtraction"
                elif '*' in pattern:
                    result = num1 * num2
                    operation = "multiplication"
                elif '/' in pattern:
                    if num2 == 0:
                        return "Error: Division by zero"
                    result = num1 / num2
                    operation = "division"
                elif '%' in pattern:
                    result = num1 % num2
                    operation = "modulo"
                
                return f"The result of {operation} {num1} and {num2} is {result}"
        
        # Handle percentage calculations
        percentage_match = re.search(r'(\d+)%\s*of\s*(\d+)', question)
        if percentage_match:
            percentage = float(percentage_match.group(1))
            value = float(percentage_match.group(2))
            result = (percentage / 100) * value
            return f"{percentage}% of {value} is {result}"
        
        return "I cannot perform the requested calculation with the given information."
    
    def handle_temporal(self, question: str) -> str:
        """Handle temporal questions."""
        # Extract dates
        date_patterns = [
            r'(\d{4})-(\d{2})-(\d{2})',
            r'(\d{1,2})/(\d{1,2})/(\d{4})',
            r'(\w+)\s+(\d{1,2}),?\s+(\d{4})'
        ]
        
        for pattern in date_patterns:
            match = re.search(pattern, question)
            if match:
                if pattern == r'(\d{4})-(\d{2})-(\d{2})':
                    year, month, day = match.groups()
                    return f"The date is {year}-{month}-{day}"
                elif pattern == r'(\d{1,2})/(\d{1,2})/(\d{4})':
                    month, day, year = match.groups()
                    return f"The date is {month}/{day}/{year}"
                elif pattern == r'(\w+)\s+(\d{1,2}),?\s+(\d{4})':
                    month, day, year = match.groups()
                    return f"The date is {month} {day}, {year}"
        
        return "I cannot determine the specific date or time from the question."
    
    def handle_factual(self, question: str, file_content: str) -> str:
        """Handle factual questions."""
        # If there's file content, try to extract relevant information
        if file_content:
            # Simple keyword matching
            question_keywords = self.extract_keywords(question)
            file_lines = file_content.split('\n')
            
            for line in file_lines:
                if any(keyword.lower() in line.lower() for keyword in question_keywords):
                    return f"Based on the file content: {line.strip()}"
        
        # For general factual questions, provide a structured response
        return self.generate_structured_answer(question)
    
    def handle_general(self, question: str, file_content: str) -> str:
        """Handle general questions."""
        # Combine file content analysis with general reasoning
        if file_content:
            return f"Based on the provided information: {file_content[:200]}..."
        
        return self.generate_structured_answer(question)
    
    def extract_keywords(self, text: str) -> List[str]:
        """Extract important keywords from text."""
        # Remove common words
        stop_words = {"the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with", "by", "is", "are", "was", "were"}
        words = re.findall(r'\b\w+\b', text.lower())
        keywords = [word for word in words if word not in stop_words and len(word) > 2]
        return keywords
    
    def generate_structured_answer(self, question: str) -> str:
        """Generate a structured answer for general questions."""
        # This is a placeholder - you would implement your own reasoning here
        # You could integrate with external APIs like OpenAI, Anthropic, etc.
        
        # Example structure:
        answer_parts = [
            "Based on my analysis of the question:",
            f"- Question type: {self.analyze_question_type(question)}",
            "- Key information needed: [identify what's needed]",
            "- Reasoning approach: [describe your method]",
            "- Answer: [provide your answer]"
        ]
        
        return "\n".join(answer_parts)
    
    def enhance_with_external_api(self, question: str) -> str:
        """
        Example of how to integrate with external APIs.
        Uncomment and customize this method if you want to use external services.
        """
        # Example with OpenAI (you would need to add your API key)
        """
        import openai
        
        try:
            response = openai.ChatCompletion.create(
                model="gpt-4",
                messages=[
                    {"role": "system", "content": "You are a helpful assistant that answers questions accurately and concisely."},
                    {"role": "user", "content": question}
                ],
                temperature=0.1
            )
            return response.choices[0].message.content
        except Exception as e:
            return f"Error calling external API: {e}"
        """
        
        # Placeholder return
        return "External API integration not configured. Please implement your own API calls."

# Example usage and testing
if __name__ == "__main__":
    # Create an instance of the example agent
    agent = ExampleGAIAAgent()
    
    # Test questions
    test_questions = [
        {
            "task_id": "test_001",
            "question": "What is 15 + 27?"
        },
        {
            "task_id": "test_002", 
            "question": "What is 25% of 80?"
        },
        {
            "task_id": "test_003",
            "question": "What is the date 2024-03-15?"
        },
        {
            "task_id": "test_004",
            "question": "What is the capital of France?"
        }
    ]
    
    # Test the agent
    print("Testing Example GAIA Agent:")
    print("=" * 50)
    
    for i, question in enumerate(test_questions, 1):
        print(f"\nTest {i}:")
        print(f"Question: {question['question']}")
        answer = agent.generate_answer(question)
        print(f"Answer: {answer}")
        print("-" * 30)