makeitfr commited on
Commit
895e50d
·
verified ·
1 Parent(s): 0162498

Upload OmniParser/omnitool/gradio/agent/vlm_agent_with_orchestrator.py with huggingface_hub

Browse files
OmniParser/omnitool/gradio/agent/vlm_agent_with_orchestrator.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from collections.abc import Callable
3
+ from typing import cast, Callable
4
+ import uuid
5
+ from PIL import Image, ImageDraw
6
+ import base64
7
+ from io import BytesIO
8
+ import copy
9
+ from pathlib import Path
10
+ from datetime import datetime
11
+ from anthropic import APIResponse
12
+ from anthropic.types import ToolResultBlockParam
13
+ from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock, BetaMessageParam, BetaUsage
14
+
15
+ from agent.llm_utils.oaiclient import run_oai_interleaved
16
+ from agent.llm_utils.groqclient import run_groq_interleaved
17
+ from agent.llm_utils.utils import is_image_path
18
+ import time
19
+ import re
20
+ import os
21
+ OUTPUT_DIR = "./tmp/outputs"
22
+ ORCHESTRATOR_LEDGER_PROMPT = """
23
+ Recall we are working on the following request:
24
+
25
+ {task}
26
+
27
+ To make progress on the request, please answer the following questions, including necessary reasoning:
28
+
29
+ - Is the request fully satisfied? (True if complete, or False if the original request has yet to be SUCCESSFULLY and FULLY addressed)
30
+ - Are we in a loop where we are repeating the same requests and / or getting the same responses as before? Loops can span multiple turns, and can include repeated actions like scrolling up or down more than a handful of times.
31
+ - Are we making forward progress? (True if just starting, or recent messages are adding value. False if recent messages show evidence of being stuck in a loop or if there is evidence of significant barriers to success such as the inability to read from a required file)
32
+ - What instruction or question would you give in order to complete the task?
33
+
34
+ Please output an answer in pure JSON format according to the following schema. The JSON object must be parsable as-is. DO NOT OUTPUT ANYTHING OTHER THAN JSON, AND DO NOT DEVIATE FROM THIS SCHEMA:
35
+
36
+ {{
37
+ "is_request_satisfied": {{
38
+ "reason": string,
39
+ "answer": boolean
40
+ }},
41
+ "is_in_loop": {{
42
+ "reason": string,
43
+ "answer": boolean
44
+ }},
45
+ "is_progress_being_made": {{
46
+ "reason": string,
47
+ "answer": boolean
48
+ }},
49
+ "instruction_or_question": {{
50
+ "reason": string,
51
+ "answer": string
52
+ }}
53
+ }}
54
+ """
55
+
56
+ def extract_data(input_string, data_type):
57
+ # Regular expression to extract content starting from '```python' until the end if there are no closing backticks
58
+ pattern = f"```{data_type}" + r"(.*?)(```|$)"
59
+ # Extract content
60
+ # re.DOTALL allows '.' to match newlines as well
61
+ matches = re.findall(pattern, input_string, re.DOTALL)
62
+ # Return the first match if exists, trimming whitespace and ignoring potential closing backticks
63
+ return matches[0][0].strip() if matches else input_string
64
+
65
+ class VLMOrchestratedAgent:
66
+ def __init__(
67
+ self,
68
+ model: str,
69
+ provider: str,
70
+ api_key: str,
71
+ output_callback: Callable,
72
+ api_response_callback: Callable,
73
+ max_tokens: int = 4096,
74
+ only_n_most_recent_images: int | None = None,
75
+ print_usage: bool = True,
76
+ save_folder: str = None,
77
+ ):
78
+ if model == "omniparser + gpt-4o" or model == "omniparser + gpt-4o-orchestrated":
79
+ self.model = "gpt-4o-2024-11-20"
80
+ elif model == "omniparser + R1" or model == "omniparser + R1-orchestrated":
81
+ self.model = "deepseek-r1-distill-llama-70b"
82
+ elif model == "omniparser + qwen2.5vl" or model == "omniparser + qwen2.5vl-orchestrated":
83
+ self.model = "qwen2.5-vl-72b-instruct"
84
+ elif model == "omniparser + o1" or model == "omniparser + o1-orchestrated":
85
+ self.model = "o1"
86
+ elif model == "omniparser + o3-mini" or model == "omniparser + o3-mini-orchestrated":
87
+ self.model = "o3-mini"
88
+ else:
89
+ raise ValueError(f"Model {model} not supported")
90
+
91
+
92
+ self.provider = provider
93
+ self.api_key = api_key
94
+ self.api_response_callback = api_response_callback
95
+ self.max_tokens = max_tokens
96
+ self.only_n_most_recent_images = only_n_most_recent_images
97
+ self.output_callback = output_callback
98
+ self.save_folder = save_folder
99
+
100
+ self.print_usage = print_usage
101
+ self.total_token_usage = 0
102
+ self.total_cost = 0
103
+ self.step_count = 0
104
+ self.plan, self.ledger = None, None
105
+
106
+ self.system = ''
107
+
108
+ def __call__(self, messages: list, parsed_screen: list[str, list, dict]):
109
+ if self.step_count == 0:
110
+ plan = self._initialize_task(messages)
111
+ self.output_callback(f'-- Plan: {plan} --', )
112
+ # update messages with the plan
113
+ messages.append({"role": "assistant", "content": plan})
114
+ else:
115
+ updated_ledger = self._update_ledger(messages)
116
+ self.output_callback(
117
+ f'<details>'
118
+ f' <summary><strong>Task Progress Ledger (click to expand)</strong></summary>'
119
+ f' <div style="padding: 10px; background-color: #f8f9fa; border-radius: 5px; margin-top: 5px;">'
120
+ f' <pre>{updated_ledger}</pre>'
121
+ f' </div>'
122
+ f'</details>',
123
+ )
124
+ # update messages with the ledger
125
+ messages.append({"role": "assistant", "content": updated_ledger})
126
+ self.ledger = updated_ledger
127
+
128
+ self.step_count += 1
129
+ # save the image to the output folder
130
+ with open(f"{self.save_folder}/screenshot_{self.step_count}.png", "wb") as f:
131
+ f.write(base64.b64decode(parsed_screen['original_screenshot_base64']))
132
+ with open(f"{self.save_folder}/som_screenshot_{self.step_count}.png", "wb") as f:
133
+ f.write(base64.b64decode(parsed_screen['som_image_base64']))
134
+
135
+ latency_omniparser = parsed_screen['latency']
136
+ screen_info = str(parsed_screen['screen_info'])
137
+ screenshot_uuid = parsed_screen['screenshot_uuid']
138
+ screen_width, screen_height = parsed_screen['width'], parsed_screen['height']
139
+
140
+ boxids_and_labels = parsed_screen["screen_info"]
141
+ system = self._get_system_prompt(boxids_and_labels)
142
+
143
+ # drop looping actions msg, byte image etc
144
+ planner_messages = messages
145
+ _remove_som_images(planner_messages)
146
+ _maybe_filter_to_n_most_recent_images(planner_messages, self.only_n_most_recent_images)
147
+
148
+ if isinstance(planner_messages[-1], dict):
149
+ if not isinstance(planner_messages[-1]["content"], list):
150
+ planner_messages[-1]["content"] = [planner_messages[-1]["content"]]
151
+ planner_messages[-1]["content"].append(f"{OUTPUT_DIR}/screenshot_{screenshot_uuid}.png")
152
+ planner_messages[-1]["content"].append(f"{OUTPUT_DIR}/screenshot_som_{screenshot_uuid}.png")
153
+
154
+ start = time.time()
155
+ if "gpt" in self.model or "o1" in self.model or "o3-mini" in self.model:
156
+ vlm_response, token_usage = run_oai_interleaved(
157
+ messages=planner_messages,
158
+ system=system,
159
+ model_name=self.model,
160
+ api_key=self.api_key,
161
+ max_tokens=self.max_tokens,
162
+ provider_base_url="https://api.openai.com/v1",
163
+ temperature=0,
164
+ )
165
+ print(f"oai token usage: {token_usage}")
166
+ self.total_token_usage += token_usage
167
+ if 'gpt' in self.model:
168
+ self.total_cost += (token_usage * 2.5 / 1000000) # https://openai.com/api/pricing/
169
+ elif 'o1' in self.model:
170
+ self.total_cost += (token_usage * 15 / 1000000) # https://openai.com/api/pricing/
171
+ elif 'o3-mini' in self.model:
172
+ self.total_cost += (token_usage * 1.1 / 1000000) # https://openai.com/api/pricing/
173
+ elif "r1" in self.model:
174
+ vlm_response, token_usage = run_groq_interleaved(
175
+ messages=planner_messages,
176
+ system=system,
177
+ model_name=self.model,
178
+ api_key=self.api_key,
179
+ max_tokens=self.max_tokens,
180
+ )
181
+ print(f"groq token usage: {token_usage}")
182
+ self.total_token_usage += token_usage
183
+ self.total_cost += (token_usage * 0.99 / 1000000)
184
+ elif "qwen" in self.model:
185
+ vlm_response, token_usage = run_oai_interleaved(
186
+ messages=planner_messages,
187
+ system=system,
188
+ model_name=self.model,
189
+ api_key=self.api_key,
190
+ max_tokens=min(2048, self.max_tokens),
191
+ provider_base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
192
+ temperature=0,
193
+ )
194
+ print(f"qwen token usage: {token_usage}")
195
+ self.total_token_usage += token_usage
196
+ self.total_cost += (token_usage * 2.2 / 1000000) # https://help.aliyun.com/zh/model-studio/getting-started/models?spm=a2c4g.11186623.0.0.74b04823CGnPv7#fe96cfb1a422a
197
+ else:
198
+ raise ValueError(f"Model {self.model} not supported")
199
+ latency_vlm = time.time() - start
200
+
201
+ # Update step counter with both latencies
202
+ self.output_callback(f'<i>Step {self.step_count} | OmniParser: {latency_omniparser:.2f}s | LLM: {latency_vlm:.2f}s</i>', )
203
+
204
+ print(f"{vlm_response}")
205
+
206
+ if self.print_usage:
207
+ print(f"Total token so far: {self.total_token_usage}. Total cost so far: $USD{self.total_cost:.5f}")
208
+
209
+ vlm_response_json = extract_data(vlm_response, "json")
210
+ vlm_response_json = json.loads(vlm_response_json)
211
+
212
+ img_to_show_base64 = parsed_screen["som_image_base64"]
213
+ if "Box ID" in vlm_response_json:
214
+ try:
215
+ bbox = parsed_screen["parsed_content_list"][int(vlm_response_json["Box ID"])]["bbox"]
216
+ vlm_response_json["box_centroid_coordinate"] = [int((bbox[0] + bbox[2]) / 2 * screen_width), int((bbox[1] + bbox[3]) / 2 * screen_height)]
217
+ img_to_show_data = base64.b64decode(img_to_show_base64)
218
+ img_to_show = Image.open(BytesIO(img_to_show_data))
219
+
220
+ draw = ImageDraw.Draw(img_to_show)
221
+ x, y = vlm_response_json["box_centroid_coordinate"]
222
+ radius = 10
223
+ draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill='red')
224
+ draw.ellipse((x - radius*3, y - radius*3, x + radius*3, y + radius*3), fill=None, outline='red', width=2)
225
+
226
+ buffered = BytesIO()
227
+ img_to_show.save(buffered, format="PNG")
228
+ img_to_show_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
229
+ except:
230
+ print(f"Error parsing: {vlm_response_json}")
231
+ pass
232
+ self.output_callback(f'<img src="data:image/png;base64,{img_to_show_base64}">', )
233
+
234
+ # Display screen info in a collapsible dropdown
235
+ self.output_callback(
236
+ f'<details>'
237
+ f' <summary><strong>Parsed Screen Elements (click to expand)</strong></summary>'
238
+ f' <div style="padding: 10px; background-color: #f8f9fa; border-radius: 5px; margin-top: 5px;">'
239
+ f' <pre>{screen_info}</pre>'
240
+ f' </div>'
241
+ f'</details>',
242
+ )
243
+
244
+ vlm_plan_str = ""
245
+ for key, value in vlm_response_json.items():
246
+ if key == "Reasoning":
247
+ vlm_plan_str += f'{value}'
248
+ else:
249
+ vlm_plan_str += f'\n{key}: {value}'
250
+
251
+ # construct the response so that anthropicExcutor can execute the tool
252
+ response_content = [BetaTextBlock(text=vlm_plan_str, type='text')]
253
+ if 'box_centroid_coordinate' in vlm_response_json:
254
+ move_cursor_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
255
+ input={'action': 'mouse_move', 'coordinate': vlm_response_json["box_centroid_coordinate"]},
256
+ name='computer', type='tool_use')
257
+ response_content.append(move_cursor_block)
258
+
259
+ if vlm_response_json["Next Action"] == "None":
260
+ print("Task paused/completed.")
261
+ elif vlm_response_json["Next Action"] == "type":
262
+ sim_content_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
263
+ input={'action': vlm_response_json["Next Action"], 'text': vlm_response_json["value"]},
264
+ name='computer', type='tool_use')
265
+ response_content.append(sim_content_block)
266
+ else:
267
+ sim_content_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
268
+ input={'action': vlm_response_json["Next Action"]},
269
+ name='computer', type='tool_use')
270
+ response_content.append(sim_content_block)
271
+ response_message = BetaMessage(id=f'toolu_{uuid.uuid4()}', content=response_content, model='', role='assistant', type='message', stop_reason='tool_use', usage=BetaUsage(input_tokens=0, output_tokens=0))
272
+
273
+ # save the intermediate step trajectory to the save folder
274
+ step_trajectory = {
275
+ "screenshot_path": f"{self.save_folder}/screenshot_{self.step_count}.png",
276
+ "som_screenshot_path": f"{self.save_folder}/som_screenshot_{self.step_count}.png",
277
+ "screen_info": screen_info,
278
+ "latency_omniparser": latency_omniparser,
279
+ "latency_vlm": latency_vlm,
280
+ "vlm_response_json": vlm_response_json,
281
+ 'ledger': self.ledger,
282
+ }
283
+ with open(f"{self.save_folder}/trajectory.json", "a") as f:
284
+ f.write(json.dumps(step_trajectory))
285
+ f.write("\n")
286
+
287
+ return response_message, vlm_response_json
288
+
289
+ def _api_response_callback(self, response: APIResponse):
290
+ self.api_response_callback(response)
291
+
292
+ def _get_system_prompt(self, screen_info: str = ""):
293
+ main_section = f"""
294
+ You are using a Windows device.
295
+ You are able to use a mouse and keyboard to interact with the computer based on the given task and screenshot.
296
+ You can only interact with the desktop GUI (no terminal or application menu access).
297
+
298
+ You may be given some history plan and actions, this is the response from the previous loop.
299
+ You should carefully consider your plan base on the task, screenshot, and history actions.
300
+
301
+ Here is the list of all detected bounding boxes by IDs on the screen and their description:{screen_info}
302
+
303
+ Your available "Next Action" only include:
304
+ - type: types a string of text.
305
+ - left_click: move mouse to box id and left clicks.
306
+ - right_click: move mouse to box id and right clicks.
307
+ - double_click: move mouse to box id and double clicks.
308
+ - hover: move mouse to box id.
309
+ - scroll_up: scrolls the screen up to view previous content.
310
+ - scroll_down: scrolls the screen down, when the desired button is not visible, or you need to see more content.
311
+ - wait: waits for 1 second for the device to load or respond.
312
+
313
+ Based on the visual information from the screenshot image and the detected bounding boxes, please determine the next action, the Box ID you should operate on (if action is one of 'type', 'hover', 'scroll_up', 'scroll_down', 'wait', there should be no Box ID field), and the value (if the action is 'type') in order to complete the task.
314
+
315
+ Output format:
316
+ ```json
317
+ {{
318
+ "Reasoning": str, # describe what is in the current screen, taking into account the history, then describe your step-by-step thoughts on how to achieve the task, choose one action from available actions at a time.
319
+ "Next Action": "action_type, action description" | "None" # one action at a time, describe it in short and precisely.
320
+ "Box ID": n,
321
+ "value": "xxx" # only provide value field if the action is type, else don't include value key
322
+ }}
323
+ ```
324
+
325
+ One Example:
326
+ ```json
327
+ {{
328
+ "Reasoning": "The current screen shows google result of amazon, in previous action I have searched amazon on google. Then I need to click on the first search results to go to amazon.com.",
329
+ "Next Action": "left_click",
330
+ "Box ID": m
331
+ }}
332
+ ```
333
+
334
+ Another Example:
335
+ ```json
336
+ {{
337
+ "Reasoning": "The current screen shows the front page of amazon. There is no previous action. Therefore I need to type "Apple watch" in the search bar.",
338
+ "Next Action": "type",
339
+ "Box ID": n,
340
+ "value": "Apple watch"
341
+ }}
342
+ ```
343
+
344
+ Another Example:
345
+ ```json
346
+ {{
347
+ "Reasoning": "The current screen does not show 'submit' button, I need to scroll down to see if the button is available.",
348
+ "Next Action": "scroll_down",
349
+ }}
350
+ ```
351
+
352
+ IMPORTANT NOTES:
353
+ 1. You should only give a single action at a time.
354
+
355
+ """
356
+ thinking_model = "r1" in self.model
357
+ if not thinking_model:
358
+ main_section += """
359
+ 2. You should give an analysis to the current screen, and reflect on what has been done by looking at the history, then describe your step-by-step thoughts on how to achieve the task.
360
+
361
+ """
362
+ else:
363
+ main_section += """
364
+ 2. In <think> XML tags give an analysis to the current screen, and reflect on what has been done by looking at the history, then describe your step-by-step thoughts on how to achieve the task. In <output> XML tags put the next action prediction JSON.
365
+
366
+ """
367
+ main_section += """
368
+ 3. Attach the next action prediction in the "Next Action".
369
+ 4. You should not include other actions, such as keyboard shortcuts.
370
+ 5. When the task is completed, don't complete additional actions. You should say "Next Action": "None" in the json field.
371
+ 6. The tasks involve buying multiple products or navigating through multiple pages. You should break it into subgoals and complete each subgoal one by one in the order of the instructions.
372
+ 7. avoid choosing the same action/elements multiple times in a row, if it happens, reflect to yourself, what may have gone wrong, and predict a different action.
373
+ 8. If you are prompted with login information page or captcha page, or you think it need user's permission to do the next action, you should say "Next Action": "None" in the json field.
374
+ """
375
+
376
+ return main_section
377
+
378
+ def _initialize_task(self, messages: list):
379
+ self._task = messages[0]["content"]
380
+ # make a plan
381
+ plan_prompt = self._get_plan_prompt(self._task)
382
+ input_message = copy.deepcopy(messages)
383
+ input_message.append({"role": "user", "content": plan_prompt})
384
+ vlm_response, token_usage = run_oai_interleaved(
385
+ messages=input_message,
386
+ system="",
387
+ model_name=self.model,
388
+ api_key=self.api_key,
389
+ max_tokens=self.max_tokens,
390
+ provider_base_url="https://api.openai.com/v1",
391
+ temperature=0,
392
+ )
393
+ plan = extract_data(vlm_response, "json")
394
+
395
+ # Create a filename with timestamp
396
+ plan_filename = f"plan.json"
397
+ plan_path = os.path.join(self.save_folder, plan_filename)
398
+
399
+ # Save the plan to a file
400
+ try:
401
+ with open(plan_path, "w") as f:
402
+ f.write(plan)
403
+ print(f"Plan successfully saved to {plan_path}")
404
+ except Exception as e:
405
+ print(f"Error saving plan to {plan_path}: {str(e)}")
406
+
407
+ return plan
408
+
409
+ def _update_ledger(self, messages):
410
+ # tobe implemented
411
+ # update the ledger with the current task and plan
412
+ # return the updated ledger
413
+ update_ledger_prompt = ORCHESTRATOR_LEDGER_PROMPT.format(task=self._task)
414
+ input_message = copy.deepcopy(messages)
415
+ input_message.append({"role": "user", "content": update_ledger_prompt})
416
+ vlm_response, token_usage = run_oai_interleaved(
417
+ messages=input_message,
418
+ system="",
419
+ model_name=self.model,
420
+ api_key=self.api_key,
421
+ max_tokens=self.max_tokens,
422
+ provider_base_url="https://api.openai.com/v1",
423
+ temperature=0,
424
+ )
425
+ updated_ledger = extract_data(vlm_response, "json")
426
+ return updated_ledger
427
+
428
+ def _get_plan_prompt(self, task):
429
+ plan_prompt = f"""
430
+ please devise a short bullet-point plan for addressing the original user task: {task}
431
+ You should write your plan in a json dict, e.g:```json
432
+ {{
433
+ 'step 1': xxx,
434
+ 'step 2': xxxx,
435
+ ...
436
+ }}```
437
+ Now start your answer directly.
438
+ """
439
+ return plan_prompt
440
+
441
+ def _remove_som_images(messages):
442
+ for msg in messages:
443
+ msg_content = msg["content"]
444
+ if isinstance(msg_content, list):
445
+ msg["content"] = [
446
+ cnt for cnt in msg_content
447
+ if not (isinstance(cnt, str) and 'som' in cnt and is_image_path(cnt))
448
+ ]
449
+
450
+
451
+ def _maybe_filter_to_n_most_recent_images(
452
+ messages: list[BetaMessageParam],
453
+ images_to_keep: int,
454
+ min_removal_threshold: int = 10,
455
+ ):
456
+ """
457
+ With the assumption that images are screenshots that are of diminishing value as
458
+ the conversation progresses, remove all but the final `images_to_keep` tool_result
459
+ images in place
460
+ """
461
+ if images_to_keep is None:
462
+ return messages
463
+
464
+ total_images = 0
465
+ for msg in messages:
466
+ for cnt in msg.get("content", []):
467
+ if isinstance(cnt, str) and is_image_path(cnt):
468
+ total_images += 1
469
+ elif isinstance(cnt, dict) and cnt.get("type") == "tool_result":
470
+ for content in cnt.get("content", []):
471
+ if isinstance(content, dict) and content.get("type") == "image":
472
+ total_images += 1
473
+
474
+ images_to_remove = total_images - images_to_keep
475
+
476
+ for msg in messages:
477
+ msg_content = msg["content"]
478
+ if isinstance(msg_content, list):
479
+ new_content = []
480
+ for cnt in msg_content:
481
+ # Remove images from SOM or screenshot as needed
482
+ if isinstance(cnt, str) and is_image_path(cnt):
483
+ if images_to_remove > 0:
484
+ images_to_remove -= 1
485
+ continue
486
+ # VLM shouldn't use anthropic screenshot tool so shouldn't have these but in case it does, remove as needed
487
+ elif isinstance(cnt, dict) and cnt.get("type") == "tool_result":
488
+ new_tool_result_content = []
489
+ for tool_result_entry in cnt.get("content", []):
490
+ if isinstance(tool_result_entry, dict) and tool_result_entry.get("type") == "image":
491
+ if images_to_remove > 0:
492
+ images_to_remove -= 1
493
+ continue
494
+ new_tool_result_content.append(tool_result_entry)
495
+ cnt["content"] = new_tool_result_content
496
+ # Append fixed content to current message's content list
497
+ new_content.append(cnt)
498
+ msg["content"] = new_content