Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -78,24 +78,65 @@ def web_search(query: str) -> str:
|
|
| 78 |
except Exception as e:
|
| 79 |
return f"Search error: {e}"
|
| 80 |
|
| 81 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
@tool
|
| 83 |
def document_qa(document: str, question: str) -> str:
|
| 84 |
"""
|
| 85 |
-
Answer a question based on a
|
| 86 |
-
This is a placeholder – in a real implementation, you would fetch the document
|
| 87 |
-
and use an LLM to answer the question. For now, it returns a default message.
|
| 88 |
|
| 89 |
Args:
|
| 90 |
document: Description or URL of the document.
|
| 91 |
-
question: The question to answer
|
| 92 |
|
| 93 |
Returns:
|
| 94 |
-
|
| 95 |
"""
|
| 96 |
-
|
| 97 |
-
# For simplicity, we return a placeholder.
|
| 98 |
-
return f"Document QA is not fully implemented. The question was: '{question}' based on document: {document[:100]}..."
|
| 99 |
|
| 100 |
# ---------- Custom Model using OpenAI ----------
|
| 101 |
class OpenAIModel(Model):
|
|
@@ -114,20 +155,37 @@ class OpenAIModel(Model):
|
|
| 114 |
temperature=0.7,
|
| 115 |
**kwargs
|
| 116 |
):
|
| 117 |
-
# Convert any message format to OpenAI dict format
|
| 118 |
openai_messages = []
|
| 119 |
for msg in messages:
|
|
|
|
| 120 |
if isinstance(msg, str):
|
| 121 |
-
|
|
|
|
| 122 |
elif isinstance(msg, dict):
|
| 123 |
role = msg.get("role", "user")
|
| 124 |
content = msg.get("content", "")
|
| 125 |
-
openai_messages.append({"role": role, "content": str(content)})
|
| 126 |
elif hasattr(msg, 'role') and hasattr(msg, 'content'):
|
| 127 |
-
|
|
|
|
| 128 |
else:
|
| 129 |
logger.warning(f"Unknown message type {type(msg)} – converting to string")
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
try:
|
| 133 |
response = self.client.chat.completions.create(
|
|
@@ -146,14 +204,13 @@ class OpenAIModel(Model):
|
|
| 146 |
message = choice.message
|
| 147 |
content = message.content if hasattr(message, 'content') else str(message)
|
| 148 |
|
| 149 |
-
# Extract token usage and
|
| 150 |
token_usage = None
|
| 151 |
if hasattr(response, 'usage'):
|
| 152 |
usage = response.usage
|
| 153 |
-
# Map OpenAI's prompt_tokens/completion_tokens to input_tokens/output_tokens
|
| 154 |
token_usage = type('TokenUsage', (), {
|
| 155 |
-
'input_tokens':
|
| 156 |
-
'output_tokens':
|
| 157 |
})()
|
| 158 |
|
| 159 |
return ChatMessage(
|
|
@@ -172,7 +229,14 @@ class OpenAIModel(Model):
|
|
| 172 |
raise Exception(f"OpenAI model {self.model} inference failed: {e}")
|
| 173 |
|
| 174 |
# ---------- Assemble the Agent ----------
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
try:
|
| 177 |
import duckduckgo_search
|
| 178 |
tools.append(web_search)
|
|
|
|
| 78 |
except Exception as e:
|
| 79 |
return f"Search error: {e}"
|
| 80 |
|
| 81 |
+
# Stub for wikipedia_search – uses web_search
|
| 82 |
+
@tool
|
| 83 |
+
def wikipedia_search(query: str) -> str:
|
| 84 |
+
"""
|
| 85 |
+
Search Wikipedia for information. Falls back to web search.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
query: The search query.
|
| 89 |
+
|
| 90 |
+
Returns:
|
| 91 |
+
Search results from Wikipedia or web.
|
| 92 |
+
"""
|
| 93 |
+
# Try to restrict to Wikipedia
|
| 94 |
+
return web_search(f"site:wikipedia.org {query}")
|
| 95 |
+
|
| 96 |
+
# Stub for video_metadata – uses web search with video title
|
| 97 |
+
@tool
|
| 98 |
+
def video_metadata(url: str) -> str:
|
| 99 |
+
"""
|
| 100 |
+
Get metadata for a YouTube video. Falls back to web search.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
url: The YouTube video URL.
|
| 104 |
+
|
| 105 |
+
Returns:
|
| 106 |
+
Information about the video.
|
| 107 |
+
"""
|
| 108 |
+
# Extract video ID if needed, but just use web search with URL
|
| 109 |
+
return web_search(f"metadata for {url}")
|
| 110 |
+
|
| 111 |
+
# Stub for chess_analysis – placeholder
|
| 112 |
+
@tool
|
| 113 |
+
def chess_analysis(image: str, turn: str) -> str:
|
| 114 |
+
"""
|
| 115 |
+
Analyze a chess position. Since image analysis is not available, returns a placeholder.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
image: Path or description of the chess position image.
|
| 119 |
+
turn: Whose turn it is.
|
| 120 |
+
|
| 121 |
+
Returns:
|
| 122 |
+
A placeholder message.
|
| 123 |
+
"""
|
| 124 |
+
return f"Chess analysis not implemented. The position is from {image} and it's {turn}'s turn. Please use web search or reasoning."
|
| 125 |
+
|
| 126 |
+
# Stub for document_qa – uses web search
|
| 127 |
@tool
|
| 128 |
def document_qa(document: str, question: str) -> str:
|
| 129 |
"""
|
| 130 |
+
Answer a question based on a document description. Falls back to web search.
|
|
|
|
|
|
|
| 131 |
|
| 132 |
Args:
|
| 133 |
document: Description or URL of the document.
|
| 134 |
+
question: The question to answer.
|
| 135 |
|
| 136 |
Returns:
|
| 137 |
+
Answer from web search.
|
| 138 |
"""
|
| 139 |
+
return web_search(f"{question} {document}")
|
|
|
|
|
|
|
| 140 |
|
| 141 |
# ---------- Custom Model using OpenAI ----------
|
| 142 |
class OpenAIModel(Model):
|
|
|
|
| 155 |
temperature=0.7,
|
| 156 |
**kwargs
|
| 157 |
):
|
| 158 |
+
# Convert any message format to OpenAI dict format, and fix roles
|
| 159 |
openai_messages = []
|
| 160 |
for msg in messages:
|
| 161 |
+
# Determine role and content
|
| 162 |
if isinstance(msg, str):
|
| 163 |
+
role = "user"
|
| 164 |
+
content = msg
|
| 165 |
elif isinstance(msg, dict):
|
| 166 |
role = msg.get("role", "user")
|
| 167 |
content = msg.get("content", "")
|
|
|
|
| 168 |
elif hasattr(msg, 'role') and hasattr(msg, 'content'):
|
| 169 |
+
role = msg.role
|
| 170 |
+
content = msg.content
|
| 171 |
else:
|
| 172 |
logger.warning(f"Unknown message type {type(msg)} – converting to string")
|
| 173 |
+
role = "user"
|
| 174 |
+
content = str(msg)
|
| 175 |
+
|
| 176 |
+
# Ensure content is string
|
| 177 |
+
content = str(content)
|
| 178 |
+
|
| 179 |
+
# Fix invalid roles
|
| 180 |
+
if role == "tool-call":
|
| 181 |
+
# smolagents uses 'tool-call' for assistant's tool call messages; map to 'assistant'
|
| 182 |
+
role = "assistant"
|
| 183 |
+
# Optionally, we could prepend a note, but keep content as is
|
| 184 |
+
elif role not in ["system", "user", "assistant", "tool", "function"]:
|
| 185 |
+
logger.warning(f"Unknown role '{role}' – mapping to 'user'")
|
| 186 |
+
role = "user"
|
| 187 |
+
|
| 188 |
+
openai_messages.append({"role": role, "content": content})
|
| 189 |
|
| 190 |
try:
|
| 191 |
response = self.client.chat.completions.create(
|
|
|
|
| 204 |
message = choice.message
|
| 205 |
content = message.content if hasattr(message, 'content') else str(message)
|
| 206 |
|
| 207 |
+
# Extract token usage and map to smolagents expected format
|
| 208 |
token_usage = None
|
| 209 |
if hasattr(response, 'usage'):
|
| 210 |
usage = response.usage
|
|
|
|
| 211 |
token_usage = type('TokenUsage', (), {
|
| 212 |
+
'input_tokens': getattr(usage, 'prompt_tokens', 0),
|
| 213 |
+
'output_tokens': getattr(usage, 'completion_tokens', 0)
|
| 214 |
})()
|
| 215 |
|
| 216 |
return ChatMessage(
|
|
|
|
| 229 |
raise Exception(f"OpenAI model {self.model} inference failed: {e}")
|
| 230 |
|
| 231 |
# ---------- Assemble the Agent ----------
|
| 232 |
+
# Include all stub tools
|
| 233 |
+
tools = [
|
| 234 |
+
calculator,
|
| 235 |
+
document_qa,
|
| 236 |
+
wikipedia_search,
|
| 237 |
+
video_metadata,
|
| 238 |
+
chess_analysis,
|
| 239 |
+
]
|
| 240 |
try:
|
| 241 |
import duckduckgo_search
|
| 242 |
tools.append(web_search)
|