aibx 1.0.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.
aibx/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """
2
+ AI Bridge (aibx) - 纯净、透明、支持自定义中转与多格式文件的 Python 3.7+ 大模型桥接库。
3
+ """
4
+
5
+ from .bridge import AIBridge, list_models
6
+ from .files import FileInput
7
+ from .models import (
8
+ AIBridgeError,
9
+ APIError,
10
+ ProtocolType,
11
+ Response,
12
+ Usage,
13
+ VendorType,
14
+ )
15
+
16
+ __all__ = [
17
+ "AIBridge",
18
+ "list_models",
19
+ "FileInput",
20
+ "Response",
21
+ "Usage",
22
+ "VendorType",
23
+ "ProtocolType",
24
+ "AIBridgeError",
25
+ "APIError",
26
+ ]
27
+ __version__ = "1.0.0"
aibx/bridge.py ADDED
@@ -0,0 +1,264 @@
1
+ """AIBridge 统一门面入口、并发批量调用与动态模型发现(兼容 Python 3.7+)。"""
2
+
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ from typing import Any, Dict, Iterator, List, Optional, Union
5
+
6
+ from .files import DEFAULT_MAX_FILE_SIZE_MB, DEFAULT_MAX_TABLE_ROWS, FileInput
7
+ from .models import APIError, ProtocolType, Response
8
+ from .vendors import VendorAdapter, get_adapter, resolve_endpoint_config
9
+
10
+
11
+ class AIBridge:
12
+ """
13
+ 纯净、透明的多供应商大模型桥接客户端。
14
+
15
+ 支持:
16
+ - 内置供应商(openai / gemini / anthropic / kimi / qwen / deepseek)默认官方地址与自定义 base_url 覆盖
17
+ - 任意第三方中转网关(不限制供应商名称,自动或显式匹配底层通信协议)
18
+ - 主流本地文件、内存字节流与网络图片 URL 开箱兼容,带大文件体积与大表行数安全护栏
19
+ - 瞬态网关错误自动退避重试、跨协议 JSON 模式、流式 SSE 与多线程并发批量处理
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ api_key: str,
25
+ model: str,
26
+ vendor: Optional[str] = None,
27
+ base_url: Optional[str] = None,
28
+ protocol: Optional[str] = None,
29
+ timeout: Optional[float] = 60.0,
30
+ headers: Optional[Dict[str, str]] = None,
31
+ max_retries: int = 0,
32
+ retry_backoff: float = 1.0,
33
+ max_file_size_mb: Optional[float] = DEFAULT_MAX_FILE_SIZE_MB,
34
+ max_table_rows: Optional[int] = DEFAULT_MAX_TABLE_ROWS,
35
+ **kwargs: Any
36
+ ) -> None:
37
+ if not api_key or not str(api_key).strip():
38
+ raise ValueError("api_key is required and cannot be empty.")
39
+ if not model or not str(model).strip():
40
+ raise ValueError("model is required and cannot be empty.")
41
+
42
+ if vendor is None and "provider" in kwargs:
43
+ vendor = kwargs.pop("provider")
44
+
45
+ self.api_key = api_key
46
+ self.model = model
47
+ self.timeout = timeout
48
+ self.headers = headers
49
+ self.max_retries = max_retries
50
+ self.retry_backoff = retry_backoff
51
+ self.max_file_size_mb = max_file_size_mb
52
+ self.max_table_rows = max_table_rows
53
+
54
+ self.vendor, self.protocol, resolved_url = resolve_endpoint_config(
55
+ vendor=vendor,
56
+ protocol=protocol,
57
+ base_url=base_url,
58
+ api_key=api_key,
59
+ )
60
+
61
+ self._adapter: VendorAdapter = get_adapter(
62
+ api_key=self.api_key,
63
+ vendor=self.vendor,
64
+ protocol=self.protocol,
65
+ model=self.model,
66
+ base_url=resolved_url,
67
+ timeout=self.timeout,
68
+ headers=self.headers,
69
+ max_retries=self.max_retries,
70
+ retry_backoff=self.retry_backoff,
71
+ max_file_size_mb=self.max_file_size_mb,
72
+ max_table_rows=self.max_table_rows,
73
+ **kwargs
74
+ )
75
+ self.base_url = self._adapter.base_url
76
+
77
+ def close(self) -> None:
78
+ """关闭底层 HTTP 连接池。"""
79
+ self._adapter.close()
80
+
81
+ def __enter__(self) -> "AIBridge":
82
+ return self
83
+
84
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
85
+ self.close()
86
+
87
+ def chat(
88
+ self,
89
+ prompt: str = "",
90
+ files: Optional[List[FileInput]] = None,
91
+ model: Optional[str] = None,
92
+ system: Optional[str] = None,
93
+ messages: Optional[List[Dict[str, Any]]] = None,
94
+ stream: bool = False,
95
+ pdf_mode: str = "auto",
96
+ json_mode: bool = False,
97
+ timeout: Optional[float] = None,
98
+ max_retries: Optional[int] = None,
99
+ max_file_size_mb: Optional[float] = None,
100
+ max_table_rows: Optional[int] = None,
101
+ **kwargs: Any
102
+ ) -> Union[Response, Iterator[str]]:
103
+ """发送对话请求(stream=False 返回 Response,stream=True 返回文本块迭代器)。"""
104
+ return self._adapter.chat(
105
+ prompt=prompt,
106
+ files=files,
107
+ model=model or self.model,
108
+ system=system,
109
+ messages=messages,
110
+ stream=stream,
111
+ pdf_mode=pdf_mode,
112
+ json_mode=json_mode,
113
+ timeout=timeout,
114
+ max_retries=max_retries,
115
+ max_file_size_mb=max_file_size_mb,
116
+ max_table_rows=max_table_rows,
117
+ **kwargs
118
+ )
119
+
120
+ def chat_many(
121
+ self,
122
+ items: List[Union[str, Dict[str, Any]]],
123
+ max_workers: int = 5,
124
+ return_exceptions: bool = False,
125
+ **common_kwargs: Any
126
+ ) -> List[Union[Response, Exception]]:
127
+ """
128
+ 基于标准库线程池并发执行多条对话/文档分析任务,严格保持返回顺序与输入一致。
129
+
130
+ Args:
131
+ items: 任务列表,每项可为字符串 prompt,或字典参数包(如 {"prompt": "...", "files": [...]})。
132
+ max_workers: 最大并发线程数,默认 5。
133
+ return_exceptions: 为 True 时捕获单项异常并原位返回 Exception 而不中断其余任务;
134
+ 为 False(默认)时遇到异常立即抛出。
135
+ **common_kwargs: 应用于全部任务的公共参数(如 system / temperature / json_mode / max_retries)。
136
+ """
137
+ if max_workers < 1:
138
+ raise ValueError("max_workers must be >= 1.")
139
+ if common_kwargs.get("stream"):
140
+ raise ValueError("chat_many() does not support stream=True.")
141
+ if not items:
142
+ return []
143
+
144
+ def _run_one(item: Union[str, Dict[str, Any]]) -> Union[Response, Exception]:
145
+ call_kwargs = dict(common_kwargs)
146
+ if isinstance(item, str):
147
+ call_kwargs["prompt"] = item
148
+ elif isinstance(item, dict):
149
+ if item.get("stream"):
150
+ raise ValueError("chat_many() does not support stream=True in item.")
151
+ call_kwargs.update(item)
152
+ else:
153
+ raise ValueError("Each item in chat_many() must be str or dict.")
154
+ call_kwargs["stream"] = False
155
+
156
+ try:
157
+ resp = self.chat(**call_kwargs)
158
+ return resp # type: ignore
159
+ except Exception as exc:
160
+ if return_exceptions:
161
+ return exc
162
+ raise
163
+
164
+ worker_count = min(max_workers, len(items))
165
+ with ThreadPoolExecutor(max_workers=worker_count) as executor:
166
+ futures = [executor.submit(_run_one, item) for item in items]
167
+ return [fut.result() for fut in futures]
168
+
169
+ def list_models(
170
+ self,
171
+ keyword: Optional[str] = None,
172
+ timeout: Optional[float] = None,
173
+ max_retries: Optional[int] = None,
174
+ ) -> List[str]:
175
+ """查询当前客户端配置端点下的可用模型列表。"""
176
+ models = self._adapter.list_models(timeout=timeout, max_retries=max_retries)
177
+ if keyword:
178
+ kw = keyword.lower()
179
+ models = [m for m in models if kw in m.lower()]
180
+ return models
181
+
182
+ @property
183
+ def adapter(self) -> VendorAdapter:
184
+ """获取底层协议适配器实例。"""
185
+ return self._adapter
186
+
187
+
188
+ def list_models(
189
+ api_key: str,
190
+ base_url: Optional[str] = None,
191
+ vendor: Optional[str] = None,
192
+ protocol: Optional[str] = None,
193
+ keyword: Optional[str] = None,
194
+ timeout: Optional[float] = 30.0,
195
+ headers: Optional[Dict[str, str]] = None,
196
+ max_retries: int = 0,
197
+ ) -> List[str]:
198
+ """
199
+ 根据 api_key 和可选 base_url 动态查询可用模型列表。
200
+
201
+ 当传入未知自定义 base_url 且未显式指定 vendor / protocol 时,
202
+ 会自动按 OpenAI -> Gemini -> Anthropic 顺序嗅探模型列表接口。
203
+ """
204
+ if not api_key or not str(api_key).strip():
205
+ raise ValueError("api_key is required and cannot be empty.")
206
+
207
+ if protocol or vendor:
208
+ adapter = get_adapter(
209
+ api_key=api_key,
210
+ vendor=vendor,
211
+ protocol=protocol,
212
+ base_url=base_url,
213
+ timeout=timeout,
214
+ headers=headers,
215
+ max_retries=max_retries,
216
+ )
217
+ try:
218
+ result = adapter.list_models(timeout=timeout, max_retries=max_retries)
219
+ finally:
220
+ adapter.close()
221
+ if keyword:
222
+ kw = keyword.lower()
223
+ result = [m for m in result if kw in m.lower()]
224
+ return result
225
+
226
+ _, primary_proto, _ = resolve_endpoint_config(base_url=base_url, api_key=api_key)
227
+ probe_order = [primary_proto]
228
+ if base_url:
229
+ for candidate in (
230
+ ProtocolType.OPENAI.value,
231
+ ProtocolType.GEMINI.value,
232
+ ProtocolType.ANTHROPIC.value,
233
+ ):
234
+ if candidate not in probe_order:
235
+ probe_order.append(candidate)
236
+
237
+ first_error: Optional[Exception] = None
238
+ for proto in probe_order:
239
+ adapter = get_adapter(
240
+ api_key=api_key,
241
+ protocol=proto,
242
+ base_url=base_url,
243
+ timeout=timeout,
244
+ headers=headers,
245
+ max_retries=max_retries,
246
+ )
247
+ try:
248
+ models = adapter.list_models(timeout=timeout, max_retries=max_retries)
249
+ if keyword:
250
+ kw = keyword.lower()
251
+ models = [m for m in models if kw in m.lower()]
252
+ return models
253
+ except APIError as exc:
254
+ if first_error is None:
255
+ first_error = exc
256
+ if exc.status_code not in (400, 401, 403, 404, 405):
257
+ raise
258
+ continue
259
+ finally:
260
+ adapter.close()
261
+
262
+ if first_error is not None:
263
+ raise first_error
264
+ return []