braid-ai 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_ai/__init__.py +412 -0
- braid_ai/auth.py +141 -0
- braid_ai/cancel.py +153 -0
- braid_ai/event_stream.py +311 -0
- braid_ai/models.py +496 -0
- braid_ai/overflow.py +177 -0
- braid_ai/providers/__init__.py +5 -0
- braid_ai/providers/anthropic.py +1003 -0
- braid_ai/providers/faux.py +642 -0
- braid_ai/providers/openai_compat.py +995 -0
- braid_ai/providers/openai_responses.py +503 -0
- braid_ai/retry.py +332 -0
- braid_ai/sse.py +158 -0
- braid_ai/streaming_json.py +362 -0
- braid_ai/transcript.py +223 -0
- braid_ai/types.py +617 -0
- braid_ai/utils/__init__.py +10 -0
- braid_ai/utils/clock.py +73 -0
- braid_ai/utils/json.py +147 -0
- braid_ai/validation.py +136 -0
- braid_ai/wire.py +710 -0
- braid_ai-0.1.0.dist-info/METADATA +9 -0
- braid_ai-0.1.0.dist-info/RECORD +25 -0
- braid_ai-0.1.0.dist-info/WHEEL +4 -0
- braid_ai-0.1.0.dist-info/licenses/LICENSE +21 -0
braid_ai/__init__.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
"""模型边界层:只认识消息、事件流和 Provider,不知道 Agent、会话、工具的存在。
|
|
2
|
+
|
|
3
|
+
不得导入 braid_agent / braid_coding_agent。
|
|
4
|
+
|
|
5
|
+
## 导入开销
|
|
6
|
+
|
|
7
|
+
``braid_ai`` 的导出覆盖类型、事件流、Provider 与校验四层。一次 ``braid --version``
|
|
8
|
+
不该为此加载 HTTP 客户端、JSON Schema 与全部 Provider,因此本模块只声明导出名,
|
|
9
|
+
真正导入发生在第一次读取属性时(PEP 562)。``from braid_ai import Models`` 仍然可用,
|
|
10
|
+
代价是只加载 ``braid_ai.models`` 这一条依赖链。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import importlib
|
|
16
|
+
from typing import TYPE_CHECKING, Final
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from braid_ai.auth import (
|
|
20
|
+
AuthResolver,
|
|
21
|
+
ChainedAuthResolver,
|
|
22
|
+
ConfigFileAuthResolver,
|
|
23
|
+
EnvAuthResolver,
|
|
24
|
+
HasEnvKeys,
|
|
25
|
+
)
|
|
26
|
+
from braid_ai.cancel import CancelToken, RequestAborted, iter_until_cancelled
|
|
27
|
+
from braid_ai.event_stream import (
|
|
28
|
+
AssistantMessageEventStream,
|
|
29
|
+
EventStream,
|
|
30
|
+
StreamEndedWithoutResult,
|
|
31
|
+
cancel_and_wait,
|
|
32
|
+
)
|
|
33
|
+
from braid_ai.models import (
|
|
34
|
+
EXTENDED_THINKING_LEVELS,
|
|
35
|
+
Models,
|
|
36
|
+
ModelsError,
|
|
37
|
+
ModelsErrorCode,
|
|
38
|
+
Provider,
|
|
39
|
+
clamp_thinking_level,
|
|
40
|
+
get_supported_thinking_levels,
|
|
41
|
+
)
|
|
42
|
+
from braid_ai.overflow import (
|
|
43
|
+
get_overflow_patterns,
|
|
44
|
+
is_context_overflow,
|
|
45
|
+
is_recoverable_length,
|
|
46
|
+
)
|
|
47
|
+
from braid_ai.providers.anthropic import (
|
|
48
|
+
AnthropicConfig,
|
|
49
|
+
AnthropicProvider,
|
|
50
|
+
build_anthropic_request,
|
|
51
|
+
convert_anthropic_messages,
|
|
52
|
+
convert_anthropic_tools,
|
|
53
|
+
)
|
|
54
|
+
from braid_ai.providers.faux import (
|
|
55
|
+
FauxProvider,
|
|
56
|
+
FauxProviderState,
|
|
57
|
+
FauxResponse,
|
|
58
|
+
FauxResponseFactory,
|
|
59
|
+
faux_message,
|
|
60
|
+
faux_text,
|
|
61
|
+
faux_thinking,
|
|
62
|
+
faux_tool_call,
|
|
63
|
+
)
|
|
64
|
+
from braid_ai.providers.openai_compat import (
|
|
65
|
+
MissingApiKeyError,
|
|
66
|
+
OpenAICompatConfig,
|
|
67
|
+
OpenAICompatProvider,
|
|
68
|
+
ProviderError,
|
|
69
|
+
build_chat_completions_request,
|
|
70
|
+
convert_messages,
|
|
71
|
+
convert_tools,
|
|
72
|
+
)
|
|
73
|
+
from braid_ai.providers.openai_responses import (
|
|
74
|
+
OpenAIResponsesProvider,
|
|
75
|
+
build_responses_request,
|
|
76
|
+
convert_responses_input,
|
|
77
|
+
convert_responses_tools,
|
|
78
|
+
)
|
|
79
|
+
from braid_ai.retry import (
|
|
80
|
+
DEFAULT_MAX_AGENT_RETRY_DELAY_MS,
|
|
81
|
+
RetryBackoffCancelled,
|
|
82
|
+
RetryCallbacks,
|
|
83
|
+
RetryPolicy,
|
|
84
|
+
RetrySleepFn,
|
|
85
|
+
backoff_sleep,
|
|
86
|
+
is_retryable_assistant_error,
|
|
87
|
+
retry_assistant_call,
|
|
88
|
+
retry_delay_ms,
|
|
89
|
+
)
|
|
90
|
+
from braid_ai.sse import SseDecoder, iter_sse_payloads
|
|
91
|
+
from braid_ai.streaming_json import StreamingJsonParser, ToolCallArgumentsStream
|
|
92
|
+
from braid_ai.transcript import (
|
|
93
|
+
ToolStateChanges,
|
|
94
|
+
collapse_system_messages,
|
|
95
|
+
declarations_equal,
|
|
96
|
+
get_current_system_message,
|
|
97
|
+
get_current_system_text,
|
|
98
|
+
get_current_tools,
|
|
99
|
+
get_declared_tools,
|
|
100
|
+
get_tool_state_changes,
|
|
101
|
+
to_tool_declaration,
|
|
102
|
+
)
|
|
103
|
+
from braid_ai.types import (
|
|
104
|
+
CACHE_ANCHORS,
|
|
105
|
+
AssistantMessage,
|
|
106
|
+
AssistantMessageEvent,
|
|
107
|
+
CacheAnchor,
|
|
108
|
+
ContentBlock,
|
|
109
|
+
Cost,
|
|
110
|
+
DoneEvent,
|
|
111
|
+
ErrorEvent,
|
|
112
|
+
ImageContent,
|
|
113
|
+
JsonValue,
|
|
114
|
+
Message,
|
|
115
|
+
Model,
|
|
116
|
+
ModelCost,
|
|
117
|
+
ModelInput,
|
|
118
|
+
ModelThinkingLevel,
|
|
119
|
+
SimpleStreamOptions,
|
|
120
|
+
StartEvent,
|
|
121
|
+
StopReason,
|
|
122
|
+
StreamOptions,
|
|
123
|
+
SystemMessage,
|
|
124
|
+
TextContent,
|
|
125
|
+
TextDeltaEvent,
|
|
126
|
+
TextEndEvent,
|
|
127
|
+
TextStartEvent,
|
|
128
|
+
ThinkingContent,
|
|
129
|
+
ThinkingDeltaEvent,
|
|
130
|
+
ThinkingEndEvent,
|
|
131
|
+
ThinkingStartEvent,
|
|
132
|
+
Tool,
|
|
133
|
+
ToolCall,
|
|
134
|
+
ToolCallDeltaEvent,
|
|
135
|
+
ToolCallEndEvent,
|
|
136
|
+
ToolCallStartEvent,
|
|
137
|
+
ToolReference,
|
|
138
|
+
ToolResultMessage,
|
|
139
|
+
TranscriptContext,
|
|
140
|
+
Usage,
|
|
141
|
+
UserMessage,
|
|
142
|
+
)
|
|
143
|
+
from braid_ai.utils.clock import Clock, FakeClock, SystemClock
|
|
144
|
+
from braid_ai.utils.json import json_text, parse_tool_call_arguments, repair_json
|
|
145
|
+
from braid_ai.validation import ToolArgumentsError, validate_tool_arguments
|
|
146
|
+
from braid_ai.wire import (
|
|
147
|
+
WireError,
|
|
148
|
+
content_text,
|
|
149
|
+
message_from_wire,
|
|
150
|
+
message_to_wire,
|
|
151
|
+
system_message_text,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
#: 导出名 → 定义它的模块。导入发生在第一次读取属性时。
|
|
155
|
+
_LAZY_EXPORTS: Final[dict[str, str]] = {
|
|
156
|
+
"AuthResolver": "braid_ai.auth",
|
|
157
|
+
"ChainedAuthResolver": "braid_ai.auth",
|
|
158
|
+
"ConfigFileAuthResolver": "braid_ai.auth",
|
|
159
|
+
"EnvAuthResolver": "braid_ai.auth",
|
|
160
|
+
"HasEnvKeys": "braid_ai.auth",
|
|
161
|
+
"CancelToken": "braid_ai.cancel",
|
|
162
|
+
"RequestAborted": "braid_ai.cancel",
|
|
163
|
+
"iter_until_cancelled": "braid_ai.cancel",
|
|
164
|
+
"AssistantMessageEventStream": "braid_ai.event_stream",
|
|
165
|
+
"EventStream": "braid_ai.event_stream",
|
|
166
|
+
"StreamEndedWithoutResult": "braid_ai.event_stream",
|
|
167
|
+
"cancel_and_wait": "braid_ai.event_stream",
|
|
168
|
+
"EXTENDED_THINKING_LEVELS": "braid_ai.models",
|
|
169
|
+
"Models": "braid_ai.models",
|
|
170
|
+
"ModelsError": "braid_ai.models",
|
|
171
|
+
"ModelsErrorCode": "braid_ai.models",
|
|
172
|
+
"Provider": "braid_ai.models",
|
|
173
|
+
"clamp_thinking_level": "braid_ai.models",
|
|
174
|
+
"get_supported_thinking_levels": "braid_ai.models",
|
|
175
|
+
"get_overflow_patterns": "braid_ai.overflow",
|
|
176
|
+
"is_context_overflow": "braid_ai.overflow",
|
|
177
|
+
"is_recoverable_length": "braid_ai.overflow",
|
|
178
|
+
"AnthropicConfig": "braid_ai.providers.anthropic",
|
|
179
|
+
"AnthropicProvider": "braid_ai.providers.anthropic",
|
|
180
|
+
"build_anthropic_request": "braid_ai.providers.anthropic",
|
|
181
|
+
"convert_anthropic_messages": "braid_ai.providers.anthropic",
|
|
182
|
+
"convert_anthropic_tools": "braid_ai.providers.anthropic",
|
|
183
|
+
"FauxProvider": "braid_ai.providers.faux",
|
|
184
|
+
"FauxProviderState": "braid_ai.providers.faux",
|
|
185
|
+
"FauxResponse": "braid_ai.providers.faux",
|
|
186
|
+
"FauxResponseFactory": "braid_ai.providers.faux",
|
|
187
|
+
"faux_message": "braid_ai.providers.faux",
|
|
188
|
+
"faux_text": "braid_ai.providers.faux",
|
|
189
|
+
"faux_thinking": "braid_ai.providers.faux",
|
|
190
|
+
"faux_tool_call": "braid_ai.providers.faux",
|
|
191
|
+
"MissingApiKeyError": "braid_ai.providers.openai_compat",
|
|
192
|
+
"OpenAICompatConfig": "braid_ai.providers.openai_compat",
|
|
193
|
+
"OpenAICompatProvider": "braid_ai.providers.openai_compat",
|
|
194
|
+
"ProviderError": "braid_ai.providers.openai_compat",
|
|
195
|
+
"build_chat_completions_request": "braid_ai.providers.openai_compat",
|
|
196
|
+
"convert_messages": "braid_ai.providers.openai_compat",
|
|
197
|
+
"convert_tools": "braid_ai.providers.openai_compat",
|
|
198
|
+
"OpenAIResponsesProvider": "braid_ai.providers.openai_responses",
|
|
199
|
+
"build_responses_request": "braid_ai.providers.openai_responses",
|
|
200
|
+
"convert_responses_input": "braid_ai.providers.openai_responses",
|
|
201
|
+
"convert_responses_tools": "braid_ai.providers.openai_responses",
|
|
202
|
+
"DEFAULT_MAX_AGENT_RETRY_DELAY_MS": "braid_ai.retry",
|
|
203
|
+
"RetryBackoffCancelled": "braid_ai.retry",
|
|
204
|
+
"RetryCallbacks": "braid_ai.retry",
|
|
205
|
+
"RetryPolicy": "braid_ai.retry",
|
|
206
|
+
"RetrySleepFn": "braid_ai.retry",
|
|
207
|
+
"backoff_sleep": "braid_ai.retry",
|
|
208
|
+
"is_retryable_assistant_error": "braid_ai.retry",
|
|
209
|
+
"retry_assistant_call": "braid_ai.retry",
|
|
210
|
+
"retry_delay_ms": "braid_ai.retry",
|
|
211
|
+
"SseDecoder": "braid_ai.sse",
|
|
212
|
+
"iter_sse_payloads": "braid_ai.sse",
|
|
213
|
+
"StreamingJsonParser": "braid_ai.streaming_json",
|
|
214
|
+
"ToolCallArgumentsStream": "braid_ai.streaming_json",
|
|
215
|
+
"ToolStateChanges": "braid_ai.transcript",
|
|
216
|
+
"collapse_system_messages": "braid_ai.transcript",
|
|
217
|
+
"declarations_equal": "braid_ai.transcript",
|
|
218
|
+
"get_current_system_message": "braid_ai.transcript",
|
|
219
|
+
"get_current_system_text": "braid_ai.transcript",
|
|
220
|
+
"get_current_tools": "braid_ai.transcript",
|
|
221
|
+
"get_declared_tools": "braid_ai.transcript",
|
|
222
|
+
"get_tool_state_changes": "braid_ai.transcript",
|
|
223
|
+
"to_tool_declaration": "braid_ai.transcript",
|
|
224
|
+
"CACHE_ANCHORS": "braid_ai.types",
|
|
225
|
+
"AssistantMessage": "braid_ai.types",
|
|
226
|
+
"AssistantMessageEvent": "braid_ai.types",
|
|
227
|
+
"CacheAnchor": "braid_ai.types",
|
|
228
|
+
"ContentBlock": "braid_ai.types",
|
|
229
|
+
"Cost": "braid_ai.types",
|
|
230
|
+
"DoneEvent": "braid_ai.types",
|
|
231
|
+
"ErrorEvent": "braid_ai.types",
|
|
232
|
+
"ImageContent": "braid_ai.types",
|
|
233
|
+
"JsonValue": "braid_ai.types",
|
|
234
|
+
"Message": "braid_ai.types",
|
|
235
|
+
"Model": "braid_ai.types",
|
|
236
|
+
"ModelCost": "braid_ai.types",
|
|
237
|
+
"ModelInput": "braid_ai.types",
|
|
238
|
+
"ModelThinkingLevel": "braid_ai.types",
|
|
239
|
+
"SimpleStreamOptions": "braid_ai.types",
|
|
240
|
+
"StartEvent": "braid_ai.types",
|
|
241
|
+
"StopReason": "braid_ai.types",
|
|
242
|
+
"StreamOptions": "braid_ai.types",
|
|
243
|
+
"SystemMessage": "braid_ai.types",
|
|
244
|
+
"TextContent": "braid_ai.types",
|
|
245
|
+
"TextDeltaEvent": "braid_ai.types",
|
|
246
|
+
"TextEndEvent": "braid_ai.types",
|
|
247
|
+
"TextStartEvent": "braid_ai.types",
|
|
248
|
+
"ThinkingContent": "braid_ai.types",
|
|
249
|
+
"ThinkingDeltaEvent": "braid_ai.types",
|
|
250
|
+
"ThinkingEndEvent": "braid_ai.types",
|
|
251
|
+
"ThinkingStartEvent": "braid_ai.types",
|
|
252
|
+
"Tool": "braid_ai.types",
|
|
253
|
+
"ToolCall": "braid_ai.types",
|
|
254
|
+
"ToolCallDeltaEvent": "braid_ai.types",
|
|
255
|
+
"ToolCallEndEvent": "braid_ai.types",
|
|
256
|
+
"ToolCallStartEvent": "braid_ai.types",
|
|
257
|
+
"ToolReference": "braid_ai.types",
|
|
258
|
+
"ToolResultMessage": "braid_ai.types",
|
|
259
|
+
"TranscriptContext": "braid_ai.types",
|
|
260
|
+
"Usage": "braid_ai.types",
|
|
261
|
+
"UserMessage": "braid_ai.types",
|
|
262
|
+
"Clock": "braid_ai.utils.clock",
|
|
263
|
+
"FakeClock": "braid_ai.utils.clock",
|
|
264
|
+
"SystemClock": "braid_ai.utils.clock",
|
|
265
|
+
"json_text": "braid_ai.utils.json",
|
|
266
|
+
"parse_tool_call_arguments": "braid_ai.utils.json",
|
|
267
|
+
"repair_json": "braid_ai.utils.json",
|
|
268
|
+
"ToolArgumentsError": "braid_ai.validation",
|
|
269
|
+
"validate_tool_arguments": "braid_ai.validation",
|
|
270
|
+
"WireError": "braid_ai.wire",
|
|
271
|
+
"content_text": "braid_ai.wire",
|
|
272
|
+
"message_from_wire": "braid_ai.wire",
|
|
273
|
+
"message_to_wire": "braid_ai.wire",
|
|
274
|
+
"system_message_text": "braid_ai.wire",
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def __getattr__(name: str) -> object:
|
|
279
|
+
"""按需导入导出名;未声明的名字照常报错。"""
|
|
280
|
+
module_name = _LAZY_EXPORTS.get(name)
|
|
281
|
+
if module_name is None:
|
|
282
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
283
|
+
module = importlib.import_module(module_name)
|
|
284
|
+
value = getattr(module, name)
|
|
285
|
+
globals()[name] = value
|
|
286
|
+
return value
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
__version__: Final[str] = "0.1.0"
|
|
290
|
+
|
|
291
|
+
__all__ = [
|
|
292
|
+
"CACHE_ANCHORS",
|
|
293
|
+
"DEFAULT_MAX_AGENT_RETRY_DELAY_MS",
|
|
294
|
+
"EXTENDED_THINKING_LEVELS",
|
|
295
|
+
"AnthropicConfig",
|
|
296
|
+
"AnthropicProvider",
|
|
297
|
+
"AssistantMessage",
|
|
298
|
+
"AssistantMessageEvent",
|
|
299
|
+
"AssistantMessageEventStream",
|
|
300
|
+
"AuthResolver",
|
|
301
|
+
"CacheAnchor",
|
|
302
|
+
"CancelToken",
|
|
303
|
+
"ChainedAuthResolver",
|
|
304
|
+
"Clock",
|
|
305
|
+
"ConfigFileAuthResolver",
|
|
306
|
+
"ContentBlock",
|
|
307
|
+
"Cost",
|
|
308
|
+
"DoneEvent",
|
|
309
|
+
"EnvAuthResolver",
|
|
310
|
+
"ErrorEvent",
|
|
311
|
+
"EventStream",
|
|
312
|
+
"FakeClock",
|
|
313
|
+
"FauxProvider",
|
|
314
|
+
"FauxProviderState",
|
|
315
|
+
"FauxResponse",
|
|
316
|
+
"FauxResponseFactory",
|
|
317
|
+
"HasEnvKeys",
|
|
318
|
+
"ImageContent",
|
|
319
|
+
"JsonValue",
|
|
320
|
+
"Message",
|
|
321
|
+
"MissingApiKeyError",
|
|
322
|
+
"Model",
|
|
323
|
+
"ModelCost",
|
|
324
|
+
"ModelInput",
|
|
325
|
+
"ModelThinkingLevel",
|
|
326
|
+
"Models",
|
|
327
|
+
"ModelsError",
|
|
328
|
+
"ModelsErrorCode",
|
|
329
|
+
"OpenAICompatConfig",
|
|
330
|
+
"OpenAICompatProvider",
|
|
331
|
+
"OpenAIResponsesProvider",
|
|
332
|
+
"Provider",
|
|
333
|
+
"ProviderError",
|
|
334
|
+
"RequestAborted",
|
|
335
|
+
"RetryBackoffCancelled",
|
|
336
|
+
"RetryCallbacks",
|
|
337
|
+
"RetryPolicy",
|
|
338
|
+
"RetrySleepFn",
|
|
339
|
+
"SimpleStreamOptions",
|
|
340
|
+
"SseDecoder",
|
|
341
|
+
"StartEvent",
|
|
342
|
+
"StopReason",
|
|
343
|
+
"StreamEndedWithoutResult",
|
|
344
|
+
"StreamOptions",
|
|
345
|
+
"StreamingJsonParser",
|
|
346
|
+
"SystemClock",
|
|
347
|
+
"SystemMessage",
|
|
348
|
+
"TextContent",
|
|
349
|
+
"TextDeltaEvent",
|
|
350
|
+
"TextEndEvent",
|
|
351
|
+
"TextStartEvent",
|
|
352
|
+
"ThinkingContent",
|
|
353
|
+
"ThinkingDeltaEvent",
|
|
354
|
+
"ThinkingEndEvent",
|
|
355
|
+
"ThinkingStartEvent",
|
|
356
|
+
"Tool",
|
|
357
|
+
"ToolArgumentsError",
|
|
358
|
+
"ToolCall",
|
|
359
|
+
"ToolCallArgumentsStream",
|
|
360
|
+
"ToolCallDeltaEvent",
|
|
361
|
+
"ToolCallEndEvent",
|
|
362
|
+
"ToolCallStartEvent",
|
|
363
|
+
"ToolReference",
|
|
364
|
+
"ToolResultMessage",
|
|
365
|
+
"ToolStateChanges",
|
|
366
|
+
"TranscriptContext",
|
|
367
|
+
"Usage",
|
|
368
|
+
"UserMessage",
|
|
369
|
+
"WireError",
|
|
370
|
+
"__version__",
|
|
371
|
+
"backoff_sleep",
|
|
372
|
+
"build_anthropic_request",
|
|
373
|
+
"build_chat_completions_request",
|
|
374
|
+
"build_responses_request",
|
|
375
|
+
"cancel_and_wait",
|
|
376
|
+
"clamp_thinking_level",
|
|
377
|
+
"collapse_system_messages",
|
|
378
|
+
"content_text",
|
|
379
|
+
"convert_anthropic_messages",
|
|
380
|
+
"convert_anthropic_tools",
|
|
381
|
+
"convert_messages",
|
|
382
|
+
"convert_responses_input",
|
|
383
|
+
"convert_responses_tools",
|
|
384
|
+
"convert_tools",
|
|
385
|
+
"declarations_equal",
|
|
386
|
+
"faux_message",
|
|
387
|
+
"faux_text",
|
|
388
|
+
"faux_thinking",
|
|
389
|
+
"faux_tool_call",
|
|
390
|
+
"get_current_system_message",
|
|
391
|
+
"get_current_system_text",
|
|
392
|
+
"get_current_tools",
|
|
393
|
+
"get_declared_tools",
|
|
394
|
+
"get_overflow_patterns",
|
|
395
|
+
"get_supported_thinking_levels",
|
|
396
|
+
"get_tool_state_changes",
|
|
397
|
+
"is_context_overflow",
|
|
398
|
+
"is_recoverable_length",
|
|
399
|
+
"is_retryable_assistant_error",
|
|
400
|
+
"iter_sse_payloads",
|
|
401
|
+
"iter_until_cancelled",
|
|
402
|
+
"json_text",
|
|
403
|
+
"message_from_wire",
|
|
404
|
+
"message_to_wire",
|
|
405
|
+
"parse_tool_call_arguments",
|
|
406
|
+
"repair_json",
|
|
407
|
+
"retry_assistant_call",
|
|
408
|
+
"retry_delay_ms",
|
|
409
|
+
"system_message_text",
|
|
410
|
+
"to_tool_declaration",
|
|
411
|
+
"validate_tool_arguments",
|
|
412
|
+
]
|
braid_ai/auth.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""凭证解析:把"Provider 是谁"翻译成"这次请求用什么 Key"。
|
|
2
|
+
|
|
3
|
+
主干只有一条:**按 provider 解析出 API Key,解析不到就报告"未配置"**。
|
|
4
|
+
|
|
5
|
+
凭证在这套架构里是独立的一层,而不是 Provider 的私有字段:
|
|
6
|
+
|
|
7
|
+
- **模型目录**(:class:`~braid_ai.types.Model`)回答"有哪些模型、能力价格如何";
|
|
8
|
+
- **Provider**(:mod:`braid_ai.models`)回答"请求怎么发、流怎么归一化";
|
|
9
|
+
- **凭证**回答"这次请求以谁的身份发出"。
|
|
10
|
+
|
|
11
|
+
三层分开,同一个 Provider 才能在"环境变量 / 配置文件 / 显式传参"之间切换而
|
|
12
|
+
不动传输代码;测试也能用假环境变量驱动真分发逻辑。
|
|
13
|
+
|
|
14
|
+
解析的优先级链::
|
|
15
|
+
|
|
16
|
+
显式参数(``StreamOptions.api_key``)
|
|
17
|
+
> 环境变量(:class:`EnvAuthResolver`)
|
|
18
|
+
> 配置文件(:class:`ConfigFileAuthResolver`)
|
|
19
|
+
> 无(→ :class:`braid_ai.models.ModelsError`)
|
|
20
|
+
|
|
21
|
+
环境变量名**不硬编码在解析器里**:每个 Provider 在自己的 ``env_keys`` 里声明
|
|
22
|
+
认识哪些变量。解析器只负责"按声明顺序取第一个非空值"。这样新增 Provider
|
|
23
|
+
不需要改解析器,测试注入假环境也不需要 monkeypatch 全局状态。
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
from collections.abc import Mapping, Sequence
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from typing import Protocol, runtime_checkable
|
|
33
|
+
|
|
34
|
+
from braid_ai.types import JsonValue
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@runtime_checkable
|
|
38
|
+
class HasEnvKeys(Protocol):
|
|
39
|
+
"""带凭证声明的东西:一个 id,外加它认识的环境变量名。
|
|
40
|
+
|
|
41
|
+
:class:`braid_ai.models.Provider` 继承这个协议。单独提出来是因为 auth 只需要
|
|
42
|
+
这两个字段——凭证解析不应该依赖传输实现(拿得到 ``stream`` 方法也用不上)。
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def id(self) -> str: ...
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def env_keys(self) -> Sequence[str]: ...
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@runtime_checkable
|
|
53
|
+
class AuthResolver(Protocol):
|
|
54
|
+
"""凭证解析器:按 provider 返回一个 API Key,或 ``None``(未配置)。
|
|
55
|
+
|
|
56
|
+
``None`` 不是错误:调用方(:class:`braid_ai.models.Models`)决定"未配置"算不算
|
|
57
|
+
失败——声明了 ``env_keys`` 的 provider 解析不到凭证是配置错误,keyless 的
|
|
58
|
+
provider(``env_keys`` 为空)本来就无需凭证。
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
def resolve(self, provider: HasEnvKeys) -> str | None: ...
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class EnvAuthResolver:
|
|
65
|
+
"""环境变量解析:按 ``provider.env_keys`` 声明顺序取第一个非空值。
|
|
66
|
+
|
|
67
|
+
解析规则:**声明顺序就是优先顺序**。
|
|
68
|
+
anthropic 声明 ``[ANTHROPIC_AUTH_TOKEN, ANTHROPIC_OAUTH_TOKEN, ANTHROPIC_API_KEY]``
|
|
69
|
+
时会先取 AUTH_TOKEN——清单本身表达了"哪个变量优先"。
|
|
70
|
+
|
|
71
|
+
``env`` 参数默认接 ``os.environ``;测试注入一个普通 ``dict`` 即可离线驱动,
|
|
72
|
+
不需要 monkeypatch 进程全局状态。
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def __init__(self, env: Mapping[str, str] | None = None) -> None:
|
|
76
|
+
self._env: Mapping[str, str] = os.environ if env is None else env
|
|
77
|
+
|
|
78
|
+
def resolve(self, provider: HasEnvKeys) -> str | None:
|
|
79
|
+
for name in provider.env_keys:
|
|
80
|
+
value = self._env.get(name)
|
|
81
|
+
if value:
|
|
82
|
+
return value
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class ConfigFileAuthResolver:
|
|
87
|
+
"""配置文件解析:一个 JSON 文件,形如 ``{"deepseek": "sk-..."}``。
|
|
88
|
+
|
|
89
|
+
键是 provider id,值是 API Key。文件**每次解析都重读**——这是刻意的:
|
|
90
|
+
长任务里的短期 Token 会在中途轮换,缓存一份就等于把"启动时刻的凭证"
|
|
91
|
+
钉到进程结束。
|
|
92
|
+
|
|
93
|
+
文件不存在、不是合法 JSON、值不是字符串——一律视为"该 provider 未配置",
|
|
94
|
+
而不是抛异常。配置文件属于用户手写的环境,格式写错时"降级到无凭证、
|
|
95
|
+
报未配置错误"比"解析栈崩溃"更可行动:错误消息会把三种设置方式都列出来。
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def __init__(self, path: Path) -> None:
|
|
99
|
+
self._path = path
|
|
100
|
+
|
|
101
|
+
def resolve(self, provider: HasEnvKeys) -> str | None:
|
|
102
|
+
try:
|
|
103
|
+
text = self._path.read_text(encoding="utf-8")
|
|
104
|
+
except OSError:
|
|
105
|
+
return None
|
|
106
|
+
try:
|
|
107
|
+
data: JsonValue = json.loads(text)
|
|
108
|
+
except ValueError:
|
|
109
|
+
return None
|
|
110
|
+
if not isinstance(data, dict):
|
|
111
|
+
return None
|
|
112
|
+
value = data.get(provider.id)
|
|
113
|
+
return value if isinstance(value, str) and value else None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class ChainedAuthResolver:
|
|
117
|
+
"""按顺序尝试多个解析器,第一个非空结果生效。
|
|
118
|
+
|
|
119
|
+
默认链的优先级:环境变量在前、配置文件在后::
|
|
120
|
+
|
|
121
|
+
ChainedAuthResolver([EnvAuthResolver(), ConfigFileAuthResolver(path)])
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
def __init__(self, resolvers: Sequence[AuthResolver]) -> None:
|
|
125
|
+
self._resolvers: tuple[AuthResolver, ...] = tuple(resolvers)
|
|
126
|
+
|
|
127
|
+
def resolve(self, provider: HasEnvKeys) -> str | None:
|
|
128
|
+
for resolver in self._resolvers:
|
|
129
|
+
key = resolver.resolve(provider)
|
|
130
|
+
if key:
|
|
131
|
+
return key
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
__all__ = [
|
|
136
|
+
"AuthResolver",
|
|
137
|
+
"ChainedAuthResolver",
|
|
138
|
+
"ConfigFileAuthResolver",
|
|
139
|
+
"EnvAuthResolver",
|
|
140
|
+
"HasEnvKeys",
|
|
141
|
+
]
|