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/queues.py ADDED
@@ -0,0 +1,61 @@
1
+ """待注入消息队列:steering 与 follow-up 共用的排队原语。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Literal
7
+
8
+ from braid_agent.types import AgentMessage
9
+
10
+ #: 队列的取出方式。
11
+ #:
12
+ #: - ``one-at-a-time``:每次只取最旧的一条。
13
+ #: - ``all``:一次取走全部。
14
+ type QueueMode = Literal["all", "one-at-a-time"]
15
+
16
+
17
+ @dataclass(slots=True)
18
+ class PendingMessageQueue:
19
+ """先进先出的消息队列,按 :attr:`mode` 决定一次取几条。
20
+
21
+ ``peek`` 与 ``drain`` 的区别只在"取不取走":``peek`` 用于"预览下一步会注入什么"
22
+ (UI 显示待处理指令),``drain`` 用于真正的注入。两者返回的都是**新列表**,
23
+ 调用方改它不会改到队列内部。
24
+ """
25
+
26
+ mode: QueueMode = "one-at-a-time"
27
+ _messages: list[AgentMessage] = field(default_factory=list[AgentMessage])
28
+
29
+ def enqueue(self, message: AgentMessage) -> None:
30
+ """排到队尾。允许同一对象重复入队:两条内容相同的指令是两条指令。"""
31
+ self._messages.append(message)
32
+
33
+ def has_items(self) -> bool:
34
+ """队列里还有没有消息。"""
35
+ return bool(self._messages)
36
+
37
+ def __len__(self) -> int:
38
+ return len(self._messages)
39
+
40
+ def peek(self) -> list[AgentMessage]:
41
+ """按当前模式选出**下一次注入**的那批消息,但不取走。"""
42
+ if self.mode == "all":
43
+ return list(self._messages)
44
+ return self._messages[:1]
45
+
46
+ def drain(self) -> list[AgentMessage]:
47
+ """取走 :meth:`peek` 选出的那批消息。
48
+
49
+ ``one-at-a-time`` 模式下,剩余消息的顺序保持不变——用户连发三条时,第二、
50
+ 第三条的先后是用户给的顺序,不是调度器的顺序。
51
+ """
52
+ drained = self.peek()
53
+ self._messages = self._messages[len(drained) :]
54
+ return drained
55
+
56
+ def clear(self) -> None:
57
+ """丢掉全部待注入消息。用于 ``Agent.reset`` 与显式清空。"""
58
+ self._messages = []
59
+
60
+
61
+ __all__ = ["PendingMessageQueue", "QueueMode"]
braid_agent/tools.py ADDED
@@ -0,0 +1,198 @@
1
+ """工具协议:**可执行**的工具长什么样,执行完要交回什么。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
6
+ from dataclasses import dataclass, field
7
+ from typing import Literal
8
+
9
+ from braid_ai.cancel import CancelToken
10
+ from braid_ai.types import ImageContent, JsonValue, TextContent, Tool, ToolCall, Usage
11
+
12
+ #: 一批工具调用的执行方式。
13
+ #:
14
+ #: - ``sequential``:准备、执行、收尾、发结果整套走完,再开始下一个调用。
15
+ #: - ``parallel``:逐个准备(可能弹权限框,必须串行),然后允许的调用同时执行;
16
+ #: ``tool_execution_end`` 按完成顺序发,工具结果消息按助手消息里的调用顺序发。
17
+ #:
18
+ #: 这是``AgentLoopConfig.tool_execution`` 与 ``AgentTool.execution_mode`` 共用的取值。
19
+ type ToolExecutionMode = Literal["sequential", "parallel"]
20
+
21
+ #: 工具上报进度的回调。**必须是 async**:它内部要 ``await`` 事件投递,同步回调会让
22
+ #: 工具作者写出"发了事件但没送到"的代码。没有订阅者时循环传一个空实现。
23
+ type ToolUpdateSink = Callable[[AgentToolResult], Awaitable[None]]
24
+
25
+ #: 工具的执行签名:``(tool_call_id, 已校验的参数, 取消令牌, 进度回调) -> 结果``。
26
+ #:
27
+ #: 参数是**已校验**的副本,工具可以直接修改;``tool_call_id`` 用于关联日志与 UI;
28
+ #: ``signal`` 让长任务(子进程、大文件)在取消时自行退出。
29
+ type ToolExecute = Callable[
30
+ [str, dict[str, JsonValue], CancelToken | None, ToolUpdateSink],
31
+ Awaitable[AgentToolResult],
32
+ ]
33
+
34
+ #: 校验前的参数修补:把旧格式或近似写法改成当前 schema 认可的形态。
35
+ #:
36
+ #: 它存在的理由是**版本兼容**:模型见过旧版工具声明时,仍可能按旧字段名调用。
37
+ #: 修补发生在校验之前,所以它必须返回一个对象(不是 None);返回原对象表示不改。
38
+ type PrepareArguments = Callable[[dict[str, JsonValue]], dict[str, JsonValue]]
39
+
40
+
41
+ @dataclass(slots=True)
42
+ class AgentToolResult:
43
+ """一次工具执行的结果。
44
+
45
+ ``content`` 是**模型可见**的内容(文本/图片)。空列表是合法的:工具可以只做副作用
46
+ (写文件、发通知),循环会把它原样写进转录,不做 ``None`` 兜底。
47
+
48
+ ``is_error`` 表达"执行了但失败了",与抛异常等价,区别只在保留的结构化信息。
49
+
50
+ ``terminate`` 是给循环的**建议**,不是命令:只有整批调用的最终结果都为 ``True``
51
+ 时,循环才在这一回合之后停下来(不再请求模型)。单个工具说"我做完了"不足以
52
+ 结束,因为同批的其他工具可能还需要模型看一眼结果。
53
+ """
54
+
55
+ content: list[TextContent | ImageContent] = field(
56
+ default_factory=list[TextContent | ImageContent]
57
+ )
58
+ #: 给 UI / 日志的结构化细节(截断位置、diff、退出码)。不发给模型。
59
+ details: JsonValue = None
60
+ #: 与工具 ``output_schema`` 对应的机器可读结果。不发给模型,供程序化调用方使用。
61
+ structured_content: JsonValue = None
62
+ is_error: bool = False
63
+ #: 工具自身的用量(例如它内部又调了模型)。不进主对话的 token 统计。
64
+ usage: Usage | None = None
65
+ #: "这一批到此为止"的建议。只有整批都为 ``True`` 才生效。
66
+ terminate: bool = False
67
+
68
+
69
+ @dataclass(slots=True)
70
+ class AgentTool:
71
+ """一个可执行工具。
72
+
73
+ ``parameters`` 是原始 JSON Schema(``dict``),与发给 Provider 的那份**同一对象来源**:
74
+ 声明与校验用同一份 schema,才不会有"模型按 A 声明调用、我们用 B 校验"的错位。
75
+
76
+ ``execution_mode`` 是**单工具**的执行方式覆盖,方向只有一个:把整批拉向更保守的一侧。
77
+ 任何一个调用命中 ``"sequential"``,整批退化为串行。反过来不成立——单个工具无法把
78
+ 批次变成并发,因为并发的前提是"这一批里没有必须独占的调用"。
79
+
80
+ 三个超时字段是**上限声明**,由循环兑现:``default_timeout_s`` 是模型没给参数时的
81
+ 允许时长,``max_timeout_s`` 是模型上调时不能越过的硬顶,``timeout_parameter``
82
+ 指向那个可以让模型参与决定的参数名。三者都为 ``None`` 表示"这个工具的执行时长
83
+ 不由循环约束"——本地文件操作属于这一类,它们的时间由下层 I/O 决定,而 ``bash``、
84
+ ``task`` 这类能无限等下去的工具必须声明。
85
+
86
+ 声明之外,工具自己也可以在同一组数字上终止下层操作(``bash`` 杀进程组),这样
87
+ 超时时能带回半截输出。两层用的必须是同一份取舍:``resolve_tool_timeout()``
88
+ 就是给这两处共用的。
89
+ """
90
+
91
+ name: str
92
+ label: str
93
+ description: str
94
+ parameters: dict[str, JsonValue]
95
+ execute: ToolExecute
96
+ #: 校验前的参数修补。``None`` 表示参数已经是当前格式。
97
+ prepare_arguments: PrepareArguments | None = None
98
+ #: 执行方式覆盖。``None`` 表示跟随 ``AgentLoopConfig.tool_execution``。
99
+ execution_mode: ToolExecutionMode | None = None
100
+ #: 模型没指定超时时的允许时长(秒)。``None`` 表示不设上限。
101
+ default_timeout_s: float | None = None
102
+ #: 模型上调的超时不能越过这个值(秒)。``None`` 表示只受 ``default_timeout_s`` 约束。
103
+ max_timeout_s: float | None = None
104
+ #: 承载"这次调用等多长时间"的参数名。声明了它,模型才能在一次调用里上调。
105
+ timeout_parameter: str | None = None
106
+
107
+
108
+ def resolve_tool_timeout(
109
+ *,
110
+ requested: JsonValue,
111
+ default_s: float | None,
112
+ max_s: float | None,
113
+ ) -> float | None:
114
+ """把"模型这次要多长时间"收进工具声明的范围内,返回秒数。
115
+
116
+ 三条规则,按顺序生效:
117
+
118
+ 1. 两个声明都为 ``None`` → ``None``,循环不设上限。
119
+ 2. ``requested`` 有值 → 用它,但不越过 ``max_s``。它必须是正的有限数;写成字符串
120
+ 或负数就地报错,不做猜测。
121
+ 3. ``requested`` 为 ``None`` → ``default_s``;它也没声明时退回 ``max_s``。
122
+
123
+ ``max_s`` 只限制模型,不限制默认值:默认值是工具作者写下的常量,与模型临时要求的
124
+ 数字不是同一件事。
125
+
126
+ 抽成纯函数是为了让**工具自己**与**循环**用同一份取舍:``bash`` 在自己的超时点上
127
+ 终止子进程(能带回半截输出),循环在晚一点的硬停止点兜底。两处算出的时长必须一致,
128
+ 否则会出现"提示里写 120 秒、实际 135 秒才停"这种没人能解释的结果。
129
+ """
130
+ cap = max_s if max_s is not None else default_s
131
+ if default_s is None and cap is None:
132
+ return None
133
+ if requested is not None:
134
+ if isinstance(requested, bool) or not isinstance(requested, int | float):
135
+ raise ValueError(f"超时参数必须是秒数(数字),收到 {requested!r}")
136
+ seconds = float(requested)
137
+ if not 0 < seconds < float("inf"):
138
+ raise ValueError(f"超时参数必须是正的有限秒数,收到 {requested!r}")
139
+ return seconds if cap is None else min(seconds, cap)
140
+ return default_s if default_s is not None else cap
141
+
142
+
143
+ def tool_timeout_seconds(tool: AgentTool, args: Mapping[str, JsonValue]) -> float | None:
144
+ """一次调用允许的时间(秒)。``None`` 表示循环不设上限。
145
+
146
+ 工具没有声明 ``timeout_parameter`` 时,模型写的任何 ``timeout`` 都不参与计算——
147
+ "这个参数是超时"是工具的声明,不由参数名猜。
148
+ """
149
+ requested = args.get(tool.timeout_parameter) if tool.timeout_parameter is not None else None
150
+ return resolve_tool_timeout(
151
+ requested=requested,
152
+ default_s=tool.default_timeout_s,
153
+ max_s=tool.max_timeout_s,
154
+ )
155
+
156
+
157
+ @dataclass(slots=True)
158
+ class AgentToolCallOutcome:
159
+ """一次工具调用的最终产出:调用本体、结果、错误标记、耗时。
160
+
161
+ ``duration_ms`` 用**单调时钟**测量,且只覆盖 ``execute`` 本身。没执行(未知工具、
162
+ 参数非法)时为 ``None``——不是 0,因为"没跑"和"跑了 0 毫秒"是两件事。
163
+ """
164
+
165
+ tool_call: ToolCall
166
+ result: AgentToolResult
167
+ is_error: bool
168
+ duration_ms: int | None = None
169
+
170
+
171
+ def tool_declaration(tool: AgentTool) -> Tool:
172
+ """把一个可执行工具折成模型可见的声明。
173
+
174
+ 只取三个字段,是刻意的:``label`` 给人看,``execute`` 是运行时行为,两个都不该进
175
+ 请求体。声明与执行共享同一份 ``parameters``(同一对象来源),所以模型按什么调用、
176
+ 我们就按什么校验。
177
+ """
178
+ return Tool(name=tool.name, description=tool.description, parameters=tool.parameters)
179
+
180
+
181
+ def tool_declarations(tools: Sequence[AgentTool]) -> list[Tool]:
182
+ """按给定顺序折叠成声明列表。顺序即模型看到的顺序。"""
183
+ return [tool_declaration(tool) for tool in tools]
184
+
185
+
186
+ __all__ = [
187
+ "AgentTool",
188
+ "AgentToolCallOutcome",
189
+ "AgentToolResult",
190
+ "PrepareArguments",
191
+ "ToolExecute",
192
+ "ToolExecutionMode",
193
+ "ToolUpdateSink",
194
+ "resolve_tool_timeout",
195
+ "tool_declaration",
196
+ "tool_declarations",
197
+ "tool_timeout_seconds",
198
+ ]