Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -8,7 +8,6 @@ from smolagents.models import Model
|
|
| 8 |
import openai
|
| 9 |
from bs4 import BeautifulSoup
|
| 10 |
|
| 11 |
-
# Set up logging
|
| 12 |
logging.basicConfig(level=logging.INFO)
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
|
@@ -32,18 +31,10 @@ def save_cache():
|
|
| 32 |
with open(CACHE_FILE, "w") as f:
|
| 33 |
json.dump(answer_cache, f)
|
| 34 |
|
| 35 |
-
# ---------- Tools ----------
|
| 36 |
@tool
|
| 37 |
def calculator(expression: str) -> str:
|
| 38 |
-
"""
|
| 39 |
-
Safely evaluate a mathematical expression.
|
| 40 |
-
|
| 41 |
-
Args:
|
| 42 |
-
expression: A string containing a simple arithmetic expression (e.g., '2 + 2').
|
| 43 |
-
|
| 44 |
-
Returns:
|
| 45 |
-
The result as a string, or an error message if the expression is invalid.
|
| 46 |
-
"""
|
| 47 |
allowed_chars = set("0123456789+-*/(). ")
|
| 48 |
if not all(c in allowed_chars for c in expression):
|
| 49 |
return "Error: Expression contains disallowed characters."
|
|
@@ -55,16 +46,7 @@ def calculator(expression: str) -> str:
|
|
| 55 |
|
| 56 |
@tool
|
| 57 |
def web_search(query: str) -> str:
|
| 58 |
-
"""
|
| 59 |
-
Search the web for up-to-date information.
|
| 60 |
-
|
| 61 |
-
Args:
|
| 62 |
-
query: The search query string.
|
| 63 |
-
|
| 64 |
-
Returns:
|
| 65 |
-
A string containing up to three search result snippets with titles and URLs,
|
| 66 |
-
or an error message if the search fails.
|
| 67 |
-
"""
|
| 68 |
try:
|
| 69 |
from duckduckgo_search import DDGS
|
| 70 |
with DDGS() as ddgs:
|
|
@@ -82,15 +64,7 @@ def web_search(query: str) -> str:
|
|
| 82 |
|
| 83 |
@tool
|
| 84 |
def visit_webpage(url: str) -> str:
|
| 85 |
-
"""
|
| 86 |
-
Visit a webpage and return its text content (first 5000 characters).
|
| 87 |
-
|
| 88 |
-
Args:
|
| 89 |
-
url: The URL of the webpage.
|
| 90 |
-
|
| 91 |
-
Returns:
|
| 92 |
-
The text content of the page, or an error message.
|
| 93 |
-
"""
|
| 94 |
try:
|
| 95 |
response = requests.get(url, timeout=10)
|
| 96 |
response.raise_for_status()
|
|
@@ -107,15 +81,7 @@ def visit_webpage(url: str) -> str:
|
|
| 107 |
|
| 108 |
@tool
|
| 109 |
def wikipedia_search(query: str) -> str:
|
| 110 |
-
"""
|
| 111 |
-
Search Wikipedia for a given query. Returns a summary of the top result.
|
| 112 |
-
|
| 113 |
-
Args:
|
| 114 |
-
query: The search term.
|
| 115 |
-
|
| 116 |
-
Returns:
|
| 117 |
-
A summary from Wikipedia, or an error message.
|
| 118 |
-
"""
|
| 119 |
try:
|
| 120 |
import wikipedia
|
| 121 |
wikipedia.set_lang("en")
|
|
@@ -131,17 +97,18 @@ def wikipedia_search(query: str) -> str:
|
|
| 131 |
return f"Wikipedia error: {e}"
|
| 132 |
|
| 133 |
@tool
|
| 134 |
-
def final_answer(answer
|
| 135 |
"""
|
| 136 |
-
Output the final answer
|
| 137 |
-
|
| 138 |
-
Args:
|
| 139 |
-
answer: The final answer as a string.
|
| 140 |
-
|
| 141 |
-
Returns:
|
| 142 |
-
The answer, which will be returned to the user.
|
| 143 |
"""
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
# ---------- Custom Model using OpenAI ----------
|
| 147 |
class OpenAIModel(Model):
|
|
@@ -151,15 +118,7 @@ class OpenAIModel(Model):
|
|
| 151 |
self.model = model
|
| 152 |
logger.info(f"✅ OpenAIModel initialized with model: {model}")
|
| 153 |
|
| 154 |
-
def generate(
|
| 155 |
-
self,
|
| 156 |
-
messages,
|
| 157 |
-
stop_sequences=None,
|
| 158 |
-
grammar=None,
|
| 159 |
-
max_tokens=500,
|
| 160 |
-
temperature=0.7,
|
| 161 |
-
**kwargs
|
| 162 |
-
):
|
| 163 |
openai_messages = []
|
| 164 |
for msg in messages:
|
| 165 |
if isinstance(msg, str):
|
|
@@ -188,16 +147,12 @@ class OpenAIModel(Model):
|
|
| 188 |
stop=stop_sequences,
|
| 189 |
**kwargs
|
| 190 |
)
|
| 191 |
-
logger.info(f"OpenAI response type: {type(response)}")
|
| 192 |
-
|
| 193 |
if hasattr(response, 'choices') and len(response.choices) > 0:
|
| 194 |
choice = response.choices[0]
|
| 195 |
if hasattr(choice, 'message'):
|
| 196 |
message = choice.message
|
| 197 |
content = message.content if hasattr(message, 'content') else str(message)
|
| 198 |
-
|
| 199 |
-
content = str(content)
|
| 200 |
-
|
| 201 |
token_usage = None
|
| 202 |
if hasattr(response, 'usage'):
|
| 203 |
usage = response.usage
|
|
@@ -205,32 +160,23 @@ class OpenAIModel(Model):
|
|
| 205 |
'input_tokens': getattr(usage, 'prompt_tokens', 0),
|
| 206 |
'output_tokens': getattr(usage, 'completion_tokens', 0)
|
| 207 |
})()
|
| 208 |
-
|
| 209 |
from smolagents.models import ChatMessage
|
| 210 |
-
return ChatMessage(
|
| 211 |
-
role="assistant",
|
| 212 |
-
content=content,
|
| 213 |
-
token_usage=token_usage
|
| 214 |
-
)
|
| 215 |
else:
|
| 216 |
-
logger.error(f"Choice has no 'message' attribute: {choice}")
|
| 217 |
-
from smolagents.models import ChatMessage
|
| 218 |
return ChatMessage(role="assistant", content=str(choice))
|
| 219 |
else:
|
| 220 |
-
logger.error(f"Unexpected response structure: {response}")
|
| 221 |
-
from smolagents.models import ChatMessage
|
| 222 |
return ChatMessage(role="assistant", content=str(response))
|
| 223 |
except Exception as e:
|
| 224 |
logger.error(f"OpenAI API error: {e}")
|
| 225 |
raise Exception(f"OpenAI model {self.model} inference failed: {e}")
|
| 226 |
|
| 227 |
-
# ---------- System
|
| 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.
|
| 231 |
- visit_webpage(url): fetch and return text content of a webpage.
|
| 232 |
- wikipedia_search(query): search Wikipedia and return a summary.
|
| 233 |
-
- final_answer(answer): call this when you have the final answer.
|
| 234 |
|
| 235 |
Always follow this structure:
|
| 236 |
- First, think about what you need to do.
|
|
@@ -279,8 +225,9 @@ class CustomAgent:
|
|
| 279 |
{"role": "user", "content": question}
|
| 280 |
]
|
| 281 |
answer = agent.run(messages)
|
| 282 |
-
#
|
| 283 |
if not isinstance(answer, str):
|
|
|
|
| 284 |
answer = str(answer)
|
| 285 |
except Exception as e:
|
| 286 |
logger.error(f"❌ Agent error: {e}")
|
|
|
|
| 8 |
import openai
|
| 9 |
from bs4 import BeautifulSoup
|
| 10 |
|
|
|
|
| 11 |
logging.basicConfig(level=logging.INFO)
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
|
|
|
| 31 |
with open(CACHE_FILE, "w") as f:
|
| 32 |
json.dump(answer_cache, f)
|
| 33 |
|
| 34 |
+
# ---------- Tools (all return strings) ----------
|
| 35 |
@tool
|
| 36 |
def calculator(expression: str) -> str:
|
| 37 |
+
"""Safely evaluate a mathematical expression."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
allowed_chars = set("0123456789+-*/(). ")
|
| 39 |
if not all(c in allowed_chars for c in expression):
|
| 40 |
return "Error: Expression contains disallowed characters."
|
|
|
|
| 46 |
|
| 47 |
@tool
|
| 48 |
def web_search(query: str) -> str:
|
| 49 |
+
"""Search the web and return up to three snippets."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
try:
|
| 51 |
from duckduckgo_search import DDGS
|
| 52 |
with DDGS() as ddgs:
|
|
|
|
| 64 |
|
| 65 |
@tool
|
| 66 |
def visit_webpage(url: str) -> str:
|
| 67 |
+
"""Fetch and return text content of a webpage (first 5000 chars)."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
try:
|
| 69 |
response = requests.get(url, timeout=10)
|
| 70 |
response.raise_for_status()
|
|
|
|
| 81 |
|
| 82 |
@tool
|
| 83 |
def wikipedia_search(query: str) -> str:
|
| 84 |
+
"""Search Wikipedia and return a summary."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
try:
|
| 86 |
import wikipedia
|
| 87 |
wikipedia.set_lang("en")
|
|
|
|
| 97 |
return f"Wikipedia error: {e}"
|
| 98 |
|
| 99 |
@tool
|
| 100 |
+
def final_answer(answer) -> str:
|
| 101 |
"""
|
| 102 |
+
Output the final answer. Use this tool when you have determined the answer.
|
| 103 |
+
The answer can be any type; it will be converted to a string.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
"""
|
| 105 |
+
# Log the type for debugging
|
| 106 |
+
logger.info(f"final_answer called with type: {type(answer)}")
|
| 107 |
+
# Convert to string safely
|
| 108 |
+
if isinstance(answer, (list, tuple, dict)):
|
| 109 |
+
# If it's a collection, convert to a readable string
|
| 110 |
+
return json.dumps(answer)
|
| 111 |
+
return str(answer)
|
| 112 |
|
| 113 |
# ---------- Custom Model using OpenAI ----------
|
| 114 |
class OpenAIModel(Model):
|
|
|
|
| 118 |
self.model = model
|
| 119 |
logger.info(f"✅ OpenAIModel initialized with model: {model}")
|
| 120 |
|
| 121 |
+
def generate(self, messages, stop_sequences=None, grammar=None, max_tokens=500, temperature=0.7, **kwargs):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
openai_messages = []
|
| 123 |
for msg in messages:
|
| 124 |
if isinstance(msg, str):
|
|
|
|
| 147 |
stop=stop_sequences,
|
| 148 |
**kwargs
|
| 149 |
)
|
|
|
|
|
|
|
| 150 |
if hasattr(response, 'choices') and len(response.choices) > 0:
|
| 151 |
choice = response.choices[0]
|
| 152 |
if hasattr(choice, 'message'):
|
| 153 |
message = choice.message
|
| 154 |
content = message.content if hasattr(message, 'content') else str(message)
|
| 155 |
+
content = str(content) # ensure string
|
|
|
|
|
|
|
| 156 |
token_usage = None
|
| 157 |
if hasattr(response, 'usage'):
|
| 158 |
usage = response.usage
|
|
|
|
| 160 |
'input_tokens': getattr(usage, 'prompt_tokens', 0),
|
| 161 |
'output_tokens': getattr(usage, 'completion_tokens', 0)
|
| 162 |
})()
|
|
|
|
| 163 |
from smolagents.models import ChatMessage
|
| 164 |
+
return ChatMessage(role="assistant", content=content, token_usage=token_usage)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
else:
|
|
|
|
|
|
|
| 166 |
return ChatMessage(role="assistant", content=str(choice))
|
| 167 |
else:
|
|
|
|
|
|
|
| 168 |
return ChatMessage(role="assistant", content=str(response))
|
| 169 |
except Exception as e:
|
| 170 |
logger.error(f"OpenAI API error: {e}")
|
| 171 |
raise Exception(f"OpenAI model {self.model} inference failed: {e}")
|
| 172 |
|
| 173 |
+
# ---------- System Prompt ----------
|
| 174 |
SYSTEM_PROMPT = """You are an expert assistant that solves tasks by writing and executing Python code. You have access to the following tools:
|
| 175 |
- calculator(expression): evaluate a math expression.
|
| 176 |
- web_search(query): search the web and return snippets.
|
| 177 |
- visit_webpage(url): fetch and return text content of a webpage.
|
| 178 |
- wikipedia_search(query): search Wikipedia and return a summary.
|
| 179 |
+
- final_answer(answer): call this when you have the final answer. The answer will be converted to a string automatically.
|
| 180 |
|
| 181 |
Always follow this structure:
|
| 182 |
- First, think about what you need to do.
|
|
|
|
| 225 |
{"role": "user", "content": question}
|
| 226 |
]
|
| 227 |
answer = agent.run(messages)
|
| 228 |
+
# Final safety: convert any non-string to string
|
| 229 |
if not isinstance(answer, str):
|
| 230 |
+
logger.warning(f"Agent returned non-string type {type(answer)} – converting")
|
| 231 |
answer = str(answer)
|
| 232 |
except Exception as e:
|
| 233 |
logger.error(f"❌ Agent error: {e}")
|