Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,6 +7,7 @@ import asyncio
|
|
| 7 |
import aiohttp
|
| 8 |
import time
|
| 9 |
import random
|
|
|
|
| 10 |
from smolagents import FinalAnswerTool, Tool, tool, OpenAIServerModel, DuckDuckGoSearchTool, CodeAgent, VisitWebpageTool
|
| 11 |
|
| 12 |
|
|
@@ -20,6 +21,35 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 20 |
|
| 21 |
OPENAI_TOKEN = os.getenv("OPENAI_API_KEY")
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
# --- Basic Agent Definition ---
|
| 24 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 25 |
class SlpMultiAgent:
|
|
@@ -35,20 +65,19 @@ class SlpMultiAgent:
|
|
| 35 |
MAX_QUESTION_LENGTH = 1000
|
| 36 |
short_question = question # [:MAX_QUESTION_LENGTH]
|
| 37 |
|
| 38 |
-
# Use GPT-3.5-turbo model with
|
| 39 |
model = OpenAIServerModel(
|
| 40 |
-
model_id="gpt-3.5-turbo
|
| 41 |
-
temperature=0.
|
| 42 |
-
max_tokens=
|
| 43 |
-
# Removed request_timeout parameter
|
| 44 |
)
|
| 45 |
|
| 46 |
# Here you can implement your agent logic, tools, and model calls
|
| 47 |
web_agent = CodeAgent(
|
| 48 |
-
tools=[
|
| 49 |
model=model,
|
| 50 |
-
additional_authorized_imports=["pandas", "time"],
|
| 51 |
-
max_steps=
|
| 52 |
name="WebAgent",
|
| 53 |
verbosity_level=0,
|
| 54 |
description="An agent that can search the web and visit webpages to find information."
|
|
@@ -56,10 +85,9 @@ class SlpMultiAgent:
|
|
| 56 |
|
| 57 |
manager_agent = CodeAgent(
|
| 58 |
model=OpenAIServerModel(
|
| 59 |
-
model_id="gpt-3.5-turbo
|
| 60 |
-
temperature=0.
|
| 61 |
-
max_tokens=
|
| 62 |
-
# Removed request_timeout parameter
|
| 63 |
),
|
| 64 |
tools=[],
|
| 65 |
managed_agents=[web_agent],
|
|
@@ -67,11 +95,13 @@ class SlpMultiAgent:
|
|
| 67 |
description="A manager agent that can delegate tasks to other agents and manage their execution.",
|
| 68 |
additional_authorized_imports=[
|
| 69 |
"pandas",
|
| 70 |
-
"time"
|
|
|
|
|
|
|
| 71 |
],
|
| 72 |
planning_interval=3,
|
| 73 |
verbosity_level=1,
|
| 74 |
-
max_steps=
|
| 75 |
final_answer_checks=[check_reasoning]
|
| 76 |
)
|
| 77 |
|
|
@@ -85,18 +115,15 @@ class SlpMultiAgent:
|
|
| 85 |
result = await loop.run_in_executor(
|
| 86 |
None,
|
| 87 |
lambda: manager_agent.run(f"""
|
| 88 |
-
|
| 89 |
|
| 90 |
-
|
| 91 |
-
1. Think step by step before answering
|
| 92 |
-
2. Use tools only when necessary
|
| 93 |
-
3. Use your own knowledge when possible
|
| 94 |
-
4. Be clear about uncertainties
|
| 95 |
-
5. Provide complete answers
|
| 96 |
-
6. When using code, keep it minimal and focused
|
| 97 |
-
7. For code blocks, use <code> and </code> tags, NOT triple backticks
|
| 98 |
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
""")
|
| 101 |
)
|
| 102 |
break # Success, exit retry loop
|
|
@@ -125,12 +152,11 @@ def check_reasoning(final_answer, agent_memory):
|
|
| 125 |
try:
|
| 126 |
multimodal_model = OpenAIServerModel(
|
| 127 |
model_id="gpt-3.5-turbo",
|
| 128 |
-
max_tokens=
|
| 129 |
-
# Removed request_timeout parameter
|
| 130 |
)
|
| 131 |
|
| 132 |
-
#
|
| 133 |
-
prompt = f"
|
| 134 |
|
| 135 |
messages = [
|
| 136 |
{
|
|
@@ -140,17 +166,24 @@ def check_reasoning(final_answer, agent_memory):
|
|
| 140 |
]
|
| 141 |
|
| 142 |
# Add retry mechanism for rate limits
|
| 143 |
-
max_retries =
|
| 144 |
for attempt in range(max_retries):
|
| 145 |
try:
|
| 146 |
output = multimodal_model(messages)
|
| 147 |
if hasattr(output, 'content'):
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
break
|
| 150 |
except Exception as e:
|
| 151 |
if attempt < max_retries - 1:
|
| 152 |
print(f"Retry {attempt+1}/{max_retries} due to: {e}")
|
| 153 |
-
time.sleep(
|
| 154 |
else:
|
| 155 |
print(f"Final attempt failed: {e}")
|
| 156 |
|
|
@@ -221,8 +254,8 @@ async def run_and_submit_all(profile):
|
|
| 221 |
answers_payload = []
|
| 222 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 223 |
|
| 224 |
-
# Process questions with
|
| 225 |
-
semaphore = asyncio.Semaphore(
|
| 226 |
|
| 227 |
async def process_question(item):
|
| 228 |
task_id = item.get("task_id")
|
|
@@ -242,12 +275,12 @@ async def run_and_submit_all(profile):
|
|
| 242 |
except Exception as e:
|
| 243 |
print(f"Error running agent on task {task_id}, attempt {attempt+1}: {e}")
|
| 244 |
if "rate limit" in str(e).lower() and attempt < max_retries - 1:
|
| 245 |
-
#
|
| 246 |
-
wait_time = (
|
| 247 |
print(f"Rate limit hit. Waiting {wait_time:.2f} seconds before retry...")
|
| 248 |
await asyncio.sleep(wait_time)
|
| 249 |
elif attempt < max_retries - 1:
|
| 250 |
-
await asyncio.sleep(
|
| 251 |
else:
|
| 252 |
# All retries failed, return default answer
|
| 253 |
default_answer = "This is a default answer."
|
|
|
|
| 7 |
import aiohttp
|
| 8 |
import time
|
| 9 |
import random
|
| 10 |
+
import json
|
| 11 |
from smolagents import FinalAnswerTool, Tool, tool, OpenAIServerModel, DuckDuckGoSearchTool, CodeAgent, VisitWebpageTool
|
| 12 |
|
| 13 |
|
|
|
|
| 21 |
|
| 22 |
OPENAI_TOKEN = os.getenv("OPENAI_API_KEY")
|
| 23 |
|
| 24 |
+
# --- Custom Tools ---
|
| 25 |
+
class ReliableSearchTool(Tool):
|
| 26 |
+
"""A search tool that handles timeouts and rate limits gracefully."""
|
| 27 |
+
|
| 28 |
+
def __init__(self):
|
| 29 |
+
super().__init__(
|
| 30 |
+
name="reliable_search",
|
| 31 |
+
description="Search the web for information with built-in retry and fallback mechanisms",
|
| 32 |
+
fn=self.search
|
| 33 |
+
)
|
| 34 |
+
self.ddg_tool = DuckDuckGoSearchTool()
|
| 35 |
+
self.max_retries = 3
|
| 36 |
+
self.timeout = 10
|
| 37 |
+
|
| 38 |
+
def search(self, query: str) -> str:
|
| 39 |
+
"""Search the web with retry logic and fallbacks."""
|
| 40 |
+
for attempt in range(self.max_retries):
|
| 41 |
+
try:
|
| 42 |
+
# Try DuckDuckGo first
|
| 43 |
+
result = self.ddg_tool(query)
|
| 44 |
+
if result and len(result) > 50: # Ensure we got a meaningful result
|
| 45 |
+
return result
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"DuckDuckGo search failed (attempt {attempt+1}/{self.max_retries}): {e}")
|
| 48 |
+
time.sleep(2) # Brief pause before retry
|
| 49 |
+
|
| 50 |
+
# If all DuckDuckGo attempts failed, return a fallback response
|
| 51 |
+
return f"I couldn't search for '{query}' due to search service limitations. Using my existing knowledge instead."
|
| 52 |
+
|
| 53 |
# --- Basic Agent Definition ---
|
| 54 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 55 |
class SlpMultiAgent:
|
|
|
|
| 65 |
MAX_QUESTION_LENGTH = 1000
|
| 66 |
short_question = question # [:MAX_QUESTION_LENGTH]
|
| 67 |
|
| 68 |
+
# Use GPT-3.5-turbo model with optimized settings
|
| 69 |
model = OpenAIServerModel(
|
| 70 |
+
model_id="gpt-3.5-turbo",
|
| 71 |
+
temperature=0.1, # Slight randomness for better reasoning
|
| 72 |
+
max_tokens=800 # Reduced tokens for cost efficiency
|
|
|
|
| 73 |
)
|
| 74 |
|
| 75 |
# Here you can implement your agent logic, tools, and model calls
|
| 76 |
web_agent = CodeAgent(
|
| 77 |
+
tools=[ReliableSearchTool(), VisitWebpageTool()], # Use our custom reliable search tool
|
| 78 |
model=model,
|
| 79 |
+
additional_authorized_imports=["pandas", "time", "json", "requests"],
|
| 80 |
+
max_steps=3, # Further reduced steps for efficiency
|
| 81 |
name="WebAgent",
|
| 82 |
verbosity_level=0,
|
| 83 |
description="An agent that can search the web and visit webpages to find information."
|
|
|
|
| 85 |
|
| 86 |
manager_agent = CodeAgent(
|
| 87 |
model=OpenAIServerModel(
|
| 88 |
+
model_id="gpt-3.5-turbo",
|
| 89 |
+
temperature=0.1,
|
| 90 |
+
max_tokens=800
|
|
|
|
| 91 |
),
|
| 92 |
tools=[],
|
| 93 |
managed_agents=[web_agent],
|
|
|
|
| 95 |
description="A manager agent that can delegate tasks to other agents and manage their execution.",
|
| 96 |
additional_authorized_imports=[
|
| 97 |
"pandas",
|
| 98 |
+
"time",
|
| 99 |
+
"json",
|
| 100 |
+
"requests"
|
| 101 |
],
|
| 102 |
planning_interval=3,
|
| 103 |
verbosity_level=1,
|
| 104 |
+
max_steps=6, # Reduced steps for efficiency
|
| 105 |
final_answer_checks=[check_reasoning]
|
| 106 |
)
|
| 107 |
|
|
|
|
| 115 |
result = await loop.run_in_executor(
|
| 116 |
None,
|
| 117 |
lambda: manager_agent.run(f"""
|
| 118 |
+
Answer this question accurately and concisely:
|
| 119 |
|
| 120 |
+
{short_question}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
+
Instructions:
|
| 123 |
+
- Think step by step
|
| 124 |
+
- Use search only if you need current/specific information
|
| 125 |
+
- Be precise and factual
|
| 126 |
+
- If uncertain, state your confidence level
|
| 127 |
""")
|
| 128 |
)
|
| 129 |
break # Success, exit retry loop
|
|
|
|
| 152 |
try:
|
| 153 |
multimodal_model = OpenAIServerModel(
|
| 154 |
model_id="gpt-3.5-turbo",
|
| 155 |
+
max_tokens=100 # Reduced tokens for cost efficiency
|
|
|
|
| 156 |
)
|
| 157 |
|
| 158 |
+
# More focused validation prompt
|
| 159 |
+
prompt = f"Rate answer quality 1-10: {final_answer[:200]}..."
|
| 160 |
|
| 161 |
messages = [
|
| 162 |
{
|
|
|
|
| 166 |
]
|
| 167 |
|
| 168 |
# Add retry mechanism for rate limits
|
| 169 |
+
max_retries = 2 # Reduced retries
|
| 170 |
for attempt in range(max_retries):
|
| 171 |
try:
|
| 172 |
output = multimodal_model(messages)
|
| 173 |
if hasattr(output, 'content'):
|
| 174 |
+
# Actually check the response instead of always returning True
|
| 175 |
+
response = output.content.lower()
|
| 176 |
+
# Look for quality indicators
|
| 177 |
+
if any(word in response for word in ['7', '8', '9', '10', 'good', 'correct']):
|
| 178 |
+
return True
|
| 179 |
+
elif any(word in response for word in ['1', '2', '3', '4', 'poor', 'wrong']):
|
| 180 |
+
return False
|
| 181 |
+
return True # Default to pass if unclear
|
| 182 |
break
|
| 183 |
except Exception as e:
|
| 184 |
if attempt < max_retries - 1:
|
| 185 |
print(f"Retry {attempt+1}/{max_retries} due to: {e}")
|
| 186 |
+
time.sleep(3) # Reduced wait time
|
| 187 |
else:
|
| 188 |
print(f"Final attempt failed: {e}")
|
| 189 |
|
|
|
|
| 254 |
answers_payload = []
|
| 255 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 256 |
|
| 257 |
+
# Process questions with optimized concurrency
|
| 258 |
+
semaphore = asyncio.Semaphore(2) # Process 2 questions at a time for better efficiency
|
| 259 |
|
| 260 |
async def process_question(item):
|
| 261 |
task_id = item.get("task_id")
|
|
|
|
| 275 |
except Exception as e:
|
| 276 |
print(f"Error running agent on task {task_id}, attempt {attempt+1}: {e}")
|
| 277 |
if "rate limit" in str(e).lower() and attempt < max_retries - 1:
|
| 278 |
+
# Exponential backoff with jitter
|
| 279 |
+
wait_time = (2 ** attempt) * 5 + random.uniform(0, 3)
|
| 280 |
print(f"Rate limit hit. Waiting {wait_time:.2f} seconds before retry...")
|
| 281 |
await asyncio.sleep(wait_time)
|
| 282 |
elif attempt < max_retries - 1:
|
| 283 |
+
await asyncio.sleep(5) # Reduced wait time
|
| 284 |
else:
|
| 285 |
# All retries failed, return default answer
|
| 286 |
default_answer = "This is a default answer."
|