m-ric HF Staff commited on
Commit
4208d01
·
2 Parent(s): db2c7c1 53c4545

Merge branch 'main' of https://huggingface.co/spaces/smolagents/computer-agent

Browse files
Files changed (2) hide show
  1. app.py +10 -2
  2. e2bqwen.py +106 -50
app.py CHANGED
@@ -355,6 +355,14 @@ def cleanup_sandboxes():
355
 
356
  def get_or_create_sandbox(session_hash):
357
  current_time = time.time()
 
 
 
 
 
 
 
 
358
 
359
  # Check if sandbox exists and is still valid
360
  if (session_hash in SANDBOXES and
@@ -553,7 +561,7 @@ with gr.Blocks(theme=theme, css=custom_css, js=custom_js) as demo:
553
  )
554
  with gr.Sidebar(position="left"):
555
  task_input = gr.Textbox(
556
- value="Find picture of cute puppies",
557
  label="Enter your task below:",
558
  elem_classes="primary-color-label"
559
  )
@@ -565,7 +573,7 @@ with gr.Blocks(theme=theme, css=custom_css, js=custom_js) as demo:
565
  "Check the commuting time between Bern and Zurich on Google maps",
566
  "Write 'Hello World' in a text editor",
567
  "Search a flight Paris - Berlin for tomorrow",
568
- "Could you head to Fontainebleau (France) in Google Maps then drag and drop to position the castle of Fontainebleau exactly in the center?",
569
  "Download me a picture of a puppy from Google, then head to Hugging Face, find a Space dedicated to background removal, and use it to remove the puppy picture's background"
570
  ],
571
  inputs = task_input,
 
355
 
356
  def get_or_create_sandbox(session_hash):
357
  current_time = time.time()
358
+ print("======")
359
+ print(":=======")
360
+ print("Session hash:", session_hash)
361
+ print("Sandboxes:", SANDBOXES.keys())
362
+ print("Session hash in SANDBOXES:", session_hash in SANDBOXES)
363
+ print("Session hash in SANDBOX_METADATA:", session_hash in SANDBOX_METADATA)
364
+ if session_hash in SANDBOX_METADATA:
365
+ print("Session not timeout:", current_time - SANDBOX_METADATA[session_hash]['created_at'] < SANDBOX_TIMEOUT)
366
 
367
  # Check if sandbox exists and is still valid
368
  if (session_hash in SANDBOXES and
 
561
  )
562
  with gr.Sidebar(position="left"):
563
  task_input = gr.Textbox(
564
+ value="Download a picture of a cute puppy",
565
  label="Enter your task below:",
566
  elem_classes="primary-color-label"
567
  )
 
573
  "Check the commuting time between Bern and Zurich on Google maps",
574
  "Write 'Hello World' in a text editor",
575
  "Search a flight Paris - Berlin for tomorrow",
576
+ "Could you head to Fontainebleau (France) in Google Maps, and get me the name of the pond just south of the castle?",
577
  "Download me a picture of a puppy from Google, then head to Hugging Face, find a Space dedicated to background removal, and use it to remove the puppy picture's background"
578
  ],
579
  inputs = task_input,
e2bqwen.py CHANGED
@@ -22,6 +22,23 @@ from smolagents.agent_types import AgentImage
22
  from PIL import ImageDraw
23
 
24
  E2B_SYSTEM_PROMPT_TEMPLATE = """You are a desktop automation assistant that can control a remote desktop environment.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  On top of performing computations in the Python code snippets that you create, you only have access to these tools to interact with the desktop, no additional ones:
26
  {%- for tool in tools.values() %}
27
  - {{ tool.name }}: {{ tool.description }}
@@ -30,68 +47,105 @@ On top of performing computations in the Python code snippets that you create, y
30
  {%- endfor %}
31
 
32
  The desktop has a resolution of <<resolution_x>>x<<resolution_y>>, take it into account to decide clicking coordinates.
 
 
 
33
 
34
- IMPORTANT:
35
- - Remember the tools that you have as those can save you time, for example open_url to enter a website rather than searching for the browser in the OS.
36
- - Whenever you click, MAKE SURE to click in the middle of the button, text, link or any other clickable element. Not under, not on the side. IN THE MIDDLE. In menus it is always better to click in the middle of the text rather than in the tiny icon. Calculate extremelly well the coordinates. A mistake here can make the full task fail.
37
- - To navigate the desktop you should open menus and click. Menus usually expand with more options, the tiny triangle next to some text in a menu means that menu expands. For example in Office in the Applications menu expands showing presentation or writing applications.
38
- - Always analyze the latest screenshot carefully before performing actions. If you clicked somewhere in the previous action, a red crosshair will appear at the exact click location: if nothing happened, check that this location is exactly where you intended to click. Otherwise correct the click coordinates.
39
-
40
- You must proceed step by step:
41
- 1. Understand the task thoroughly
42
- 2. Break down the task into logical steps
43
- 3. For each step:
44
- a. Analyze the current screenshot to identify UI elements
45
- b. Plan the appropriate action with precise coordinates
46
- c. Execute ONE action at a time using the proper tool
47
- d. Wait for the action to complete before proceeding
48
-
49
- After each action, you'll receive an updated screenshot. Review it carefully before your next action.
50
-
51
- COMMAND FORMAT:
52
- Always format your actions as Python code blocks. For example:
53
-
54
  ```python
55
  click(250, 300)
56
  ```<end_code>
 
57
 
58
-
59
- TASK EXAMPLE:
60
  For a task like "Open a text editor and type 'Hello World'":
61
- 1- First, analyze the screenshot to find the Applications menu and click on it being very precise, clicking in the middle of the text 'Applications':
 
 
 
 
 
 
62
  ```python
63
  click(50, 10)
64
  ```<end_code>
65
- 2- Remembering that menus are navigated through clicking, after analyzing the screenshot with the applications menu open we see that a notes application probably fits in the Accessories section (we see it is a section in the menu thanks to the tiny white triangle after the text accessories). We look for Accessories and click on it being very precise, clicking in the middle of the text 'Accessories'. DO NOT try to move through the menus with scroll, it won't work:
 
 
 
 
 
 
 
66
  ```python
67
  click(76, 195)
68
  ```<end_code>
69
- 3- Remembering that menus are navigated through clicking, after analyzing the screenshot with the submenu Accessories open, look for 'Text Editor' and click on it being very precise, clicking in the middle of the text 'Text Editor':
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  ```python
71
  click(241, 441)
72
  ```<end_code>
73
- 4- Once Notepad is open, type the requested text:
 
 
 
 
 
 
 
74
  ```python
75
  type_text("Hello World")
76
  ```<end_code>
77
 
78
- 5- Task is completed:
 
 
 
 
 
 
79
  ```python
80
  final_answer("Done")
81
  ```<end_code>
82
-
83
- Remember to:
84
- Always wait for appropriate loading times
 
 
 
 
 
 
 
 
 
85
  Use precise coordinates based on the current screenshot
86
- Execute one action at a time
87
  On each step, look at the last screenshot and action to validate if previous steps worked and decide the next action. If you repeated an action already without effect, it means that this action is useless: don't repeat it and try something else.
88
  Use click to move through menus on the desktop and scroll for web and specific applications.
89
- When clicking an element, always make sure to click THE MIDDLE of that element! Else you risk to miss it.
90
  Always analyze the latest screenshot carefully before performing actions. Make sure to:
91
- 1. Look at elements on the screen to determine what to click or interact with
92
- 2. Use precise coordinates for mouse movements and clicks
93
- 3. You can wait for page loads or animations to complete using the wait() tool
94
- 4. Sometimes you may have missed a click, so never assume that you're on the right page, always make sure that your previous action worked. In the screenshot you can see if the mouse is out of the clickable area. Pay special attention to this.
95
  """
96
 
97
  def draw_marker_on_image(image, click_coordinates):
@@ -162,9 +216,8 @@ class E2BVisionAgent(CodeAgent):
162
  """
163
  self.desktop.move_mouse(x, y)
164
  self.desktop.left_click()
 
165
  self.logger.log(f"Clicked at coordinates ({x}, {y})")
166
- self.memory.steps[-1].click_coordinates = [x, y]
167
- print("FLAGG", self.memory.steps[-1])
168
  return f"Clicked at coordinates ({x}, {y})"
169
 
170
  @tool
@@ -177,8 +230,8 @@ class E2BVisionAgent(CodeAgent):
177
  """
178
  self.desktop.move_mouse(x, y)
179
  self.desktop.right_click()
 
180
  self.logger.log(f"Right-clicked at coordinates ({x}, {y})")
181
- self.memory.steps[-1].click_coordinates = [x, y]
182
  return f"Right-clicked at coordinates ({x}, {y})"
183
 
184
  @tool
@@ -191,8 +244,8 @@ class E2BVisionAgent(CodeAgent):
191
  """
192
  self.desktop.move_mouse(x, y)
193
  self.desktop.double_click()
 
194
  self.logger.log(f"Double-clicked at coordinates ({x}, {y})")
195
- self.memory.steps[-1].click_coordinates = [x, y]
196
  return f"Double-clicked at coordinates ({x}, {y})"
197
 
198
  @tool
@@ -320,6 +373,17 @@ class E2BVisionAgent(CodeAgent):
320
  screenshot_bytes = self.desktop.screenshot()
321
  image = Image.open(BytesIO(screenshot_bytes))
322
 
 
 
 
 
 
 
 
 
 
 
 
323
  # Create a filename with step number
324
  screenshot_path = os.path.join(self.data_dir, f"step_{current_step:03d}.png")
325
  image.save(screenshot_path)
@@ -334,22 +398,14 @@ class E2BVisionAgent(CodeAgent):
334
  and previous_memory_step.step_number <= current_step - 2
335
  ):
336
  previous_memory_step.observations_images = None
337
- if (
338
- isinstance(previous_memory_step, ActionStep)
339
- and previous_memory_step.step_number == current_step - 1
340
- and hasattr(memory_step, "click_coordinates")
341
- ):
342
- print("Drawing cross on previous step image")
343
- draw_marker_on_image(previous_memory_step.observations_images[0], memory_step.click_coordinates)
344
-
345
- if hasattr(memory_step, "click_coordinates"):
346
- draw_marker_on_image(image, memory_step.click_coordinates)
347
 
348
  # Add to the current memory step
349
  memory_step.observations_images = [image.copy()]
350
 
351
  # memory_step.observations_images = [screenshot_path] # IF YOU USE THIS INSTEAD OF ABOVE, LAUNCHING A SECOND TASK BREAKS
352
 
 
 
353
 
354
  def close(self):
355
  """Clean up resources"""
 
22
  from PIL import ImageDraw
23
 
24
  E2B_SYSTEM_PROMPT_TEMPLATE = """You are a desktop automation assistant that can control a remote desktop environment.
25
+ <action process>
26
+ You willbe given a task to solve in several steps. At each step you will perform an action.
27
+ After each action, you'll receive an updated screenshot.
28
+ Then you will proceed as follows, with these sections: don't skip any!
29
+
30
+ Short term goal: ...
31
+ Where I am: ...
32
+ What I see: ...
33
+ Reflection: ...
34
+ Action: ...
35
+ Code:
36
+ ```python
37
+ click(250, 300)
38
+ ```<end_code>
39
+ </action_process>
40
+
41
+ <tools>
42
  On top of performing computations in the Python code snippets that you create, you only have access to these tools to interact with the desktop, no additional ones:
43
  {%- for tool in tools.values() %}
44
  - {{ tool.name }}: {{ tool.description }}
 
47
  {%- endfor %}
48
 
49
  The desktop has a resolution of <<resolution_x>>x<<resolution_y>>, take it into account to decide clicking coordinates.
50
+ If you clicked somewhere in the previous action, a red crosshair will appear at the exact location of the previous click.
51
+ The image might have change since then but the cross stays at the previous click. If your click seems to have changed nothing, check that this location is exactly where you intended to click. Otherwise correct the click coordinates.
52
+ </tools>
53
 
54
+ <code_format>
55
+ Always format your actions as Python code blocks, as shown below:
56
+ Code:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  ```python
58
  click(250, 300)
59
  ```<end_code>
60
+ </code_format>
61
 
62
+ <task_resolution_example>
 
63
  For a task like "Open a text editor and type 'Hello World'":
64
+ Step 1:
65
+ Short term goal: I want to open a text editor.
66
+ Where I am: I am on the homepage of my desktop.
67
+ What I see: I see the applications
68
+ Reflection: I think that a notes application would fit in the Applications menu, let's open it.
69
+ Action: I'll click it, carefully clicking in the middle of the text 'Applications'/
70
+ Code:
71
  ```python
72
  click(50, 10)
73
  ```<end_code>
74
+
75
+ Step 2:
76
+ Short term goal: I want to open a text editor.
77
+ Where I am: I am on the homepage of my desktop, with the applications menu open.
78
+ What I see: I see an Accessories section, I see it is a section in the menu thanks to the tiny white triangle after the text accessories.
79
+ Reflection: I think that a notes application would fit the Accessories section. I SHOULD NOT try to move through the menus with scroll, it won't work:.
80
+ Action: I'll look for Accessories and click on it being very precise, clicking in the middle of the text 'Accessories'.
81
+ Code:
82
  ```python
83
  click(76, 195)
84
  ```<end_code>
85
+
86
+ Step 3:
87
+ Short term goal: I want to open a text editor.
88
+ Where I am: I am under the Accessories menu.
89
+ What I see: under the open submenu Accessories, I've found 'Text Editor'.
90
+ Reflection: This must be my notes app. I remember that menus are navigated through clicking.
91
+ Action: I will now click on it being very precise, clicking in the middle of the text 'Text Editor'.
92
+ Code:
93
+ ```python
94
+ click(251, 441)
95
+ ```<end_code>
96
+
97
+ Step 4:
98
+ Short term goal: I want to open a text editor.
99
+ Where I am: I am still under the Accessories menu.
100
+ What I see: Nothing has changed compared to previous screenshot. Under the open submenu Accessories, I still see 'Text Editor'. The red crosshair is off from the element.
101
+ Reflection: My last click must have been off. Let's correct this.
102
+ Action: I will click the correct place, right in the middle of the element.
103
+ Code:
104
  ```python
105
  click(241, 441)
106
  ```<end_code>
107
+
108
+ Step 5:
109
+ Short term goal: I want to type 'Hello World'.
110
+ Where I am: I have opened a Notepad.
111
+ What I see: The Notepad app is open on an empty page
112
+ Reflection: Now Notepad is open as intended, time to type text.
113
+ Action: I will type the requested text.
114
+ Code:
115
  ```python
116
  type_text("Hello World")
117
  ```<end_code>
118
 
119
+ Step 6:
120
+ Short term goal: I want to type 'Hello World'.
121
+ Where I am: I have opened a Notepad.
122
+ What I see: The Notepad app displays 'Hello World'
123
+ Reflection: Now that I've 1. Opened the notepad and 2. typed 'Hello World', and 3. the result seems correct, I think the Task is completed.
124
+ Action: I will return a confirmation that the task is completed.
125
+ Code:
126
  ```python
127
  final_answer("Done")
128
  ```<end_code>
129
+ </task_resolution_example>
130
+
131
+ <click_guidelines>
132
+ Look at elements on the screen to determine what to click or interact with.
133
+ Use precise coordinates for mouse movements and clicks. When clicking an element, ALWAYS CLICK THE MIDDLE of that element, not UNDER OR ABOVE! Else you risk to miss it.
134
+ Sometimes you may have missed a click, so never assume that you're on the right page, always make sure that your previous action worked. In the screenshot you can see if the mouse is out of the clickable area. Pay special attention to this.
135
+ Remember the tools that you have as those can save you time, for example open_url to enter a website rather than searching for the browser in the OS.
136
+ Whenever you click, MAKE SURE to click in the middle of the button, text, link or any other clickable element. Not under, not on the side. IN THE MIDDLE. In menus it is always better to click in the middle of the text rather than in the tiny icon. Calculate extremelly well the coordinates. A mistake here can make the full task fail.
137
+ </click_guidelines>
138
+
139
+ <general_guidelines>
140
+ You can wait for appropriate loading times using the wait() tool. But don't wait forever, sometimes you've just misclicked and the process didn't launch.
141
  Use precise coordinates based on the current screenshot
142
+ Execute one action at a time: don't try to pack a click and typing in one action.
143
  On each step, look at the last screenshot and action to validate if previous steps worked and decide the next action. If you repeated an action already without effect, it means that this action is useless: don't repeat it and try something else.
144
  Use click to move through menus on the desktop and scroll for web and specific applications.
 
145
  Always analyze the latest screenshot carefully before performing actions. Make sure to:
146
+ To navigate the desktop you should open menus and click. Menus usually expand with more options, the tiny triangle next to some text in a menu means that menu expands. For example in Office in the Applications menu expands showing presentation or writing applications.
147
+ Always analyze the latest screenshot carefully before performing actions.
148
+ </general_guidelines>
 
149
  """
150
 
151
  def draw_marker_on_image(image, click_coordinates):
 
216
  """
217
  self.desktop.move_mouse(x, y)
218
  self.desktop.left_click()
219
+ self.click_coordinates = [x, y]
220
  self.logger.log(f"Clicked at coordinates ({x}, {y})")
 
 
221
  return f"Clicked at coordinates ({x}, {y})"
222
 
223
  @tool
 
230
  """
231
  self.desktop.move_mouse(x, y)
232
  self.desktop.right_click()
233
+ self.click_coordinates = [x, y]
234
  self.logger.log(f"Right-clicked at coordinates ({x}, {y})")
 
235
  return f"Right-clicked at coordinates ({x}, {y})"
236
 
237
  @tool
 
244
  """
245
  self.desktop.move_mouse(x, y)
246
  self.desktop.double_click()
247
+ self.click_coordinates = [x, y]
248
  self.logger.log(f"Double-clicked at coordinates ({x}, {y})")
 
249
  return f"Double-clicked at coordinates ({x}, {y})"
250
 
251
  @tool
 
373
  screenshot_bytes = self.desktop.screenshot()
374
  image = Image.open(BytesIO(screenshot_bytes))
375
 
376
+ if getattr(self, "click_coordinates", None):
377
+ # If a click was performed in the last action, mark it on the image
378
+ x, y = self.click_coordinates
379
+ draw = ImageDraw.Draw(image)
380
+ cross_size, linewidth = 10, 3
381
+ # Draw red cross lines
382
+ draw.line((x - cross_size, y, x + cross_size, y), fill="red", width=linewidth)
383
+ draw.line((x, y - cross_size, x, y + cross_size), fill="red", width=linewidth)
384
+ # Add a circle around it for better visibility
385
+ draw.ellipse((x - cross_size * 2, y - cross_size * 2, x + cross_size * 2, y + cross_size * 2), outline="red", width=linewidth)
386
+
387
  # Create a filename with step number
388
  screenshot_path = os.path.join(self.data_dir, f"step_{current_step:03d}.png")
389
  image.save(screenshot_path)
 
398
  and previous_memory_step.step_number <= current_step - 2
399
  ):
400
  previous_memory_step.observations_images = None
 
 
 
 
 
 
 
 
 
 
401
 
402
  # Add to the current memory step
403
  memory_step.observations_images = [image.copy()]
404
 
405
  # memory_step.observations_images = [screenshot_path] # IF YOU USE THIS INSTEAD OF ABOVE, LAUNCHING A SECOND TASK BREAKS
406
 
407
+ self.click_coordinates = None # Reset click marker
408
+
409
 
410
  def close(self):
411
  """Clean up resources"""