iamdimadem commited on
Commit
38ac685
·
1 Parent(s): 81917a3

add: playwright

Browse files
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .env
2
+ *.pyc
.vscode/settings.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "python.testing.pytestArgs": [
3
+ "."
4
+ ],
5
+ "python.testing.unittestEnabled": false,
6
+ "python.testing.pytestEnabled": true
7
+ }
agent/__init__.py ADDED
File without changes
agent/agent.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from smolagents import CodeAgent, LiteLLMModel, ToolCollection, MCPClient, PythonInterpreterTool
3
+ from .tools.PlaywrightMCP import PlaywrightMCP
4
+
5
+ ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
6
+
7
+ def create_agent():
8
+ model = LiteLLMModel(
9
+ model_id="claude-sonnet-4-20250514",
10
+ api_key=ANTHROPIC_API_KEY,
11
+ )
12
+
13
+ # Передаем API ключ в PlaywrightMCP для анализа изображений
14
+ pw_mcp = PlaywrightMCP(anthropic_api_key=ANTHROPIC_API_KEY)
15
+ available_tools = pw_mcp.get_tools()
16
+
17
+ available_tools.append(PythonInterpreterTool())
18
+
19
+ agent = CodeAgent(
20
+ tools=available_tools,
21
+ model=model,
22
+ add_base_tools=False
23
+ )
24
+
25
+ agent._pw_mcp = pw_mcp
26
+
27
+ return agent
28
+
29
+ def cleanup_agent(agent):
30
+ if hasattr(agent, '_pw_mcp'):
31
+ agent._pw_mcp.disconnect()
agent/tools/ImageViewTool.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import Tool
2
+ from mcp.types import ImageContent
3
+ import base64
4
+ import os
5
+ import tempfile
6
+ from datetime import datetime
7
+
8
+ class ImageViewTool(Tool):
9
+ name = "image_view"
10
+ description = "Save and prepare images for analysis by the AI model"
11
+ inputs = {
12
+ "image_content": {
13
+ "type": "any",
14
+ "description": "ImageContent object from browser_screen_capture"
15
+ },
16
+ "filename": {
17
+ "type": "string",
18
+ "description": "Optional filename for the saved image",
19
+ "default": None,
20
+ "nullable": True
21
+ }
22
+ }
23
+ output_type = "string"
24
+
25
+ def forward(self, image_content, filename=None):
26
+ """
27
+ Сохраняет изображение в временную папку и возвращает путь.
28
+ Модель Claude может анализировать изображения по пути.
29
+ """
30
+ try:
31
+ # Проверяем, что получили ImageContent или извлекаем его из результата
32
+ if hasattr(image_content, '__iter__') and not isinstance(image_content, (str, bytes)):
33
+ # Если это список или кортеж, берем первый элемент
34
+ for item in image_content:
35
+ if isinstance(item, ImageContent):
36
+ image_content = item
37
+ break
38
+
39
+ if not isinstance(image_content, ImageContent):
40
+ return f"Expected ImageContent object, got: {type(image_content)}"
41
+
42
+ # Создаем имя файла
43
+ if not filename:
44
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
45
+ filename = f"screenshot_{timestamp}.png"
46
+
47
+ # Создаем временную папку если её нет
48
+ temp_dir = os.path.join(tempfile.gettempdir(), "agent_screenshots")
49
+ os.makedirs(temp_dir, exist_ok=True)
50
+
51
+ # Полный путь к файлу
52
+ filepath = os.path.join(temp_dir, filename)
53
+
54
+ # Декодируем base64 и сохраняем файл
55
+ image_data = base64.b64decode(image_content.data)
56
+ with open(filepath, 'wb') as f:
57
+ f.write(image_data)
58
+
59
+ return f"Image saved to: {filepath}\n\nYou can now analyze this image. The image shows a screenshot that was captured."
60
+
61
+ except Exception as e:
62
+ return f"Error saving image: {str(e)}"
agent/tools/PlaywrightMCP.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from mcp import StdioServerParameters
3
+ from smolagents import MCPClient
4
+
5
+ class PlaywrightMCP:
6
+ def __init__(self):
7
+ self.client = None
8
+ self.tools = []
9
+
10
+ def init(self):
11
+ server_parameters = StdioServerParameters(
12
+ command="npx",
13
+ args=["@playwright/mcp@latest"],
14
+ env=os.environ,
15
+ )
16
+
17
+ self.client = MCPClient(server_parameters)
18
+ self.tools = self.client.get_tools()
19
+ return self.tools
20
+
21
+ def get_tools(self):
22
+ if not self.tools:
23
+ return self.init()
24
+ return self.tools
25
+
26
+ def disconnect(self):
27
+ if self.client:
28
+ self.client.disconnect()
29
+ self.client = None
30
+ self.tools = []
agent/tools/__init__.py ADDED
File without changes
app.py CHANGED
@@ -3,6 +3,8 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
@@ -15,9 +17,18 @@ class BasicAgent:
15
  print("BasicAgent initialized.")
16
  def __call__(self, question: str) -> str:
17
  print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ # --- Imports ---
7
+ from agent.agent import create_agent, cleanup_agent
8
 
9
  # (Keep Constants as is)
10
  # --- Constants ---
 
17
  print("BasicAgent initialized.")
18
  def __call__(self, question: str) -> str:
19
  print(f"Agent received question (first 50 chars): {question[:50]}...")
20
+ agent = None
21
+ try:
22
+ agent = create_agent()
23
+ response = agent.run(question)
24
+ print(f"Agent returned response: {response}")
25
+ return response
26
+ except Exception as e:
27
+ print(f"Error in BasicAgent call: {e}")
28
+ return f"Error processing question: {e}"
29
+ finally:
30
+ if agent:
31
+ cleanup_agent(agent)
32
 
33
  def run_and_submit_all( profile: gr.OAuthProfile | None):
34
  """
dev.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Activate your virtual environment if needed
4
+ # source venv/bin/activate
5
+
6
+ # Run the Python app
7
+ . .venv/bin/activate && python app.py
requirements.txt CHANGED
@@ -1,2 +1,7 @@
1
  gradio
2
- requests
 
 
 
 
 
 
1
  gradio
2
+ gradio[oauth]
3
+ smolagents
4
+ smolagents[litellm]
5
+ smolagents[mcp]
6
+ requests
7
+ mcp