Commit ·
a437ec2
1
Parent(s): c288490
Enhance agent with specialized tools and improved file handling
Browse files- Increased max steps from 5 to 10 for more complex questions
- Added YouTubeTranscriptionTool for video-related questions
- Added ImageAnalysisTool for image and chess position questions
- Improved file attachment handling with better context
- Enhanced system prompt with specialized tool guidance
- direct_agent_fixed.py +178 -5
direct_agent_fixed.py
CHANGED
|
@@ -50,6 +50,126 @@ class WebSearchTool:
|
|
| 50 |
except Exception as e:
|
| 51 |
return f"Error searching the web: {str(e)}"
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
class WebBrowseTool:
|
| 54 |
def run(self, url):
|
| 55 |
try:
|
|
@@ -193,7 +313,9 @@ class DirectAgent:
|
|
| 193 |
"web_browse": WebBrowseTool(),
|
| 194 |
"read_file": ReadFileTool(),
|
| 195 |
"calculate": CalculateTool(),
|
| 196 |
-
"analyze_excel": AnalyzeExcelTool()
|
|
|
|
|
|
|
| 197 |
}
|
| 198 |
|
| 199 |
# Tool descriptions for the LLM
|
|
@@ -286,6 +408,40 @@ class DirectAgent:
|
|
| 286 |
"required": ["file_path", "query"]
|
| 287 |
}
|
| 288 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
}
|
| 290 |
]
|
| 291 |
|
|
@@ -299,7 +455,13 @@ When presented with a question:
|
|
| 299 |
4. Always present your final answer directly without adding 'FINAL ANSWER:' or similar phrases
|
| 300 |
5. If you use research or external information, incorporate it naturally into your response
|
| 301 |
|
| 302 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
def _handle_tool_call(self, tool_calls):
|
| 305 |
results = []
|
|
@@ -401,15 +563,26 @@ Be precise and focus only on answering the question asked. Do not add disclaimer
|
|
| 401 |
"""Run the agent on a question and return the answer."""
|
| 402 |
# Add context about any files if provided
|
| 403 |
if context and "file_path" in context:
|
| 404 |
-
|
| 405 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
|
| 407 |
messages = [
|
| 408 |
{"role": "system", "content": self.system_message},
|
| 409 |
{"role": "user", "content": question}
|
| 410 |
]
|
| 411 |
|
| 412 |
-
max_steps =
|
| 413 |
|
| 414 |
for step in range(max_steps):
|
| 415 |
print(f"Step {step+1}/{max_steps}")
|
|
|
|
| 50 |
except Exception as e:
|
| 51 |
return f"Error searching the web: {str(e)}"
|
| 52 |
|
| 53 |
+
class YouTubeTranscriptionTool:
|
| 54 |
+
def run(self, url):
|
| 55 |
+
"""Attempt to get a summary or transcript of a YouTube video."""
|
| 56 |
+
try:
|
| 57 |
+
if "youtube.com" not in url and "youtu.be" not in url:
|
| 58 |
+
return f"Error: The URL provided does not appear to be a YouTube link: {url}"
|
| 59 |
+
|
| 60 |
+
# Extract video ID from the URL
|
| 61 |
+
video_id = None
|
| 62 |
+
if "youtube.com/watch" in url and "v=" in url:
|
| 63 |
+
video_id = url.split("v=")[1].split("&")[0]
|
| 64 |
+
elif "youtu.be/" in url:
|
| 65 |
+
video_id = url.split("youtu.be/")[1].split("?")[0]
|
| 66 |
+
|
| 67 |
+
if not video_id:
|
| 68 |
+
return f"Error: Could not extract video ID from URL: {url}"
|
| 69 |
+
|
| 70 |
+
# First, try to get video info from the YouTube API
|
| 71 |
+
video_info_url = f"https://www.googleapis.com/youtube/v3/videos?id={video_id}&part=snippet&key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8"
|
| 72 |
+
|
| 73 |
+
try:
|
| 74 |
+
response = requests.get(video_info_url)
|
| 75 |
+
response.raise_for_status()
|
| 76 |
+
data = response.json()
|
| 77 |
+
|
| 78 |
+
if "items" in data and len(data["items"]) > 0:
|
| 79 |
+
title = data["items"][0]["snippet"]["title"]
|
| 80 |
+
description = data["items"][0]["snippet"]["description"]
|
| 81 |
+
channel = data["items"][0]["snippet"]["channelTitle"]
|
| 82 |
+
published_at = data["items"][0]["snippet"]["publishedAt"]
|
| 83 |
+
|
| 84 |
+
# Try to get transcripts (this is just a fallback as YouTube doesn't provide transcripts via API)
|
| 85 |
+
web_search = WebSearchTool()
|
| 86 |
+
transcript_results = web_search.run(f"youtube transcript {title} {channel}")
|
| 87 |
+
|
| 88 |
+
return f"""YouTube Video Information:
|
| 89 |
+
Title: {title}
|
| 90 |
+
Channel: {channel}
|
| 91 |
+
Published: {published_at}
|
| 92 |
+
Description: {description[:500]}{"..." if len(description) > 500 else ""}
|
| 93 |
+
|
| 94 |
+
Video URL: {url}
|
| 95 |
+
Video ID: {video_id}
|
| 96 |
+
|
| 97 |
+
Transcript Search Results:
|
| 98 |
+
{transcript_results}
|
| 99 |
+
"""
|
| 100 |
+
else:
|
| 101 |
+
return f"No information found for video ID: {video_id}"
|
| 102 |
+
|
| 103 |
+
except Exception as api_error:
|
| 104 |
+
# Fallback to web scraping if the API fails
|
| 105 |
+
try:
|
| 106 |
+
response = requests.get(url, headers={
|
| 107 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
|
| 108 |
+
})
|
| 109 |
+
response.raise_for_status()
|
| 110 |
+
|
| 111 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 112 |
+
title = soup.select_one("meta[property='og:title']")["content"] if soup.select_one("meta[property='og:title']") else "Unknown Title"
|
| 113 |
+
|
| 114 |
+
return f"""YouTube Video:
|
| 115 |
+
Title: {title}
|
| 116 |
+
URL: {url}
|
| 117 |
+
|
| 118 |
+
I was unable to retrieve the transcript automatically. Here's what you can do:
|
| 119 |
+
1. Check if the video has captions available on YouTube
|
| 120 |
+
2. Try to find a summary or transcript of this video through a web search
|
| 121 |
+
3. Look for information about the video content in the video description or comments
|
| 122 |
+
"""
|
| 123 |
+
except Exception as scrape_error:
|
| 124 |
+
return f"Error extracting YouTube video information: {str(scrape_error)}\nAPI Error: {str(api_error)}"
|
| 125 |
+
|
| 126 |
+
except Exception as e:
|
| 127 |
+
return f"Error processing YouTube URL: {str(e)}"
|
| 128 |
+
|
| 129 |
+
class ImageAnalysisTool:
|
| 130 |
+
def run(self, image_url_or_description):
|
| 131 |
+
"""Analyze an image or process an image description."""
|
| 132 |
+
try:
|
| 133 |
+
# Check if the input is a URL
|
| 134 |
+
if image_url_or_description.startswith(('http://', 'https://')):
|
| 135 |
+
try:
|
| 136 |
+
# Try to download the image
|
| 137 |
+
response = requests.get(image_url_or_description, timeout=10)
|
| 138 |
+
response.raise_for_status()
|
| 139 |
+
|
| 140 |
+
# Check if it's an image
|
| 141 |
+
content_type = response.headers.get('Content-Type', '')
|
| 142 |
+
if 'image' not in content_type:
|
| 143 |
+
return f"The URL does not point to an image. Content-Type: {content_type}"
|
| 144 |
+
|
| 145 |
+
# For a real implementation, here you would use Vision APIs
|
| 146 |
+
# Since we can't do that, we'll provide information about the image
|
| 147 |
+
image_size = len(response.content)
|
| 148 |
+
return f"""
|
| 149 |
+
Image Analysis:
|
| 150 |
+
URL: {image_url_or_description}
|
| 151 |
+
Size: {image_size} bytes
|
| 152 |
+
Content-Type: {content_type}
|
| 153 |
+
|
| 154 |
+
I can't view the image directly, but based on the URL and metadata, this appears to be a valid image.
|
| 155 |
+
To analyze the specific content, please provide a description of what you see in the image, and I can help interpret it.
|
| 156 |
+
"""
|
| 157 |
+
except Exception as url_error:
|
| 158 |
+
return f"Error accessing image URL: {str(url_error)}"
|
| 159 |
+
else:
|
| 160 |
+
# If it's not a URL, treat it as a description
|
| 161 |
+
return f"""
|
| 162 |
+
Based on the description: "{image_url_or_description}"
|
| 163 |
+
|
| 164 |
+
I'll analyze this as a text description rather than a direct image. If you're describing a chess position,
|
| 165 |
+
please format it using standard chess notation (e.g., FEN notation like "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1").
|
| 166 |
+
|
| 167 |
+
For other types of images, please provide details about what you see in the image, and I can help interpret the content.
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
except Exception as e:
|
| 171 |
+
return f"Error analyzing image: {str(e)}"
|
| 172 |
+
|
| 173 |
class WebBrowseTool:
|
| 174 |
def run(self, url):
|
| 175 |
try:
|
|
|
|
| 313 |
"web_browse": WebBrowseTool(),
|
| 314 |
"read_file": ReadFileTool(),
|
| 315 |
"calculate": CalculateTool(),
|
| 316 |
+
"analyze_excel": AnalyzeExcelTool(),
|
| 317 |
+
"analyze_youtube": YouTubeTranscriptionTool(),
|
| 318 |
+
"analyze_image": ImageAnalysisTool()
|
| 319 |
}
|
| 320 |
|
| 321 |
# Tool descriptions for the LLM
|
|
|
|
| 408 |
"required": ["file_path", "query"]
|
| 409 |
}
|
| 410 |
}
|
| 411 |
+
},
|
| 412 |
+
{
|
| 413 |
+
"type": "function",
|
| 414 |
+
"function": {
|
| 415 |
+
"name": "analyze_youtube",
|
| 416 |
+
"description": "Analyze a YouTube video to get information and potentially its transcript.",
|
| 417 |
+
"parameters": {
|
| 418 |
+
"type": "object",
|
| 419 |
+
"properties": {
|
| 420 |
+
"url": {
|
| 421 |
+
"type": "string",
|
| 422 |
+
"description": "The YouTube video URL"
|
| 423 |
+
}
|
| 424 |
+
},
|
| 425 |
+
"required": ["url"]
|
| 426 |
+
}
|
| 427 |
+
}
|
| 428 |
+
},
|
| 429 |
+
{
|
| 430 |
+
"type": "function",
|
| 431 |
+
"function": {
|
| 432 |
+
"name": "analyze_image",
|
| 433 |
+
"description": "Analyze an image from a URL or a description of an image (like a chess position).",
|
| 434 |
+
"parameters": {
|
| 435 |
+
"type": "object",
|
| 436 |
+
"properties": {
|
| 437 |
+
"image_url_or_description": {
|
| 438 |
+
"type": "string",
|
| 439 |
+
"description": "The URL of the image or a description of the image content"
|
| 440 |
+
}
|
| 441 |
+
},
|
| 442 |
+
"required": ["image_url_or_description"]
|
| 443 |
+
}
|
| 444 |
+
}
|
| 445 |
}
|
| 446 |
]
|
| 447 |
|
|
|
|
| 455 |
4. Always present your final answer directly without adding 'FINAL ANSWER:' or similar phrases
|
| 456 |
5. If you use research or external information, incorporate it naturally into your response
|
| 457 |
|
| 458 |
+
For specialized types of questions:
|
| 459 |
+
- For YouTube video questions, use the analyze_youtube tool to get information about the video
|
| 460 |
+
- For image or chess position questions, use the analyze_image tool with either the image URL or a description
|
| 461 |
+
- For Excel/spreadsheet file questions, use the analyze_excel tool with proper parameters
|
| 462 |
+
- When calculations are needed, use the calculate tool to ensure accurate results
|
| 463 |
+
|
| 464 |
+
Be precise and focus only on answering the question asked. Your final answer should be direct, concise, and straightforward without excessive explanations or disclaimers. If the information cannot be found or determined with confidence, clearly state that you don't know rather than providing uncertain information."""
|
| 465 |
|
| 466 |
def _handle_tool_call(self, tool_calls):
|
| 467 |
results = []
|
|
|
|
| 563 |
"""Run the agent on a question and return the answer."""
|
| 564 |
# Add context about any files if provided
|
| 565 |
if context and "file_path" in context:
|
| 566 |
+
file_path = context.get("file_path", "")
|
| 567 |
+
file_name = context.get("file_name", "")
|
| 568 |
+
|
| 569 |
+
# Try to determine the file type
|
| 570 |
+
file_extension = file_path.lower().split(".")[-1] if "." in file_path else ""
|
| 571 |
+
|
| 572 |
+
if file_extension in ["xlsx", "xls", "csv"]:
|
| 573 |
+
question += f"\n\nAttached file information: {file_name} (Excel/spreadsheet file)"
|
| 574 |
+
question += f"\nYou can analyze this spreadsheet using the analyze_excel tool with the path: {file_path}"
|
| 575 |
+
question += f"\nFor example: analyze_excel('{file_path}', 'What is the total sales?')"
|
| 576 |
+
else:
|
| 577 |
+
question += f"\n\nAttached file information: {file_name}"
|
| 578 |
+
question += f"\nYou can access this file using the read_file tool with the path: {file_path}"
|
| 579 |
|
| 580 |
messages = [
|
| 581 |
{"role": "system", "content": self.system_message},
|
| 582 |
{"role": "user", "content": question}
|
| 583 |
]
|
| 584 |
|
| 585 |
+
max_steps = 10 # Increased the number of iterations for more complex questions
|
| 586 |
|
| 587 |
for step in range(max_steps):
|
| 588 |
print(f"Step {step+1}/{max_steps}")
|