File size: 6,072 Bytes
9a6a4dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Integration example showing how to use the QuestionClassifier with the BasicAgent.

This demonstrates how the extracted classification logic can be integrated back
into the main agent architecture for clean separation of concerns.
"""

from question_classifier import QuestionClassifier


class EnhancedBasicAgentWithClassifier:
    """
    Example of how to integrate the QuestionClassifier with the BasicAgent.
    
    This shows the clean separation achieved by extracting classification logic
    into its own utility module.
    """
    
    def __init__(self):
        """Initialize the agent with the external classifier."""
        print("EnhancedBasicAgentWithClassifier initialized.")
        
        # Initialize the question classifier
        self.classifier = QuestionClassifier()
        
        # System prompt (same as original)
        self.system_prompt = """You are a helpful AI assistant that provides accurate, concise answers.
        I will ask you a question. Report your thoughts, and finish your answer with just the final answer.

        Your final answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
        If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
        Provide only the answer without any prefix like "FINAL ANSWER:" - just return the specific answer requested.
        If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
        If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""
    
    def __call__(self, question: str) -> str:
        """Process a question using the external classifier."""
        print(f"Agent received question: {question[:100]}...")
        
        try:
            # Use the external classifier
            classification = self.classifier.classify_question(question)
            
            # Get detailed analysis for debugging/logging
            analysis = self.classifier.get_detailed_analysis(question)
            print(f"Classification: {classification} (confidence: {analysis['confidence']})")
            
            # Route based on classification
            answer = self._route_question(question, classification)
            print(f"Agent returning answer: {answer}")
            return answer
            
        except Exception as e:
            print(f"Error processing question: {e}")
            return "unknown"
    
    def _route_question(self, question: str, classification: str) -> str:
        """Route question to appropriate handler based on classification."""
        
        if classification == 'calculation':
            return self._handle_calculation(question)
        elif classification == 'url':
            return self._handle_url_access(question)
        elif classification == 'general_web_search':
            return self._handle_web_search(question)
        else:
            return self._handle_unknown(question)
    
    def _handle_calculation(self, question: str) -> str:
        """Handle calculation questions."""
        # This would contain the math/conversion logic from the original BasicAgent
        print("Routing to calculation handler")
        return "calculation_result"  # Placeholder
    
    def _handle_url_access(self, question: str) -> str:
        """Handle questions requiring specific URL/webpage access."""
        # This would contain logic to access specific URLs or databases
        print("Routing to URL access handler")
        return "url_content_result"  # Placeholder
    
    def _handle_web_search(self, question: str) -> str:
        """Handle questions requiring general web search."""
        # This would contain the web search logic
        print("Routing to web search handler")
        return "web_search_result"  # Placeholder
    
    def _handle_unknown(self, question: str) -> str:
        """Handle unknown/unclassified questions."""
        print("Routing to unknown handler")
        return "unknown"


def demonstrate_classification():
    """Demonstrate the classification system."""
    
    print("Question Classification Demonstration")
    print("=" * 50)
    
    # Initialize classifier
    classifier = QuestionClassifier()
    
    # Test questions
    test_questions = [
        "What is 25 + 37?",
        "Convert 100 fahrenheit to celsius", 
        "What albums did Mercedes Sosa release between 2000 and 2009?",
        "How many continents are there?",
        "Who is the president of France?",
        "What is the capital of Japan?"
    ]
    
    for question in test_questions:
        classification, confidence, scores = classifier.classify_with_confidence(question)
        
        print(f"\nQ: {question}")
        print(f"Classification: {classification}")
        print(f"Confidence: {confidence}")
        print(f"Scores: {scores}")
        
        # Show routing decision
        if classification == 'calculation':
            print("→ Route to: Math/Conversion Handler")
        elif classification == 'url':
            print("→ Route to: Specific URL/Database Access")
        else:
            print("→ Route to: General Web Search")


def demonstrate_integration():
    """Demonstrate integration with agent."""
    
    print("\n\nAgent Integration Demonstration")
    print("=" * 50)
    
    # Initialize enhanced agent
    agent = EnhancedBasicAgentWithClassifier()
    
    # Test questions
    test_questions = [
        "Calculate 15 + 25",
        "Mercedes Sosa albums 2000-2009",
        "How many planets in solar system?"
    ]
    
    for question in test_questions:
        print(f"\nTesting: {question}")
        result = agent(question)
        print(f"Result: {result}")


if __name__ == "__main__":
    # Run demonstrations
    demonstrate_classification()
    demonstrate_integration()