Spaces:
Runtime error
Runtime error
Update agents/agent.py
Browse files- agents/agent.py +29 -47
agents/agent.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
CellposeAgent with
|
| 3 |
"""
|
| 4 |
import torch
|
| 5 |
import json
|
|
@@ -23,8 +23,8 @@ class CellposeAgent:
|
|
| 23 |
@staticmethod
|
| 24 |
def attach_images_callback(step_log: ActionStep, agent: ToolCallingAgent) -> None:
|
| 25 |
"""
|
| 26 |
-
|
| 27 |
-
|
| 28 |
"""
|
| 29 |
if not isinstance(step_log, ActionStep):
|
| 30 |
return
|
|
@@ -72,44 +72,19 @@ class CellposeAgent:
|
|
| 72 |
try:
|
| 73 |
obs_data = json.loads(step_log.observations)
|
| 74 |
|
| 75 |
-
#
|
| 76 |
-
if obs_data.get("status") == "
|
| 77 |
-
|
| 78 |
-
print(f"[Callback] Attaching image: {image_path}")
|
| 79 |
-
|
| 80 |
-
try:
|
| 81 |
-
img = Image.open(image_path)
|
| 82 |
-
compressed_img = resize_and_compress_image(img, max_size=512, quality=75)
|
| 83 |
-
|
| 84 |
-
# Attach compressed PIL Image
|
| 85 |
-
step_log.observations_images = [compressed_img]
|
| 86 |
-
|
| 87 |
-
# Keep metadata for context
|
| 88 |
-
obs_data["image_info"] = {
|
| 89 |
-
"original_dimensions": f"{img.size[0]}x{img.size[1]} pixels",
|
| 90 |
-
"processed_dimensions": f"{compressed_img.size[0]}x{compressed_img.size[1]} pixels",
|
| 91 |
-
"mode": compressed_img.mode,
|
| 92 |
-
"note": "Image compressed for API efficiency (JPEG quality=75)"
|
| 93 |
-
}
|
| 94 |
-
step_log.observations = json.dumps(obs_data, indent=2)
|
| 95 |
-
print(f"[Callback] β Attached compressed image for VLM inspection")
|
| 96 |
-
except Exception as e:
|
| 97 |
-
print(f"[Callback] Error attaching image: {e}")
|
| 98 |
-
|
| 99 |
-
# Pattern 2: Segmented image ONLY from refine_segmentation
|
| 100 |
-
elif obs_data.get("status") == "ready_for_visual_analysis":
|
| 101 |
-
paths = obs_data.get("image_paths", {})
|
| 102 |
-
segmented = paths.get("segmented")
|
| 103 |
|
| 104 |
if segmented:
|
| 105 |
-
print(f"[Callback] Attaching segmented image
|
| 106 |
try:
|
| 107 |
seg_img = Image.open(segmented)
|
| 108 |
|
| 109 |
# Compress the segmented image
|
| 110 |
compressed_seg = resize_and_compress_image(seg_img, max_size=512, quality=75)
|
| 111 |
|
| 112 |
-
# Attach
|
| 113 |
step_log.observations_images = [compressed_seg]
|
| 114 |
|
| 115 |
obs_data["images_info"] = {
|
|
@@ -123,6 +98,10 @@ class CellposeAgent:
|
|
| 123 |
print(f"[Callback] β Attached compressed segmented image for VLM inspection")
|
| 124 |
except Exception as e:
|
| 125 |
print(f"[Callback] Error attaching segmented image: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
except json.JSONDecodeError:
|
| 128 |
pass
|
|
@@ -133,21 +112,22 @@ class CellposeAgent:
|
|
| 133 |
@staticmethod
|
| 134 |
def manage_image_memory(step_log: ActionStep, agent: ToolCallingAgent) -> None:
|
| 135 |
"""
|
| 136 |
-
Aggressive memory management:
|
| 137 |
-
|
| 138 |
"""
|
| 139 |
if not isinstance(step_log, ActionStep):
|
| 140 |
return
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
# Clear images from ALL previous steps (keeping only current)
|
| 145 |
for previous_step in agent.memory.steps:
|
| 146 |
-
if isinstance(previous_step, ActionStep)
|
| 147 |
-
|
| 148 |
-
if previous_step.observations_images is not None:
|
| 149 |
print(f" [Memory] Clearing images from step {previous_step.step_number}")
|
| 150 |
-
previous_step.observations_images = None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
|
| 153 |
def __init__(self):
|
|
@@ -158,8 +138,9 @@ class CellposeAgent:
|
|
| 158 |
When a user provides an image:
|
| 159 |
1. use appropriate tools to review which cellpose-sam parameters are available.
|
| 160 |
2. use the tool: `get_segmentation_parameters`
|
| 161 |
-
- **IMPORTANT**:
|
| 162 |
-
-
|
|
|
|
| 163 |
3. carefully analyze the image metadata and matched parameters:
|
| 164 |
- consider cell density based on image dimensions
|
| 165 |
- compare matched parameter values to image characteristics
|
|
@@ -168,8 +149,9 @@ class CellposeAgent:
|
|
| 168 |
5. Provide your final parameter recommendations in a clear, structured format
|
| 169 |
6. Use the parameters to run cellpose_sam through the tool: run_cellpose_sam
|
| 170 |
7. after run_cellpose_sam, call the tool: refine_cellpose_sam_segmentation
|
| 171 |
-
- **IMPORTANT**: After this tool runs, you
|
| 172 |
-
-
|
|
|
|
| 173 |
- Use the visual analysis checklist provided in the tool output
|
| 174 |
8. Based on visual analysis of the segmented image:
|
| 175 |
- Assess if cell boundaries are accurate
|
|
@@ -195,7 +177,7 @@ class CellposeAgent:
|
|
| 195 |
- Be concise and actionable
|
| 196 |
- Always explain your reasoning when adjusting parameters
|
| 197 |
- If keeping original matched parameters, briefly confirm why it's appropriate
|
| 198 |
-
- Base your decisions on visual observation of the segmented output
|
| 199 |
|
| 200 |
**CRITICAL - Final Response Format:**
|
| 201 |
When segmentation is complete, you MUST provide a comprehensive text summary that includes:
|
|
|
|
| 1 |
"""
|
| 2 |
+
CellposeAgent with optimized image attachment - only attaches when visual inspection is needed
|
| 3 |
"""
|
| 4 |
import torch
|
| 5 |
import json
|
|
|
|
| 23 |
@staticmethod
|
| 24 |
def attach_images_callback(step_log: ActionStep, agent: ToolCallingAgent) -> None:
|
| 25 |
"""
|
| 26 |
+
OPTIMIZED: Only attach images for visual refinement step to save tokens.
|
| 27 |
+
For all other steps, skip image attachment - images are accessible via file paths.
|
| 28 |
"""
|
| 29 |
if not isinstance(step_log, ActionStep):
|
| 30 |
return
|
|
|
|
| 72 |
try:
|
| 73 |
obs_data = json.loads(step_log.observations)
|
| 74 |
|
| 75 |
+
# ONLY attach images for visual refinement step
|
| 76 |
+
if obs_data.get("status") == "ready_for_visual_analysis":
|
| 77 |
+
segmented = obs_data.get("image_paths", {}).get("segmented")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
if segmented:
|
| 80 |
+
print(f"[Callback] Attaching segmented image for visual analysis: {segmented}")
|
| 81 |
try:
|
| 82 |
seg_img = Image.open(segmented)
|
| 83 |
|
| 84 |
# Compress the segmented image
|
| 85 |
compressed_seg = resize_and_compress_image(seg_img, max_size=512, quality=75)
|
| 86 |
|
| 87 |
+
# Attach the segmented image
|
| 88 |
step_log.observations_images = [compressed_seg]
|
| 89 |
|
| 90 |
obs_data["images_info"] = {
|
|
|
|
| 98 |
print(f"[Callback] β Attached compressed segmented image for VLM inspection")
|
| 99 |
except Exception as e:
|
| 100 |
print(f"[Callback] Error attaching segmented image: {e}")
|
| 101 |
+
else:
|
| 102 |
+
# For all other steps, explicitly skip image attachment to save tokens
|
| 103 |
+
step_log.observations_images = []
|
| 104 |
+
print(f"[Callback] Skipped image attachment (not a refinement step) to save tokens")
|
| 105 |
|
| 106 |
except json.JSONDecodeError:
|
| 107 |
pass
|
|
|
|
| 112 |
@staticmethod
|
| 113 |
def manage_image_memory(step_log: ActionStep, agent: ToolCallingAgent) -> None:
|
| 114 |
"""
|
| 115 |
+
Aggressive memory management: clear ALL images from ALL previous steps.
|
| 116 |
+
Use empty list instead of None for more reliable cleanup.
|
| 117 |
"""
|
| 118 |
if not isinstance(step_log, ActionStep):
|
| 119 |
return
|
| 120 |
|
| 121 |
+
# Clear images from ALL previous steps (more aggressive)
|
|
|
|
|
|
|
| 122 |
for previous_step in agent.memory.steps:
|
| 123 |
+
if isinstance(previous_step, ActionStep):
|
| 124 |
+
if previous_step.observations_images is not None and len(previous_step.observations_images) > 0:
|
|
|
|
| 125 |
print(f" [Memory] Clearing images from step {previous_step.step_number}")
|
| 126 |
+
previous_step.observations_images = [] # Empty list, not None
|
| 127 |
+
|
| 128 |
+
# Try to clear any cached references (defensive)
|
| 129 |
+
if hasattr(previous_step, '_observations_images'):
|
| 130 |
+
previous_step._observations_images = []
|
| 131 |
|
| 132 |
|
| 133 |
def __init__(self):
|
|
|
|
| 138 |
When a user provides an image:
|
| 139 |
1. use appropriate tools to review which cellpose-sam parameters are available.
|
| 140 |
2. use the tool: `get_segmentation_parameters`
|
| 141 |
+
- **IMPORTANT**: You will receive image metadata (dimensions, properties, statistics)
|
| 142 |
+
- The actual image file is accessible via the file path in the response
|
| 143 |
+
- Use the metadata to reason about appropriate parameter values
|
| 144 |
3. carefully analyze the image metadata and matched parameters:
|
| 145 |
- consider cell density based on image dimensions
|
| 146 |
- compare matched parameter values to image characteristics
|
|
|
|
| 149 |
5. Provide your final parameter recommendations in a clear, structured format
|
| 150 |
6. Use the parameters to run cellpose_sam through the tool: run_cellpose_sam
|
| 151 |
7. after run_cellpose_sam, call the tool: refine_cellpose_sam_segmentation
|
| 152 |
+
- **IMPORTANT**: After this tool runs, you WILL SEE the SEGMENTED image (colored masks overlay)
|
| 153 |
+
- This is the ONLY step where you can visually inspect the actual image
|
| 154 |
+
- Visually assess the segmentation quality - are cells properly detected and separated?
|
| 155 |
- Use the visual analysis checklist provided in the tool output
|
| 156 |
8. Based on visual analysis of the segmented image:
|
| 157 |
- Assess if cell boundaries are accurate
|
|
|
|
| 177 |
- Be concise and actionable
|
| 178 |
- Always explain your reasoning when adjusting parameters
|
| 179 |
- If keeping original matched parameters, briefly confirm why it's appropriate
|
| 180 |
+
- Base your decisions on visual observation of the segmented output (when available in refinement step)
|
| 181 |
|
| 182 |
**CRITICAL - Final Response Format:**
|
| 183 |
When segmentation is complete, you MUST provide a comprehensive text summary that includes:
|