braid-agent 0.1.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.
- braid_agent/__init__.py +123 -0
- braid_agent/agent.py +589 -0
- braid_agent/loop.py +1533 -0
- braid_agent/queues.py +61 -0
- braid_agent/tools.py +198 -0
- braid_agent/types.py +675 -0
- braid_agent-0.1.0.dist-info/METADATA +8 -0
- braid_agent-0.1.0.dist-info/RECORD +10 -0
- braid_agent-0.1.0.dist-info/WHEEL +4 -0
- braid_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
braid_agent/loop.py
ADDED
|
@@ -0,0 +1,1533 @@
|
|
|
1
|
+
"""回合状态机:一次 prompt 如何变成一串事件、消息与工具结果。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import copy
|
|
7
|
+
import inspect
|
|
8
|
+
import json
|
|
9
|
+
from collections.abc import Awaitable, Coroutine, Sequence
|
|
10
|
+
from dataclasses import dataclass, field, replace
|
|
11
|
+
from typing import Any, Literal, cast
|
|
12
|
+
|
|
13
|
+
from braid_agent.tools import (
|
|
14
|
+
AgentTool,
|
|
15
|
+
AgentToolCallOutcome,
|
|
16
|
+
AgentToolResult,
|
|
17
|
+
ToolUpdateSink,
|
|
18
|
+
tool_declarations,
|
|
19
|
+
tool_timeout_seconds,
|
|
20
|
+
)
|
|
21
|
+
from braid_agent.types import (
|
|
22
|
+
DEFAULT_TOOL_TIMEOUT_GRACE_SECONDS,
|
|
23
|
+
AfterToolCall,
|
|
24
|
+
AfterToolCallContext,
|
|
25
|
+
AfterToolCallResult,
|
|
26
|
+
AgentContext,
|
|
27
|
+
AgentEndEvent,
|
|
28
|
+
AgentEvent,
|
|
29
|
+
AgentEventSink,
|
|
30
|
+
AgentLoopConfig,
|
|
31
|
+
AgentMessage,
|
|
32
|
+
AgentStartEvent,
|
|
33
|
+
AgentTurnContext,
|
|
34
|
+
BeforeToolCall,
|
|
35
|
+
BeforeToolCallContext,
|
|
36
|
+
LoopGuardTriggeredEvent,
|
|
37
|
+
MessageEndEvent,
|
|
38
|
+
MessagePoller,
|
|
39
|
+
MessageStartEvent,
|
|
40
|
+
MessageUpdateEvent,
|
|
41
|
+
StreamFn,
|
|
42
|
+
ToolExecutionEndEvent,
|
|
43
|
+
ToolExecutionStartEvent,
|
|
44
|
+
ToolExecutionUpdateEvent,
|
|
45
|
+
TurnAction,
|
|
46
|
+
TurnEndEvent,
|
|
47
|
+
TurnStartEvent,
|
|
48
|
+
failure_message_text,
|
|
49
|
+
)
|
|
50
|
+
from braid_ai.cancel import CancelToken
|
|
51
|
+
from braid_ai.event_stream import EventStream
|
|
52
|
+
from braid_ai.transcript import (
|
|
53
|
+
ToolStateChanges,
|
|
54
|
+
get_current_tools,
|
|
55
|
+
get_tool_state_changes,
|
|
56
|
+
to_tool_declaration,
|
|
57
|
+
)
|
|
58
|
+
from braid_ai.types import (
|
|
59
|
+
AssistantMessage,
|
|
60
|
+
DoneEvent,
|
|
61
|
+
ErrorEvent,
|
|
62
|
+
JsonValue,
|
|
63
|
+
StartEvent,
|
|
64
|
+
SystemMessage,
|
|
65
|
+
TextContent,
|
|
66
|
+
TextDeltaEvent,
|
|
67
|
+
TextEndEvent,
|
|
68
|
+
TextStartEvent,
|
|
69
|
+
ThinkingDeltaEvent,
|
|
70
|
+
ThinkingEndEvent,
|
|
71
|
+
ThinkingStartEvent,
|
|
72
|
+
ToolCall,
|
|
73
|
+
ToolCallDeltaEvent,
|
|
74
|
+
ToolCallEndEvent,
|
|
75
|
+
ToolCallStartEvent,
|
|
76
|
+
ToolResultMessage,
|
|
77
|
+
TranscriptContext,
|
|
78
|
+
)
|
|
79
|
+
from braid_ai.utils.clock import Clock
|
|
80
|
+
from braid_ai.validation import validate_tool_arguments
|
|
81
|
+
|
|
82
|
+
#: 一次 run 的事件流;结果值是本次 run 产生的消息列表。
|
|
83
|
+
type AgentEventStream = EventStream[AgentEvent, list[AgentMessage]]
|
|
84
|
+
|
|
85
|
+
#: 后台转发任务必须有人持有引用,否则可能在消费者的 ``async for`` 里被 GC 掉;
|
|
86
|
+
#: 任务结束即移除。放在模块级是因为这里只有函数、没有可挂载的实例。
|
|
87
|
+
_background: set[asyncio.Task[None]] = set()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# ---------------------------------------------------------------------- 公开入口
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def agent_loop(
|
|
94
|
+
prompts: Sequence[AgentMessage],
|
|
95
|
+
context: AgentContext,
|
|
96
|
+
config: AgentLoopConfig,
|
|
97
|
+
*,
|
|
98
|
+
stream_fn: StreamFn,
|
|
99
|
+
signal: CancelToken | None = None,
|
|
100
|
+
) -> AgentEventStream:
|
|
101
|
+
"""用一组新 prompt 启动一次 run,返回事件流。
|
|
102
|
+
|
|
103
|
+
流在后台任务里推进,调用方立刻拿到流:``async for`` 收事件,``await stream.result()``
|
|
104
|
+
拿本次 run 产生的消息。终态事件是 ``agent_end``。
|
|
105
|
+
|
|
106
|
+
:param prompts: 追加到上下文末尾的消息,按顺序发 ``message_start`` / ``message_end``。
|
|
107
|
+
:param context: 进入本次 run 的转录快照与可执行工具。内部复制转录的顶层列表,
|
|
108
|
+
不改写调用方的列表;``tools`` 按原样使用(工具对象本身是共享的)。
|
|
109
|
+
:raises RuntimeError: 不在事件循环内调用(后台任务需要运行中的 loop)。
|
|
110
|
+
"""
|
|
111
|
+
_require_running_loop("agent_loop")
|
|
112
|
+
stream = _create_agent_stream()
|
|
113
|
+
coroutine = run_agent_loop(
|
|
114
|
+
prompts, context, config, stream.push, stream_fn=stream_fn, signal=signal
|
|
115
|
+
)
|
|
116
|
+
_drive_in_background(stream, coroutine, config)
|
|
117
|
+
return stream
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def agent_loop_continue(
|
|
121
|
+
context: AgentContext,
|
|
122
|
+
config: AgentLoopConfig,
|
|
123
|
+
*,
|
|
124
|
+
stream_fn: StreamFn,
|
|
125
|
+
signal: CancelToken | None = None,
|
|
126
|
+
) -> AgentEventStream:
|
|
127
|
+
"""从现有转录继续一次 run,不追加新消息(重试、恢复的场景会用到)。
|
|
128
|
+
|
|
129
|
+
转录最后一条必须能变成 ``user`` 或 ``toolResult`` 消息,否则 Provider 会拒掉请求。
|
|
130
|
+
这里只检查最明显的一种违约(尾部是助手消息):真实校验依赖 ``convert_to_llm``,
|
|
131
|
+
而它每回合只调用一次,没有便宜的地方提前验证。
|
|
132
|
+
|
|
133
|
+
:raises ValueError: 转录为空,或最后一条消息的角色是 ``assistant``。
|
|
134
|
+
:raises RuntimeError: 不在事件循环内调用。
|
|
135
|
+
"""
|
|
136
|
+
_require_continuable(context)
|
|
137
|
+
_require_running_loop("agent_loop_continue")
|
|
138
|
+
stream = _create_agent_stream()
|
|
139
|
+
coroutine = run_agent_loop_continue(
|
|
140
|
+
context, config, stream.push, stream_fn=stream_fn, signal=signal
|
|
141
|
+
)
|
|
142
|
+
_drive_in_background(stream, coroutine, config)
|
|
143
|
+
return stream
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
async def run_agent_loop(
|
|
147
|
+
prompts: Sequence[AgentMessage],
|
|
148
|
+
context: AgentContext,
|
|
149
|
+
config: AgentLoopConfig,
|
|
150
|
+
emit: AgentEventSink,
|
|
151
|
+
*,
|
|
152
|
+
stream_fn: StreamFn,
|
|
153
|
+
signal: CancelToken | None = None,
|
|
154
|
+
) -> list[AgentMessage]:
|
|
155
|
+
"""推进一次 run 并把每个事件交给 ``emit``,返回本次 run 产生的消息。
|
|
156
|
+
|
|
157
|
+
这是低层实现,不给调用方留"半途接管"的余地:失败一律以异常形式抛出,由上层决定
|
|
158
|
+
怎么变成消息(:func:`agent_loop` 转成失败消息;``Agent`` 用同样的规则收尾)。
|
|
159
|
+
"""
|
|
160
|
+
initial = declare_tool_changes(context, prompts, now_ms=config.clock.now_ms())
|
|
161
|
+
new_messages: list[AgentMessage] = list(initial)
|
|
162
|
+
current = AgentContext(messages=[*context.messages, *initial], tools=list(context.tools))
|
|
163
|
+
|
|
164
|
+
await _emit(emit, AgentStartEvent())
|
|
165
|
+
await _emit(emit, TurnStartEvent())
|
|
166
|
+
for message in initial:
|
|
167
|
+
await _emit(emit, MessageStartEvent(message=_snapshot(message)))
|
|
168
|
+
await _emit(emit, MessageEndEvent(message=_snapshot(message)))
|
|
169
|
+
|
|
170
|
+
guards = _LoopGuards.from_config(config)
|
|
171
|
+
await _run_loop(current, new_messages, config, signal, emit, stream_fn, guards)
|
|
172
|
+
return new_messages
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
async def run_agent_loop_continue(
|
|
176
|
+
context: AgentContext,
|
|
177
|
+
config: AgentLoopConfig,
|
|
178
|
+
emit: AgentEventSink,
|
|
179
|
+
*,
|
|
180
|
+
stream_fn: StreamFn,
|
|
181
|
+
signal: CancelToken | None = None,
|
|
182
|
+
) -> list[AgentMessage]:
|
|
183
|
+
"""从现有转录继续一次 run。返回的消息**只有**本次 run 新增的部分。"""
|
|
184
|
+
_require_continuable(context)
|
|
185
|
+
new_messages: list[AgentMessage] = []
|
|
186
|
+
current = AgentContext(messages=list(context.messages), tools=list(context.tools))
|
|
187
|
+
|
|
188
|
+
await _emit(emit, AgentStartEvent())
|
|
189
|
+
await _emit(emit, TurnStartEvent())
|
|
190
|
+
guards = _LoopGuards.from_config(config)
|
|
191
|
+
await _run_loop(current, new_messages, config, signal, emit, stream_fn, guards)
|
|
192
|
+
return new_messages
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# ---------------------------------------------------------------------- 工具装载
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def declare_tool_changes(
|
|
199
|
+
context: AgentContext,
|
|
200
|
+
pending_messages: Sequence[AgentMessage],
|
|
201
|
+
*,
|
|
202
|
+
now_ms: int,
|
|
203
|
+
) -> list[AgentMessage]:
|
|
204
|
+
"""把工具装载的差异变成一条系统消息,插在待发消息里。
|
|
205
|
+
|
|
206
|
+
``context.tools`` 是**能执行**的集合,转录里的系统消息才是**已声明**给模型的集合。
|
|
207
|
+
两者不一致时,模型要么调用一个不存在的工具,要么不知道某个工具
|
|
208
|
+
已经可用。差异必须显式告知,而且必须作为消息写进转录——否则下一回合、恢复、分支
|
|
209
|
+
之后都不再成立。
|
|
210
|
+
|
|
211
|
+
三档行为:
|
|
212
|
+
|
|
213
|
+
- **已有待发系统消息**:它的工具字段被视为"调用方的意图",计算基线时先清空,
|
|
214
|
+
再把算出来的差异写回去。合并而不是追加,避免同一回合出现两条工具补丁。
|
|
215
|
+
- **没有待发系统消息,但有差异**:新建一条空内容系统消息,插在第一条非系统消息
|
|
216
|
+
之前。系统消息的 ``content`` 可以为空——它的作用就是携带工具补丁。
|
|
217
|
+
- **没有差异**:原样返回,不产生任何消息。
|
|
218
|
+
|
|
219
|
+
:param context: 提供 ``messages``(转录事实)与 ``tools``(可执行集合)。
|
|
220
|
+
:param pending_messages: 即将追加的消息,可能为空。
|
|
221
|
+
:param now_ms: 新建系统消息的时间戳。显式传入以保证测试可复现。
|
|
222
|
+
"""
|
|
223
|
+
pending = list(pending_messages)
|
|
224
|
+
# 用倒序索引而不是 ``list.index``:消息是值相等的 dataclass,两条内容相同的系统消息
|
|
225
|
+
# 会让 ``index`` 找到前面那条,补丁就写到了已经发过的地方。
|
|
226
|
+
existing: SystemMessage | None = None
|
|
227
|
+
system_index = -1
|
|
228
|
+
for index in range(len(pending) - 1, -1, -1):
|
|
229
|
+
candidate = pending[index]
|
|
230
|
+
if isinstance(candidate, SystemMessage):
|
|
231
|
+
existing = candidate
|
|
232
|
+
system_index = index
|
|
233
|
+
break
|
|
234
|
+
|
|
235
|
+
# 基线 = 待发消息把"工具字段"清空后的样子。这些字段是调用方想说的话,
|
|
236
|
+
# 不是转录里已经发生过的事实;拿它们当基线会让差异反复重算错。
|
|
237
|
+
baseline: list[AgentMessage] = list(pending)
|
|
238
|
+
if existing is not None:
|
|
239
|
+
baseline[system_index] = _with_tool_changes(existing, ToolStateChanges())
|
|
240
|
+
|
|
241
|
+
changes = get_tool_state_changes(
|
|
242
|
+
get_current_tools(_system_messages([*context.messages, *baseline])),
|
|
243
|
+
[to_tool_declaration(declaration) for declaration in tool_declarations(context.tools)],
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
if existing is not None:
|
|
247
|
+
if changes.is_empty and not existing.tools_added and not existing.tools_removed:
|
|
248
|
+
return pending
|
|
249
|
+
baseline[system_index] = _with_tool_changes(existing, changes)
|
|
250
|
+
return baseline
|
|
251
|
+
if changes.is_empty:
|
|
252
|
+
return pending
|
|
253
|
+
update = _with_tool_changes(SystemMessage(timestamp=now_ms, content=""), changes)
|
|
254
|
+
insert_at = next(
|
|
255
|
+
(index for index, message in enumerate(pending) if not isinstance(message, SystemMessage)),
|
|
256
|
+
len(pending),
|
|
257
|
+
)
|
|
258
|
+
return [*pending[:insert_at], update, *pending[insert_at:]]
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _system_messages(messages: Sequence[AgentMessage]) -> list[SystemMessage]:
|
|
262
|
+
"""只留系统消息。工具声明只存在于系统消息里,其余角色查了也没有。"""
|
|
263
|
+
return [message for message in messages if isinstance(message, SystemMessage)]
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _with_tool_changes(message: SystemMessage, changes: ToolStateChanges) -> SystemMessage:
|
|
267
|
+
"""复制一条系统消息,把工具字段换成 ``changes``。空列表表示"删掉该字段"。"""
|
|
268
|
+
return replace(
|
|
269
|
+
message,
|
|
270
|
+
tools_added=changes.tools_added or None,
|
|
271
|
+
tools_removed=changes.tools_removed or None,
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
# ------------------------------------------------------------------------ 回合
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
@dataclass(slots=True)
|
|
279
|
+
class _LoopGuards:
|
|
280
|
+
"""一次 run 的护栏状态:回合数、请求数、连续相同调用。
|
|
281
|
+
|
|
282
|
+
三份状态放在一个对象里,因为它们都由配置的三个上限驱动,且都要在"这一次 run"
|
|
283
|
+
的边界上从零开始。分散成三个局部变量会让 ``_run_loop`` 的签名再长三个参数,
|
|
284
|
+
也说不清"它们是同一件事的三个侧面"。
|
|
285
|
+
|
|
286
|
+
计数器在**放行时**递增,不是在完成时:预算是"允许发起多少次",用完成后的数字
|
|
287
|
+
去比会在最后一次越过上限之后才发现,那一次的花费已经产生。
|
|
288
|
+
|
|
289
|
+
``summaries`` 只保留当前签名对应的那几次调用的结果摘要。换一个签名就清空——
|
|
290
|
+
拦截消息要说的是"你刚才这三次做的是同一件事",混进别次调用的摘要会让人读错。
|
|
291
|
+
"""
|
|
292
|
+
|
|
293
|
+
max_turns: int | None
|
|
294
|
+
max_requests: int | None
|
|
295
|
+
max_repeats: int
|
|
296
|
+
turns: int = 0
|
|
297
|
+
requests: int = 0
|
|
298
|
+
signature: str | None = None
|
|
299
|
+
attempts: int = 0
|
|
300
|
+
summaries: list[str] = field(default_factory=list[str])
|
|
301
|
+
|
|
302
|
+
@classmethod
|
|
303
|
+
def from_config(cls, config: AgentLoopConfig) -> _LoopGuards:
|
|
304
|
+
return cls(
|
|
305
|
+
max_turns=config.max_turns,
|
|
306
|
+
max_requests=config.max_requests_per_run,
|
|
307
|
+
max_repeats=config.max_repeated_tool_calls,
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
def admit_turn(self) -> LoopGuardTriggeredEvent | None:
|
|
311
|
+
"""放行一个回合,返回 ``None``;预算用尽时返回触发事件且不递增。"""
|
|
312
|
+
if self.max_turns is not None and self.turns >= self.max_turns:
|
|
313
|
+
return LoopGuardTriggeredEvent(
|
|
314
|
+
guard="max_turns",
|
|
315
|
+
message=(
|
|
316
|
+
f"Turn limit reached: this run used {self.turns} of {self.max_turns} "
|
|
317
|
+
"allowed turns. Report what is done and what is left; the remaining "
|
|
318
|
+
"work needs a new run."
|
|
319
|
+
),
|
|
320
|
+
limit=self.max_turns,
|
|
321
|
+
used=self.turns,
|
|
322
|
+
)
|
|
323
|
+
self.turns += 1
|
|
324
|
+
return None
|
|
325
|
+
|
|
326
|
+
def admit_request(self) -> LoopGuardTriggeredEvent | None:
|
|
327
|
+
"""放行一次模型请求,语义同 :meth:`admit_turn`。"""
|
|
328
|
+
if self.max_requests is not None and self.requests >= self.max_requests:
|
|
329
|
+
return LoopGuardTriggeredEvent(
|
|
330
|
+
guard="request_budget",
|
|
331
|
+
message=(
|
|
332
|
+
f"Request budget exhausted: this run used {self.requests} of "
|
|
333
|
+
f"{self.max_requests} allowed model requests. Report what is done and "
|
|
334
|
+
"what is left; the remaining work needs a new run."
|
|
335
|
+
),
|
|
336
|
+
limit=self.max_requests,
|
|
337
|
+
used=self.requests,
|
|
338
|
+
)
|
|
339
|
+
self.requests += 1
|
|
340
|
+
return None
|
|
341
|
+
|
|
342
|
+
def reset_repeats(self) -> None:
|
|
343
|
+
"""忘掉重复计数。用户插话之后,同一个调用重新调用是有理由的。"""
|
|
344
|
+
self.signature = None
|
|
345
|
+
self.attempts = 0
|
|
346
|
+
self.summaries.clear()
|
|
347
|
+
|
|
348
|
+
def reject_repeat(self, tool_call: ToolCall) -> LoopGuardTriggeredEvent | None:
|
|
349
|
+
"""记账一次预检;第 ``max_repeats`` 次相同调用返回拦截事件。
|
|
350
|
+
|
|
351
|
+
"相同"指工具名与参数都相同。参数按排序后的 JSON 比较,键顺序不同不算变化——
|
|
352
|
+
模型换个键序重发同一个调用,仍然是同一个调用。
|
|
353
|
+
"""
|
|
354
|
+
signature = _call_signature(tool_call)
|
|
355
|
+
if signature != self.signature:
|
|
356
|
+
self.signature = signature
|
|
357
|
+
self.attempts = 0
|
|
358
|
+
self.summaries.clear()
|
|
359
|
+
self.attempts += 1
|
|
360
|
+
if self.attempts < self.max_repeats:
|
|
361
|
+
return None
|
|
362
|
+
return LoopGuardTriggeredEvent(
|
|
363
|
+
guard="repeated_tool_call",
|
|
364
|
+
message=(
|
|
365
|
+
f'Tool call "{tool_call.name}" was blocked: the same call with identical '
|
|
366
|
+
f"arguments has been requested {self.attempts} times in a row without "
|
|
367
|
+
"progress. Change the arguments, use a different tool, or explain why "
|
|
368
|
+
"repeating it would help."
|
|
369
|
+
),
|
|
370
|
+
limit=self.max_repeats,
|
|
371
|
+
used=self.attempts,
|
|
372
|
+
tool_name=tool_call.name,
|
|
373
|
+
repeats=self.attempts,
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
def blocked_result(self, event: LoopGuardTriggeredEvent) -> AgentToolResult:
|
|
377
|
+
"""拦截结果:事件里那句话,加上此前几次调用的摘要。"""
|
|
378
|
+
text = event.message
|
|
379
|
+
if self.summaries:
|
|
380
|
+
text = f"{text}\n\nPrevious attempts:\n" + "\n".join(self.summaries)
|
|
381
|
+
return AgentToolResult(content=[TextContent(text=text)], details={})
|
|
382
|
+
|
|
383
|
+
def observe(
|
|
384
|
+
self, tool_calls: Sequence[ToolCall], messages: Sequence[ToolResultMessage]
|
|
385
|
+
) -> None:
|
|
386
|
+
"""把这一批的结果记进摘要表。只记当前签名的那几条(见类文档)。"""
|
|
387
|
+
for tool_call, message in zip(tool_calls, messages, strict=True):
|
|
388
|
+
if _call_signature(tool_call) != self.signature:
|
|
389
|
+
continue
|
|
390
|
+
self.summaries.append(f"{len(self.summaries) + 1}. {_summarize_result(message)}")
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _call_signature(tool_call: ToolCall) -> str:
|
|
394
|
+
"""``工具名 + 规范化参数`` 的指纹。参数键序不影响结果。"""
|
|
395
|
+
encoded = json.dumps(tool_call.arguments, sort_keys=True, ensure_ascii=False)
|
|
396
|
+
return f"{tool_call.name}\n{encoded}"
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _summarize_result(message: ToolResultMessage) -> str:
|
|
400
|
+
"""一条工具结果的摘要:成功/失败 + 前 200 字符正文。"""
|
|
401
|
+
text = " ".join(
|
|
402
|
+
block.text.strip() for block in message.content if isinstance(block, TextContent)
|
|
403
|
+
)
|
|
404
|
+
text = " ".join(text.split())
|
|
405
|
+
if len(text) > 200:
|
|
406
|
+
text = text[:200] + "…"
|
|
407
|
+
status = "error" if message.is_error else "ok"
|
|
408
|
+
return f"{status}: {text or '(no text)'}"
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
async def _run_loop(
|
|
412
|
+
context: AgentContext,
|
|
413
|
+
new_messages: list[AgentMessage],
|
|
414
|
+
config: AgentLoopConfig,
|
|
415
|
+
signal: CancelToken | None,
|
|
416
|
+
emit: AgentEventSink,
|
|
417
|
+
stream_fn: StreamFn,
|
|
418
|
+
guards: _LoopGuards,
|
|
419
|
+
) -> None:
|
|
420
|
+
"""回合循环:请求模型、执行它要求的工具、决定要不要再来一回合。
|
|
421
|
+
|
|
422
|
+
出口有五个:
|
|
423
|
+
|
|
424
|
+
- 助手消息终态是 ``error``/``aborted``:硬退出,不执行工具、不再请求。
|
|
425
|
+
- ``finish_turn`` 返回 ``"end"``:这一回合做完就停,**不去轮询队列**。
|
|
426
|
+
- 这一回合没有工具调用,且两条队列都空:正常停下。
|
|
427
|
+
- 工具批次整批要求 ``terminate``:做完就停。
|
|
428
|
+
- 护栏拒绝放行下一个回合(回合上限、请求预算):发一条写明原因的错误消息再退出。
|
|
429
|
+
|
|
430
|
+
前四个是"任务做完了",第五个是"代价到头了"。两者的收尾形状一样(``turn_end`` →
|
|
431
|
+
``agent_end``),区别在最后那条助手消息的 ``stop_reason`` 与 ``error_message``:
|
|
432
|
+
调用方据此判断这次 run 是正常完成还是被止损。
|
|
433
|
+
|
|
434
|
+
两层循环的分工是这一节最容易被写错的地方:
|
|
435
|
+
|
|
436
|
+
- **内层**跑完一个回合就检查 steering。它可能因为"还有工具结果要发回去"或
|
|
437
|
+
"有新指令要注入"而继续,也可能退出。
|
|
438
|
+
- **外层**只在内层真的停下来之后才检查 follow-up。把 follow-up 放进内层,
|
|
439
|
+
它就会和 steering 一样在每次工具批次后注入——那等于把"等它干完"变成
|
|
440
|
+
"打断它"。
|
|
441
|
+
|
|
442
|
+
第一个回合的 ``turn_start`` 由 :func:`run_agent_loop` 发出,这里只为后续回合补。
|
|
443
|
+
"后续回合"的判据是 ``last_turn is not None``:用状态而不是计数器,增量注入
|
|
444
|
+
(steering / follow-up)与工具结果引出下一回合走的是同一条路径。
|
|
445
|
+
"""
|
|
446
|
+
pending = await _poll(config.get_steering_messages)
|
|
447
|
+
last_turn: AgentTurnContext | None = None
|
|
448
|
+
explicit_continuation = False
|
|
449
|
+
|
|
450
|
+
while True:
|
|
451
|
+
has_more_tool_calls = True
|
|
452
|
+
|
|
453
|
+
while has_more_tool_calls or pending:
|
|
454
|
+
if last_turn is not None:
|
|
455
|
+
await _emit(emit, TurnStartEvent())
|
|
456
|
+
|
|
457
|
+
injected = declare_tool_changes(context, pending, now_ms=config.clock.now_ms())
|
|
458
|
+
for message in injected:
|
|
459
|
+
await _emit(emit, MessageStartEvent(message=_snapshot(message)))
|
|
460
|
+
await _emit(emit, MessageEndEvent(message=_snapshot(message)))
|
|
461
|
+
context.messages.append(message)
|
|
462
|
+
new_messages.append(message)
|
|
463
|
+
pending = []
|
|
464
|
+
if injected:
|
|
465
|
+
# 有新消息进上下文(用户插话,或工具集变化带来的声明补丁):同一个调用
|
|
466
|
+
# 再发一次有了新的理由,重复计数归零。
|
|
467
|
+
guards.reset_repeats()
|
|
468
|
+
|
|
469
|
+
refusal = guards.admit_turn() or guards.admit_request()
|
|
470
|
+
if refusal is not None:
|
|
471
|
+
await _fail_run_guard(refusal, config, emit, new_messages)
|
|
472
|
+
return
|
|
473
|
+
|
|
474
|
+
message = await _stream_assistant_response(context, config, signal, emit, stream_fn)
|
|
475
|
+
new_messages.append(message)
|
|
476
|
+
|
|
477
|
+
if message.stop_reason == "error" or message.stop_reason == "aborted":
|
|
478
|
+
last_turn = _turn_context(message, [], context, new_messages)
|
|
479
|
+
# 决策被忽略:失败与取消是硬出口,钩子只在这里做记录。
|
|
480
|
+
await _decide_finish_turn(config, last_turn, signal)
|
|
481
|
+
await _emit(emit, TurnEndEvent(message=_snapshot(message)))
|
|
482
|
+
await _emit(emit, AgentEndEvent(messages=list(new_messages)))
|
|
483
|
+
return
|
|
484
|
+
|
|
485
|
+
tool_calls = [block for block in message.content if isinstance(block, ToolCall)]
|
|
486
|
+
tool_results: list[ToolResultMessage] = []
|
|
487
|
+
has_more_tool_calls = False
|
|
488
|
+
if tool_calls:
|
|
489
|
+
# ``length`` 意味着输出被 token 上限截断,这批调用可能带着被截断的参数:
|
|
490
|
+
# 全部判失败,让模型重新发起,而不是拿半截参数去动文件系统。
|
|
491
|
+
batch = (
|
|
492
|
+
await _fail_truncated_tool_calls(tool_calls, config, emit)
|
|
493
|
+
if message.stop_reason == "length"
|
|
494
|
+
else await _execute_tool_calls(
|
|
495
|
+
context, message, tool_calls, config, signal, emit, guards
|
|
496
|
+
)
|
|
497
|
+
)
|
|
498
|
+
tool_results = batch.messages
|
|
499
|
+
has_more_tool_calls = not batch.terminate
|
|
500
|
+
context.messages.extend(tool_results)
|
|
501
|
+
new_messages.extend(tool_results)
|
|
502
|
+
|
|
503
|
+
last_turn = _turn_context(message, tool_results, context, new_messages)
|
|
504
|
+
decision = await _decide_finish_turn(config, last_turn, signal)
|
|
505
|
+
await _emit(
|
|
506
|
+
emit,
|
|
507
|
+
TurnEndEvent(
|
|
508
|
+
message=_snapshot(message),
|
|
509
|
+
tool_results=[_snapshot(result) for result in tool_results],
|
|
510
|
+
),
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
if decision == "end":
|
|
514
|
+
await _emit(emit, AgentEndEvent(messages=list(new_messages)))
|
|
515
|
+
return
|
|
516
|
+
|
|
517
|
+
explicit_continuation = decision == "continue"
|
|
518
|
+
pending = await _poll(config.get_steering_messages)
|
|
519
|
+
if has_more_tool_calls or pending:
|
|
520
|
+
# 工具结果或新指令已经能引出下一回合,``continue`` 不必再单独兑现。
|
|
521
|
+
explicit_continuation = False
|
|
522
|
+
|
|
523
|
+
follow_ups = await _poll(config.get_follow_up_messages)
|
|
524
|
+
if follow_ups:
|
|
525
|
+
explicit_continuation = False
|
|
526
|
+
pending = follow_ups
|
|
527
|
+
continue
|
|
528
|
+
|
|
529
|
+
if explicit_continuation:
|
|
530
|
+
# 钩子要求再请求一次,但没有任何消息能引出它:用当前上下文跑一个"空回合"。
|
|
531
|
+
explicit_continuation = False
|
|
532
|
+
continue
|
|
533
|
+
|
|
534
|
+
break
|
|
535
|
+
|
|
536
|
+
await _emit(emit, AgentEndEvent(messages=list(new_messages)))
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
async def _stream_assistant_response(
|
|
540
|
+
context: AgentContext,
|
|
541
|
+
config: AgentLoopConfig,
|
|
542
|
+
signal: CancelToken | None,
|
|
543
|
+
emit: AgentEventSink,
|
|
544
|
+
stream_fn: StreamFn,
|
|
545
|
+
) -> AssistantMessage:
|
|
546
|
+
"""请求一次模型,把流式事件转成 Agent 事件,返回终态助手消息。"""
|
|
547
|
+
messages = context.messages
|
|
548
|
+
if config.transform_context is not None:
|
|
549
|
+
messages = await _resolve(config.transform_context(list(messages), signal))
|
|
550
|
+
llm_messages = await _resolve(config.convert_to_llm(list(messages)))
|
|
551
|
+
llm_context = TranscriptContext(messages=list(llm_messages))
|
|
552
|
+
|
|
553
|
+
api_key: str | None = None
|
|
554
|
+
if config.get_api_key is not None:
|
|
555
|
+
api_key = await _resolve(config.get_api_key(config.model.provider))
|
|
556
|
+
options = replace(
|
|
557
|
+
config.stream_options,
|
|
558
|
+
# 钩子解析不到就保留调用方显式给的值,仍为空则交给 Models 的解析链。
|
|
559
|
+
api_key=api_key or config.stream_options.api_key,
|
|
560
|
+
signal=signal,
|
|
561
|
+
)
|
|
562
|
+
response = stream_fn(config.model, llm_context, options)
|
|
563
|
+
|
|
564
|
+
final: AssistantMessage | None = None
|
|
565
|
+
# partial 在转录里的位置。用索引而不是"最后一条":一旦将来在流进行中有别的消息
|
|
566
|
+
# 插进转录,按"最后一条"替换就会改错对象。
|
|
567
|
+
partial_index: int | None = None
|
|
568
|
+
|
|
569
|
+
try:
|
|
570
|
+
async for event in response:
|
|
571
|
+
match event:
|
|
572
|
+
case StartEvent():
|
|
573
|
+
context.messages.append(event.partial)
|
|
574
|
+
partial_index = len(context.messages) - 1
|
|
575
|
+
await _emit(emit, MessageStartEvent(message=_snapshot(event.partial)))
|
|
576
|
+
case (
|
|
577
|
+
TextStartEvent()
|
|
578
|
+
| TextDeltaEvent()
|
|
579
|
+
| TextEndEvent()
|
|
580
|
+
| ThinkingStartEvent()
|
|
581
|
+
| ThinkingDeltaEvent()
|
|
582
|
+
| ThinkingEndEvent()
|
|
583
|
+
| ToolCallStartEvent()
|
|
584
|
+
| ToolCallDeltaEvent()
|
|
585
|
+
| ToolCallEndEvent()
|
|
586
|
+
):
|
|
587
|
+
# Provider 违约:没有 start 就发增量。忽略增量,让最终消息兜底,
|
|
588
|
+
# 而不是把半个消息塞进转录。
|
|
589
|
+
if partial_index is None:
|
|
590
|
+
continue
|
|
591
|
+
context.messages[partial_index] = event.partial
|
|
592
|
+
await _emit(
|
|
593
|
+
emit,
|
|
594
|
+
MessageUpdateEvent(
|
|
595
|
+
message=_snapshot(event.partial), assistant_message_event=event
|
|
596
|
+
),
|
|
597
|
+
)
|
|
598
|
+
case DoneEvent():
|
|
599
|
+
final = _with_thinking_level(event.message, config)
|
|
600
|
+
break
|
|
601
|
+
case ErrorEvent():
|
|
602
|
+
final = _with_thinking_level(event.error, config)
|
|
603
|
+
break
|
|
604
|
+
|
|
605
|
+
if final is None:
|
|
606
|
+
# 流关闭却没有终态事件:Provider 违约。能拿到结果就用结果(有些实现只调
|
|
607
|
+
# `end(message)`),拿不到就让 `result()` 大声失败,由上层编码成失败消息。
|
|
608
|
+
final = _with_thinking_level(await response.result(), config)
|
|
609
|
+
finally:
|
|
610
|
+
# 消费者在这里结束(正常、异常、被取消三种都可能)。不关闭的话,还在跑的
|
|
611
|
+
# 生产者会继续把整个响应读完,事件堆在没人取的缓冲区里。
|
|
612
|
+
await response.aclose()
|
|
613
|
+
|
|
614
|
+
if partial_index is not None:
|
|
615
|
+
context.messages[partial_index] = final
|
|
616
|
+
else:
|
|
617
|
+
context.messages.append(final)
|
|
618
|
+
await _emit(emit, MessageStartEvent(message=_snapshot(final)))
|
|
619
|
+
await _emit(emit, MessageEndEvent(message=_snapshot(final)))
|
|
620
|
+
return final
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
# ------------------------------------------------------------------------ 工具
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
@dataclass(slots=True)
|
|
627
|
+
class _PreparedToolCall:
|
|
628
|
+
"""预检通过的一次调用:工具对象 + 已校验的参数。
|
|
629
|
+
|
|
630
|
+
``tool_call`` 是**模型给出的原始调用块**。修补过的参数只放在 ``args`` 里,不写回调用块:
|
|
631
|
+
事件与结果消息应当能复原"模型到底写了什么",否则排查"为什么这个调用动了那个文件"时,
|
|
632
|
+
看到的是我们改写后的版本。
|
|
633
|
+
"""
|
|
634
|
+
|
|
635
|
+
tool_call: ToolCall
|
|
636
|
+
tool: AgentTool
|
|
637
|
+
args: dict[str, JsonValue]
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
@dataclass(slots=True)
|
|
641
|
+
class _ExecutedToolCall:
|
|
642
|
+
"""``execute`` 的直接产出。收尾钩子还没跑,所以这不是最终结果。"""
|
|
643
|
+
|
|
644
|
+
result: AgentToolResult
|
|
645
|
+
is_error: bool
|
|
646
|
+
duration_ms: int
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
@dataclass(slots=True)
|
|
650
|
+
class _ToolCallBatch:
|
|
651
|
+
"""一批工具调用的产出。
|
|
652
|
+
|
|
653
|
+
``messages`` 严格按助手消息里的调用顺序排列;``terminate`` 表示整批都要求早停。
|
|
654
|
+
"""
|
|
655
|
+
|
|
656
|
+
messages: list[ToolResultMessage]
|
|
657
|
+
terminate: bool
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
#: 被护栏拦下的一次调用:已定论的结果 + 要发的诊断事件。
|
|
661
|
+
type _Rejection = tuple[AgentToolCallOutcome, LoopGuardTriggeredEvent]
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
async def run_tool_call(
|
|
665
|
+
tool_call: ToolCall,
|
|
666
|
+
*,
|
|
667
|
+
tools: Sequence[AgentTool],
|
|
668
|
+
assistant_message: AssistantMessage,
|
|
669
|
+
context: AgentContext,
|
|
670
|
+
clock: Clock,
|
|
671
|
+
signal: CancelToken | None = None,
|
|
672
|
+
on_update: ToolUpdateSink | None = None,
|
|
673
|
+
before_tool_call: BeforeToolCall | None = None,
|
|
674
|
+
after_tool_call: AfterToolCall | None = None,
|
|
675
|
+
timeout_grace_s: float = DEFAULT_TOOL_TIMEOUT_GRACE_SECONDS,
|
|
676
|
+
) -> AgentToolCallOutcome:
|
|
677
|
+
"""跑一次工具调用:修补参数 → 校验 → ``before_tool_call`` → 执行 → ``after_tool_call``。
|
|
678
|
+
|
|
679
|
+
不抛异常、不发事件、不写转录。所有失败路径的出口相同(``is_error=True``):
|
|
680
|
+
|
|
681
|
+
- **未知工具**:模型调用了一个没注册的名字。不执行,直接给错误结果。
|
|
682
|
+
- **参数非法**:``prepare_arguments`` 先修补(旧字段名 → 新字段名),再按 schema 校验。
|
|
683
|
+
修补或校验抛出的异常被翻译成错误结果,工具本身**不会**被调用。
|
|
684
|
+
- **被钩子拦截**:``before_tool_call`` 返回 ``block=True``,不执行,``reason`` 作为内容。
|
|
685
|
+
- **工具抛异常**:捕获,翻译成错误结果。循环继续——工具崩溃不该让整次 run 崩掉。
|
|
686
|
+
- **超过工具声明的超时**:`execute` 被取消,产出一条写明时长的错误结果。这一条同样
|
|
687
|
+
不让 run 中断:模型可以换一条更小的操作再来一次。
|
|
688
|
+
- **收尾钩子抛异常**:整条结果换成错误,**不保留**半覆盖的字段。
|
|
689
|
+
|
|
690
|
+
为什么单独抽成公开函数:模型发起的调用、并发批次、以及工具内部再调用别的工具
|
|
691
|
+
(MCP 工具)走的是同一段逻辑。三处各写一份,权限钩子迟早会在某条路径上漏掉,
|
|
692
|
+
而漏掉的那条正好是绕过检查的口子。
|
|
693
|
+
|
|
694
|
+
:param assistant_message: 发起这次调用的助手消息。钩子用它判断语境。
|
|
695
|
+
:param context: 此刻的上下文快照。钩子只读。
|
|
696
|
+
:param timeout_grace_s: 循环的硬停止比工具声明的时间晚多少秒。
|
|
697
|
+
"""
|
|
698
|
+
preparation = await _prepare_tool_call(
|
|
699
|
+
tool_call,
|
|
700
|
+
tools=tools,
|
|
701
|
+
assistant_message=assistant_message,
|
|
702
|
+
context=context,
|
|
703
|
+
signal=signal,
|
|
704
|
+
before=before_tool_call,
|
|
705
|
+
)
|
|
706
|
+
if isinstance(preparation, AgentToolCallOutcome):
|
|
707
|
+
return preparation
|
|
708
|
+
executed = await _execute_prepared_tool_call(
|
|
709
|
+
preparation, clock, signal, on_update, timeout_grace_s=timeout_grace_s
|
|
710
|
+
)
|
|
711
|
+
return await _finalize_tool_call(
|
|
712
|
+
preparation,
|
|
713
|
+
executed,
|
|
714
|
+
context=context,
|
|
715
|
+
assistant_message=assistant_message,
|
|
716
|
+
after=after_tool_call,
|
|
717
|
+
signal=signal,
|
|
718
|
+
)
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
async def _prepare_tool_call(
|
|
722
|
+
tool_call: ToolCall,
|
|
723
|
+
*,
|
|
724
|
+
tools: Sequence[AgentTool],
|
|
725
|
+
assistant_message: AssistantMessage,
|
|
726
|
+
context: AgentContext,
|
|
727
|
+
signal: CancelToken | None,
|
|
728
|
+
before: BeforeToolCall | None,
|
|
729
|
+
) -> _PreparedToolCall | AgentToolCallOutcome:
|
|
730
|
+
"""预检一次调用。返回"可以执行"或"已有结论",两者必居其一。
|
|
731
|
+
|
|
732
|
+
预检必须串行:它可能跑权限钩子(弹框、查 ACL),并发跑会让"允许 A、拒绝 B"的决定
|
|
733
|
+
在时间上互相穿插,用户看到两个框同时弹出来。执行阶段才允许并发。
|
|
734
|
+
|
|
735
|
+
取消检查放在三个位置:入口(还没轮到这个调用)、钩子之后(钩子可能等了很久)、
|
|
736
|
+
返回之前。任何一处发现已取消,都产出 ``Operation aborted`` 而不是放行——被取消的
|
|
737
|
+
批次不应该再启动新的副作用。
|
|
738
|
+
"""
|
|
739
|
+
if _cancelled(signal):
|
|
740
|
+
return _aborted_outcome(tool_call)
|
|
741
|
+
|
|
742
|
+
tool = _find_tool(tools, tool_call.name)
|
|
743
|
+
if tool is None:
|
|
744
|
+
return AgentToolCallOutcome(
|
|
745
|
+
tool_call=tool_call,
|
|
746
|
+
result=_error_result(f"Tool {tool_call.name} not found"),
|
|
747
|
+
is_error=True,
|
|
748
|
+
)
|
|
749
|
+
|
|
750
|
+
try:
|
|
751
|
+
prepared = tool_call
|
|
752
|
+
if tool.prepare_arguments is not None:
|
|
753
|
+
prepared = replace(tool_call, arguments=tool.prepare_arguments(tool_call.arguments))
|
|
754
|
+
arguments = validate_tool_arguments(tool.parameters, prepared)
|
|
755
|
+
if before is not None:
|
|
756
|
+
decision = await _resolve(
|
|
757
|
+
before(
|
|
758
|
+
BeforeToolCallContext(
|
|
759
|
+
assistant_message=assistant_message,
|
|
760
|
+
tool_call=tool_call,
|
|
761
|
+
args=arguments,
|
|
762
|
+
context=context,
|
|
763
|
+
),
|
|
764
|
+
signal,
|
|
765
|
+
)
|
|
766
|
+
)
|
|
767
|
+
if _cancelled(signal):
|
|
768
|
+
return _aborted_outcome(tool_call)
|
|
769
|
+
if decision is not None and decision.block:
|
|
770
|
+
result = _error_result(decision.reason or "Tool execution was blocked")
|
|
771
|
+
result.terminate = decision.terminate
|
|
772
|
+
return AgentToolCallOutcome(tool_call=tool_call, result=result, is_error=True)
|
|
773
|
+
if _cancelled(signal):
|
|
774
|
+
return _aborted_outcome(tool_call)
|
|
775
|
+
return _PreparedToolCall(tool_call=tool_call, tool=tool, args=arguments)
|
|
776
|
+
except Exception as error: # 参数修补、校验、钩子三处的失败都让这条调用不成立
|
|
777
|
+
return AgentToolCallOutcome(
|
|
778
|
+
tool_call=tool_call,
|
|
779
|
+
result=_error_result(_describe(error)),
|
|
780
|
+
is_error=True,
|
|
781
|
+
)
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
class _ToolTimedOut(Exception):
|
|
785
|
+
"""内部信号:工具在硬停止点上被取消。
|
|
786
|
+
|
|
787
|
+
单独一个异常类型而不是直接看 ``TimeoutError``:工具自己也可能抛 ``TimeoutError``
|
|
788
|
+
(``socket`` 与 ``asyncio`` 用的是同一个内置类型)。那种失败要按工具错误原样报出,
|
|
789
|
+
不能改写成"循环在 N 秒时终止了它"。
|
|
790
|
+
"""
|
|
791
|
+
|
|
792
|
+
def __init__(self, seconds: float) -> None:
|
|
793
|
+
super().__init__(f"tool stopped after {seconds:g} seconds")
|
|
794
|
+
self.seconds = seconds
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
async def _execute_prepared_tool_call(
|
|
798
|
+
prepared: _PreparedToolCall,
|
|
799
|
+
clock: Clock,
|
|
800
|
+
signal: CancelToken | None,
|
|
801
|
+
on_update: ToolUpdateSink | None,
|
|
802
|
+
*,
|
|
803
|
+
timeout_grace_s: float,
|
|
804
|
+
) -> _ExecutedToolCall:
|
|
805
|
+
"""执行一次已预检的调用,并按工具声明的上限给它一个硬停止。
|
|
806
|
+
|
|
807
|
+
两层上限是同一件事的两端:工具自己(例如 ``bash``)在声明的时长上终止子进程,
|
|
808
|
+
能带回"超时前打印了什么";循环这一层是**网**,比工具自己的停止点晚
|
|
809
|
+
``timeout_grace_s`` 秒,只在工具自己没有兑现时兜住——一条不响应取消的外部调用
|
|
810
|
+
不该让整个会话等下去。
|
|
811
|
+
|
|
812
|
+
超时用 ``asyncio.timeout`` 实现:它取消的是 ``execute`` 这个协程,工具里的
|
|
813
|
+
``await`` 点会收到 ``CancelledError``,子进程、子任务的清理走它们自己的
|
|
814
|
+
``finally``。被外部取消时这里不会抛出 ``TimeoutError``(``asyncio`` 会原样
|
|
815
|
+
传播 ``CancelledError``),两种中止因此不会混成一条结果。
|
|
816
|
+
"""
|
|
817
|
+
started = clock.monotonic_ms()
|
|
818
|
+
try:
|
|
819
|
+
limit = tool_timeout_seconds(prepared.tool, prepared.args)
|
|
820
|
+
result = await _execute_with_limit(prepared, limit, signal, on_update, timeout_grace_s)
|
|
821
|
+
except _ToolTimedOut as stopped:
|
|
822
|
+
return _ExecutedToolCall(
|
|
823
|
+
result=_timeout_result(prepared.tool_call.name, stopped.seconds),
|
|
824
|
+
is_error=True,
|
|
825
|
+
duration_ms=clock.monotonic_ms() - started,
|
|
826
|
+
)
|
|
827
|
+
except Exception as error:
|
|
828
|
+
return _ExecutedToolCall(
|
|
829
|
+
result=_error_result(_describe(error)),
|
|
830
|
+
is_error=True,
|
|
831
|
+
duration_ms=clock.monotonic_ms() - started,
|
|
832
|
+
)
|
|
833
|
+
return _ExecutedToolCall(
|
|
834
|
+
result=result,
|
|
835
|
+
is_error=result.is_error,
|
|
836
|
+
duration_ms=clock.monotonic_ms() - started,
|
|
837
|
+
)
|
|
838
|
+
|
|
839
|
+
|
|
840
|
+
async def _execute_with_limit(
|
|
841
|
+
prepared: _PreparedToolCall,
|
|
842
|
+
limit: float | None,
|
|
843
|
+
signal: CancelToken | None,
|
|
844
|
+
on_update: ToolUpdateSink | None,
|
|
845
|
+
timeout_grace_s: float,
|
|
846
|
+
) -> AgentToolResult:
|
|
847
|
+
"""在声明的上限(加上宽限)内执行工具。``None`` 表示不加限制。"""
|
|
848
|
+
|
|
849
|
+
async def run() -> AgentToolResult:
|
|
850
|
+
return await prepared.tool.execute(
|
|
851
|
+
prepared.tool_call.id,
|
|
852
|
+
prepared.args,
|
|
853
|
+
signal,
|
|
854
|
+
on_update if on_update is not None else _ignore_update,
|
|
855
|
+
)
|
|
856
|
+
|
|
857
|
+
if limit is None:
|
|
858
|
+
return await run()
|
|
859
|
+
hard_stop = limit + timeout_grace_s
|
|
860
|
+
deadline = asyncio.timeout(hard_stop)
|
|
861
|
+
try:
|
|
862
|
+
async with deadline:
|
|
863
|
+
return await run()
|
|
864
|
+
except TimeoutError as error:
|
|
865
|
+
# ``expired()`` 区分两种来源:这个上下文到点了,还是工具自己抛的 TimeoutError。
|
|
866
|
+
if not deadline.expired():
|
|
867
|
+
raise
|
|
868
|
+
raise _ToolTimedOut(hard_stop) from error
|
|
869
|
+
|
|
870
|
+
|
|
871
|
+
async def _finalize_tool_call(
|
|
872
|
+
prepared: _PreparedToolCall,
|
|
873
|
+
executed: _ExecutedToolCall,
|
|
874
|
+
*,
|
|
875
|
+
context: AgentContext,
|
|
876
|
+
assistant_message: AssistantMessage,
|
|
877
|
+
after: AfterToolCall | None,
|
|
878
|
+
signal: CancelToken | None,
|
|
879
|
+
) -> AgentToolCallOutcome:
|
|
880
|
+
"""跑收尾钩子,把它的部分覆盖合进执行结果。
|
|
881
|
+
|
|
882
|
+
合并是**字段级替换**:给了哪个字段就换哪个,``None`` 表示不动。不做深合并——深合并
|
|
883
|
+
会把"我改了一行 details"变成"我把工具的 details 结构改了一半",调用方再也说不清
|
|
884
|
+
最终结果是谁写的。
|
|
885
|
+
|
|
886
|
+
钩子抛异常时整条结果换成错误,不留半覆盖的字段:一半由工具写、一半由钩子写的结果,
|
|
887
|
+
比直接报错更难排查。
|
|
888
|
+
"""
|
|
889
|
+
result = executed.result
|
|
890
|
+
is_error = executed.is_error
|
|
891
|
+
if after is not None:
|
|
892
|
+
try:
|
|
893
|
+
override = await _resolve(
|
|
894
|
+
after(
|
|
895
|
+
AfterToolCallContext(
|
|
896
|
+
assistant_message=assistant_message,
|
|
897
|
+
tool_call=prepared.tool_call,
|
|
898
|
+
args=prepared.args,
|
|
899
|
+
result=result,
|
|
900
|
+
is_error=is_error,
|
|
901
|
+
context=context,
|
|
902
|
+
),
|
|
903
|
+
signal,
|
|
904
|
+
)
|
|
905
|
+
)
|
|
906
|
+
except Exception as error:
|
|
907
|
+
return AgentToolCallOutcome(
|
|
908
|
+
tool_call=prepared.tool_call,
|
|
909
|
+
result=_error_result(_describe(error)),
|
|
910
|
+
is_error=True,
|
|
911
|
+
duration_ms=executed.duration_ms,
|
|
912
|
+
)
|
|
913
|
+
if override is not None:
|
|
914
|
+
result = _apply_after_override(result, override)
|
|
915
|
+
if override.is_error is not None:
|
|
916
|
+
is_error = override.is_error
|
|
917
|
+
return AgentToolCallOutcome(
|
|
918
|
+
tool_call=prepared.tool_call,
|
|
919
|
+
result=result,
|
|
920
|
+
is_error=is_error,
|
|
921
|
+
duration_ms=executed.duration_ms,
|
|
922
|
+
)
|
|
923
|
+
|
|
924
|
+
|
|
925
|
+
def _apply_after_override(
|
|
926
|
+
result: AgentToolResult,
|
|
927
|
+
override: AfterToolCallResult,
|
|
928
|
+
) -> AgentToolResult:
|
|
929
|
+
"""把收尾钩子的覆盖合进结果。
|
|
930
|
+
|
|
931
|
+
覆盖了 ``content`` 却没给 ``structured_content`` 时,丢弃原来的结构化结果:两者是
|
|
932
|
+
同一份结果的两种形态,换了模型可见的那份却留着机器可读的旧那份,等于交给调用方
|
|
933
|
+
两份互相矛盾的数据。想两份都保留,就在同一次覆盖里都给出。
|
|
934
|
+
"""
|
|
935
|
+
structured = override.structured_content
|
|
936
|
+
if structured is None and override.content is None:
|
|
937
|
+
structured = result.structured_content
|
|
938
|
+
return AgentToolResult(
|
|
939
|
+
content=override.content if override.content is not None else result.content,
|
|
940
|
+
details=override.details if override.details is not None else result.details,
|
|
941
|
+
structured_content=structured,
|
|
942
|
+
is_error=result.is_error,
|
|
943
|
+
usage=override.usage if override.usage is not None else result.usage,
|
|
944
|
+
terminate=override.terminate if override.terminate is not None else result.terminate,
|
|
945
|
+
)
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
async def _execute_tool_calls(
|
|
949
|
+
context: AgentContext,
|
|
950
|
+
assistant_message: AssistantMessage,
|
|
951
|
+
tool_calls: Sequence[ToolCall],
|
|
952
|
+
config: AgentLoopConfig,
|
|
953
|
+
signal: CancelToken | None,
|
|
954
|
+
emit: AgentEventSink,
|
|
955
|
+
guards: _LoopGuards,
|
|
956
|
+
) -> _ToolCallBatch:
|
|
957
|
+
"""按执行方式把一批调用分派给顺序或并发路径。
|
|
958
|
+
|
|
959
|
+
只有"拉向串行"的方向存在:配置写了 ``sequential``,或者这批里任何一个工具声明了
|
|
960
|
+
``execution_mode="sequential"``,整批串行。反过来(单工具要求并发)不成立,
|
|
961
|
+
因为"另一个工具要独占"这件事,单个工具无从知道。
|
|
962
|
+
|
|
963
|
+
重复调用的判定在**分派之前**一次算完:预检本来就要串行走一遍,护栏搭在这条路上
|
|
964
|
+
才不会因为并发执行而让"第几次"取决于完成顺序。被拦下的调用仍然会得到
|
|
965
|
+
``tool_execution_start`` / ``end`` 与一条 ``is_error`` 结果——模型必须看到"我被拦了、
|
|
966
|
+
为什么",否则它会以为调用还在排队。
|
|
967
|
+
"""
|
|
968
|
+
rejections = _reject_repeated_calls(guards, tool_calls)
|
|
969
|
+
if config.tool_execution == "sequential" or _requires_sequential(tool_calls, context.tools):
|
|
970
|
+
batch = await _execute_tool_calls_sequential(
|
|
971
|
+
context, assistant_message, tool_calls, config, signal, emit, rejections
|
|
972
|
+
)
|
|
973
|
+
else:
|
|
974
|
+
batch = await _execute_tool_calls_parallel(
|
|
975
|
+
context, assistant_message, tool_calls, config, signal, emit, rejections
|
|
976
|
+
)
|
|
977
|
+
guards.observe(tool_calls, batch.messages)
|
|
978
|
+
return batch
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
def _reject_repeated_calls(
|
|
982
|
+
guards: _LoopGuards,
|
|
983
|
+
tool_calls: Sequence[ToolCall],
|
|
984
|
+
) -> list[_Rejection | None]:
|
|
985
|
+
"""逐条问护栏"这次还能不能跑",返回与调用等长的结论表。
|
|
986
|
+
|
|
987
|
+
这里只算结论,不发事件:事件必须排在那条调用的 ``tool_execution_start`` 之后,
|
|
988
|
+
而 ``tool_execution_start`` 由两个执行器各自发(顺序路径与并发路径的时机不同)。
|
|
989
|
+
"""
|
|
990
|
+
rejections: list[_Rejection | None] = []
|
|
991
|
+
for tool_call in tool_calls:
|
|
992
|
+
event = guards.reject_repeat(tool_call)
|
|
993
|
+
if event is None:
|
|
994
|
+
rejections.append(None)
|
|
995
|
+
continue
|
|
996
|
+
outcome = AgentToolCallOutcome(
|
|
997
|
+
tool_call=tool_call,
|
|
998
|
+
result=guards.blocked_result(event),
|
|
999
|
+
is_error=True,
|
|
1000
|
+
)
|
|
1001
|
+
rejections.append((outcome, event))
|
|
1002
|
+
return rejections
|
|
1003
|
+
|
|
1004
|
+
|
|
1005
|
+
async def _execute_tool_calls_sequential(
|
|
1006
|
+
context: AgentContext,
|
|
1007
|
+
assistant_message: AssistantMessage,
|
|
1008
|
+
tool_calls: Sequence[ToolCall],
|
|
1009
|
+
config: AgentLoopConfig,
|
|
1010
|
+
signal: CancelToken | None,
|
|
1011
|
+
emit: AgentEventSink,
|
|
1012
|
+
rejections: Sequence[_Rejection | None],
|
|
1013
|
+
) -> _ToolCallBatch:
|
|
1014
|
+
"""顺序执行:准备、执行、收尾、发结果整套走完,再开始下一个调用。
|
|
1015
|
+
|
|
1016
|
+
第 n 个调用开始时,前 n-1 个结果消息已经在转录里。取消之后**剩余调用仍各得一条结果**
|
|
1017
|
+
(``Operation aborted``),不留下没有结果的工具调用。
|
|
1018
|
+
"""
|
|
1019
|
+
messages: list[ToolResultMessage] = []
|
|
1020
|
+
outcomes: list[AgentToolCallOutcome] = []
|
|
1021
|
+
for index, tool_call in enumerate(tool_calls):
|
|
1022
|
+
await _emit_tool_call_start(tool_call, emit)
|
|
1023
|
+
rejection = rejections[index] if index < len(rejections) else None
|
|
1024
|
+
if rejection is not None:
|
|
1025
|
+
outcome, event = rejection
|
|
1026
|
+
await _emit(emit, event)
|
|
1027
|
+
outcomes.append(outcome)
|
|
1028
|
+
messages.append(await _finish_tool_call(outcome, config, emit))
|
|
1029
|
+
continue
|
|
1030
|
+
outcome = await run_tool_call(
|
|
1031
|
+
tool_call,
|
|
1032
|
+
tools=context.tools,
|
|
1033
|
+
assistant_message=assistant_message,
|
|
1034
|
+
context=context,
|
|
1035
|
+
clock=config.clock,
|
|
1036
|
+
signal=signal,
|
|
1037
|
+
on_update=_update_sink(tool_call, emit),
|
|
1038
|
+
before_tool_call=config.before_tool_call,
|
|
1039
|
+
after_tool_call=config.after_tool_call,
|
|
1040
|
+
timeout_grace_s=config.tool_timeout_grace_s,
|
|
1041
|
+
)
|
|
1042
|
+
outcomes.append(outcome)
|
|
1043
|
+
messages.append(await _finish_tool_call(outcome, config, emit))
|
|
1044
|
+
return _ToolCallBatch(messages=messages, terminate=_should_terminate(outcomes))
|
|
1045
|
+
|
|
1046
|
+
|
|
1047
|
+
async def _execute_tool_calls_parallel(
|
|
1048
|
+
context: AgentContext,
|
|
1049
|
+
assistant_message: AssistantMessage,
|
|
1050
|
+
tool_calls: Sequence[ToolCall],
|
|
1051
|
+
config: AgentLoopConfig,
|
|
1052
|
+
signal: CancelToken | None,
|
|
1053
|
+
emit: AgentEventSink,
|
|
1054
|
+
rejections: Sequence[_Rejection | None],
|
|
1055
|
+
) -> _ToolCallBatch:
|
|
1056
|
+
"""预检串行、执行并发、结果消息按源顺序。
|
|
1057
|
+
|
|
1058
|
+
三个阶段的顺序各有理由:
|
|
1059
|
+
|
|
1060
|
+
1. **预检串行**:权限钩子可能弹框、查远程 ACL,并发跑会让用户的决定互相穿插;
|
|
1061
|
+
而且预检失败就不执行,没有加速的余地。
|
|
1062
|
+
2. **执行并发**:真实工具多数时间在等 I/O(读文件、跑命令、请求接口)。
|
|
1063
|
+
3. **消息按源顺序**:转录是下一回合的请求内容,顺序必须与助手消息里的调用顺序一致,
|
|
1064
|
+
否则模型看到的是"结果排在调用之前"。``tool_execution_end`` 则按完成顺序发,
|
|
1065
|
+
因为它是给 UI 的实时通知:"这条跑完了"。
|
|
1066
|
+
"""
|
|
1067
|
+
lock = asyncio.Lock()
|
|
1068
|
+
serialized = _serialized_sink(emit, lock)
|
|
1069
|
+
prepared_calls: list[_PreparedToolCall | None] = [None] * len(tool_calls)
|
|
1070
|
+
outcomes: list[AgentToolCallOutcome | None] = [None] * len(tool_calls)
|
|
1071
|
+
|
|
1072
|
+
for index, tool_call in enumerate(tool_calls):
|
|
1073
|
+
await _emit_tool_call_start(tool_call, emit)
|
|
1074
|
+
rejection = rejections[index] if index < len(rejections) else None
|
|
1075
|
+
if rejection is not None:
|
|
1076
|
+
# 护栏的结论同样是"已有结论":不进入并发阶段,立刻发结束事件。
|
|
1077
|
+
outcome, event = rejection
|
|
1078
|
+
outcomes[index] = outcome
|
|
1079
|
+
await _emit(serialized, event)
|
|
1080
|
+
await _emit(serialized, _tool_end_event(outcome))
|
|
1081
|
+
continue
|
|
1082
|
+
preparation = await _prepare_tool_call(
|
|
1083
|
+
tool_call,
|
|
1084
|
+
tools=context.tools,
|
|
1085
|
+
assistant_message=assistant_message,
|
|
1086
|
+
context=context,
|
|
1087
|
+
signal=signal,
|
|
1088
|
+
before=config.before_tool_call,
|
|
1089
|
+
)
|
|
1090
|
+
if isinstance(preparation, AgentToolCallOutcome):
|
|
1091
|
+
# 已有结论(未知工具、参数非法、被拦截):立刻发结束事件,不进入并发阶段。
|
|
1092
|
+
outcomes[index] = preparation
|
|
1093
|
+
await _emit(serialized, _tool_end_event(preparation))
|
|
1094
|
+
else:
|
|
1095
|
+
prepared_calls[index] = preparation
|
|
1096
|
+
|
|
1097
|
+
async def run(index: int, prepared: _PreparedToolCall) -> None:
|
|
1098
|
+
if _cancelled(signal):
|
|
1099
|
+
# 预检通过但轮到自己时已被取消:不启动副作用,仍给一条结果。
|
|
1100
|
+
outcome = _aborted_outcome(prepared.tool_call)
|
|
1101
|
+
else:
|
|
1102
|
+
executed = await _execute_prepared_tool_call(
|
|
1103
|
+
prepared,
|
|
1104
|
+
config.clock,
|
|
1105
|
+
signal,
|
|
1106
|
+
_update_sink(prepared.tool_call, serialized),
|
|
1107
|
+
timeout_grace_s=config.tool_timeout_grace_s,
|
|
1108
|
+
)
|
|
1109
|
+
outcome = await _finalize_tool_call(
|
|
1110
|
+
prepared,
|
|
1111
|
+
executed,
|
|
1112
|
+
context=context,
|
|
1113
|
+
assistant_message=assistant_message,
|
|
1114
|
+
after=config.after_tool_call,
|
|
1115
|
+
signal=signal,
|
|
1116
|
+
)
|
|
1117
|
+
outcomes[index] = outcome
|
|
1118
|
+
await _emit(serialized, _tool_end_event(outcome))
|
|
1119
|
+
|
|
1120
|
+
async with asyncio.TaskGroup() as group:
|
|
1121
|
+
for index, prepared in enumerate(prepared_calls):
|
|
1122
|
+
if prepared is not None:
|
|
1123
|
+
group.create_task(run(index, prepared))
|
|
1124
|
+
|
|
1125
|
+
finalized = [cast("AgentToolCallOutcome", outcome) for outcome in outcomes]
|
|
1126
|
+
messages: list[ToolResultMessage] = []
|
|
1127
|
+
for outcome in finalized:
|
|
1128
|
+
messages.append(await _emit_tool_result_message(outcome, config, emit))
|
|
1129
|
+
return _ToolCallBatch(messages=messages, terminate=_should_terminate(finalized))
|
|
1130
|
+
|
|
1131
|
+
|
|
1132
|
+
def _requires_sequential(tool_calls: Sequence[ToolCall], tools: Sequence[AgentTool]) -> bool:
|
|
1133
|
+
"""这批调用里是不是有工具要求独占执行。"""
|
|
1134
|
+
for tool_call in tool_calls:
|
|
1135
|
+
tool = _find_tool(tools, tool_call.name)
|
|
1136
|
+
if tool is not None and tool.execution_mode == "sequential":
|
|
1137
|
+
return True
|
|
1138
|
+
return False
|
|
1139
|
+
|
|
1140
|
+
|
|
1141
|
+
def _should_terminate(outcomes: Sequence[AgentToolCallOutcome]) -> bool:
|
|
1142
|
+
"""整批早停:数量非空,且**每一个**最终结果都要求终止。
|
|
1143
|
+
|
|
1144
|
+
"所有结果都为真"这条规则让多个工具可以各自表态:一个说"我做完了",另一个说
|
|
1145
|
+
"还得再查一次",整批就继续。只有一个结果时,它等价于"这个工具要求停"。
|
|
1146
|
+
"""
|
|
1147
|
+
return bool(outcomes) and all(outcome.result.terminate for outcome in outcomes)
|
|
1148
|
+
|
|
1149
|
+
|
|
1150
|
+
async def _fail_truncated_tool_calls(
|
|
1151
|
+
tool_calls: Sequence[ToolCall],
|
|
1152
|
+
config: AgentLoopConfig,
|
|
1153
|
+
emit: AgentEventSink,
|
|
1154
|
+
) -> _ToolCallBatch:
|
|
1155
|
+
"""``stop_reason="length"``:整批调用判失败,一个都不执行。
|
|
1156
|
+
|
|
1157
|
+
流式工具参数用"尽力修复"的解析器收尾,截断后的参数可能**恰好**是合法 JSON,
|
|
1158
|
+
甚至能过 schema 校验——然后拿着残缺的路径或命令去改文件。判断"这批参数是否完整"
|
|
1159
|
+
并不比判断"输出是否被截断"更可靠,所以整批拒绝。
|
|
1160
|
+
"""
|
|
1161
|
+
messages: list[ToolResultMessage] = []
|
|
1162
|
+
for tool_call in tool_calls:
|
|
1163
|
+
await _emit_tool_call_start(tool_call, emit)
|
|
1164
|
+
outcome = AgentToolCallOutcome(
|
|
1165
|
+
tool_call=tool_call,
|
|
1166
|
+
result=_error_result(
|
|
1167
|
+
f'Tool call "{tool_call.name}" was not executed: the response hit the '
|
|
1168
|
+
"output token limit, so its arguments may be truncated. "
|
|
1169
|
+
"Re-issue the tool call with complete arguments."
|
|
1170
|
+
),
|
|
1171
|
+
is_error=True,
|
|
1172
|
+
)
|
|
1173
|
+
messages.append(await _finish_tool_call(outcome, config, emit))
|
|
1174
|
+
return _ToolCallBatch(messages=messages, terminate=False)
|
|
1175
|
+
|
|
1176
|
+
|
|
1177
|
+
async def _emit_tool_call_start(tool_call: ToolCall, emit: AgentEventSink) -> None:
|
|
1178
|
+
await _emit(
|
|
1179
|
+
emit,
|
|
1180
|
+
ToolExecutionStartEvent(
|
|
1181
|
+
tool_call_id=tool_call.id,
|
|
1182
|
+
tool_name=tool_call.name,
|
|
1183
|
+
args=_snapshot(tool_call.arguments),
|
|
1184
|
+
),
|
|
1185
|
+
)
|
|
1186
|
+
|
|
1187
|
+
|
|
1188
|
+
def _tool_end_event(outcome: AgentToolCallOutcome) -> ToolExecutionEndEvent:
|
|
1189
|
+
return ToolExecutionEndEvent(
|
|
1190
|
+
tool_call_id=outcome.tool_call.id,
|
|
1191
|
+
tool_name=outcome.tool_call.name,
|
|
1192
|
+
result=_snapshot(outcome.result),
|
|
1193
|
+
is_error=outcome.is_error,
|
|
1194
|
+
duration_ms=outcome.duration_ms,
|
|
1195
|
+
)
|
|
1196
|
+
|
|
1197
|
+
|
|
1198
|
+
async def _finish_tool_call(
|
|
1199
|
+
outcome: AgentToolCallOutcome,
|
|
1200
|
+
config: AgentLoopConfig,
|
|
1201
|
+
emit: AgentEventSink,
|
|
1202
|
+
) -> ToolResultMessage:
|
|
1203
|
+
"""发 ``tool_execution_end``,再发出工具结果消息。返回的消息已可写进转录。
|
|
1204
|
+
|
|
1205
|
+
事件先于消息:订阅者看到"执行结束"时,手里已经有完整结果;随后到达的
|
|
1206
|
+
``message_start`` 只是说"它进转录了"。
|
|
1207
|
+
"""
|
|
1208
|
+
await _emit(emit, _tool_end_event(outcome))
|
|
1209
|
+
return await _emit_tool_result_message(outcome, config, emit)
|
|
1210
|
+
|
|
1211
|
+
|
|
1212
|
+
async def _emit_tool_result_message(
|
|
1213
|
+
outcome: AgentToolCallOutcome,
|
|
1214
|
+
config: AgentLoopConfig,
|
|
1215
|
+
emit: AgentEventSink,
|
|
1216
|
+
) -> ToolResultMessage:
|
|
1217
|
+
"""造一条工具结果消息并发它的 start/end 事件。**唯一的**发结果消息的入口。
|
|
1218
|
+
|
|
1219
|
+
工具结果消息只有这里能造,是因为它的顺序是契约:并发批次必须等全部调用收尾之后,
|
|
1220
|
+
才按源顺序逐条发。如果让每条并发任务自己发消息,顺序就变成完成顺序,模型下一回合
|
|
1221
|
+
看到的结果会与它发出的调用错位。
|
|
1222
|
+
"""
|
|
1223
|
+
message = _tool_result_message(outcome, config)
|
|
1224
|
+
await _emit(emit, MessageStartEvent(message=_snapshot(message)))
|
|
1225
|
+
await _emit(emit, MessageEndEvent(message=_snapshot(message)))
|
|
1226
|
+
return message
|
|
1227
|
+
|
|
1228
|
+
|
|
1229
|
+
def _tool_result_message(
|
|
1230
|
+
outcome: AgentToolCallOutcome,
|
|
1231
|
+
config: AgentLoopConfig,
|
|
1232
|
+
) -> ToolResultMessage:
|
|
1233
|
+
"""工具产出 → 转录里的 ``toolResult`` 消息。
|
|
1234
|
+
|
|
1235
|
+
``tool_call_id`` 是唯一关联依据:模型看到的是"我调了 call_1,回来一条带 call_1 的
|
|
1236
|
+
结果"。这条消息缺了 id,或者 id 对不上,Provider 会拒掉整个请求。
|
|
1237
|
+
"""
|
|
1238
|
+
return ToolResultMessage(
|
|
1239
|
+
tool_call_id=outcome.tool_call.id,
|
|
1240
|
+
tool_name=outcome.tool_call.name,
|
|
1241
|
+
content=list(outcome.result.content),
|
|
1242
|
+
details=outcome.result.details,
|
|
1243
|
+
usage=outcome.result.usage,
|
|
1244
|
+
is_error=outcome.is_error,
|
|
1245
|
+
duration_ms=outcome.duration_ms,
|
|
1246
|
+
timestamp=config.clock.now_ms(),
|
|
1247
|
+
)
|
|
1248
|
+
|
|
1249
|
+
|
|
1250
|
+
def _update_sink(tool_call: ToolCall, emit: AgentEventSink) -> ToolUpdateSink:
|
|
1251
|
+
"""把工具上报的进度包成 ``tool_execution_update`` 事件。"""
|
|
1252
|
+
|
|
1253
|
+
async def sink(partial: AgentToolResult) -> None:
|
|
1254
|
+
await _emit(
|
|
1255
|
+
emit,
|
|
1256
|
+
ToolExecutionUpdateEvent(
|
|
1257
|
+
tool_call_id=tool_call.id,
|
|
1258
|
+
tool_name=tool_call.name,
|
|
1259
|
+
args=_snapshot(tool_call.arguments),
|
|
1260
|
+
partial_result=_snapshot(partial),
|
|
1261
|
+
),
|
|
1262
|
+
)
|
|
1263
|
+
|
|
1264
|
+
return sink
|
|
1265
|
+
|
|
1266
|
+
|
|
1267
|
+
async def _ignore_update(_result: AgentToolResult) -> None:
|
|
1268
|
+
"""没有订阅者时的进度回调:什么都不做,但仍然是 async(见 ``ToolUpdateSink``)。"""
|
|
1269
|
+
|
|
1270
|
+
|
|
1271
|
+
def _error_result(message: str) -> AgentToolResult:
|
|
1272
|
+
"""错误结果的统一形状:一段文本 + 空 ``details``。"""
|
|
1273
|
+
return AgentToolResult(content=[TextContent(text=message)], details={})
|
|
1274
|
+
|
|
1275
|
+
|
|
1276
|
+
def _timeout_result(tool_name: str, seconds: float) -> AgentToolResult:
|
|
1277
|
+
"""超时结果的文本:说清是哪条调用、等了多久、以及已经中止。
|
|
1278
|
+
|
|
1279
|
+
模型拿到的应当是"我能改什么",所以同时给出两条可执行的方向:缩小这次操作的范围,
|
|
1280
|
+
或者在该工具允许时把 ``timeout`` 调大。只写 ``timeout`` 会让它反复重试同一条命令。
|
|
1281
|
+
"""
|
|
1282
|
+
return AgentToolResult(
|
|
1283
|
+
content=[
|
|
1284
|
+
TextContent(
|
|
1285
|
+
text=(
|
|
1286
|
+
f'Tool "{tool_name}" was stopped after {seconds:g} seconds and returned '
|
|
1287
|
+
"no result. The operation is already terminated. Narrow what this call "
|
|
1288
|
+
"does, or raise its timeout parameter if the tool accepts one."
|
|
1289
|
+
)
|
|
1290
|
+
)
|
|
1291
|
+
],
|
|
1292
|
+
details={"timeout_seconds": seconds},
|
|
1293
|
+
is_error=True,
|
|
1294
|
+
)
|
|
1295
|
+
|
|
1296
|
+
|
|
1297
|
+
# ------------------------------------------------------------------------ 失败
|
|
1298
|
+
|
|
1299
|
+
|
|
1300
|
+
async def _fail_run_guard(
|
|
1301
|
+
event: LoopGuardTriggeredEvent,
|
|
1302
|
+
config: AgentLoopConfig,
|
|
1303
|
+
emit: AgentEventSink,
|
|
1304
|
+
new_messages: list[AgentMessage],
|
|
1305
|
+
) -> None:
|
|
1306
|
+
"""因为护栏而结束本次 run:先发诊断事件,再补一条失败助手消息。
|
|
1307
|
+
|
|
1308
|
+
顺序与形状同 :func:`_emit_run_failure`:``message_start`` → ``message_end`` →
|
|
1309
|
+
``turn_end`` → ``agent_end``。差别在这条消息是**转录里的记录**——用户恢复会话时
|
|
1310
|
+
能看到"这次是在第 N 回合被上限叫停的",而不是一个没有解释的结束。
|
|
1311
|
+
"""
|
|
1312
|
+
await _emit(emit, event)
|
|
1313
|
+
failure = AssistantMessage(
|
|
1314
|
+
timestamp=config.clock.now_ms(),
|
|
1315
|
+
content=[TextContent(text=failure_message_text("error", event.message))],
|
|
1316
|
+
api=config.model.api,
|
|
1317
|
+
provider=config.model.provider,
|
|
1318
|
+
model=config.model.id,
|
|
1319
|
+
stop_reason="error",
|
|
1320
|
+
error_message=event.message,
|
|
1321
|
+
)
|
|
1322
|
+
new_messages.append(failure)
|
|
1323
|
+
await _emit(emit, MessageStartEvent(message=_snapshot(failure)))
|
|
1324
|
+
await _emit(emit, MessageEndEvent(message=_snapshot(failure)))
|
|
1325
|
+
await _emit(emit, TurnEndEvent(message=_snapshot(failure)))
|
|
1326
|
+
await _emit(emit, AgentEndEvent(messages=list(new_messages)))
|
|
1327
|
+
|
|
1328
|
+
|
|
1329
|
+
async def _emit_run_failure(
|
|
1330
|
+
stop_reason: Literal["error", "aborted"],
|
|
1331
|
+
text: str,
|
|
1332
|
+
config: AgentLoopConfig,
|
|
1333
|
+
emit: AgentEventSink,
|
|
1334
|
+
) -> list[AgentMessage]:
|
|
1335
|
+
"""把 run 级的异常收成一条失败助手消息,并补齐收尾事件。
|
|
1336
|
+
|
|
1337
|
+
这段逻辑放在流边界,补的是完整事件序列,不只是 ``agent_end``——只发
|
|
1338
|
+
``agent_end`` 的订阅者会以为整条流正常结束了。
|
|
1339
|
+
"""
|
|
1340
|
+
failure = AssistantMessage(
|
|
1341
|
+
timestamp=config.clock.now_ms(),
|
|
1342
|
+
content=[TextContent(text=failure_message_text(stop_reason, text))],
|
|
1343
|
+
api=config.model.api,
|
|
1344
|
+
provider=config.model.provider,
|
|
1345
|
+
model=config.model.id,
|
|
1346
|
+
stop_reason=stop_reason,
|
|
1347
|
+
error_message=text,
|
|
1348
|
+
)
|
|
1349
|
+
await _emit(emit, MessageStartEvent(message=_snapshot(failure)))
|
|
1350
|
+
await _emit(emit, MessageEndEvent(message=_snapshot(failure)))
|
|
1351
|
+
await _emit(emit, TurnEndEvent(message=_snapshot(failure)))
|
|
1352
|
+
await _emit(emit, AgentEndEvent(messages=[failure]))
|
|
1353
|
+
return [failure]
|
|
1354
|
+
|
|
1355
|
+
|
|
1356
|
+
async def _drive(
|
|
1357
|
+
stream: AgentEventStream,
|
|
1358
|
+
run: Coroutine[Any, Any, list[AgentMessage]],
|
|
1359
|
+
config: AgentLoopConfig,
|
|
1360
|
+
) -> None:
|
|
1361
|
+
"""后台任务:跑完 run,把结果(或失败)交给流。
|
|
1362
|
+
|
|
1363
|
+
``asyncio.CancelledError`` 单独处理:任务被取消时流必须收尾,否则消费者永远等不到
|
|
1364
|
+
``agent_end``;收尾之后让取消继续向上传播,不吞掉它。
|
|
1365
|
+
"""
|
|
1366
|
+
try:
|
|
1367
|
+
messages = await run
|
|
1368
|
+
except asyncio.CancelledError:
|
|
1369
|
+
stream.end(await _emit_run_failure("aborted", "Run was cancelled", config, stream.push))
|
|
1370
|
+
raise
|
|
1371
|
+
except Exception as error:
|
|
1372
|
+
stream.end(await _emit_run_failure("error", _describe(error), config, stream.push))
|
|
1373
|
+
else:
|
|
1374
|
+
stream.end(messages)
|
|
1375
|
+
|
|
1376
|
+
|
|
1377
|
+
# ------------------------------------------------------------------------ 内部
|
|
1378
|
+
|
|
1379
|
+
|
|
1380
|
+
def _create_agent_stream() -> AgentEventStream:
|
|
1381
|
+
"""``agent_end`` 既是完成信号,也是结果载体。"""
|
|
1382
|
+
return EventStream[AgentEvent, list[AgentMessage]](
|
|
1383
|
+
is_complete=_is_agent_end,
|
|
1384
|
+
extract_result=_extract_run_messages,
|
|
1385
|
+
)
|
|
1386
|
+
|
|
1387
|
+
|
|
1388
|
+
def _is_agent_end(event: AgentEvent) -> bool:
|
|
1389
|
+
return isinstance(event, AgentEndEvent)
|
|
1390
|
+
|
|
1391
|
+
|
|
1392
|
+
def _extract_run_messages(event: AgentEvent) -> list[AgentMessage]:
|
|
1393
|
+
"""只有 ``agent_end`` 携带结果;其余事件不构成"这次 run 产出了什么"。"""
|
|
1394
|
+
return list(event.messages) if isinstance(event, AgentEndEvent) else []
|
|
1395
|
+
|
|
1396
|
+
|
|
1397
|
+
def _drive_in_background(
|
|
1398
|
+
stream: AgentEventStream,
|
|
1399
|
+
coroutine: Coroutine[Any, Any, list[AgentMessage]],
|
|
1400
|
+
config: AgentLoopConfig,
|
|
1401
|
+
) -> None:
|
|
1402
|
+
loop = asyncio.get_running_loop()
|
|
1403
|
+
task = loop.create_task(_drive(stream, coroutine, config))
|
|
1404
|
+
_background.add(task)
|
|
1405
|
+
task.add_done_callback(_background.discard)
|
|
1406
|
+
|
|
1407
|
+
|
|
1408
|
+
def _require_running_loop(name: str) -> None:
|
|
1409
|
+
try:
|
|
1410
|
+
asyncio.get_running_loop()
|
|
1411
|
+
except RuntimeError as error:
|
|
1412
|
+
raise RuntimeError(
|
|
1413
|
+
f"{name}() 必须在事件循环内调用(asyncio.run 或 pytest-asyncio)"
|
|
1414
|
+
) from error
|
|
1415
|
+
|
|
1416
|
+
|
|
1417
|
+
def _require_continuable(context: AgentContext) -> None:
|
|
1418
|
+
if not context.messages:
|
|
1419
|
+
raise ValueError("Cannot continue: no messages in context")
|
|
1420
|
+
if context.messages[-1].role == "assistant":
|
|
1421
|
+
raise ValueError("Cannot continue from message role: assistant")
|
|
1422
|
+
|
|
1423
|
+
|
|
1424
|
+
async def _emit(sink: AgentEventSink, event: AgentEvent) -> None:
|
|
1425
|
+
"""调用事件接收器。同步接收器(如 ``EventStream.push``)不额外调度。"""
|
|
1426
|
+
result = sink(event)
|
|
1427
|
+
if inspect.isawaitable(result):
|
|
1428
|
+
await result
|
|
1429
|
+
|
|
1430
|
+
|
|
1431
|
+
def _serialized_sink(sink: AgentEventSink, lock: asyncio.Lock) -> AgentEventSink:
|
|
1432
|
+
"""给事件接收器加一把锁,供并发任务共用。
|
|
1433
|
+
|
|
1434
|
+
并发任务的 ``await emit(...)`` 会交错:一个任务把事件交出去、在订阅者的 ``await``
|
|
1435
|
+
上让出控制权,另一个任务就开始交付自己的事件,两个订阅者回调因此在时间上重叠。
|
|
1436
|
+
订阅者通常是 UI 或持久化写入,它们需要看到"一条事件完整处理完"的边界。
|
|
1437
|
+
|
|
1438
|
+
只包住**交付**这一段,不包住工具执行:锁在工具运行期间必须放开,否则并发等于串行。
|
|
1439
|
+
"""
|
|
1440
|
+
|
|
1441
|
+
async def serialized(event: AgentEvent) -> None:
|
|
1442
|
+
async with lock:
|
|
1443
|
+
await _emit(sink, event)
|
|
1444
|
+
|
|
1445
|
+
return serialized
|
|
1446
|
+
|
|
1447
|
+
|
|
1448
|
+
def _cancelled(signal: CancelToken | None) -> bool:
|
|
1449
|
+
return signal is not None and signal.cancelled
|
|
1450
|
+
|
|
1451
|
+
|
|
1452
|
+
def _aborted_outcome(tool_call: ToolCall) -> AgentToolCallOutcome:
|
|
1453
|
+
"""被取消的调用:一条错误结果,没有耗时(它根本没跑)。"""
|
|
1454
|
+
return AgentToolCallOutcome(
|
|
1455
|
+
tool_call=tool_call,
|
|
1456
|
+
result=_error_result("Operation aborted"),
|
|
1457
|
+
is_error=True,
|
|
1458
|
+
)
|
|
1459
|
+
|
|
1460
|
+
|
|
1461
|
+
def _find_tool(tools: Sequence[AgentTool], name: str) -> AgentTool | None:
|
|
1462
|
+
return next((tool for tool in tools if tool.name == name), None)
|
|
1463
|
+
|
|
1464
|
+
|
|
1465
|
+
async def _resolve[T](value: T | Awaitable[T]) -> T:
|
|
1466
|
+
"""``同步值或 awaitable`` 二选一:钩子允许两种写法,省掉"必须包一层 async"。"""
|
|
1467
|
+
if inspect.isawaitable(value):
|
|
1468
|
+
return cast("T", await value)
|
|
1469
|
+
return value
|
|
1470
|
+
|
|
1471
|
+
|
|
1472
|
+
async def _poll(poller: MessagePoller | None) -> list[AgentMessage]:
|
|
1473
|
+
"""轮询一条队列。没配钩子与钩子返回空列表是同一件事:这一次没有消息。
|
|
1474
|
+
|
|
1475
|
+
``list(...)`` 是刻意的:钩子(``PendingMessageQueue.drain``)已经返回新列表,
|
|
1476
|
+
但循环不该假设这一点——返回内部列表的实现会在这里被复制一次,代价是每次轮询一次
|
|
1477
|
+
指针复制,收益是"队列被清空不影响已排入本回合的消息"。
|
|
1478
|
+
"""
|
|
1479
|
+
if poller is None:
|
|
1480
|
+
return []
|
|
1481
|
+
return list(await _resolve(poller()))
|
|
1482
|
+
|
|
1483
|
+
|
|
1484
|
+
def _turn_context(
|
|
1485
|
+
message: AssistantMessage,
|
|
1486
|
+
tool_results: list[ToolResultMessage],
|
|
1487
|
+
context: AgentContext,
|
|
1488
|
+
new_messages: list[AgentMessage],
|
|
1489
|
+
) -> AgentTurnContext:
|
|
1490
|
+
"""构造回合快照。三个列表都是循环正在用的对象,不复制(见 ``AgentTurnContext``)。"""
|
|
1491
|
+
return AgentTurnContext(
|
|
1492
|
+
message=message,
|
|
1493
|
+
tool_results=tool_results,
|
|
1494
|
+
context=context,
|
|
1495
|
+
new_messages=new_messages,
|
|
1496
|
+
)
|
|
1497
|
+
|
|
1498
|
+
|
|
1499
|
+
async def _decide_finish_turn(
|
|
1500
|
+
config: AgentLoopConfig,
|
|
1501
|
+
turn: AgentTurnContext,
|
|
1502
|
+
signal: CancelToken | None,
|
|
1503
|
+
) -> TurnAction | None:
|
|
1504
|
+
"""问一次"这个回合之后还跑不跑"。钩子抛异常照常向上传播(属于编程错误)。"""
|
|
1505
|
+
if config.finish_turn is None:
|
|
1506
|
+
return None
|
|
1507
|
+
return await _resolve(config.finish_turn(turn, signal))
|
|
1508
|
+
|
|
1509
|
+
|
|
1510
|
+
def _snapshot[T](value: T) -> T:
|
|
1511
|
+
"""事件的快照。订阅者改事件里的消息或结果,不能改到转录。"""
|
|
1512
|
+
return copy.deepcopy(value)
|
|
1513
|
+
|
|
1514
|
+
|
|
1515
|
+
def _with_thinking_level(message: AssistantMessage, config: AgentLoopConfig) -> AssistantMessage:
|
|
1516
|
+
"""记录**请求的**思考级别(Provider 实际用没用是另一回事)。"""
|
|
1517
|
+
message.thinking_level = config.stream_options.reasoning or "off"
|
|
1518
|
+
return message
|
|
1519
|
+
|
|
1520
|
+
|
|
1521
|
+
def _describe(error: BaseException) -> str:
|
|
1522
|
+
"""异常 → 消息文本。空消息的异常只留类名,否则失败消息读起来像"什么都没有"。"""
|
|
1523
|
+
return str(error) or type(error).__name__
|
|
1524
|
+
|
|
1525
|
+
|
|
1526
|
+
__all__ = [
|
|
1527
|
+
"AgentEventStream",
|
|
1528
|
+
"agent_loop",
|
|
1529
|
+
"agent_loop_continue",
|
|
1530
|
+
"run_agent_loop",
|
|
1531
|
+
"run_agent_loop_continue",
|
|
1532
|
+
"run_tool_call",
|
|
1533
|
+
]
|