File size: 7,431 Bytes
5463b45 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | """The pruner has to keep the message list valid, not just small.
Anthropic rejects a conversation whose tool_use blocks have lost their
tool_result, and rejects an empty tool_result, so both invariants are re-checked
after every kind of trim. Only the mixin is under test, so Harbor's provider
classes are stubbed when Harbor is not importable from this interpreter.
"""
import asyncio
import sys
import types
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]/"scripts"))
try:
import harbor.agents.computer_1.providers.anthropic # noqa: F401
except ImportError:
module = types.ModuleType("harbor.agents.computer_1.providers.anthropic")
module.AnthropicProvider = type("AnthropicProvider", (), {})
module.BedrockProvider = type("BedrockProvider", (), {})
for name in ("harbor", "harbor.agents", "harbor.agents.computer_1",
"harbor.agents.computer_1.providers"):
sys.modules.setdefault(name, types.ModuleType(name))
sys.modules[module.__name__] = module
from pruned_providers import ( # noqa: E402
KEEP_IMAGE_TURNS,
KEEP_TURNS,
MAX_RECOVERIES,
PLACEHOLDER,
PrunedAnthropicMessages,
images_in,
)
def image():
return {"type": "image",
"source": {"type": "base64", "media_type": "image/webp", "data": "aaaa"}}
def conversation(turns):
"""One instruction turn plus *turns* assistant/tool-result exchanges."""
messages = [{"role": "user",
"content": [{"type": "text", "text": "instruction"}, image()]}]
for index in range(turns):
messages.append({"role": "assistant", "content": [
{"type": "text", "text": f"thinking {index}"},
{"type": "tool_use", "id": f"call{index}", "name": "computer", "input": {}}]})
messages.append({"role": "user", "content": [
{"type": "tool_result", "tool_use_id": f"call{index}", "is_error": False,
"content": [{"type": "text", "text": "screenshot"}, image()]},
{"type": "text", "text": "Continue with the task."}]})
return messages
class Recorded:
"""Stands in for the provider's real request, and can reject it as too long."""
async def _call_api(self):
self.calls += 1
self.sizes.append((len(self._messages), total_images(self._messages)))
if self.calls <= self.failures:
raise RuntimeError("Error code: 400 - {'message': 'Input is too long.'}")
return "response"
class Pruned(PrunedAnthropicMessages, Recorded):
def __init__(self, messages, failures=0):
self._messages = messages
self.failures = failures
self.calls = 0
self.sizes = []
class Failing:
"""A provider that fails for a reason pruning cannot fix."""
async def _call_api(self):
raise RuntimeError("Model overloaded")
class Overloaded(PrunedAnthropicMessages, Failing):
def __init__(self, messages):
self._messages = messages
def total_images(messages):
return sum(images_in(message) for message in messages)
def texts(messages):
"""Every text block, including the ones nested inside a tool_result."""
found = []
for message in messages:
for block in message["content"]:
if block.get("type") == "text":
found.append(block["text"])
elif block.get("type") == "tool_result":
found += [inner["text"] for inner in block["content"]
if inner.get("type") == "text"]
return found
def tool_use_ids(messages):
return [block["id"] for message in messages if message["role"] == "assistant"
for block in message["content"] if block.get("type") == "tool_use"]
def tool_result_ids(messages):
return [block["tool_use_id"] for message in messages if message["role"] == "user"
for block in message["content"] if block.get("type") == "tool_result"]
class Pruning(unittest.TestCase):
def check(self, messages):
"""What the API itself would reject."""
roles = [message["role"] for message in messages]
self.assertEqual(roles, ["user" if index % 2 == 0 else "assistant"
for index in range(len(roles))])
self.assertEqual(tool_use_ids(messages), tool_result_ids(messages))
for message in messages:
for block in message["content"]:
if block.get("type") == "tool_result":
self.assertTrue(block["content"], "tool_result must not be empty")
def test_image_trim_keeps_the_recent_views(self):
agent = Pruned(conversation(40))
self.assertEqual(agent.trim_images(5), 36) # 41 image turns, 5 kept
self.assertEqual(total_images(agent._messages), 5)
self.check(agent._messages)
def test_a_removed_screenshot_leaves_a_note_behind(self):
agent = Pruned(conversation(6))
agent.trim_images(1)
self.assertIn(PLACEHOLDER, texts(agent._messages))
def test_the_instruction_turn_survives_a_turn_drop(self):
agent = Pruned(conversation(60))
self.assertEqual(agent.drop_oldest_turns(20), 100)
self.assertEqual(len(agent._messages), 21)
self.assertEqual(agent._messages[0]["content"][0]["text"], "instruction")
self.check(agent._messages)
def test_turn_drop_is_a_no_op_when_the_history_is_short(self):
agent = Pruned(conversation(4))
self.assertEqual(agent.drop_oldest_turns(KEEP_TURNS), 0)
self.assertEqual(len(agent._messages), 9)
def test_a_long_session_is_pruned_before_the_request(self):
agent = Pruned(conversation(80))
asyncio.run(agent._call_api())
turns, images = agent.sizes[0]
self.assertEqual(images, KEEP_IMAGE_TURNS)
self.assertLessEqual(turns, KEEP_TURNS+1)
self.check(agent._messages)
def test_a_short_session_is_left_alone(self):
agent = Pruned(conversation(6))
asyncio.run(agent._call_api())
self.assertEqual(agent.sizes[0], (13, 7))
def test_a_rejected_request_is_pruned_harder_and_retried(self):
agent = Pruned(conversation(80), failures=2)
self.assertEqual(asyncio.run(agent._call_api()), "response")
self.assertEqual(agent.calls, 3)
self.assertLess(agent.sizes[-1][1], agent.sizes[0][1])
self.assertLess(agent.sizes[-1][0], agent.sizes[0][0])
self.assertLess(agent.keep_image_turns, KEEP_IMAGE_TURNS)
self.check(agent._messages)
def test_the_tighter_budget_sticks_for_later_requests(self):
agent = Pruned(conversation(80), failures=1)
asyncio.run(agent._call_api())
tightened = agent.keep_image_turns
self.assertLess(tightened, KEEP_IMAGE_TURNS)
agent.failures = 0
asyncio.run(agent._call_api())
self.assertEqual(agent.keep_image_turns, tightened)
def test_other_errors_are_not_swallowed(self):
agent = Overloaded(conversation(10))
with self.assertRaisesRegex(RuntimeError, "overloaded"):
asyncio.run(agent._call_api())
def test_recovery_gives_up_rather_than_looping(self):
agent = Pruned(conversation(80), failures=99)
with self.assertRaises(RuntimeError):
asyncio.run(agent._call_api())
self.assertLessEqual(agent.calls, MAX_RECOVERIES+1)
if __name__ == "__main__":
unittest.main()
|