File size: 25,080 Bytes
162ee47 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 |
"""
GAIA-Ready AI Agent using smolagents framework
This agent is designed to meet the requirements of the Hugging Face Agents Course
and perform well on the GAIA benchmark. It implements the Think-Act-Observe workflow
and includes tools for web search, calculation, image analysis, and code execution.
"""
import os
import json
import base64
import requests
from typing import List, Dict, Any, Optional, Union, Callable
import re
import time
from datetime import datetime
import traceback
# Install required packages if not already installed
try:
from smolagents import Agent, InferenceClientModel, Tool
from smolagents.memory import Memory
except ImportError:
import subprocess
subprocess.check_call(["pip", "install", "smolagents"])
from smolagents import Agent, InferenceClientModel, Tool
from smolagents.memory import Memory
try:
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import io
except ImportError:
import subprocess
subprocess.check_call(["pip", "install", "numpy", "matplotlib", "pillow"])
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import io
try:
import requests
from bs4 import BeautifulSoup
except ImportError:
import subprocess
subprocess.check_call(["pip", "install", "requests", "beautifulsoup4"])
import requests
from bs4 import BeautifulSoup
class MemoryManager:
"""
Custom memory manager for the agent that maintains short-term, long-term,
and working memory.
"""
def __init__(self):
self.short_term_memory = [] # Current conversation context
self.long_term_memory = [] # Key facts and results
self.working_memory = {} # Temporary storage for complex tasks
self.max_short_term_items = 10
self.max_long_term_items = 50
def add_to_short_term(self, item: Dict[str, Any]) -> None:
"""Add an item to short-term memory, maintaining size limit"""
self.short_term_memory.append(item)
if len(self.short_term_memory) > self.max_short_term_items:
self.short_term_memory.pop(0)
def add_to_long_term(self, item: Dict[str, Any]) -> None:
"""Add an important item to long-term memory, maintaining size limit"""
self.long_term_memory.append(item)
if len(self.long_term_memory) > self.max_long_term_items:
self.long_term_memory.pop(0)
def store_in_working_memory(self, key: str, value: Any) -> None:
"""Store a value in working memory under the specified key"""
self.working_memory[key] = value
def get_from_working_memory(self, key: str) -> Optional[Any]:
"""Retrieve a value from working memory by key"""
return self.working_memory.get(key)
def clear_working_memory(self) -> None:
"""Clear the working memory"""
self.working_memory = {}
def get_relevant_memories(self, query: str) -> List[Dict[str, Any]]:
"""
Retrieve memories relevant to the current query
Simple implementation using keyword matching
"""
relevant_memories = []
query_keywords = set(query.lower().split())
# Check long-term memory first
for memory in self.long_term_memory:
memory_text = memory.get("content", "").lower()
if any(keyword in memory_text for keyword in query_keywords):
relevant_memories.append(memory)
# Then check short-term memory
for memory in self.short_term_memory:
memory_text = memory.get("content", "").lower()
if any(keyword in memory_text for keyword in query_keywords):
relevant_memories.append(memory)
return relevant_memories
def get_memory_summary(self) -> str:
"""Get a summary of the current memory state for the agent"""
short_term_summary = "\n".join([f"- {m.get('content', '')}" for m in self.short_term_memory[-5:]])
long_term_summary = "\n".join([f"- {m.get('content', '')}" for m in self.long_term_memory[-5:]])
working_memory_summary = "\n".join([f"- {k}: {v}" for k, v in self.working_memory.items()])
return f"""
MEMORY SUMMARY:
--------------
Recent Short-Term Memory:
{short_term_summary}
Important Long-Term Memory:
{long_term_summary}
Working Memory:
{working_memory_summary}
"""
# Tool implementations
def web_search_function(query: str) -> str:
"""
Search the web for information using a search API
Args:
query: The search query
Returns:
Search results as a string
"""
try:
# Using a public search API (replace with your preferred API)
url = f"https://ddg-api.herokuapp.com/search?query={query}"
response = requests.get(url)
if response.status_code == 200:
results = response.json()
formatted_results = []
for i, result in enumerate(results[:5]): # Limit to top 5 results
title = result.get('title', 'No title')
snippet = result.get('snippet', 'No snippet')
link = result.get('link', 'No link')
formatted_results.append(f"{i+1}. {title}\n {snippet}\n URL: {link}\n")
return "Search Results:\n" + "\n".join(formatted_results)
else:
return f"Error: Search request failed with status code {response.status_code}"
except Exception as e:
return f"Error performing web search: {str(e)}"
def web_page_content_function(url: str) -> str:
"""
Fetch and extract content from a web page
Args:
url: The URL of the web page to fetch
Returns:
Extracted content as a string
"""
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
# Remove script and style elements
for script in soup(["script", "style"]):
script.extract()
# Extract text
text = soup.get_text()
# Clean up text
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = '\n'.join(chunk for chunk in chunks if chunk)
# Limit length to avoid overwhelming the model
if len(text) > 4000:
text = text[:4000] + "...\n[Content truncated due to length]"
return f"Content from {url}:\n\n{text}"
else:
return f"Error: Failed to fetch web page with status code {response.status_code}"
except Exception as e:
return f"Error fetching web page content: {str(e)}"
def calculator_function(expression: str) -> str:
"""
Evaluate a mathematical expression
Args:
expression: The mathematical expression to evaluate
Returns:
Result of the calculation as a string
"""
try:
# Clean the expression to ensure it's safe to evaluate
# Remove any characters that aren't digits, operators, or parentheses
clean_expr = re.sub(r'[^0-9+\-*/().^ ]', '', expression)
# Replace ^ with ** for exponentiation
clean_expr = clean_expr.replace('^', '**')
# Evaluate the expression
result = eval(clean_expr)
return f"Expression: {expression}\nResult: {result}"
except Exception as e:
return f"Error calculating result: {str(e)}"
def python_executor_function(code: str) -> str:
"""
Execute Python code and return the result
Args:
code: The Python code to execute
Returns:
Output of the code execution as a string
"""
try:
# Create a string buffer to capture output
from io import StringIO
import sys
old_stdout = sys.stdout
redirected_output = StringIO()
sys.stdout = redirected_output
# Execute the code
exec_globals = {
"np": np,
"plt": plt,
"requests": requests,
"BeautifulSoup": BeautifulSoup,
"Image": Image,
"io": io,
"json": json,
"base64": base64,
"re": re,
"time": time,
"datetime": datetime
}
exec(code, exec_globals)
# Restore stdout and get the output
sys.stdout = old_stdout
output = redirected_output.getvalue()
return f"Code executed successfully:\n\n{output}"
except Exception as e:
return f"Error executing Python code: {str(e)}\n{traceback.format_exc()}"
def image_analyzer_function(image_url: str) -> str:
"""
Analyze an image and provide a description
Args:
image_url: URL of the image to analyze
Returns:
Description of the image as a string
"""
try:
# Fetch the image
response = requests.get(image_url)
if response.status_code == 200:
# Convert to base64 for inclusion in the response
image_data = base64.b64encode(response.content).decode('utf-8')
# In a real implementation, you would use a vision model here
# For now, we'll return a placeholder response
return f"""
Image Analysis:
- Successfully retrieved image from {image_url}
- Image size: {len(response.content)} bytes
[Note: In a production environment, this would use a vision model to analyze the image content]
To properly analyze this image, please describe what you see in the image.
"""
else:
return f"Error: Failed to fetch image with status code {response.status_code}"
except Exception as e:
return f"Error analyzing image: {str(e)}"
def text_processor_function(text: str, operation: str) -> str:
"""
Process and analyze text
Args:
text: The text to process
operation: The operation to perform (summarize, analyze_sentiment, extract_keywords)
Returns:
Processed text as a string
"""
try:
if operation == "summarize":
# Simple extractive summarization
sentences = text.split('. ')
if len(sentences) <= 3:
return f"Summary: {text}"
# Take first and last sentences, plus one from the middle
summary = f"{sentences[0]}. {sentences[len(sentences)//2]}. {sentences[-1]}"
return f"Summary: {summary}"
elif operation == "analyze_sentiment":
# Very simple sentiment analysis
positive_words = ['good', 'great', 'excellent', 'positive', 'happy', 'love', 'like']
negative_words = ['bad', 'poor', 'negative', 'unhappy', 'hate', 'dislike']
text_lower = text.lower()
positive_count = sum(1 for word in positive_words if word in text_lower)
negative_count = sum(1 for word in negative_words if word in text_lower)
if positive_count > negative_count:
sentiment = "positive"
elif negative_count > positive_count:
sentiment = "negative"
else:
sentiment = "neutral"
return f"Sentiment Analysis: {sentiment} (positive words: {positive_count}, negative words: {negative_count})"
elif operation == "extract_keywords":
# Simple keyword extraction
import re
from collections import Counter
# Remove punctuation and convert to lowercase
text_clean = re.sub(r'[^\w\s]', '', text.lower())
# Remove common stop words
stop_words = ['the', 'a', 'an', 'and', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by']
words = [word for word in text_clean.split() if word not in stop_words and len(word) > 2]
# Count word frequencies
word_counts = Counter(words)
# Get top 10 keywords
keywords = [word for word, count in word_counts.most_common(10)]
return f"Keywords: {', '.join(keywords)}"
else:
return f"Error: Unknown operation '{operation}'. Supported operations: summarize, analyze_sentiment, extract_keywords"
except Exception as e:
return f"Error processing text: {str(e)}"
def file_manager_function(operation: str, filename: str, content: str = None) -> str:
"""
Save and load data from files
Args:
operation: The operation to perform (save, load)
filename: The name of the file
content: The content to save (for save operation)
Returns:
Result of the operation as a string
"""
try:
if operation == "save":
if content is None:
return "Error: Content is required for save operation"
with open(filename, 'w') as f:
f.write(content)
return f"Successfully saved content to {filename}"
elif operation == "load":
if not os.path.exists(filename):
return f"Error: File {filename} does not exist"
with open(filename, 'r') as f:
content = f.read()
return f"Content of {filename}:\n\n{content}"
else:
return f"Error: Unknown operation '{operation}'. Supported operations: save, load"
except Exception as e:
return f"Error managing file: {str(e)}"
class GAIAAgent:
"""
AI Agent designed to perform well on the GAIA benchmark
Implements the Think-Act-Observe workflow
"""
def __init__(self, api_key=None, use_local_model=False):
self.memory_manager = MemoryManager()
# Initialize the LLM model
if use_local_model:
# Use Ollama for local model
try:
from smolagents import LiteLLMModel
self.model = LiteLLMModel(
model_id="ollama_chat/qwen2:7b",
api_base="http://127.0.0.1:11434",
num_ctx=8192,
)
except Exception as e:
print(f"Error initializing local model: {str(e)}")
print("Falling back to Hugging Face Inference API")
self.model = InferenceClientModel(
model_id="mistralai/Mixtral-8x7B-Instruct-v0.1",
api_key=api_key or os.environ.get("HF_API_KEY", "")
)
else:
# Use Hugging Face Inference API
self.model = InferenceClientModel(
model_id="mistralai/Mixtral-8x7B-Instruct-v0.1",
api_key=api_key or os.environ.get("HF_API_KEY", "")
)
# Define tools
self.tools = [
Tool(
name="web_search",
description="Search the web for information",
function=web_search_function
),
Tool(
name="web_page_content",
description="Fetch and extract content from a web page",
function=web_page_content_function
),
Tool(
name="calculator",
description="Perform mathematical calculations",
function=calculator_function
),
Tool(
name="image_analyzer",
description="Analyze image content",
function=image_analyzer_function
),
Tool(
name="python_executor",
description="Execute Python code",
function=python_executor_function
),
Tool(
name="text_processor",
description="Process and analyze text",
function=text_processor_function
),
Tool(
name="file_manager",
description="Save and load data from files",
function=file_manager_function
)
]
# System prompt
self.system_prompt = """
You are an advanced AI assistant designed to solve complex tasks from the GAIA benchmark.
You have access to various tools that can help you solve these tasks.
Always follow the Think-Act-Observe workflow:
1. Think: Carefully analyze the task and plan your approach
2. Act: Use appropriate tools to gather information or perform actions
3. Observe: Analyze the results of your actions and adjust your approach if needed
For complex tasks, break them down into smaller steps.
Always verify your answers before submitting them.
When using tools:
- web_search: Use to find information online
- web_page_content: Use to extract content from specific web pages
- calculator: Use for mathematical calculations
- image_analyzer: Use to analyze image content
- python_executor: Use to run Python code for complex operations
- text_processor: Use to process and analyze text (summarize, analyze_sentiment, extract_keywords)
- file_manager: Use to save and load data from files (save, load)
Be thorough, methodical, and precise in your reasoning.
"""
# Initialize the agent
self.agent = Agent(
model=self.model,
tools=self.tools,
system_prompt=self.system_prompt
)
def think(self, query):
"""
Analyze the task and plan an approach
Args:
query: The user's query or task
Returns:
Dictionary containing analysis and plan
"""
# Retrieve relevant memories
relevant_memories = self.memory_manager.get_relevant_memories(query)
# Construct a thinking prompt
thinking_prompt = f"""
TASK: {query}
RELEVANT MEMORIES:
{relevant_memories if relevant_memories else "No relevant memories found."}
Please analyze this task and create a plan:
1. What is this task asking for?
2. What information do I need to solve it?
3. What tools would be most helpful?
4. What steps should I take to solve it?
Provide your analysis and plan.
"""
# Use the agent to generate a plan
response = self.agent.chat(thinking_prompt)
# Store the thinking in memory
self.memory_manager.add_to_short_term({
"type": "thinking",
"content": response,
"timestamp": datetime.now().isoformat()
})
# Extract plan components (in a real implementation, this would be more structured)
return {
"analysis": response,
"plan": response # For now, we're using the full response as the plan
}
def act(self, plan, query):
"""
Execute actions based on the plan
Args:
plan: The plan generated by the think step
query: The original query
Returns:
Results of the actions
"""
# Use the agent to determine which tools to use based on the plan
tool_selection_prompt = f"""
TASK: {query}
MY PLAN:
{plan['plan']}
Based on this plan, which tool should I use first and with what parameters?
Respond in the following format:
TOOL: [tool name]
PARAMETERS: [parameters for the tool]
REASONING: [why this tool is appropriate]
"""
tool_selection = self.agent.chat(tool_selection_prompt)
# Store the tool selection in memory
self.memory_manager.add_to_short_term({
"type": "tool_selection",
"content": tool_selection,
"timestamp": datetime.now().isoformat()
})
# Execute the selected tool (in a real implementation, this would parse the tool selection more robustly)
# For now, we'll use the agent's built-in tool execution
action_prompt = f"""
TASK: {query}
MY PLAN:
{plan['plan']}
TOOL SELECTION:
{tool_selection}
Please execute the appropriate tool to help solve this task.
"""
action_result = self.agent.chat(action_prompt)
# Store the action result in memory
self.memory_manager.add_to_short_term({
"type": "action_result",
"content": action_result,
"timestamp": datetime.now().isoformat()
})
return action_result
def observe(self, action_result, plan, query):
"""
Analyze the results of actions and determine next steps
Args:
action_result: Results from the act step
plan: The original plan
query: The original query
Returns:
Observation and next steps
"""
observation_prompt = f"""
TASK: {query}
MY PLAN:
{plan['plan']}
ACTION RESULT:
{action_result}
Please analyze these results:
1. What did I learn from this action?
2. Does this fully answer the original task?
3. If not, what should I do next?
4. If yes, what is the final answer?
Provide your analysis and next steps or final answer.
"""
observation = self.agent.chat(observation_prompt)
# Store the observation in memory
self.memory_manager.add_to_short_term({
"type": "observation",
"content": observation,
"timestamp": datetime.now().isoformat()
})
# Check if we need to continue with more actions
if "next steps" in observation.lower() or "next tool" in observation.lower():
continue_execution = True
else:
# If it seems like we have a final answer, store it in long-term memory
self.memory_manager.add_to_long_term({
"type": "final_answer",
"query": query,
"content": observation,
"timestamp": datetime.now().isoformat()
})
continue_execution = False
return {
"observation": observation,
"continue": continue_execution
}
def solve(self, query, max_iterations=5):
"""
Solve a task using the Think-Act-Observe workflow
Args:
query: The user's query or task
max_iterations: Maximum number of iterations to prevent infinite loops
Returns:
Final answer to the query
"""
# Store the query in memory
self.memory_manager.add_to_short_term({
"type": "query",
"content": query,
"timestamp": datetime.now().isoformat()
})
# Initialize the workflow
iteration = 0
final_answer = None
while iteration < max_iterations:
print(f"Iteration {iteration + 1}/{max_iterations}")
# Think
print("Thinking...")
plan = self.think(query)
# Act
print("Acting...")
action_result = self.act(plan, query)
# Observe
print("Observing...")
observation = self.observe(action_result, plan, query)
# Check if we have a final answer
if not observation["continue"]:
final_answer = observation["observation"]
break
# Update the query with the observation for the next iteration
query = f"""
Original task: {query}
Progress so far:
{observation["observation"]}
Please continue solving this task.
"""
iteration += 1
# If we reached max iterations without a final answer
if final_answer is None:
final_answer = f"""
I've spent {max_iterations} iterations trying to solve this task.
Here's my best answer based on what I've learned:
{observation["observation"]}
Note: This answer may be incomplete as I reached the maximum number of iterations.
"""
return final_answer
# Example usage
if __name__ == "__main__":
# Initialize the agent
agent = GAIAAgent(use_local_model=False)
# Example GAIA-style query
query = "What is the capital of France and what is its population? Also, calculate 15% of this population."
# Solve the query
answer = agent.solve(query)
print("\nFinal Answer:")
print(answer)
|