Skip to main content Switch to mobile version aibx 1.0.1 A pure, lightweight AI model bridge for Python 3.7+ with custom relay and multi-file support.
pip install aibx==1.0.1 Copy PIP instructions
轻量、纯净、生产就绪的 Python 大模型桥接库 —— 兼容 Python 3.7 ~ 3.13+,自带 PEP 561 完整 IDE 类型补全,一套接口同时打通官方 API 与任意第三方中转站,内置主流办公文档、内存字节流与多模态文件直传能力。
核心类与方法全解 (API 参考) AIBridge 初始化参数
bot.chat_many() 多线程并发批量调用
list_models() 与 bot.list_models() 模型列表查询
bot.close() 与 with 上下文管理
返回值与异常对象说明 Response、resp.json() 与 Usage 对象
内置供应商预设与 base_url 规则
发布到 PyPI 后,在任何其他电脑、服务器或虚拟环境中(支持 Python 3.7 及以上版本)直接安装:
# 安装 pip install aibx # 升级到最新版本 pip install -U aibx 安装名与导入名一致:PyPI 包名与 Python import 模块名均为 aibx(内置 py.typed 标记,VS Code / PyCharm 开箱即享参数提示与返回值补全)。
from aibx import ( AIBridge, # 核心客户端类 list_models, # 动态查询可用模型列表函数 Response, # 响应数据类型(含 .json() 解析方法) Usage, # Token 统计数据类型 APIError, # 接口非 2xx 与流中途异常类 FileInput, # 文件入参联合类型标注(可选) VendorType, # 内置供应商枚举(可选) ProtocolType, # 底层协议枚举(可选) ) 🚀 2. 30 秒快速上手
from aibx import AIBridge # 方式 A:选择内置厂商,不填 base_url -> 自动走官方默认地址 bot_official = AIBridge( vendor="openai", api_key="sk-official-xxx", model="gpt-4o", ) # 方式 B:选择内置厂商,同时自定义中转站 base_url 与 api_key(可开启瞬态自动重试) bot_relay = AIBridge( vendor="openai", base_url="https://your-relay.com/v1", api_key="sk-relay-xxx", model="gpt-4o-mini", max_retries=2, # 遇中转站 429/502/503/504 或超时自动退避重试 ) # 方式 C:不限制厂商名,直接传 base_url + api_key + model 接入任意中转站 bot_any = AIBridge( base_url="https://your-relay.com/v1", api_key="sk-relay-xxx", model="claude-3-7-sonnet", ) resp = bot_any.chat("你好,请用一句话介绍你自己") print(resp.content) # 模型回复文本 print(resp.usage.total_tokens) # 总消耗 Token 数 📖 3. 核心类与方法全解 (API 参考)
bot = AIBridge( api_key: str, model: str, vendor: Optional[str] = None, base_url: Optional[str] = None, protocol: Optional[str] = None, timeout: Optional[float] = 60.0, headers: Optional[Dict[str, str]] = None, max_retries: int = 0, retry_backoff: float = 1.0, max_file_size_mb: Optional[float] = 30.0, max_table_rows: Optional[int] = 1000, no_proxy: bool = False, proxies: Optional[Dict[str, Optional[str]]] = None, **kwargs ) 参数名 类型 必填 默认值 说明 api_key str 是 — 官方或中转站的 API 密钥(不可为空字符串)。 model str 是 — 默认调用的模型名称(如 "gpt-4o"、"gemini-2.0-flash"、"deepseek-chat")。 vendor str | None 否 None 供应商名称(内置 "openai" / "gemini" / "anthropic" / "kimi" / "qwen" / "deepseek" 或自定义名;兼容别名 provider=)。 base_url str | None 否 None 自定义 API 地址(中转站、反代或本地 Ollama)。不填则使用官方默认地址。 protocol str | None 否 None 强制指定底层通信协议:"openai" / "gemini" / "anthropic"。一般留空自动识别即可。 timeout float | None 否 60.0 请求超时时间(秒)。传 None 表示不限时。 headers Dict[str, str] | None 否 None 每次请求附加的自定义 HTTP 请求头。 max_retries int 否 0 遇到瞬态错误(HTTP 429/502/503/504、超时或连接中断)时的最大重试次数,优先尊重 Retry-After 头。默认 0(不重试)。 retry_backoff float 否 1.0 指数退避基数(秒),第 n 次重试等待 min(retry_backoff * 2^n, 30.0) 秒。 max_file_size_mb float | None 否 30.0 单文件最大体积保护阈值(MB),超限直接抛出 ValueError 防止 OOM 与网关 413 拒绝;传 None 不限。 max_table_rows int | None 否 1000 Excel / CSV 单工作表最大保留行数,超长表自动截断并附注总行数说明;传 None 不限。 no_proxy bool 否 False 设为 True 时强制绕过 Windows/系统全局代理及 HTTP_PROXY / HTTPS_PROXY 环境变量,直连目标地址。 proxies Dict[str, str | None] | None 否 None 显式指定自定义 HTTP/HTTPS 代理(如 {"https": "http://127.0.0.1:7890"})。 pool_maxsize int 否 32 (通过 kwargs 传入)内部 HTTP 连接池大小,优化高并发多线程吞吐。 session requests.Session 否 None (通过 kwargs 传入)复用外部自定义的 requests.Session(如代理 proxies 或 SSL 配置)。 **kwargs Any 否 — 全局默认采样/请求参数(如 temperature=0.3、max_tokens=2048、json_mode=True),自动合并进每次 chat() 请求中。 3.2 bot.chat() 对话与文件方法
result = bot.chat( prompt: str = "", files: Optional[List[FileInput]] = None, model: Optional[str] = None, system: Optional[str] = None, messages: Optional[List[Dict[str, Any]]] = None, stream: bool = False, pdf_mode: str = "auto", json_mode: bool = False, timeout: Optional[float] = None, max_retries: Optional[int] = None, max_file_size_mb: Optional[float] = None, max_table_rows: Optional[int] = None, **kwargs ) 参数名 类型 必填 默认值 说明 prompt str 否 "" 用户提示词文本(可直接作第 1 个位置参数传入:bot.chat("你好"))。 files List[FileInput] | None 否 None 附件列表,支持混合传入:本地文件路径、内存字节流元组 (filename, bytes/BytesIO)、网络图片 URL (https://...)。 model str | None 否 None 仅本次请求临时切换其他模型名称。 system str | None 否 None 系统级指令(System Prompt),内部自动适配各协议结构。 messages List[Dict] | None 否 None 多轮历史对话消息列表 [{"role": "user", "content": "..."}, ...]。 stream bool 否 False False 返回 Response 对象;True 返回逐块产出的 Iterator[str] 文本流。 pdf_mode str 否 "auto" "auto"(原生 PDF 优先,遇不支持网关自动用 pypdf 抽文本重试)/ "base64" / "text"。 json_mode bool 否 False 设为 True 跨协议强制要求输出合法 JSON(OpenAI 自动配 response_format、Gemini 自动配 responseMimeType、Anthropic 自动附加系统约束),配合 resp.json() 直接获取 dict。 timeout float | None 否 None 仅覆盖本次请求的超时秒数。 max_retries int | None 否 None 仅覆盖本次请求的重试次数。 max_file_size_mb float | None 否 None 仅覆盖本次请求的单文件体积上限(MB)。 max_table_rows int | None 否 None 仅覆盖本次请求的表格最大保留行数。 **kwargs Any 否 — 单次采样/扩展参数透传(temperature、max_tokens、top_p、headers 等)。 3.3 bot.chat_many() 多线程并发批量调用
基于 Python 3.7+ 标准库 ThreadPoolExecutor 实现零额外依赖的高并发批量处理,返回列表顺序严格与输入 items 一一对应:
results = bot.chat_many( items: List[Union[str, Dict[str, Any]]], # 每项可为 prompt 字符串,或 chat 参数字典 max_workers: int = 5, # 最大并发线程数 return_exceptions: bool = False, # True: 单条失败原位返回 Exception,不中断其他任务 **common_kwargs # 公共参数(如 system / temperature / json_mode / max_retries) ) 3.4 list_models() 与 bot.list_models() 模型列表查询
from aibx import list_models # 独立函数(无需先确定 model,支持未知中转站自动按 OpenAI -> Gemini -> Anthropic 顺序嗅探) models = list_models( api_key="sk-relay-...", base_url="https://your-relay.com/v1", keyword="claude", # 可选关键字过滤(不区分大小写) max_retries=1, ) # 或在已创建的 bot 实例上调用 models = bot.list_models(keyword="flash", timeout=15) 3.5 bot.close() 与 with 上下文管理
AIBridge 内部复用扩容后的 HTTP 连接池(默认 pool_maxsize=32)。推荐使用 with 语句自动管理连接池释放:
with AIBridge(api_key="sk-...", model="gpt-4o", base_url="https://your-relay.com/v1") as bot: resp = bot.chat("你好") print(resp.content) 📊 4. 返回值与异常对象说明
4.1 Response、resp.json() 与 Usage 对象
当上游官方接口或中转站返回非 2xx 状态码或在流式 SSE 中途报错时,抛出 APIError:
from aibx import AIBridge, APIError try: resp = bot.chat("你好") except FileNotFoundError as e: print("本地文件路径不存在:", e) except ValueError as e: print("入参、文件格式、体积超限或 JSON 解析失败:", e) except APIError as e: print("HTTP 状态码:", e.status_code) print("原始错误返回:", e.response_body) 🏢 5. 内置供应商预设与 base_url 规则
base_url 智能规则:仅填域名自动补 /v1;已带自定义版本路径(如 /v4、/compatible-mode/v1)保持原样;末尾加 # 强制保留原路径不补全。
📂 6. 支持的文件输入形态、格式与安全护栏
本地文件路径:"./report.pdf"、Path("D:/data.xlsx")
内存字节流 / 文件对象元组(免写磁盘临时文件,适合 FastAPI / Flask Web 后端):("report.xlsx", excel_bytes)、("invoice.pdf", io.BytesIO(raw))
网络图片 URL:"https://cdn.example.com/chart.png"(OpenAI / Anthropic 原生直传 URL,Gemini 自动按体积上限安全拉取并转内联 Base64)
7.1 结构化 JSON 提取(json_mode=True + resp.json())
resp = bot.chat( prompt="从这份发票 PDF 中提取字段:invoice_no, total_amount, date", files=[r"D:\work\invoice.pdf"], json_mode=True, temperature=0.0, ) data = resp.json() # 直接得到 Python dict,无需手动正则去 ```json print(data["invoice_no"], data["total_amount"]) 7.2 Web 后端内存文件直传 + 网络图片 URL(无需写临时文件)
# 例如 FastAPI UploadFile 读取到 raw_bytes 后直接传入 resp = bot.chat( prompt="对比上传的 Excel 报表与线上活动海报图,核对促销价格是否一致", files=[ ("promo_prices.xlsx", excel_bytes), "https://cdn.example.com/posters/double11.png", ], ) print(resp.content) 7.3 多线程并发批量处理文档(chat_many + 自动重试)
tasks = [ {"prompt": "提取核心风险点", "files": [r"D:\docs\contract_1.docx"]}, {"prompt": "提取核心风险点", "files": [r"D:\docs\contract_2.pdf"]}, {"prompt": "提取核心风险点", "files": [r"D:\docs\contract_3.xlsx"]}, ] with AIBridge( api_key="sk-relay-...", model="gpt-4o-mini", base_url="https://your-relay.com/v1", max_retries=2, ) as bot: results = bot.chat_many( tasks, max_workers=5, return_exceptions=True, json_mode=True, ) for idx, res in enumerate(results): if isinstance(res, Exception): print("第 {0} 份文档失败: {1}".format(idx + 1, res)) else: print("第 {0} 份结果: {1}".format(idx + 1, res.json())) 7.4 流式实时打印回复(打字机效果)
for text_piece in bot.chat("请详细讲解 TCP 三次握手过程", stream=True): print(text_piece, end="", flush=True) print() 📄 License
Released: Dec 1, 2026
MIT View SPDX License List
ai anthropic claude deepseek gemini kimi llm openai qwen relay
Development Status 5 - Production/Stable
Intended Audience Developers
Programming Language Python :: 3
Release files for aibx 1.0.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
Built distribution (wheel)
Total release size: 110.9 kB
Release files / aibx-1.0.1.tar.gz
Release files / aibx-1.0.1-py3-none-any.whl
Security for aibx 1.0.1
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.
Release history Release notifications | RSS feed
Dec 1, 2026 2 release files No provenance
"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.
© 2026 Python Software Foundation
Deployed from a8e35ed











