Kackle commited on
Commit
0d14730
·
verified ·
1 Parent(s): 753b17e

extra knowledge added

Browse files
Files changed (1) hide show
  1. app.py +70 -24
app.py CHANGED
@@ -22,6 +22,32 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
22
  OPENAI_TOKEN = os.getenv("OPENAI_API_KEY")
23
 
24
  # --- Custom Tools ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  class ReliableSearchTool(Tool):
26
  name = "reliable_search"
27
  description = "Search the web for information with built-in retry and fallback mechanisms"
@@ -86,36 +112,48 @@ class SlpMultiAgent:
86
  max_tokens=1000 # Keep higher tokens for complex reasoning
87
  )
88
 
89
- # Here you can implement your agent logic, tools, and model calls
90
- web_agent = CodeAgent(
91
- tools=[ReliableSearchTool(), VisitWebpageTool()], # Use custom reliable search tool
 
 
 
 
 
 
 
 
 
 
92
  model=model,
93
- additional_authorized_imports=["pandas", "time", "json", "requests", "urllib"],
94
- max_steps=5, # Keep sufficient steps for complex tasks
95
- name="WebAgent",
96
  verbosity_level=0,
97
- description="An agent that can search the web and visit webpages to find information."
98
  )
99
 
100
  manager_agent = CodeAgent(
101
  model=OpenAIServerModel(
102
  model_id="gpt-3.5-turbo-16k",
103
- temperature=0.1,
104
- max_tokens=1000
105
  ),
106
- tools=[],
107
- managed_agents=[web_agent],
108
  name="ManagerAgent",
109
- description="A manager agent that can delegate tasks to other agents and manage their execution.",
110
  additional_authorized_imports=[
111
  "pandas",
112
  "time",
113
  "json",
114
- "requests"
 
 
115
  ],
116
- planning_interval=3,
117
  verbosity_level=1,
118
- max_steps=10, # Keep full steps for complex reasoning
119
  final_answer_checks=[check_reasoning]
120
  )
121
 
@@ -131,15 +169,19 @@ class SlpMultiAgent:
131
  lambda: manager_agent.run(f"""
132
  Question: {short_question}
133
 
134
- IMPORTANT: You must end with a final_answer() call containing ONLY the direct answer.
 
 
 
 
 
 
 
 
135
 
136
- Steps:
137
- 1. Think through the problem
138
- 2. Use search if needed with: <code>search_result = reliable_search("query")</code>
139
- 3. End with: <code>final_answer("direct answer only")</code>
140
 
141
- Do NOT include thoughts, explanations, or reasoning in the final_answer().
142
- The final_answer() should contain only the specific answer requested.
143
  """)
144
  )
145
  break # Success, exit retry loop
@@ -183,13 +225,17 @@ class SlpMultiAgent:
183
  def check_reasoning(final_answer, agent_memory):
184
  try:
185
  # Simple validation - check if answer looks complete
186
- if not final_answer or len(final_answer.strip()) < 2:
187
  return False
188
 
189
  # Check if it's just thoughts/reasoning instead of an answer
190
- bad_patterns = ['### Thought:', '### Code:', 'I will', 'Let me', 'First, I', 'Next, I']
191
  if any(pattern in final_answer for pattern in bad_patterns):
192
  return False
 
 
 
 
193
 
194
  return True # Pass if it looks like a real answer
195
  except Exception as e:
 
22
  OPENAI_TOKEN = os.getenv("OPENAI_API_KEY")
23
 
24
  # --- Custom Tools ---
25
+ class KnowledgeBaseTool(Tool):
26
+ name = "knowledge_base"
27
+ description = "Access structured knowledge for common topics"
28
+ inputs = {"topic": {"type": "string", "description": "The topic to look up"}}
29
+ output_type = "string"
30
+
31
+ def __init__(self):
32
+ super().__init__()
33
+ self.is_initialized = True
34
+ # Common knowledge base
35
+ self.knowledge = {
36
+ "olympics": "Olympic Games data: Countries, athletes, years, sports",
37
+ "countries": "Country codes: ISO, IOC, FIFA codes and country information",
38
+ "sports": "Sports history, rules, famous athletes and events",
39
+ "science": "Scientific facts, formulas, discoveries, and researchers",
40
+ "history": "Historical events, dates, people, and places",
41
+ "geography": "Countries, capitals, populations, and geographical features"
42
+ }
43
+
44
+ def forward(self, topic: str) -> str:
45
+ topic_lower = topic.lower()
46
+ for key, info in self.knowledge.items():
47
+ if key in topic_lower:
48
+ return f"Knowledge base: {info}. Use this context to answer questions about {topic}."
49
+ return f"No specific knowledge base entry for '{topic}'. Use general reasoning."
50
+
51
  class ReliableSearchTool(Tool):
52
  name = "reliable_search"
53
  description = "Search the web for information with built-in retry and fallback mechanisms"
 
112
  max_tokens=1000 # Keep higher tokens for complex reasoning
113
  )
114
 
115
+ # Create specialized agents
116
+ research_agent = CodeAgent(
117
+ tools=[ReliableSearchTool(), KnowledgeBaseTool()],
118
+ model=model,
119
+ additional_authorized_imports=["pandas", "time", "json", "requests", "urllib", "re", "datetime"],
120
+ max_steps=4,
121
+ name="ResearchAgent",
122
+ verbosity_level=0,
123
+ description="Specialized agent for research and fact-finding with knowledge base access."
124
+ )
125
+
126
+ analysis_agent = CodeAgent(
127
+ tools=[],
128
  model=model,
129
+ additional_authorized_imports=["pandas", "time", "json", "requests", "math", "statistics"],
130
+ max_steps=3,
131
+ name="AnalysisAgent",
132
  verbosity_level=0,
133
+ description="Specialized agent for data analysis, calculations, and logical reasoning."
134
  )
135
 
136
  manager_agent = CodeAgent(
137
  model=OpenAIServerModel(
138
  model_id="gpt-3.5-turbo-16k",
139
+ temperature=0.2, # Slightly higher for better reasoning variety
140
+ max_tokens=1200
141
  ),
142
+ tools=[KnowledgeBaseTool()],
143
+ managed_agents=[research_agent, analysis_agent],
144
  name="ManagerAgent",
145
+ description="A manager agent that coordinates research and analysis agents to solve complex questions.",
146
  additional_authorized_imports=[
147
  "pandas",
148
  "time",
149
  "json",
150
+ "requests",
151
+ "re",
152
+ "math"
153
  ],
154
+ planning_interval=2,
155
  verbosity_level=1,
156
+ max_steps=8,
157
  final_answer_checks=[check_reasoning]
158
  )
159
 
 
169
  lambda: manager_agent.run(f"""
170
  Question: {short_question}
171
 
172
+ You have access to ResearchAgent and AnalysisAgent. Use them strategically:
173
+ - ResearchAgent: For finding facts, searching, and knowledge lookup
174
+ - AnalysisAgent: For calculations, data processing, and logical reasoning
175
+
176
+ Process:
177
+ 1. Analyze what type of question this is
178
+ 2. Use knowledge_base() to check for relevant context
179
+ 3. Delegate to appropriate agents if needed
180
+ 4. Synthesize information and provide final answer
181
 
182
+ CRITICAL: End with <code>final_answer("exact answer only")</code>
 
 
 
183
 
184
+ The final_answer must contain ONLY the specific answer requested - no explanations.
 
185
  """)
186
  )
187
  break # Success, exit retry loop
 
225
  def check_reasoning(final_answer, agent_memory):
226
  try:
227
  # Simple validation - check if answer looks complete
228
+ if not final_answer or len(final_answer.strip()) < 1:
229
  return False
230
 
231
  # Check if it's just thoughts/reasoning instead of an answer
232
+ bad_patterns = ['### Thought:', '### Code:', 'I will', 'Let me', 'First, I', 'Next, I', 'Step 1:', 'Based on']
233
  if any(pattern in final_answer for pattern in bad_patterns):
234
  return False
235
+
236
+ # Check if answer is too long (likely contains reasoning)
237
+ if len(final_answer) > 300:
238
+ return False
239
 
240
  return True # Pass if it looks like a real answer
241
  except Exception as e: