python-codex 0.6.2__py3-none-any.whl → 0.7.0__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 -314
- pycodex/bootstrap.py +8 -0
- pycodex/config.py +4 -2
- pycodex/context.py +32 -11
- pycodex/events.py +116 -7
- pycodex/model.py +214 -99
- pycodex/multi_agents.py +11 -40
- pycodex/prompts/models.json +351 -6
- pycodex/protocol.py +1 -0
- pycodex/runtime.py +173 -127
- pycodex/tools/__init__.py +1 -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 +15 -3
- pycodex/utils/compactor.py +28 -98
- pycodex/utils/compat.py +6 -0
- pycodex/utils/event_helpers.py +9 -0
- pycodex/utils/http_headers.py +25 -0
- pycodex/utils/model_metadata.py +5 -4
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/METADATA +34 -8
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/RECORD +35 -34
- responses_server/app.py +6 -0
- responses_server/config.py +4 -1
- responses_server/gemini_api.py +40 -13
- responses_server/messages_api.py +12 -6
- responses_server/payload_processors.py +1 -1
- responses_server/request_translation.py +55 -13
- responses_server/stream_router.py +9 -0
- responses_server/transport.py +24 -11
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/WHEEL +0 -0
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/entry_points.txt +0 -0
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.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,18 +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
158
|
# Agent identity stays fixed when resume changes the rollout session.
|
|
117
159
|
self.agent_id = session_id
|
|
118
160
|
self.agent_path = agent_path
|
|
119
161
|
self._configure_recording(session_id, session_file_path)
|
|
120
162
|
self._last_total_usage_tokens: "typing.Union[int, None]" = None
|
|
121
|
-
self.
|
|
122
|
-
self._active_turn_id: "typing.Union[str, None]" = None
|
|
163
|
+
self._turn: "typing.Union[TurnContext, None]" = None
|
|
123
164
|
self.is_shutdown = False
|
|
124
165
|
self.accepts_input = True
|
|
125
|
-
self._stop_requested = False
|
|
126
|
-
self._follow_up_requested = False
|
|
127
166
|
|
|
128
167
|
@property
|
|
129
168
|
def history(self) -> "typing.Tuple[ConversationItem, ...]":
|
|
@@ -141,27 +180,28 @@ class Agent:
|
|
|
141
180
|
|
|
142
181
|
@property
|
|
143
182
|
def is_running(self) -> "bool":
|
|
144
|
-
return self.
|
|
183
|
+
return self._turn is not None
|
|
145
184
|
|
|
146
185
|
def execution_snapshot(self) -> "ExecutionSnapshot":
|
|
147
186
|
"""Read execution facts without retaining a second lifecycle state."""
|
|
148
187
|
return ExecutionSnapshot(
|
|
149
188
|
self.session_id, self.is_running,
|
|
150
|
-
self.
|
|
189
|
+
self._turn is not None and self._turn.stop_requested, self._last_total_usage_tokens,
|
|
151
190
|
)
|
|
152
191
|
|
|
153
192
|
async def wait_until_idle(self) -> "None":
|
|
154
|
-
while self.
|
|
155
|
-
await self.
|
|
193
|
+
while self._turn is not None:
|
|
194
|
+
await self._turn.finished.wait()
|
|
156
195
|
|
|
157
196
|
def stop_asap(self) -> "None":
|
|
158
|
-
if self.
|
|
159
|
-
self.
|
|
197
|
+
if self._turn is not None:
|
|
198
|
+
self._turn.stop_requested = True
|
|
199
|
+
self.model_client.stop_retry()
|
|
160
200
|
|
|
161
201
|
def request_follow_up(self) -> "None":
|
|
162
202
|
"""Keep the active turn open for input at its next safe boundary."""
|
|
163
|
-
if self.
|
|
164
|
-
self.
|
|
203
|
+
if self._turn is not None:
|
|
204
|
+
self._turn.follow_up_requested = True
|
|
165
205
|
|
|
166
206
|
def receive_messages(
|
|
167
207
|
self, messages: "typing.Tuple[typing.Union[UserMessage, AgentMessage, ToolResult], ...]",
|
|
@@ -244,138 +284,165 @@ class Agent:
|
|
|
244
284
|
self,
|
|
245
285
|
prune_tool_results_on_context_error: "bool" = True,
|
|
246
286
|
) -> "typing.Union[CompactResult, None]":
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
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,
|
|
259
304
|
)
|
|
260
|
-
|
|
261
|
-
self._idle.set()
|
|
262
|
-
self._idle = None
|
|
305
|
+
return result
|
|
263
306
|
|
|
264
307
|
async def run_turn(
|
|
265
308
|
self, messages: "typing.Iterable[typing.Union[UserMessage, AgentMessage, ToolResult]]",
|
|
266
309
|
turn_id: "typing.Union[str, None]" = None,
|
|
267
310
|
) -> "TurnResult":
|
|
268
|
-
|
|
269
|
-
raise RuntimeError("agent is shutdown")
|
|
270
|
-
if self.is_running:
|
|
271
|
-
raise RuntimeError("agent already has an active turn")
|
|
272
|
-
self._stop_requested = False
|
|
273
|
-
self._follow_up_requested = False
|
|
274
|
-
self._idle = asyncio.Event()
|
|
275
|
-
turn = _TurnState(turn_id or uuid7_string())
|
|
276
|
-
self._active_turn_id = turn.turn_id
|
|
277
|
-
try:
|
|
278
|
-
messages = self._bind_turn(messages)
|
|
279
|
-
self._emit(TurnStartedEvent(turn.turn_id, messages))
|
|
311
|
+
with self._open_turn(messages, turn_id) as turn:
|
|
280
312
|
while True:
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
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
|
|
288
329
|
response = await self._sample(turn)
|
|
289
|
-
self.
|
|
290
|
-
|
|
291
|
-
turn.turn_id, turn.iteration, len(response.items)
|
|
292
|
-
)
|
|
293
|
-
)
|
|
330
|
+
if await self._run_tools(turn, response):
|
|
331
|
+
continue
|
|
294
332
|
self._append_history(response.items)
|
|
295
|
-
|
|
296
|
-
for item in response.items:
|
|
297
|
-
if isinstance(item, AssistantMessage):
|
|
298
|
-
turn.output_text = item.text
|
|
299
|
-
elif isinstance(item, ToolCall):
|
|
300
|
-
tool_calls.append(item)
|
|
301
|
-
|
|
302
|
-
if tool_calls:
|
|
303
|
-
await self._execute_tool_batch(turn.turn_id, tool_calls)
|
|
304
|
-
if self._stop_requested:
|
|
333
|
+
if turn.stop_requested:
|
|
305
334
|
raise TurnInterrupted()
|
|
306
|
-
if not
|
|
335
|
+
if not turn.follow_up_requested:
|
|
307
336
|
break
|
|
308
337
|
|
|
309
|
-
|
|
310
|
-
TurnCompletedEvent(
|
|
311
|
-
turn.turn_id,
|
|
312
|
-
turn.iteration,
|
|
313
|
-
turn.output_text,
|
|
314
|
-
self._background_work_count(TurnCompletedEvent),
|
|
315
|
-
)
|
|
316
|
-
)
|
|
317
|
-
result = TurnResult(
|
|
338
|
+
return TurnResult(
|
|
318
339
|
turn_id=turn.turn_id,
|
|
319
340
|
output_text=turn.output_text,
|
|
320
341
|
iterations=turn.iteration,
|
|
321
342
|
response_items=tuple(response.items),
|
|
322
343
|
history=self.history,
|
|
323
344
|
)
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
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,
|
|
332
369
|
)
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
self._remember_token_usage(exc.usage)
|
|
338
|
-
self._emit(TokenCountEvent(exc.usage, turn.turn_id))
|
|
339
|
-
self._emit(
|
|
340
|
-
TurnFailedEvent(
|
|
341
|
-
turn.turn_id,
|
|
342
|
-
turn.iteration,
|
|
343
|
-
str(exc),
|
|
344
|
-
type(exc).__name__,
|
|
345
|
-
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__,
|
|
346
374
|
)
|
|
347
|
-
|
|
348
|
-
|
|
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
|
|
349
384
|
finally:
|
|
350
|
-
self.
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
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))
|
|
355
412
|
|
|
356
|
-
async def _sample(self, turn: "
|
|
413
|
+
async def _sample(self, turn: "TurnContext") -> "ModelResponse":
|
|
357
414
|
for attempt in range(2):
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
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
|
+
))
|
|
362
419
|
try:
|
|
363
|
-
|
|
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
|
|
364
429
|
except ContextLengthExceeded as exc:
|
|
430
|
+
self._record_usage(turn.turn_id, exc.usage)
|
|
365
431
|
if attempt == 1:
|
|
366
432
|
raise
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
await self._compact_history(
|
|
371
|
-
turn.turn_id,
|
|
372
|
-
phase="context_length_exceeded",
|
|
373
|
-
total_tokens=(
|
|
374
|
-
exc.usage.get("total_tokens") if exc.usage is not None else None
|
|
375
|
-
),
|
|
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,
|
|
376
436
|
token_limit=exc.token_limit,
|
|
377
|
-
prune_tool_results_on_context_error=True,
|
|
378
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
|
|
379
446
|
|
|
380
447
|
def shutdown(self) -> "None":
|
|
381
448
|
if self.is_shutdown:
|
|
@@ -384,11 +451,12 @@ class Agent:
|
|
|
384
451
|
self.is_shutdown = True
|
|
385
452
|
self.tool_registry.runtime_environment.shutdown(self._save_environment_state)
|
|
386
453
|
|
|
387
|
-
async def
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
tool_calls:
|
|
391
|
-
|
|
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)
|
|
392
460
|
batches: "typing.List[typing.List[ToolCall]]" = []
|
|
393
461
|
parallel_batch: "typing.List[ToolCall]" = []
|
|
394
462
|
for call in tool_calls:
|
|
@@ -409,12 +477,12 @@ class Agent:
|
|
|
409
477
|
|
|
410
478
|
results: "typing.List[ToolResult]" = []
|
|
411
479
|
for batch in batches:
|
|
412
|
-
history = self.history
|
|
480
|
+
history = self.history if turn.compact_input is None else tuple(turn.compact_input)
|
|
413
481
|
if len(batch) == 1:
|
|
414
|
-
results.append(await self._run_single_tool(
|
|
482
|
+
results.append(await self._run_single_tool(turn, batch[0], history))
|
|
415
483
|
continue
|
|
416
484
|
outcomes = await asyncio.gather(
|
|
417
|
-
*(self._run_single_tool(
|
|
485
|
+
*(self._run_single_tool(turn, call, history) for call in batch),
|
|
418
486
|
return_exceptions=True,
|
|
419
487
|
)
|
|
420
488
|
for outcome in outcomes:
|
|
@@ -423,81 +491,52 @@ class Agent:
|
|
|
423
491
|
results.append(outcome)
|
|
424
492
|
self._append_history(self.tool_registry.follow_up_messages(results))
|
|
425
493
|
self._append_history(self.tool_registry.runtime_environment.follow_up_messages())
|
|
494
|
+
if turn.stop_requested:
|
|
495
|
+
raise TurnInterrupted()
|
|
496
|
+
return True
|
|
426
497
|
|
|
427
498
|
async def _run_single_tool(
|
|
428
499
|
self,
|
|
429
|
-
|
|
500
|
+
turn: "TurnContext",
|
|
430
501
|
call: "ToolCall",
|
|
431
502
|
history: "typing.Tuple[ConversationItem, ...]",
|
|
432
503
|
) -> "ToolResult":
|
|
433
504
|
context = ToolContext(
|
|
434
|
-
turn_id=turn_id,
|
|
505
|
+
turn_id=turn.turn_id,
|
|
435
506
|
history=history,
|
|
436
507
|
cwd=self.context_manager.cwd,
|
|
437
508
|
agent_id=self.agent_id,
|
|
438
509
|
encrypted_messages=call.encrypted_function_args != [],
|
|
439
510
|
session_id=self.session_id,
|
|
440
511
|
)
|
|
441
|
-
|
|
512
|
+
EventScope.emit(ToolStartedEvent(turn.turn_id, call))
|
|
442
513
|
result = await self.tool_registry.execute(call, context)
|
|
443
514
|
self._append_history([truncate_tool_result_for_history(result)])
|
|
444
|
-
|
|
515
|
+
turn.assistant_text = ""
|
|
516
|
+
self._save_environment_state()
|
|
517
|
+
EventScope.emit(ToolCompletedEvent(turn.turn_id, call, result))
|
|
445
518
|
return result
|
|
446
519
|
|
|
447
520
|
def _save_environment_state(self) -> "None":
|
|
448
|
-
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
|
+
):
|
|
449
524
|
self._rollout_recorder.save_environment_state(
|
|
450
525
|
self.tool_registry.runtime_environment.dump_state()
|
|
451
526
|
)
|
|
452
527
|
|
|
453
|
-
def _emit(self, event: "TurnEvent") -> "None":
|
|
454
|
-
environment = self.tool_registry.runtime_environment
|
|
455
|
-
environment.handle_agent_event(event)
|
|
456
|
-
if isinstance(event, (ToolCompletedEvent, TerminalEvent)):
|
|
457
|
-
self._save_environment_state()
|
|
458
|
-
handlers = environment.event_observers(event) + [self.event_handler]
|
|
459
|
-
for handler in handlers:
|
|
460
|
-
try:
|
|
461
|
-
handler(event)
|
|
462
|
-
except Exception as exc:
|
|
463
|
-
asyncio.get_running_loop().call_exception_handler(
|
|
464
|
-
{
|
|
465
|
-
"message": "Agent event observer failed: " + event.kind,
|
|
466
|
-
"exception": exc,
|
|
467
|
-
}
|
|
468
|
-
)
|
|
469
|
-
|
|
470
|
-
def _background_work_count(self, event_type) -> "typing.Union[int, None]":
|
|
471
|
-
try:
|
|
472
|
-
return self.tool_registry.runtime_environment.background_work_count(
|
|
473
|
-
event_type in (TurnCompletedEvent, CompactCompletedEvent)
|
|
474
|
-
)
|
|
475
|
-
except Exception as exc:
|
|
476
|
-
asyncio.get_running_loop().call_exception_handler(
|
|
477
|
-
{
|
|
478
|
-
"message": "Agent background-work observer failed: "
|
|
479
|
-
+ event_type.kind,
|
|
480
|
-
"exception": exc,
|
|
481
|
-
}
|
|
482
|
-
)
|
|
483
|
-
return None
|
|
484
|
-
|
|
485
|
-
def _bind_turn(
|
|
486
|
-
self, items: "typing.Iterable[ConversationItem]"
|
|
487
|
-
) -> "typing.Tuple[ConversationItem, ...]":
|
|
488
|
-
turn_id = self._active_turn_id
|
|
489
|
-
return tuple(
|
|
490
|
-
item if isinstance(item, (ToolCall, ToolResult, ReasoningItem))
|
|
491
|
-
else replace(item, turn_id=turn_id) if turn_id is not None
|
|
492
|
-
else item
|
|
493
|
-
for item in items
|
|
494
|
-
)
|
|
495
|
-
|
|
496
528
|
def _append_history(
|
|
497
529
|
self,
|
|
498
530
|
items: "typing.Iterable[ConversationItem]",
|
|
499
531
|
) -> "None":
|
|
500
|
-
|
|
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
|
|
501
540
|
if self._rollout_recorder is not None:
|
|
502
541
|
self._rollout_recorder.append_history_items(items, self._history)
|
|
503
542
|
self._history.extend(items)
|
|
@@ -505,142 +544,114 @@ class Agent:
|
|
|
505
544
|
item for item in items if isinstance(item, (UserMessage, AgentMessage, AssistantMessage))
|
|
506
545
|
)
|
|
507
546
|
if messages:
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
if isinstance(event, TokenCountEvent):
|
|
512
|
-
self._remember_token_usage(event.usage)
|
|
513
|
-
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))
|
|
514
550
|
|
|
515
|
-
def
|
|
516
|
-
if
|
|
517
|
-
return
|
|
518
|
-
try:
|
|
519
|
-
self._last_total_usage_tokens = int(usage["total_tokens"])
|
|
520
|
-
except (KeyError, TypeError, ValueError):
|
|
551
|
+
def _record_usage(self, turn_id, usage, update_context=True):
|
|
552
|
+
if usage is None:
|
|
521
553
|
return
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
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,
|
|
530
565
|
self.tool_registry.model_visible_specs(
|
|
531
566
|
self.context_manager.resolve_code_mode_only(),
|
|
532
567
|
),
|
|
533
568
|
self._parallel_tool_calls,
|
|
534
569
|
turn_id=turn_id,
|
|
535
570
|
reasoning_effort=self.model_client.reasoning_effort,
|
|
571
|
+
capture_context=capture_context,
|
|
536
572
|
session_id=self.session_id,
|
|
537
573
|
)
|
|
538
|
-
self._emit(
|
|
539
|
-
ModelCalledEvent(turn_id, iteration, len(prompt.input), len(prompt.tools))
|
|
540
|
-
)
|
|
541
|
-
try:
|
|
542
|
-
return await self.model_client.complete(
|
|
543
|
-
prompt,
|
|
544
|
-
lambda event: self._handle_model_stream_event(turn_id, event),
|
|
545
|
-
)
|
|
546
|
-
except ResponsesIncompleteError as exc:
|
|
547
|
-
if exc.reason == "max_output_tokens":
|
|
548
|
-
self._append_history(
|
|
549
|
-
item
|
|
550
|
-
for item in exc.partial_items
|
|
551
|
-
if isinstance(item, (AssistantMessage, ReasoningItem))
|
|
552
|
-
)
|
|
553
|
-
raise
|
|
554
574
|
|
|
555
|
-
async def
|
|
575
|
+
async def _auto_compact(
|
|
556
576
|
self,
|
|
557
|
-
|
|
577
|
+
turn: "TurnContext",
|
|
558
578
|
phase: "str",
|
|
579
|
+
total_tokens: "typing.Union[int, None]",
|
|
580
|
+
token_limit: "typing.Union[int, None]",
|
|
559
581
|
) -> "None":
|
|
560
|
-
limit = self.context_manager.resolve_auto_compact_token_limit()
|
|
561
|
-
total_tokens = self._last_total_usage_tokens
|
|
562
|
-
if limit is None or total_tokens is None:
|
|
563
|
-
return
|
|
564
|
-
if total_tokens < limit or not self._history:
|
|
565
|
-
return
|
|
566
|
-
|
|
567
|
-
await self._compact_history(
|
|
568
|
-
turn_id,
|
|
569
|
-
phase=phase,
|
|
570
|
-
total_tokens=total_tokens,
|
|
571
|
-
token_limit=limit,
|
|
572
|
-
prune_tool_results_on_context_error=True,
|
|
573
|
-
)
|
|
574
|
-
|
|
575
|
-
async def _compact_history(
|
|
576
|
-
self,
|
|
577
|
-
turn_id: "str",
|
|
578
|
-
phase: "str",
|
|
579
|
-
total_tokens: "typing.Union[int, None]" = None,
|
|
580
|
-
token_limit: "typing.Union[int, None]" = None,
|
|
581
|
-
prune_tool_results_on_context_error: "bool" = False,
|
|
582
|
-
) -> "typing.Union[CompactResult, None]":
|
|
583
|
-
from .utils.compactor import compact_history
|
|
584
|
-
|
|
585
582
|
if not self._history:
|
|
586
|
-
return
|
|
587
|
-
details = (turn_id, phase, total_tokens, token_limit)
|
|
588
|
-
started_type = (
|
|
589
|
-
CompactStartedEvent if phase == "manual" else AutoCompactStartedEvent
|
|
590
|
-
)
|
|
591
|
-
self._emit(started_type(*details))
|
|
592
|
-
|
|
593
|
-
def handle_compact_stream_event(event: "ModelEvent") -> "None":
|
|
594
|
-
if isinstance(event, (StreamErrorEvent, ModelRequestTimingEvent)) or (
|
|
595
|
-
phase == "manual" and isinstance(event, TokenCountEvent)
|
|
596
|
-
):
|
|
597
|
-
self._emit(replace(event, turn_id=turn_id))
|
|
598
|
-
|
|
583
|
+
return
|
|
584
|
+
details = (turn.turn_id, phase, total_tokens, token_limit)
|
|
599
585
|
try:
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
self.
|
|
603
|
-
|
|
604
|
-
self.
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
str(recorder.rollout_path) if recorder is not None else None,
|
|
608
|
-
turn_id,
|
|
609
|
-
self.session_id,
|
|
610
|
-
)
|
|
611
|
-
if recorder is not None:
|
|
612
|
-
recorder.append_compacted_history(compact_result.history, self._history)
|
|
613
|
-
self._history = list(compact_result.history)
|
|
614
|
-
self.context_manager.reset_history_context()
|
|
615
|
-
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
|
|
616
593
|
except Exception as exc:
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
*details,
|
|
621
|
-
str(exc),
|
|
622
|
-
type(exc).__name__,
|
|
623
|
-
self._background_work_count(CompactFailedEvent),
|
|
624
|
-
)
|
|
625
|
-
)
|
|
626
|
-
else:
|
|
627
|
-
self._emit(
|
|
628
|
-
AutoCompactFailedEvent(*details, str(exc), type(exc).__name__)
|
|
629
|
-
)
|
|
594
|
+
EventScope.emit(AutoCompactFailedEvent(*details, str(exc), type(exc).__name__))
|
|
595
|
+
if isinstance(exc, ContextLengthExceeded):
|
|
596
|
+
self._record_usage(turn.turn_id, exc.usage)
|
|
630
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)
|
|
631
638
|
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
compact_result.retained_item_count,
|
|
635
|
-
compact_result.pruned_tool_results,
|
|
636
|
-
)
|
|
637
|
-
if phase == "manual":
|
|
638
|
-
self._emit(
|
|
639
|
-
CompactCompletedEvent(
|
|
640
|
-
*completed,
|
|
641
|
-
self._background_work_count(CompactCompletedEvent),
|
|
642
|
-
)
|
|
639
|
+
result = CompactResult.from_response(
|
|
640
|
+
response, self.session_file_path, len(committed), pruned,
|
|
643
641
|
)
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
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
|