final_agent / agent /tools /ImageViewTool.py
iamdimadem's picture
add: playwright
38ac685
Raw History Blame Contribute Delete
2.64 kB
from smolagents import Tool
from mcp.types import ImageContent
import base64
import os
import tempfile
from datetime import datetime
class ImageViewTool(Tool):
name = "image_view"
description = "Save and prepare images for analysis by the AI model"
inputs = {
"image_content": {
"type": "any",
"description": "ImageContent object from browser_screen_capture"
},
"filename": {
"type": "string",
"description": "Optional filename for the saved image",
"default": None,
"nullable": True
}
}
output_type = "string"
def forward(self, image_content, filename=None):
"""
Сохраняет изображение в временную папку и возвращает путь.
Модель Claude может анализировать изображения по пути.
"""
try:
# Проверяем, что получили ImageContent или извлекаем его из результата
if hasattr(image_content, '__iter__') and not isinstance(image_content, (str, bytes)):
# Если это список или кортеж, берем первый элемент
for item in image_content:
if isinstance(item, ImageContent):
image_content = item
break
if not isinstance(image_content, ImageContent):
return f"Expected ImageContent object, got: {type(image_content)}"
# Создаем имя файла
if not filename:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"screenshot_{timestamp}.png"
# Создаем временную папку если её нет
temp_dir = os.path.join(tempfile.gettempdir(), "agent_screenshots")
os.makedirs(temp_dir, exist_ok=True)
# Полный путь к файлу
filepath = os.path.join(temp_dir, filename)
# Декодируем base64 и сохраняем файл
image_data = base64.b64decode(image_content.data)
with open(filepath, 'wb') as f:
f.write(image_data)
return f"Image saved to: {filepath}\n\nYou can now analyze this image. The image shows a screenshot that was captured."
except Exception as e:
return f"Error saving image: {str(e)}"