python-codex 0.6.3__py3-none-any.whl → 0.7.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pycodex/agent.py +325 -321
- pycodex/config.py +19 -2
- pycodex/context.py +24 -9
- pycodex/events.py +127 -7
- pycodex/model.py +269 -95
- pycodex/multi_agents.py +13 -42
- pycodex/prompts/models.json +8 -8
- pycodex/protocol.py +4 -2
- pycodex/runtime.py +227 -131
- pycodex/tools/__init__.py +3 -3
- pycodex/tools/clock_manager.py +0 -7
- pycodex/tools/exec_command_tool.py +16 -5
- pycodex/tools/exec_runtime.py +5 -1
- pycodex/tools/goal_manager.py +25 -32
- pycodex/tools/runtime_services.py +21 -11
- pycodex/tools/unified_exec_manager.py +46 -3
- pycodex/utils/compactor.py +28 -101
- pycodex/utils/compat.py +6 -0
- pycodex/utils/event_helpers.py +47 -0
- pycodex/utils/history.py +22 -7
- pycodex/utils/model_metadata.py +5 -4
- pycodex/utils/session_persist.py +6 -2
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/METADATA +40 -13
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/RECORD +30 -30
- responses_server/app.py +4 -0
- responses_server/gemini_api.py +26 -7
- responses_server/transport.py +12 -5
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/WHEEL +0 -0
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/entry_points.txt +0 -0
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/licenses/LICENSE +0 -0
pycodex/agent.py
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import asyncio
|
|
2
2
|
import typing
|
|
3
|
+
from contextlib import contextmanager
|
|
3
4
|
from dataclasses import dataclass, replace
|
|
4
5
|
from pathlib import Path
|
|
5
|
-
from typing import Callable
|
|
6
6
|
|
|
7
7
|
from .context import ContextConfig, ContextManager
|
|
8
8
|
from .events import (
|
|
9
|
+
BASE_EVENT_HANDLER,
|
|
10
|
+
AssistantDeltaEvent,
|
|
9
11
|
AutoCompactCompletedEvent,
|
|
10
12
|
AutoCompactFailedEvent,
|
|
11
13
|
AutoCompactStartedEvent,
|
|
@@ -13,20 +15,22 @@ from .events import (
|
|
|
13
15
|
CompactFailedEvent,
|
|
14
16
|
CompactStartedEvent,
|
|
15
17
|
Event,
|
|
18
|
+
EventHandler,
|
|
19
|
+
EventScope,
|
|
16
20
|
MessagesAddedEvent,
|
|
17
21
|
ModelCalledEvent,
|
|
18
22
|
ModelCompletedEvent,
|
|
19
23
|
ModelEvent,
|
|
24
|
+
ModelRequestInterrupted,
|
|
20
25
|
ModelRequestTimingEvent,
|
|
21
26
|
StreamErrorEvent,
|
|
22
|
-
TerminalEvent,
|
|
23
27
|
TokenCountEvent,
|
|
24
28
|
ToolCompletedEvent,
|
|
25
29
|
ToolStartedEvent,
|
|
26
30
|
TurnCompletedEvent,
|
|
27
|
-
TurnEvent,
|
|
28
31
|
TurnFailedEvent,
|
|
29
32
|
TurnInputReadyEvent,
|
|
33
|
+
TurnInterrupted,
|
|
30
34
|
TurnInterruptedEvent,
|
|
31
35
|
TurnStartedEvent,
|
|
32
36
|
)
|
|
@@ -41,6 +45,7 @@ from .protocol import (
|
|
|
41
45
|
AssistantMessage,
|
|
42
46
|
ConversationItem,
|
|
43
47
|
ModelResponse,
|
|
48
|
+
Prompt,
|
|
44
49
|
ReasoningItem,
|
|
45
50
|
ToolCall,
|
|
46
51
|
ToolResult,
|
|
@@ -48,7 +53,8 @@ from .protocol import (
|
|
|
48
53
|
UserMessage,
|
|
49
54
|
)
|
|
50
55
|
from .tools import ToolContext, ToolRegistry
|
|
51
|
-
from .utils import
|
|
56
|
+
from .utils.compactor import DEFAULT_COMPACT_PROMPT, CompactResult, prune_oldest_tool_response
|
|
57
|
+
from .utils.random_ids import uuid7_string
|
|
52
58
|
from .utils.session_persist import (
|
|
53
59
|
SessionRolloutRecorder,
|
|
54
60
|
load_resumed_session_path,
|
|
@@ -56,25 +62,6 @@ from .utils.session_persist import (
|
|
|
56
62
|
)
|
|
57
63
|
from .utils.truncation import truncate_tool_result_for_history
|
|
58
64
|
|
|
59
|
-
if typing.TYPE_CHECKING:
|
|
60
|
-
from .utils.compactor import CompactResult
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
EventHandler = Callable[[Event], None]
|
|
64
|
-
BASE_EVENT_HANDLER: "EventHandler" = lambda _event: None
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
class TurnInterrupted(RuntimeError):
|
|
68
|
-
def __init__(self):
|
|
69
|
-
super().__init__("turn interrupted")
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
@dataclass
|
|
73
|
-
class _TurnState:
|
|
74
|
-
turn_id: "str"
|
|
75
|
-
iteration: "int" = 0
|
|
76
|
-
output_text: "typing.Union[str, None]" = None
|
|
77
|
-
|
|
78
65
|
|
|
79
66
|
@dataclass(frozen=True)
|
|
80
67
|
class ExecutionSnapshot:
|
|
@@ -84,6 +71,60 @@ class ExecutionSnapshot:
|
|
|
84
71
|
usage_tokens: "typing.Union[int, None]"
|
|
85
72
|
|
|
86
73
|
|
|
74
|
+
class TurnContext:
|
|
75
|
+
"""Per-turn execution state and model stream filter owned by an Agent."""
|
|
76
|
+
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
observer: "EventHandler",
|
|
80
|
+
turn_id: "typing.Union[str, None]" = None,
|
|
81
|
+
) -> "None":
|
|
82
|
+
self.turn_id = turn_id or uuid7_string()
|
|
83
|
+
self.messages: "typing.Tuple[ConversationItem, ...]" = ()
|
|
84
|
+
self.iteration = 0
|
|
85
|
+
self.output_text: "typing.Union[str, None]" = None
|
|
86
|
+
self.assistant_text = ""
|
|
87
|
+
self.model_errors: "typing.List[str]" = []
|
|
88
|
+
self.stop_requested = False
|
|
89
|
+
self.follow_up_requested = False
|
|
90
|
+
self.finished = asyncio.Event()
|
|
91
|
+
self.compact_input: "typing.Union[typing.List[ConversationItem], None]" = None
|
|
92
|
+
self.deliver_messages: "typing.Union[typing.Callable[[], None], None]" = None
|
|
93
|
+
self._observer = (
|
|
94
|
+
EventScope.current()
|
|
95
|
+
if observer is BASE_EVENT_HANDLER
|
|
96
|
+
else EventScope.wrap(observer)
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
def bind_items(
|
|
100
|
+
self, items: "typing.Iterable[ConversationItem]",
|
|
101
|
+
) -> "typing.Tuple[ConversationItem, ...]":
|
|
102
|
+
return tuple(
|
|
103
|
+
item if isinstance(item, (ToolCall, ToolResult, ReasoningItem))
|
|
104
|
+
else replace(item, turn_id=self.turn_id)
|
|
105
|
+
for item in items
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
@EventScope.router
|
|
109
|
+
def dispatch(self, event: "Event") -> "None":
|
|
110
|
+
if self.finished.is_set():
|
|
111
|
+
return
|
|
112
|
+
if isinstance(event, ModelEvent) and not event.turn_id:
|
|
113
|
+
if self.compact_input is not None and not isinstance(
|
|
114
|
+
event, (StreamErrorEvent, ModelRequestTimingEvent),
|
|
115
|
+
):
|
|
116
|
+
return
|
|
117
|
+
if isinstance(event, TokenCountEvent) and event.usage is not None:
|
|
118
|
+
return
|
|
119
|
+
if isinstance(event, AssistantDeltaEvent):
|
|
120
|
+
self.assistant_text += event.delta
|
|
121
|
+
elif isinstance(event, StreamErrorEvent):
|
|
122
|
+
self.assistant_text = ""
|
|
123
|
+
self.model_errors.append(event.detail())
|
|
124
|
+
event = replace(event, turn_id=self.turn_id)
|
|
125
|
+
self._observer(event)
|
|
126
|
+
|
|
127
|
+
|
|
87
128
|
class Agent:
|
|
88
129
|
"""Minimal Python port of Codex's turn loop.
|
|
89
130
|
|
|
@@ -112,19 +153,16 @@ class Agent:
|
|
|
112
153
|
)
|
|
113
154
|
self._parallel_tool_calls = parallel_tool_calls
|
|
114
155
|
self.event_handler = event_handler
|
|
156
|
+
self.runtime_scope = None
|
|
115
157
|
self._history: "typing.List[ConversationItem]" = list(initial_history)
|
|
116
|
-
self.history_revision = uuid7_string()
|
|
117
158
|
# Agent identity stays fixed when resume changes the rollout session.
|
|
118
159
|
self.agent_id = session_id
|
|
119
160
|
self.agent_path = agent_path
|
|
120
161
|
self._configure_recording(session_id, session_file_path)
|
|
121
162
|
self._last_total_usage_tokens: "typing.Union[int, None]" = None
|
|
122
|
-
self.
|
|
123
|
-
self._active_turn_id: "typing.Union[str, None]" = None
|
|
163
|
+
self._turn: "typing.Union[TurnContext, None]" = None
|
|
124
164
|
self.is_shutdown = False
|
|
125
165
|
self.accepts_input = True
|
|
126
|
-
self._stop_requested = False
|
|
127
|
-
self._follow_up_requested = False
|
|
128
166
|
|
|
129
167
|
@property
|
|
130
168
|
def history(self) -> "typing.Tuple[ConversationItem, ...]":
|
|
@@ -142,27 +180,28 @@ class Agent:
|
|
|
142
180
|
|
|
143
181
|
@property
|
|
144
182
|
def is_running(self) -> "bool":
|
|
145
|
-
return self.
|
|
183
|
+
return self._turn is not None
|
|
146
184
|
|
|
147
185
|
def execution_snapshot(self) -> "ExecutionSnapshot":
|
|
148
186
|
"""Read execution facts without retaining a second lifecycle state."""
|
|
149
187
|
return ExecutionSnapshot(
|
|
150
188
|
self.session_id, self.is_running,
|
|
151
|
-
self.
|
|
189
|
+
self._turn is not None and self._turn.stop_requested, self._last_total_usage_tokens,
|
|
152
190
|
)
|
|
153
191
|
|
|
154
192
|
async def wait_until_idle(self) -> "None":
|
|
155
|
-
while self.
|
|
156
|
-
await self.
|
|
193
|
+
while self._turn is not None:
|
|
194
|
+
await self._turn.finished.wait()
|
|
157
195
|
|
|
158
196
|
def stop_asap(self) -> "None":
|
|
159
|
-
if self.
|
|
160
|
-
self.
|
|
197
|
+
if self._turn is not None:
|
|
198
|
+
self._turn.stop_requested = True
|
|
199
|
+
self.model_client.stop_retry()
|
|
161
200
|
|
|
162
201
|
def request_follow_up(self) -> "None":
|
|
163
202
|
"""Keep the active turn open for input at its next safe boundary."""
|
|
164
|
-
if self.
|
|
165
|
-
self.
|
|
203
|
+
if self._turn is not None:
|
|
204
|
+
self._turn.follow_up_requested = True
|
|
166
205
|
|
|
167
206
|
def receive_messages(
|
|
168
207
|
self, messages: "typing.Tuple[typing.Union[UserMessage, AgentMessage, ToolResult], ...]",
|
|
@@ -203,7 +242,6 @@ class Agent:
|
|
|
203
242
|
restored_history = list(resumed["history"])
|
|
204
243
|
self._configure_recording(session_id, resumed["rollout_path"], resume=True)
|
|
205
244
|
self._history = restored_history
|
|
206
|
-
self.history_revision = uuid7_string()
|
|
207
245
|
self.context_manager.reset_history_context()
|
|
208
246
|
self._last_total_usage_tokens = None
|
|
209
247
|
self.is_shutdown = False
|
|
@@ -246,138 +284,165 @@ class Agent:
|
|
|
246
284
|
self,
|
|
247
285
|
prune_tool_results_on_context_error: "bool" = True,
|
|
248
286
|
) -> "typing.Union[CompactResult, None]":
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
287
|
+
with self._turn_context(busy_error="cannot compact while agent is running") as turn:
|
|
288
|
+
if not self._history:
|
|
289
|
+
return None
|
|
290
|
+
details = (turn.turn_id, "manual", None, None)
|
|
291
|
+
try:
|
|
292
|
+
with self._execution(turn, manual=True):
|
|
293
|
+
EventScope.emit(CompactStartedEvent(*details))
|
|
294
|
+
result = await self._run_compaction(
|
|
295
|
+
turn, prune_on_overflow=prune_tool_results_on_context_error,
|
|
296
|
+
record_usage=True,
|
|
297
|
+
)
|
|
298
|
+
except Exception as exc:
|
|
299
|
+
self._emit_terminal(CompactFailedEvent, *details, str(exc), type(exc).__name__)
|
|
300
|
+
raise
|
|
301
|
+
self._emit_terminal(
|
|
302
|
+
CompactCompletedEvent, *details, result.original_item_count,
|
|
303
|
+
result.retained_item_count, result.pruned_tool_results,
|
|
261
304
|
)
|
|
262
|
-
|
|
263
|
-
self._idle.set()
|
|
264
|
-
self._idle = None
|
|
305
|
+
return result
|
|
265
306
|
|
|
266
307
|
async def run_turn(
|
|
267
308
|
self, messages: "typing.Iterable[typing.Union[UserMessage, AgentMessage, ToolResult]]",
|
|
268
309
|
turn_id: "typing.Union[str, None]" = None,
|
|
269
310
|
) -> "TurnResult":
|
|
270
|
-
|
|
271
|
-
raise RuntimeError("agent is shutdown")
|
|
272
|
-
if self.is_running:
|
|
273
|
-
raise RuntimeError("agent already has an active turn")
|
|
274
|
-
self._stop_requested = False
|
|
275
|
-
self._follow_up_requested = False
|
|
276
|
-
self._idle = asyncio.Event()
|
|
277
|
-
turn = _TurnState(turn_id or uuid7_string())
|
|
278
|
-
self._active_turn_id = turn.turn_id
|
|
279
|
-
try:
|
|
280
|
-
messages = self._bind_turn(messages)
|
|
281
|
-
self._emit(TurnStartedEvent(turn.turn_id, messages))
|
|
311
|
+
with self._open_turn(messages, turn_id) as turn:
|
|
282
312
|
while True:
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
313
|
+
first = turn.iteration == 0
|
|
314
|
+
limit = self.context_manager.resolve_auto_compact_token_limit()
|
|
315
|
+
used = self._last_total_usage_tokens
|
|
316
|
+
if limit is not None and used is not None and used >= limit:
|
|
317
|
+
phase = "pre_turn" if first else "mid_turn"
|
|
318
|
+
await self._auto_compact(turn, phase, used, limit)
|
|
319
|
+
if first:
|
|
320
|
+
self._append_history(turn.messages)
|
|
321
|
+
turn.follow_up_requested = False
|
|
322
|
+
if turn.deliver_messages is not None:
|
|
323
|
+
turn.deliver_messages()
|
|
324
|
+
EventScope.emit(TurnInputReadyEvent(turn.turn_id))
|
|
325
|
+
if turn.stop_requested:
|
|
326
|
+
raise TurnInterrupted()
|
|
327
|
+
|
|
328
|
+
turn.iteration += 1
|
|
290
329
|
response = await self._sample(turn)
|
|
291
|
-
self.
|
|
292
|
-
|
|
293
|
-
turn.turn_id, turn.iteration, len(response.items)
|
|
294
|
-
)
|
|
295
|
-
)
|
|
330
|
+
if await self._run_tools(turn, response):
|
|
331
|
+
continue
|
|
296
332
|
self._append_history(response.items)
|
|
297
|
-
|
|
298
|
-
for item in response.items:
|
|
299
|
-
if isinstance(item, AssistantMessage):
|
|
300
|
-
turn.output_text = item.text
|
|
301
|
-
elif isinstance(item, ToolCall):
|
|
302
|
-
tool_calls.append(item)
|
|
303
|
-
|
|
304
|
-
if tool_calls:
|
|
305
|
-
await self._execute_tool_batch(turn.turn_id, tool_calls)
|
|
306
|
-
if self._stop_requested:
|
|
333
|
+
if turn.stop_requested:
|
|
307
334
|
raise TurnInterrupted()
|
|
308
|
-
if not
|
|
335
|
+
if not turn.follow_up_requested:
|
|
309
336
|
break
|
|
310
337
|
|
|
311
|
-
|
|
312
|
-
TurnCompletedEvent(
|
|
313
|
-
turn.turn_id,
|
|
314
|
-
turn.iteration,
|
|
315
|
-
turn.output_text,
|
|
316
|
-
self._background_work_count(TurnCompletedEvent),
|
|
317
|
-
)
|
|
318
|
-
)
|
|
319
|
-
result = TurnResult(
|
|
338
|
+
return TurnResult(
|
|
320
339
|
turn_id=turn.turn_id,
|
|
321
340
|
output_text=turn.output_text,
|
|
322
341
|
iterations=turn.iteration,
|
|
323
342
|
response_items=tuple(response.items),
|
|
324
343
|
history=self.history,
|
|
325
344
|
)
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
345
|
+
|
|
346
|
+
@contextmanager
|
|
347
|
+
def _turn_context(self, turn_id=None, busy_error="agent already has an active turn"):
|
|
348
|
+
if self.is_shutdown:
|
|
349
|
+
raise RuntimeError("agent is shutdown")
|
|
350
|
+
if self.is_running:
|
|
351
|
+
raise RuntimeError(busy_error)
|
|
352
|
+
turn = TurnContext(self.event_handler, turn_id)
|
|
353
|
+
try:
|
|
354
|
+
with EventScope.observe(turn.dispatch):
|
|
355
|
+
yield turn
|
|
356
|
+
finally:
|
|
357
|
+
turn.finished.set()
|
|
358
|
+
|
|
359
|
+
@contextmanager
|
|
360
|
+
def _open_turn(self, messages, turn_id):
|
|
361
|
+
with self._turn_context(turn_id) as turn:
|
|
362
|
+
try:
|
|
363
|
+
with self._execution(turn, messages):
|
|
364
|
+
EventScope.emit(TurnStartedEvent(turn.turn_id, turn.messages))
|
|
365
|
+
yield turn
|
|
366
|
+
except TurnInterrupted:
|
|
367
|
+
self._emit_terminal(
|
|
368
|
+
TurnInterruptedEvent, turn.turn_id, turn.iteration, turn.output_text,
|
|
334
369
|
)
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
self._remember_token_usage(exc.usage)
|
|
340
|
-
self._emit(TokenCountEvent(exc.usage, turn.turn_id))
|
|
341
|
-
self._emit(
|
|
342
|
-
TurnFailedEvent(
|
|
343
|
-
turn.turn_id,
|
|
344
|
-
turn.iteration,
|
|
345
|
-
str(exc),
|
|
346
|
-
type(exc).__name__,
|
|
347
|
-
self._background_work_count(TurnFailedEvent),
|
|
370
|
+
raise
|
|
371
|
+
except Exception as exc:
|
|
372
|
+
self._emit_terminal(
|
|
373
|
+
TurnFailedEvent, turn.turn_id, turn.iteration, str(exc), type(exc).__name__,
|
|
348
374
|
)
|
|
349
|
-
|
|
350
|
-
|
|
375
|
+
raise
|
|
376
|
+
self._emit_terminal(TurnCompletedEvent, turn.turn_id, turn.iteration, turn.output_text)
|
|
377
|
+
|
|
378
|
+
@contextmanager
|
|
379
|
+
def _bind_turn(self, turn, messages):
|
|
380
|
+
self._turn = turn
|
|
381
|
+
try:
|
|
382
|
+
turn.messages = turn.bind_items(messages)
|
|
383
|
+
yield turn
|
|
351
384
|
finally:
|
|
352
|
-
self.
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
385
|
+
self._turn = None
|
|
386
|
+
|
|
387
|
+
@contextmanager
|
|
388
|
+
def _execution(self, turn, messages=(), manual=False):
|
|
389
|
+
"""Let the Runtime observe input binding, tool cleanup and release of the Agent."""
|
|
390
|
+
try:
|
|
391
|
+
turn_scope = self._bind_turn(turn, messages)
|
|
392
|
+
if self.runtime_scope is not None:
|
|
393
|
+
turn_scope = self.runtime_scope(turn_scope, manual=manual)
|
|
394
|
+
with turn_scope, self.tool_registry.runtime_environment.execution(
|
|
395
|
+
self._save_environment_state, manual=manual,
|
|
396
|
+
):
|
|
397
|
+
yield
|
|
398
|
+
except ModelRequestInterrupted as exc:
|
|
399
|
+
raise TurnInterrupted() from exc
|
|
400
|
+
|
|
401
|
+
def _emit_terminal(self, event_type, *args):
|
|
402
|
+
try:
|
|
403
|
+
count = self.tool_registry.runtime_environment.background_work_count(
|
|
404
|
+
event_type in (TurnCompletedEvent, CompactCompletedEvent)
|
|
405
|
+
)
|
|
406
|
+
except (Exception, asyncio.CancelledError) as exc:
|
|
407
|
+
EventScope.report_observer_error(
|
|
408
|
+
"Agent background-work observer failed: " + event_type.kind, exc,
|
|
409
|
+
)
|
|
410
|
+
count = None
|
|
411
|
+
EventScope.emit(event_type(*args, count))
|
|
357
412
|
|
|
358
|
-
async def _sample(self, turn: "
|
|
413
|
+
async def _sample(self, turn: "TurnContext") -> "ModelResponse":
|
|
359
414
|
for attempt in range(2):
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
415
|
+
prompt = self._build_prompt(turn.turn_id, self._history)
|
|
416
|
+
EventScope.emit(ModelCalledEvent(
|
|
417
|
+
turn.turn_id, turn.iteration, len(prompt.input), len(prompt.tools),
|
|
418
|
+
))
|
|
364
419
|
try:
|
|
365
|
-
|
|
420
|
+
response = await self.model_client.complete(prompt)
|
|
421
|
+
break
|
|
422
|
+
except ResponsesIncompleteError as exc:
|
|
423
|
+
if exc.reason == "max_output_tokens":
|
|
424
|
+
self._append_history(
|
|
425
|
+
item for item in exc.partial_items
|
|
426
|
+
if isinstance(item, (AssistantMessage, ReasoningItem))
|
|
427
|
+
)
|
|
428
|
+
raise
|
|
366
429
|
except ContextLengthExceeded as exc:
|
|
430
|
+
self._record_usage(turn.turn_id, exc.usage)
|
|
367
431
|
if attempt == 1:
|
|
368
432
|
raise
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
await self._compact_history(
|
|
373
|
-
turn.turn_id,
|
|
374
|
-
phase="context_length_exceeded",
|
|
375
|
-
total_tokens=(
|
|
376
|
-
exc.usage.get("total_tokens") if exc.usage is not None else None
|
|
377
|
-
),
|
|
433
|
+
await self._auto_compact(
|
|
434
|
+
turn, phase="context_length_exceeded",
|
|
435
|
+
total_tokens=exc.usage.get("total_tokens") if exc.usage is not None else None,
|
|
378
436
|
token_limit=exc.token_limit,
|
|
379
|
-
prune_tool_results_on_context_error=True,
|
|
380
437
|
)
|
|
438
|
+
if turn.stop_requested:
|
|
439
|
+
raise TurnInterrupted()
|
|
440
|
+
self._record_usage(turn.turn_id, response.usage)
|
|
441
|
+
EventScope.emit(ModelCompletedEvent(turn.turn_id, turn.iteration, len(response.items)))
|
|
442
|
+
for item in response.items:
|
|
443
|
+
if isinstance(item, AssistantMessage):
|
|
444
|
+
turn.output_text = item.text
|
|
445
|
+
return response
|
|
381
446
|
|
|
382
447
|
def shutdown(self) -> "None":
|
|
383
448
|
if self.is_shutdown:
|
|
@@ -386,11 +451,12 @@ class Agent:
|
|
|
386
451
|
self.is_shutdown = True
|
|
387
452
|
self.tool_registry.runtime_environment.shutdown(self._save_environment_state)
|
|
388
453
|
|
|
389
|
-
async def
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
tool_calls:
|
|
393
|
-
|
|
454
|
+
async def _run_tools(self, turn: "TurnContext", response: "ModelResponse") -> "bool":
|
|
455
|
+
"""Record a tool-producing response and run its calls before the next sample."""
|
|
456
|
+
tool_calls = [item for item in response.items if isinstance(item, ToolCall)]
|
|
457
|
+
if not tool_calls:
|
|
458
|
+
return False
|
|
459
|
+
self._append_history(response.items)
|
|
394
460
|
batches: "typing.List[typing.List[ToolCall]]" = []
|
|
395
461
|
parallel_batch: "typing.List[ToolCall]" = []
|
|
396
462
|
for call in tool_calls:
|
|
@@ -411,12 +477,12 @@ class Agent:
|
|
|
411
477
|
|
|
412
478
|
results: "typing.List[ToolResult]" = []
|
|
413
479
|
for batch in batches:
|
|
414
|
-
history = self.history
|
|
480
|
+
history = self.history if turn.compact_input is None else tuple(turn.compact_input)
|
|
415
481
|
if len(batch) == 1:
|
|
416
|
-
results.append(await self._run_single_tool(
|
|
482
|
+
results.append(await self._run_single_tool(turn, batch[0], history))
|
|
417
483
|
continue
|
|
418
484
|
outcomes = await asyncio.gather(
|
|
419
|
-
*(self._run_single_tool(
|
|
485
|
+
*(self._run_single_tool(turn, call, history) for call in batch),
|
|
420
486
|
return_exceptions=True,
|
|
421
487
|
)
|
|
422
488
|
for outcome in outcomes:
|
|
@@ -425,81 +491,52 @@ class Agent:
|
|
|
425
491
|
results.append(outcome)
|
|
426
492
|
self._append_history(self.tool_registry.follow_up_messages(results))
|
|
427
493
|
self._append_history(self.tool_registry.runtime_environment.follow_up_messages())
|
|
494
|
+
if turn.stop_requested:
|
|
495
|
+
raise TurnInterrupted()
|
|
496
|
+
return True
|
|
428
497
|
|
|
429
498
|
async def _run_single_tool(
|
|
430
499
|
self,
|
|
431
|
-
|
|
500
|
+
turn: "TurnContext",
|
|
432
501
|
call: "ToolCall",
|
|
433
502
|
history: "typing.Tuple[ConversationItem, ...]",
|
|
434
503
|
) -> "ToolResult":
|
|
435
504
|
context = ToolContext(
|
|
436
|
-
turn_id=turn_id,
|
|
505
|
+
turn_id=turn.turn_id,
|
|
437
506
|
history=history,
|
|
438
507
|
cwd=self.context_manager.cwd,
|
|
439
508
|
agent_id=self.agent_id,
|
|
440
509
|
encrypted_messages=call.encrypted_function_args != [],
|
|
441
510
|
session_id=self.session_id,
|
|
442
511
|
)
|
|
443
|
-
|
|
512
|
+
EventScope.emit(ToolStartedEvent(turn.turn_id, call))
|
|
444
513
|
result = await self.tool_registry.execute(call, context)
|
|
445
514
|
self._append_history([truncate_tool_result_for_history(result)])
|
|
446
|
-
|
|
515
|
+
turn.assistant_text = ""
|
|
516
|
+
self._save_environment_state()
|
|
517
|
+
EventScope.emit(ToolCompletedEvent(turn.turn_id, call, result))
|
|
447
518
|
return result
|
|
448
519
|
|
|
449
520
|
def _save_environment_state(self) -> "None":
|
|
450
|
-
if self.recorded_session_file_path is not None
|
|
521
|
+
if self.recorded_session_file_path is not None and (
|
|
522
|
+
self._turn is None or self._turn.compact_input is None
|
|
523
|
+
):
|
|
451
524
|
self._rollout_recorder.save_environment_state(
|
|
452
525
|
self.tool_registry.runtime_environment.dump_state()
|
|
453
526
|
)
|
|
454
527
|
|
|
455
|
-
def _emit(self, event: "TurnEvent") -> "None":
|
|
456
|
-
environment = self.tool_registry.runtime_environment
|
|
457
|
-
environment.handle_agent_event(event)
|
|
458
|
-
if isinstance(event, (ToolCompletedEvent, TerminalEvent)):
|
|
459
|
-
self._save_environment_state()
|
|
460
|
-
handlers = environment.event_observers(event) + [self.event_handler]
|
|
461
|
-
for handler in handlers:
|
|
462
|
-
try:
|
|
463
|
-
handler(event)
|
|
464
|
-
except Exception as exc:
|
|
465
|
-
asyncio.get_running_loop().call_exception_handler(
|
|
466
|
-
{
|
|
467
|
-
"message": "Agent event observer failed: " + event.kind,
|
|
468
|
-
"exception": exc,
|
|
469
|
-
}
|
|
470
|
-
)
|
|
471
|
-
|
|
472
|
-
def _background_work_count(self, event_type) -> "typing.Union[int, None]":
|
|
473
|
-
try:
|
|
474
|
-
return self.tool_registry.runtime_environment.background_work_count(
|
|
475
|
-
event_type in (TurnCompletedEvent, CompactCompletedEvent)
|
|
476
|
-
)
|
|
477
|
-
except Exception as exc:
|
|
478
|
-
asyncio.get_running_loop().call_exception_handler(
|
|
479
|
-
{
|
|
480
|
-
"message": "Agent background-work observer failed: "
|
|
481
|
-
+ event_type.kind,
|
|
482
|
-
"exception": exc,
|
|
483
|
-
}
|
|
484
|
-
)
|
|
485
|
-
return None
|
|
486
|
-
|
|
487
|
-
def _bind_turn(
|
|
488
|
-
self, items: "typing.Iterable[ConversationItem]"
|
|
489
|
-
) -> "typing.Tuple[ConversationItem, ...]":
|
|
490
|
-
turn_id = self._active_turn_id
|
|
491
|
-
return tuple(
|
|
492
|
-
item if isinstance(item, (ToolCall, ToolResult, ReasoningItem))
|
|
493
|
-
else replace(item, turn_id=turn_id) if turn_id is not None
|
|
494
|
-
else item
|
|
495
|
-
for item in items
|
|
496
|
-
)
|
|
497
|
-
|
|
498
528
|
def _append_history(
|
|
499
529
|
self,
|
|
500
530
|
items: "typing.Iterable[ConversationItem]",
|
|
501
531
|
) -> "None":
|
|
502
|
-
|
|
532
|
+
turn = self._turn
|
|
533
|
+
items = tuple(items) if turn is None else turn.bind_items(items)
|
|
534
|
+
if turn is not None and turn.compact_input is not None:
|
|
535
|
+
turn.compact_input.extend(
|
|
536
|
+
replace(item, visible=False) if isinstance(item, AssistantMessage) else item
|
|
537
|
+
for item in items
|
|
538
|
+
)
|
|
539
|
+
return
|
|
503
540
|
if self._rollout_recorder is not None:
|
|
504
541
|
self._rollout_recorder.append_history_items(items, self._history)
|
|
505
542
|
self._history.extend(items)
|
|
@@ -507,147 +544,114 @@ class Agent:
|
|
|
507
544
|
item for item in items if isinstance(item, (UserMessage, AgentMessage, AssistantMessage))
|
|
508
545
|
)
|
|
509
546
|
if messages:
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
if isinstance(event, TokenCountEvent):
|
|
514
|
-
self._remember_token_usage(event.usage)
|
|
515
|
-
self._emit(replace(event, turn_id=turn_id))
|
|
547
|
+
if turn is not None and any(isinstance(item, AssistantMessage) for item in messages):
|
|
548
|
+
turn.assistant_text = ""
|
|
549
|
+
EventScope.emit(MessagesAddedEvent(messages[0].turn_id or "", messages))
|
|
516
550
|
|
|
517
|
-
def
|
|
518
|
-
if
|
|
519
|
-
return
|
|
520
|
-
try:
|
|
521
|
-
self._last_total_usage_tokens = int(usage["total_tokens"])
|
|
522
|
-
except (KeyError, TypeError, ValueError):
|
|
551
|
+
def _record_usage(self, turn_id, usage, update_context=True):
|
|
552
|
+
if usage is None:
|
|
523
553
|
return
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
554
|
+
if update_context:
|
|
555
|
+
try:
|
|
556
|
+
self._last_total_usage_tokens = int(usage["total_tokens"])
|
|
557
|
+
except (KeyError, TypeError, ValueError):
|
|
558
|
+
pass
|
|
559
|
+
self.tool_registry.runtime_environment.goal_manager.record_usage(usage)
|
|
560
|
+
EventScope.emit(TokenCountEvent(usage, turn_id))
|
|
561
|
+
|
|
562
|
+
def _build_prompt(self, turn_id: "str", history, capture_context: "bool" = True) -> "Prompt":
|
|
563
|
+
return self.context_manager.build_prompt(
|
|
564
|
+
history,
|
|
532
565
|
self.tool_registry.model_visible_specs(
|
|
533
566
|
self.context_manager.resolve_code_mode_only(),
|
|
534
567
|
),
|
|
535
568
|
self._parallel_tool_calls,
|
|
536
569
|
turn_id=turn_id,
|
|
537
570
|
reasoning_effort=self.model_client.reasoning_effort,
|
|
571
|
+
capture_context=capture_context,
|
|
538
572
|
session_id=self.session_id,
|
|
539
573
|
)
|
|
540
|
-
self._emit(
|
|
541
|
-
ModelCalledEvent(turn_id, iteration, len(prompt.input), len(prompt.tools))
|
|
542
|
-
)
|
|
543
|
-
try:
|
|
544
|
-
return await self.model_client.complete(
|
|
545
|
-
prompt,
|
|
546
|
-
lambda event: self._handle_model_stream_event(turn_id, event),
|
|
547
|
-
)
|
|
548
|
-
except ResponsesIncompleteError as exc:
|
|
549
|
-
if exc.reason == "max_output_tokens":
|
|
550
|
-
self._append_history(
|
|
551
|
-
item
|
|
552
|
-
for item in exc.partial_items
|
|
553
|
-
if isinstance(item, (AssistantMessage, ReasoningItem))
|
|
554
|
-
)
|
|
555
|
-
raise
|
|
556
574
|
|
|
557
|
-
async def
|
|
575
|
+
async def _auto_compact(
|
|
558
576
|
self,
|
|
559
|
-
|
|
577
|
+
turn: "TurnContext",
|
|
560
578
|
phase: "str",
|
|
579
|
+
total_tokens: "typing.Union[int, None]",
|
|
580
|
+
token_limit: "typing.Union[int, None]",
|
|
561
581
|
) -> "None":
|
|
562
|
-
limit = self.context_manager.resolve_auto_compact_token_limit()
|
|
563
|
-
total_tokens = self._last_total_usage_tokens
|
|
564
|
-
if limit is None or total_tokens is None:
|
|
565
|
-
return
|
|
566
|
-
if total_tokens < limit or not self._history:
|
|
567
|
-
return
|
|
568
|
-
|
|
569
|
-
await self._compact_history(
|
|
570
|
-
turn_id,
|
|
571
|
-
phase=phase,
|
|
572
|
-
total_tokens=total_tokens,
|
|
573
|
-
token_limit=limit,
|
|
574
|
-
prune_tool_results_on_context_error=True,
|
|
575
|
-
)
|
|
576
|
-
|
|
577
|
-
async def _compact_history(
|
|
578
|
-
self,
|
|
579
|
-
turn_id: "str",
|
|
580
|
-
phase: "str",
|
|
581
|
-
total_tokens: "typing.Union[int, None]" = None,
|
|
582
|
-
token_limit: "typing.Union[int, None]" = None,
|
|
583
|
-
prune_tool_results_on_context_error: "bool" = False,
|
|
584
|
-
) -> "typing.Union[CompactResult, None]":
|
|
585
|
-
from .utils.compactor import compact_history
|
|
586
|
-
|
|
587
582
|
if not self._history:
|
|
588
|
-
return
|
|
589
|
-
details = (turn_id, phase, total_tokens, token_limit)
|
|
590
|
-
started_type = (
|
|
591
|
-
CompactStartedEvent if phase == "manual" else AutoCompactStartedEvent
|
|
592
|
-
)
|
|
593
|
-
self._emit(started_type(*details))
|
|
594
|
-
|
|
595
|
-
def handle_compact_stream_event(event: "ModelEvent") -> "None":
|
|
596
|
-
if isinstance(event, (StreamErrorEvent, ModelRequestTimingEvent)) or (
|
|
597
|
-
phase == "manual" and isinstance(event, TokenCountEvent)
|
|
598
|
-
):
|
|
599
|
-
self._emit(replace(event, turn_id=turn_id))
|
|
600
|
-
|
|
583
|
+
return
|
|
584
|
+
details = (turn.turn_id, phase, total_tokens, token_limit)
|
|
601
585
|
try:
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
self.
|
|
605
|
-
|
|
606
|
-
self.
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
),
|
|
610
|
-
self._parallel_tool_calls,
|
|
611
|
-
handle_compact_stream_event,
|
|
612
|
-
prune_tool_results_on_context_error,
|
|
613
|
-
str(recorder.rollout_path) if recorder is not None else None,
|
|
614
|
-
turn_id,
|
|
615
|
-
self.session_id,
|
|
616
|
-
)
|
|
617
|
-
if recorder is not None:
|
|
618
|
-
recorder.append_compacted_history(compact_result.history, self._history)
|
|
619
|
-
self._history = list(compact_result.history)
|
|
620
|
-
self.history_revision = uuid7_string()
|
|
621
|
-
self.context_manager.reset_history_context()
|
|
622
|
-
self._last_total_usage_tokens = None
|
|
586
|
+
try:
|
|
587
|
+
EventScope.emit(AutoCompactStartedEvent(*details))
|
|
588
|
+
result = await self._run_compaction(turn)
|
|
589
|
+
finally:
|
|
590
|
+
self._save_environment_state()
|
|
591
|
+
except (TurnInterrupted, ModelRequestInterrupted):
|
|
592
|
+
raise
|
|
623
593
|
except Exception as exc:
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
*details,
|
|
628
|
-
str(exc),
|
|
629
|
-
type(exc).__name__,
|
|
630
|
-
self._background_work_count(CompactFailedEvent),
|
|
631
|
-
)
|
|
632
|
-
)
|
|
633
|
-
else:
|
|
634
|
-
self._emit(
|
|
635
|
-
AutoCompactFailedEvent(*details, str(exc), type(exc).__name__)
|
|
636
|
-
)
|
|
594
|
+
EventScope.emit(AutoCompactFailedEvent(*details, str(exc), type(exc).__name__))
|
|
595
|
+
if isinstance(exc, ContextLengthExceeded):
|
|
596
|
+
self._record_usage(turn.turn_id, exc.usage)
|
|
637
597
|
raise
|
|
598
|
+
EventScope.emit(AutoCompactCompletedEvent(
|
|
599
|
+
*details, result.original_item_count, result.retained_item_count, result.pruned_tool_results,
|
|
600
|
+
))
|
|
601
|
+
|
|
602
|
+
async def _run_compaction(
|
|
603
|
+
self, turn: "TurnContext", prune_on_overflow: "bool" = True, record_usage: "bool" = False,
|
|
604
|
+
) -> "CompactResult":
|
|
605
|
+
committed = self._history
|
|
606
|
+
working = [*committed, UserMessage(DEFAULT_COMPACT_PROMPT)]
|
|
607
|
+
first_exchange = len(working)
|
|
608
|
+
history = working
|
|
609
|
+
pruned = 0
|
|
610
|
+
recorder = self._rollout_recorder
|
|
611
|
+
turn.compact_input = working
|
|
612
|
+
try:
|
|
613
|
+
while True:
|
|
614
|
+
prompt = self._build_prompt(turn.turn_id, history, capture_context=False)
|
|
615
|
+
try:
|
|
616
|
+
response = await self.model_client.complete(prompt)
|
|
617
|
+
except ContextLengthExceeded:
|
|
618
|
+
if not prune_on_overflow:
|
|
619
|
+
raise
|
|
620
|
+
history = prune_oldest_tool_response(history)
|
|
621
|
+
if history is None:
|
|
622
|
+
raise
|
|
623
|
+
pruned += 1
|
|
624
|
+
continue
|
|
625
|
+
except ResponsesIncompleteError as exc:
|
|
626
|
+
if (
|
|
627
|
+
exc.reason != "max_output_tokens"
|
|
628
|
+
or not any(isinstance(item, AssistantMessage) for item in exc.partial_items)
|
|
629
|
+
or any(isinstance(item, ToolCall) for item in exc.partial_items)
|
|
630
|
+
):
|
|
631
|
+
raise
|
|
632
|
+
response = ModelResponse(list(exc.partial_items))
|
|
633
|
+
if record_usage:
|
|
634
|
+
self._record_usage(turn.turn_id, response.usage, update_context=False)
|
|
635
|
+
if not await self._run_tools(turn, response):
|
|
636
|
+
break
|
|
637
|
+
history = prune_oldest_tool_response(working, pruned)
|
|
638
638
|
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
compact_result.retained_item_count,
|
|
642
|
-
compact_result.pruned_tool_results,
|
|
643
|
-
)
|
|
644
|
-
if phase == "manual":
|
|
645
|
-
self._emit(
|
|
646
|
-
CompactCompletedEvent(
|
|
647
|
-
*completed,
|
|
648
|
-
self._background_work_count(CompactCompletedEvent),
|
|
649
|
-
)
|
|
639
|
+
result = CompactResult.from_response(
|
|
640
|
+
response, self.session_file_path, len(committed), pruned,
|
|
650
641
|
)
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
642
|
+
if recorder is not None:
|
|
643
|
+
recorder.append_compacted_history(result.history, committed)
|
|
644
|
+
except BaseException:
|
|
645
|
+
exchanges = working[first_exchange:]
|
|
646
|
+
if exchanges:
|
|
647
|
+
if recorder is not None:
|
|
648
|
+
recorder.append_history_items(exchanges, committed)
|
|
649
|
+
self._history = committed + exchanges
|
|
650
|
+
raise
|
|
651
|
+
finally:
|
|
652
|
+
turn.compact_input = None
|
|
653
|
+
|
|
654
|
+
self._history = list(result.history)
|
|
655
|
+
self.context_manager.reset_history_context()
|
|
656
|
+
self._last_total_usage_tokens = None
|
|
657
|
+
return result
|