44def find_items_with_images (items : List [Dict [str , Any ]]) -> List [int ]:
55 """
66 Finds all items in the conversation history that contain images
7-
7+
88 Args:
99 items: Array of conversation items to check
10-
10+
1111 Returns:
1212 Array of indices where images were found
1313 """
1414 items_with_images = []
15-
15+
1616 for index , item in enumerate (items ):
1717 has_image = False
18-
18+
1919 if isinstance (item .get ("content" ), list ):
2020 has_image = any (
2121 content_item .get ("type" ) == "tool_result"
@@ -29,40 +29,39 @@ def find_items_with_images(items: List[Dict[str, Any]]) -> List[int]:
2929 for content_item in item ["content" ]
3030 if isinstance (content_item , dict )
3131 )
32-
32+
3333 if has_image :
3434 items_with_images .append (index )
35-
35+
3636 return items_with_images
3737
3838
3939def compress_conversation_images (
40- items : List [Dict [str , Any ]],
41- keep_most_recent_count : int = 2
40+ items : List [Dict [str , Any ]], keep_most_recent_count : int = 2
4241) -> Dict [str , List [Dict [str , Any ]]]:
4342 """
4443 Compresses conversation history by removing images from older items
4544 while keeping the most recent images intact
46-
45+
4746 Args:
4847 items: Array of conversation items to process
4948 keep_most_recent_count: Number of most recent image-containing items to preserve (default: 2)
50-
49+
5150 Returns:
5251 Dictionary with processed items
5352 """
5453 items_with_images = find_items_with_images (items )
55-
54+
5655 for index , item in enumerate (items ):
5756 image_index = - 1
5857 if index in items_with_images :
5958 image_index = items_with_images .index (index )
60-
59+
6160 should_compress = (
62- image_index >= 0
61+ image_index >= 0
6362 and image_index < len (items_with_images ) - keep_most_recent_count
6463 )
65-
64+
6665 if should_compress :
6766 if isinstance (item .get ("content" ), list ):
6867 new_content = []
@@ -79,15 +78,14 @@ def compress_conversation_images(
7978 )
8079 ):
8180 # Replace the content with a text placeholder
82- new_content .append ({
83- ** content_item ,
84- "content" : "screenshot taken"
85- })
81+ new_content .append (
82+ {** content_item , "content" : "screenshot taken" }
83+ )
8684 else :
8785 new_content .append (content_item )
8886 else :
8987 new_content .append (content_item )
90-
88+
9189 item ["content" ] = new_content
92-
93- return {"items" : items }
90+
91+ return {"items" : items }
0 commit comments