(messages: list, context: dict)
| 804 | # ── Agent Loop ── |
| 805 | |
| 806 | def agent_loop(messages: list, context: dict): |
| 807 | system = get_system_prompt(context) |
| 808 | while True: |
| 809 | try: |
| 810 | response = client.messages.create( |
| 811 | model=MODEL, system=system, messages=messages, |
| 812 | tools=TOOLS, max_tokens=8000) |
| 813 | except Exception as e: |
| 814 | messages.append({"role": "assistant", "content": [ |
| 815 | {"type": "text", |
| 816 | "text": f"[Error] {type(e).__name__}: {e}"}]}) |
| 817 | return |
| 818 | |
| 819 | messages.append({"role": "assistant", "content": response.content}) |
| 820 | if response.stop_reason != "tool_use": |
| 821 | return |
| 822 | |
| 823 | results = [] |
| 824 | for block in response.content: |
| 825 | if block.type != "tool_use": |
| 826 | continue |
| 827 | print(f"\033[36m> {block.name}\033[0m") |
| 828 | |
| 829 | if should_run_background(block.name, block.input): |
| 830 | bg_id = start_background_task(block) |
| 831 | results.append({"type": "tool_result", |
| 832 | "tool_use_id": block.id, |
| 833 | "content": f"[Background task {bg_id} started] " |
| 834 | f"Result will be available when complete."}) |
| 835 | else: |
| 836 | output = execute_tool(block) |
| 837 | print(str(output)[:300]) |
| 838 | results.append({"type": "tool_result", |
| 839 | "tool_use_id": block.id, |
| 840 | "content": output}) |
| 841 | |
| 842 | # Merge background tool results + notifications into one user message |
| 843 | user_content = list(results) |
| 844 | bg_notifications = collect_background_results() |
| 845 | if bg_notifications: |
| 846 | for notif in bg_notifications: |
| 847 | user_content.append({"type": "text", "text": notif}) |
| 848 | messages.append({"role": "user", "content": user_content}) |
| 849 | context = update_context(context, messages) |
| 850 | system = get_system_prompt(context) |
| 851 | |
| 852 | |
| 853 | if __name__ == "__main__": |
no test coverage detected