Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -95,15 +95,13 @@ def visit_webpage(url: str) -> str:
|
|
| 95 |
response = requests.get(url, timeout=10)
|
| 96 |
response.raise_for_status()
|
| 97 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 98 |
-
# Remove script and style elements
|
| 99 |
for script in soup(["script", "style"]):
|
| 100 |
script.decompose()
|
| 101 |
text = soup.get_text()
|
| 102 |
-
# Collapse whitespace
|
| 103 |
lines = (line.strip() for line in text.splitlines())
|
| 104 |
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
|
| 105 |
text = ' '.join(chunk for chunk in chunks if chunk)
|
| 106 |
-
return text[:5000]
|
| 107 |
except Exception as e:
|
| 108 |
return f"Error fetching webpage: {e}"
|
| 109 |
|
|
@@ -120,14 +118,12 @@ def wikipedia_search(query: str) -> str:
|
|
| 120 |
"""
|
| 121 |
try:
|
| 122 |
import wikipedia
|
| 123 |
-
# Set language to English
|
| 124 |
wikipedia.set_lang("en")
|
| 125 |
-
# Search for the query
|
| 126 |
results = wikipedia.search(query, results=1)
|
| 127 |
if not results:
|
| 128 |
return "No Wikipedia article found."
|
| 129 |
page = wikipedia.page(results[0])
|
| 130 |
-
summary = page.summary[:2000]
|
| 131 |
return summary
|
| 132 |
except ImportError:
|
| 133 |
return "Wikipedia tool not available: install wikipedia"
|
|
@@ -145,7 +141,7 @@ def final_answer(answer: str) -> str:
|
|
| 145 |
Returns:
|
| 146 |
The answer, which will be returned to the user.
|
| 147 |
"""
|
| 148 |
-
return answer
|
| 149 |
|
| 150 |
# ---------- Custom Model using OpenAI ----------
|
| 151 |
class OpenAIModel(Model):
|
|
@@ -164,7 +160,6 @@ class OpenAIModel(Model):
|
|
| 164 |
temperature=0.7,
|
| 165 |
**kwargs
|
| 166 |
):
|
| 167 |
-
# Convert any message format to OpenAI dict format, fixing roles
|
| 168 |
openai_messages = []
|
| 169 |
for msg in messages:
|
| 170 |
if isinstance(msg, str):
|
|
@@ -179,7 +174,6 @@ class OpenAIModel(Model):
|
|
| 179 |
logger.warning(f"Unknown message type {type(msg)} β converting to string")
|
| 180 |
openai_messages.append({"role": "user", "content": str(msg)})
|
| 181 |
|
| 182 |
-
# Fix invalid roles
|
| 183 |
for msg in openai_messages:
|
| 184 |
if msg["role"] not in ["system", "user", "assistant", "tool"]:
|
| 185 |
logger.warning(f"Unknown role '{msg['role']}' β mapping to 'user'")
|
|
@@ -201,8 +195,9 @@ class OpenAIModel(Model):
|
|
| 201 |
if hasattr(choice, 'message'):
|
| 202 |
message = choice.message
|
| 203 |
content = message.content if hasattr(message, 'content') else str(message)
|
|
|
|
|
|
|
| 204 |
|
| 205 |
-
# Map token usage
|
| 206 |
token_usage = None
|
| 207 |
if hasattr(response, 'usage'):
|
| 208 |
usage = response.usage
|
|
@@ -229,7 +224,7 @@ class OpenAIModel(Model):
|
|
| 229 |
logger.error(f"OpenAI API error: {e}")
|
| 230 |
raise Exception(f"OpenAI model {self.model} inference failed: {e}")
|
| 231 |
|
| 232 |
-
# ---------- System prompt
|
| 233 |
SYSTEM_PROMPT = """You are an expert assistant that solves tasks by writing and executing Python code. You have access to the following tools:
|
| 234 |
- calculator(expression): evaluate a math expression.
|
| 235 |
- web_search(query): search the web and return snippets.
|
|
@@ -261,11 +256,11 @@ tools = [
|
|
| 261 |
final_answer,
|
| 262 |
]
|
| 263 |
|
| 264 |
-
model = OpenAIModel(model="gpt-4o-mini")
|
| 265 |
agent = CodeAgent(
|
| 266 |
tools=tools,
|
| 267 |
model=model,
|
| 268 |
-
max_steps=10,
|
| 269 |
additional_authorized_imports=["requests", "bs4", "wikipedia"],
|
| 270 |
)
|
| 271 |
|
|
@@ -279,13 +274,14 @@ class CustomAgent:
|
|
| 279 |
|
| 280 |
logger.info(f"π€ Processing question: {question[:50]}...")
|
| 281 |
try:
|
| 282 |
-
# Prepend system prompt to messages
|
| 283 |
messages = [
|
| 284 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 285 |
{"role": "user", "content": question}
|
| 286 |
]
|
| 287 |
-
# Run the agent with these messages
|
| 288 |
answer = agent.run(messages)
|
|
|
|
|
|
|
|
|
|
| 289 |
except Exception as e:
|
| 290 |
logger.error(f"β Agent error: {e}")
|
| 291 |
answer = f"Error: {e}"
|
|
|
|
| 95 |
response = requests.get(url, timeout=10)
|
| 96 |
response.raise_for_status()
|
| 97 |
soup = BeautifulSoup(response.text, 'html.parser')
|
|
|
|
| 98 |
for script in soup(["script", "style"]):
|
| 99 |
script.decompose()
|
| 100 |
text = soup.get_text()
|
|
|
|
| 101 |
lines = (line.strip() for line in text.splitlines())
|
| 102 |
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
|
| 103 |
text = ' '.join(chunk for chunk in chunks if chunk)
|
| 104 |
+
return text[:5000]
|
| 105 |
except Exception as e:
|
| 106 |
return f"Error fetching webpage: {e}"
|
| 107 |
|
|
|
|
| 118 |
"""
|
| 119 |
try:
|
| 120 |
import wikipedia
|
|
|
|
| 121 |
wikipedia.set_lang("en")
|
|
|
|
| 122 |
results = wikipedia.search(query, results=1)
|
| 123 |
if not results:
|
| 124 |
return "No Wikipedia article found."
|
| 125 |
page = wikipedia.page(results[0])
|
| 126 |
+
summary = page.summary[:2000]
|
| 127 |
return summary
|
| 128 |
except ImportError:
|
| 129 |
return "Wikipedia tool not available: install wikipedia"
|
|
|
|
| 141 |
Returns:
|
| 142 |
The answer, which will be returned to the user.
|
| 143 |
"""
|
| 144 |
+
return str(answer) # ensure string
|
| 145 |
|
| 146 |
# ---------- Custom Model using OpenAI ----------
|
| 147 |
class OpenAIModel(Model):
|
|
|
|
| 160 |
temperature=0.7,
|
| 161 |
**kwargs
|
| 162 |
):
|
|
|
|
| 163 |
openai_messages = []
|
| 164 |
for msg in messages:
|
| 165 |
if isinstance(msg, str):
|
|
|
|
| 174 |
logger.warning(f"Unknown message type {type(msg)} β converting to string")
|
| 175 |
openai_messages.append({"role": "user", "content": str(msg)})
|
| 176 |
|
|
|
|
| 177 |
for msg in openai_messages:
|
| 178 |
if msg["role"] not in ["system", "user", "assistant", "tool"]:
|
| 179 |
logger.warning(f"Unknown role '{msg['role']}' β mapping to 'user'")
|
|
|
|
| 195 |
if hasattr(choice, 'message'):
|
| 196 |
message = choice.message
|
| 197 |
content = message.content if hasattr(message, 'content') else str(message)
|
| 198 |
+
# Ensure content is a string
|
| 199 |
+
content = str(content)
|
| 200 |
|
|
|
|
| 201 |
token_usage = None
|
| 202 |
if hasattr(response, 'usage'):
|
| 203 |
usage = response.usage
|
|
|
|
| 224 |
logger.error(f"OpenAI API error: {e}")
|
| 225 |
raise Exception(f"OpenAI model {self.model} inference failed: {e}")
|
| 226 |
|
| 227 |
+
# ---------- System prompt ----------
|
| 228 |
SYSTEM_PROMPT = """You are an expert assistant that solves tasks by writing and executing Python code. You have access to the following tools:
|
| 229 |
- calculator(expression): evaluate a math expression.
|
| 230 |
- web_search(query): search the web and return snippets.
|
|
|
|
| 256 |
final_answer,
|
| 257 |
]
|
| 258 |
|
| 259 |
+
model = OpenAIModel(model="gpt-4o-mini")
|
| 260 |
agent = CodeAgent(
|
| 261 |
tools=tools,
|
| 262 |
model=model,
|
| 263 |
+
max_steps=10,
|
| 264 |
additional_authorized_imports=["requests", "bs4", "wikipedia"],
|
| 265 |
)
|
| 266 |
|
|
|
|
| 274 |
|
| 275 |
logger.info(f"π€ Processing question: {question[:50]}...")
|
| 276 |
try:
|
|
|
|
| 277 |
messages = [
|
| 278 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 279 |
{"role": "user", "content": question}
|
| 280 |
]
|
|
|
|
| 281 |
answer = agent.run(messages)
|
| 282 |
+
# Ensure answer is a string (in case agent returns something else)
|
| 283 |
+
if not isinstance(answer, str):
|
| 284 |
+
answer = str(answer)
|
| 285 |
except Exception as e:
|
| 286 |
logger.error(f"β Agent error: {e}")
|
| 287 |
answer = f"Error: {e}"
|