(messages: list)
| 359 | rounds_since_todo = 0 |
| 360 | |
| 361 | def agent_loop(messages: list): |
| 362 | global rounds_since_todo |
| 363 | while True: |
| 364 | if rounds_since_todo >= 3 and messages: |
| 365 | messages.append({"role": "user", |
| 366 | "content": "<reminder>Update your todos.</reminder>"}) |
| 367 | rounds_since_todo = 0 |
| 368 | |
| 369 | response = client.messages.create( |
| 370 | model=MODEL, system=SYSTEM, messages=messages, |
| 371 | tools=TOOLS, max_tokens=8000, |
| 372 | ) |
| 373 | messages.append({"role": "assistant", "content": response.content}) |
| 374 | |
| 375 | if response.stop_reason != "tool_use": |
| 376 | force = trigger_hooks("Stop", messages) |
| 377 | if force: |
| 378 | messages.append({"role": "user", "content": force}) |
| 379 | continue |
| 380 | return |
| 381 | |
| 382 | rounds_since_todo += 1 |
| 383 | results = [] |
| 384 | for block in response.content: |
| 385 | if block.type != "tool_use": |
| 386 | continue |
| 387 | |
| 388 | blocked = trigger_hooks("PreToolUse", block) |
| 389 | if blocked: |
| 390 | results.append({"type": "tool_result", "tool_use_id": block.id, |
| 391 | "content": str(blocked)}) |
| 392 | continue |
| 393 | |
| 394 | handler = TOOL_HANDLERS.get(block.name) |
| 395 | output = handler(**block.input) if handler else f"Unknown: {block.name}" |
| 396 | |
| 397 | trigger_hooks("PostToolUse", block, output) |
| 398 | |
| 399 | if block.name == "todo_write": |
| 400 | rounds_since_todo = 0 |
| 401 | |
| 402 | results.append({"type": "tool_result", "tool_use_id": block.id, |
| 403 | "content": output}) |
| 404 | |
| 405 | messages.append({"role": "user", "content": results}) |
| 406 | |
| 407 | |
| 408 | if __name__ == "__main__": |
no test coverage detected