rivapereira123 commited on
Commit
46d90f9
·
verified ·
1 Parent(s): 2e1d07a

Create technique_selection_agent.py

Browse files
Files changed (1) hide show
  1. core/technique_selection_agent.py +205 -0
core/technique_selection_agent.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Prompting Technique Selection Agent
3
+ Selects the most appropriate prompting technique based on task analysis.
4
+ """
5
+
6
+ from typing import Dict, List, Any, Tuple
7
+ import json
8
+
9
+ class TechniqueSelectionAgent:
10
+ def __init__(self):
11
+ # Define prompting techniques and their use cases
12
+ self.techniques = {
13
+ "zero_shot": {
14
+ "name": "Zero-shot Prompting",
15
+ "description": "Direct instruction without examples",
16
+ "use_cases": ["simple_tasks", "well_defined_instructions", "classification"],
17
+ "complexity": ["simple", "moderate"],
18
+ "task_types": ["text_generation", "classification", "simple_qa"]
19
+ },
20
+ "few_shot": {
21
+ "name": "Few-shot Prompting",
22
+ "description": "Provides examples to guide the model",
23
+ "use_cases": ["pattern_learning", "format_specification", "style_mimicking"],
24
+ "complexity": ["moderate", "complex"],
25
+ "task_types": ["text_generation", "classification", "creative_writing"]
26
+ },
27
+ "chain_of_thought": {
28
+ "name": "Chain-of-Thought (CoT) Prompting",
29
+ "description": "Breaks down reasoning into steps",
30
+ "use_cases": ["reasoning", "math_problems", "logical_analysis"],
31
+ "complexity": ["moderate", "complex"],
32
+ "task_types": ["reasoning", "question_answering", "problem_solving"]
33
+ },
34
+ "react": {
35
+ "name": "ReAct Prompting",
36
+ "description": "Combines reasoning and acting with external tools",
37
+ "use_cases": ["tool_use", "information_retrieval", "multi_step_tasks"],
38
+ "complexity": ["complex"],
39
+ "task_types": ["question_answering", "research", "data_analysis"]
40
+ },
41
+ "tree_of_thoughts": {
42
+ "name": "Tree of Thoughts (ToT)",
43
+ "description": "Explores multiple reasoning paths",
44
+ "use_cases": ["complex_problem_solving", "strategic_planning", "exploration"],
45
+ "complexity": ["complex"],
46
+ "task_types": ["reasoning", "planning", "creative_problem_solving"]
47
+ },
48
+ "self_consistency": {
49
+ "name": "Self-Consistency",
50
+ "description": "Generates multiple solutions and selects the most consistent",
51
+ "use_cases": ["accuracy_improvement", "uncertainty_reduction"],
52
+ "complexity": ["moderate", "complex"],
53
+ "task_types": ["reasoning", "calculation", "analysis"]
54
+ },
55
+ "generated_knowledge": {
56
+ "name": "Generated Knowledge Prompting",
57
+ "description": "Generates relevant knowledge before answering",
58
+ "use_cases": ["knowledge_intensive_tasks", "fact_checking"],
59
+ "complexity": ["moderate", "complex"],
60
+ "task_types": ["question_answering", "research", "analysis"]
61
+ },
62
+ "prompt_chaining": {
63
+ "name": "Prompt Chaining",
64
+ "description": "Breaks complex tasks into subtasks",
65
+ "use_cases": ["complex_workflows", "multi_step_processes"],
66
+ "complexity": ["complex"],
67
+ "task_types": ["document_analysis", "multi_step_reasoning", "workflow_automation"]
68
+ },
69
+ "meta_prompting": {
70
+ "name": "Meta Prompting",
71
+ "description": "Focuses on structural and syntactical aspects",
72
+ "use_cases": ["abstract_reasoning", "pattern_recognition"],
73
+ "complexity": ["moderate", "complex"],
74
+ "task_types": ["reasoning", "code_generation", "mathematical_problems"]
75
+ },
76
+ "pal": {
77
+ "name": "Program-Aided Language Models (PAL)",
78
+ "description": "Generates code to solve problems",
79
+ "use_cases": ["calculations", "data_processing", "algorithmic_tasks"],
80
+ "complexity": ["moderate", "complex"],
81
+ "task_types": ["code_generation", "calculation", "data_analysis"]
82
+ }
83
+ }
84
+
85
+ def select_technique(self, analysis_result: Dict[str, Any]) -> Tuple[str, Dict[str, Any]]:
86
+ """
87
+ Select the most appropriate prompting technique based on analysis.
88
+
89
+ Args:
90
+ analysis_result: Output from InputAnalysisAgent
91
+
92
+ Returns:
93
+ Tuple of (technique_key, technique_info_with_reasoning)
94
+ """
95
+ task_type = analysis_result.get('task_type', 'text_generation')
96
+ complexity = analysis_result.get('complexity', 'simple')
97
+ domain = analysis_result.get('domain', 'general')
98
+ entities = analysis_result.get('entities', [])
99
+ intent = analysis_result.get('intent', '')
100
+
101
+ # Score each technique based on compatibility
102
+ technique_scores = {}
103
+
104
+ for tech_key, tech_info in self.techniques.items():
105
+ score = 0
106
+
107
+ # Task type compatibility
108
+ if task_type in tech_info['task_types']:
109
+ score += 3
110
+ elif any(tt in task_type for tt in tech_info['task_types']):
111
+ score += 1
112
+
113
+ # Complexity compatibility
114
+ if complexity in tech_info['complexity']:
115
+ score += 2
116
+
117
+ # Special case scoring based on content analysis
118
+ score += self._get_content_based_score(tech_key, analysis_result)
119
+
120
+ technique_scores[tech_key] = score
121
+
122
+ # Select the technique with the highest score
123
+ best_technique = max(technique_scores, key=technique_scores.get)
124
+
125
+ # Prepare the result with reasoning
126
+ selected_technique = self.techniques[best_technique].copy()
127
+ selected_technique['reasoning'] = self._generate_reasoning(
128
+ best_technique, analysis_result, technique_scores
129
+ )
130
+ selected_technique['confidence'] = min(technique_scores[best_technique] / 5.0, 1.0)
131
+
132
+ return best_technique, selected_technique
133
+
134
+ def _get_content_based_score(self, technique_key: str, analysis_result: Dict[str, Any]) -> int:
135
+ """Calculate additional score based on content analysis."""
136
+ score = 0
137
+ prompt = analysis_result.get('original_prompt', '').lower()
138
+
139
+ # Keyword-based scoring
140
+ if technique_key == "chain_of_thought":
141
+ if any(word in prompt for word in ['step', 'reason', 'explain', 'how', 'why', 'solve']):
142
+ score += 2
143
+
144
+ elif technique_key == "few_shot":
145
+ if any(word in prompt for word in ['example', 'like', 'similar', 'format']):
146
+ score += 2
147
+
148
+ elif technique_key == "react":
149
+ if any(word in prompt for word in ['search', 'find', 'lookup', 'research', 'tool']):
150
+ score += 2
151
+
152
+ elif technique_key == "pal":
153
+ if any(word in prompt for word in ['calculate', 'compute', 'math', 'algorithm', 'code']):
154
+ score += 2
155
+
156
+ elif technique_key == "tree_of_thoughts":
157
+ if any(word in prompt for word in ['explore', 'consider', 'alternative', 'multiple']):
158
+ score += 2
159
+
160
+ elif technique_key == "generated_knowledge":
161
+ if any(word in prompt for word in ['fact', 'knowledge', 'information', 'research']):
162
+ score += 2
163
+
164
+ return score
165
+
166
+ def _generate_reasoning(self, technique_key: str, analysis_result: Dict[str, Any],
167
+ scores: Dict[str, int]) -> str:
168
+ """Generate human-readable reasoning for the technique selection."""
169
+
170
+ task_type = analysis_result.get('task_type', 'unknown')
171
+ complexity = analysis_result.get('complexity', 'unknown')
172
+
173
+ reasoning_parts = []
174
+
175
+ # Main selection reason
176
+ technique_name = self.techniques[technique_key]['name']
177
+ reasoning_parts.append(f"Selected {technique_name} because:")
178
+
179
+ # Task type reasoning
180
+ if task_type in self.techniques[technique_key]['task_types']:
181
+ reasoning_parts.append(f"- It's well-suited for {task_type} tasks")
182
+
183
+ # Complexity reasoning
184
+ if complexity in self.techniques[technique_key]['complexity']:
185
+ reasoning_parts.append(f"- It handles {complexity} complexity effectively")
186
+
187
+ # Content-based reasoning
188
+ content_score = self._get_content_based_score(technique_key, analysis_result)
189
+ if content_score > 0:
190
+ reasoning_parts.append("- The prompt content suggests this approach would be beneficial")
191
+
192
+ # Confidence reasoning
193
+ max_score = max(scores.values())
194
+ if scores[technique_key] == max_score:
195
+ reasoning_parts.append(f"- It scored highest ({max_score}) among all techniques")
196
+
197
+ return " ".join(reasoning_parts)
198
+
199
+ def get_technique_info(self, technique_key: str) -> Dict[str, Any]:
200
+ """Get detailed information about a specific technique."""
201
+ return self.techniques.get(technique_key, {})
202
+
203
+ def list_all_techniques(self) -> Dict[str, Dict[str, Any]]:
204
+ """Return all available techniques."""
205
+ return self.techniques