Download testing/nano_simulation_agents/src/nano_python_agents/loop.py from yuhanqin/ut-evaluation: direct link, hf CLI and curl.
- Browser
- Download file 4.2 kB
-
https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/nano_simulation_agents/src/nano_python_agents/loop.py
- Command line
-
hf download hf://datasets/yuhanqin/ut-evaluation/testing/nano_simulation_agents/src/nano_python_agents/loop.py
-
curl -L -o loop.py https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/nano_simulation_agents/src/nano_python_agents/loop.py
4.2 kB
| """Provider-neutral agent loop with strict tool-call/result pairing.""" | |
| from __future__ import annotations | |
| from datetime import date | |
| from pathlib import Path | |
| from typing import Any | |
| from nano_python_agents.gateway import Gateway | |
| from nano_python_agents.providers.base import Provider | |
| from nano_python_agents.types import Message, ToolCall, ToolResult | |
| class MaxTurnsExceeded(RuntimeError): | |
| def __init__(self, max_turns: int) -> None: | |
| super().__init__(f"Agent stopped after reaching max_turns={max_turns}") | |
| self.max_turns = max_turns | |
| def load_system_prompt( | |
| workspace_root: Path, | |
| today: date | None = None, | |
| prompt_ids: list[str] | None = None, | |
| extra_prompt_dirs: list[Path] | None = None, | |
| ) -> str: | |
| from nano_python_agents.prompt_loader import PromptRegistry | |
| registry = PromptRegistry(extra_dirs=extra_prompt_dirs) | |
| ids = prompt_ids if prompt_ids is not None else ["system"] | |
| return registry.compose( | |
| ids, | |
| workspace=str(Path(workspace_root).resolve()), | |
| today=today, | |
| ) | |
| class AgentLoop: | |
| def __init__( | |
| self, | |
| provider: Provider, | |
| gateway: Gateway, | |
| *, | |
| system_prompt: str, | |
| max_turns: int = 10, | |
| event_logger=None, | |
| ) -> None: | |
| self.provider = provider | |
| self.gateway = gateway | |
| self.system_prompt = system_prompt | |
| self.max_turns = max_turns | |
| self.events = event_logger | |
| self.messages: list[Message] = [] | |
| def run(self, user_text: str) -> str: | |
| self.messages.append(Message.user(user_text)) | |
| self._log("user_input", text=user_text) | |
| for turn_number in range(1, self.max_turns + 1): | |
| try: | |
| assistant_turn = self.provider.create_turn( | |
| self.system_prompt, | |
| self.messages, | |
| self.gateway.schemas(), | |
| ) | |
| except KeyboardInterrupt: | |
| self._log("provider_cancelled", turn=turn_number) | |
| raise | |
| self.messages.append(Message.assistant(assistant_turn)) | |
| self._log( | |
| "assistant", | |
| turn=turn_number, | |
| finish_reason=assistant_turn.finish_reason, | |
| text=assistant_turn.text, | |
| tool_call_ids=[call.id for call in assistant_turn.tool_calls], | |
| tool_names=[call.name for call in assistant_turn.tool_calls], | |
| ) | |
| if not assistant_turn.tool_calls: | |
| self._log("final", text=assistant_turn.text) | |
| return assistant_turn.text | |
| results: list[ToolResult] = [] | |
| for index, call in enumerate(assistant_turn.tool_calls): | |
| try: | |
| results.append(self.gateway.execute(call)) | |
| except KeyboardInterrupt: | |
| pending = assistant_turn.tool_calls[index:] | |
| results.extend(self._cancelled_results(pending)) | |
| self.messages.extend(Message.tool(result) for result in results) | |
| self._log( | |
| "tool_batch_cancelled", | |
| turn=turn_number, | |
| call_ids=[pending_call.id for pending_call in pending], | |
| ) | |
| raise | |
| self.messages.extend(Message.tool(result) for result in results) | |
| self._log("max_turns_exceeded", max_turns=self.max_turns) | |
| raise MaxTurnsExceeded(self.max_turns) | |
| def _cancelled_results(self, calls: list[ToolCall]) -> list[ToolResult]: | |
| results = [] | |
| for call in calls: | |
| result = ToolResult( | |
| call_id=call.id, | |
| content="Tool call cancelled by user interruption.", | |
| is_error=True, | |
| metadata={"cancelled": True}, | |
| ) | |
| results.append(result) | |
| self._log("tool_cancelled", call_id=call.id, tool=call.name) | |
| return results | |
| def _log(self, event_type: str, **fields: Any) -> None: | |
| if self.events is None: | |
| return | |
| try: | |
| self.events.log(event_type, **fields) | |
| except Exception: | |
| pass | |