File size: 4,204 Bytes
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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