Skip to main content

abtbb

一个自己也能读懂、自己也能维护的 Python 底层工具包。

日常开发真正用得上的底层能力,一次装好:日志、配置、HTTP 请求、数字转换、路径定位、命令行。

  • 运行时零依赖 —— 装它不会顺带拖进 requests / sqlalchemy / redis
  • 第三方包全部懒加载 —— http_utils / OCR 的 requests 在调用点才加载,import 本模块不碰它。 schemas / middlewares 是按需安装的功能模块(pip install 'abtbb[schemas]'),没装对应依赖时 import 它们会明确提示装什么
  • 每个函数一句话说清 —— docstring 写「为什么」和「不变量」,不写「做了什么」

安装

pip install abtbb

需要 Python 3.8+。

发布名 = import 名 = 命令名 = abtbb。 只有一个名字要记。

要用 abtbb.schemas(基于 pydantic v2)、abtbb.middlewares(基于 starlette)或 abtbb.llm(基于 langchain)就装对应的可选依赖:

pip install 'abtbb[schemas]'        # pydantic v2
pip install 'abtbb[middlewares]'    # starlette
pip install 'abtbb[ocr]'             # requests
pip install 'abtbb[llm]'             # langchain + langchain-openai

不装也不影响其它模块 —— 基础安装不引入任何第三方库。

⚠️ abtbb[llm] 里的 langchain 要求 Python >= 3.10 —— py3.8/3.9 装不了这个 extra,那一档 import abtbb.llm 照常可用,只是调用时会给出明确提示。版本也要 >= 1.3:1.0~1.2 锁的 langgraph 流式返回的是 tuple 不是 dict,chat_stream 会直接坏。

工具一览

模块 干什么
abtbb.logger 控制台 + 按天切割的文件日志
abtbb.config 读项目的 .env,值按字面推断类型
abtbb.utils 通用工具:to_json / to_str / to_int / to_float 等
abtbb.utils.json_utils JSON 文档字符串;从一段文本里定位 JSON 片段
abtbb.utils.file_utils 文件操作:容错读、写(自动建目录 / 原子写)、拷贝移动、列目录、删除
abtbb.utils.http_utils requests 的 GET/POST 封装(默认超时 + 连接复用 + 失败重试)
abtbb.utils.path_utils 定位入口脚本目录、项目根、.env 位置
abtbb.utils.datetime_utils 多类型转 datetime / 时间戳、加减天数
abtbb.exceptions 业务异常基类(零依赖,不绑任何框架)
abtbb.schemas BaseSchema(蛇形↔驼峰双向)+ PageReq 分页基类
abtbb.middlewares 统一响应格式、请求 ID、访问日志(只绑 starlette,不绑 fastapi)
abtbb.ocr.mineru 调用部署好的 mineru-api,把 PDF / 图片 / Office 文档解析成 markdown
abtbb.llm 构造 langchain chat model 和可流式对话的 Agent
abtbb.run abtbb start/stop/restart/status/list

日志和配置每个项目都要用,从顶层直接拿:

from abtbb import logger, config

用法

日志

控制台和文件双输出,文件按天切割。级别、目录、保留天数都从 .env 读。

from abtbb import logger

logger.info("hello %s", name)
logger.warning("磁盘快满了: %s", usage)
logger.exception("出错了")      # 自动带 traceback

配置

读项目根目录的 .env。值的类型按字面推断:true/false → bool,整数 → int,小数 → float,其余 → str。

from abtbb import config

config.DB_HOST                  # '10.0.0.1'
config.DB_PORT                  # 3306(int)
config.DEBUG                    # True(bool)
config.get("PORT", 8000)        # 没配就用默认值
config.get_path("OUTPUT_DIR")   # 路径类, 相对路径锚在该 key 的值来源文件旁边

优先级 os.environ > .env;读取不会写进 os.environ,不污染宿主环境。配置项清单见仓库里的 .env.example。

多环境切换:设 APP_ENV=prod 就额外加载 .env.prod,它的同名键覆盖 .env 里的值(公共配置留在 .env,只把差异写进 .env.prod):

APP_ENV=prod python main.py     # 读 .env + .env.prod

APP_ENV 只能来自进程环境变量 —— 它决定「读哪个文件」,得在读之前就知道。

查找的文件不止一个,优先级从高到低:

脚本目录/.env.<APP_ENV> > 脚本目录/.env > 项目根/.env.<APP_ENV> > 项目根/.env

相对路径锚在这个 key 的值实际来自哪个文件旁边 —— 来自 .env.prod 的锚在 .env.prod 旁边,来自 .env 的锚在 .env 旁边,只来自 os.environ 的锚在项目根。

HTTP 请求

requests 的封装:默认超时、连接复用、失败重试,其余参数原样透传。

from abtbb.utils.http_utils import get, post

resp = get("https://api.example.com/user", params={"id": 1}, timeout=5)
resp = post("https://api.example.com/user", json={"name": "x"})
resp.raise_for_status()

返回的是 requests 原生的 Response,不自动抛错 —— 4xx/5xx 算不算错误由你决定。

失败重试默认最多 3 次(加上第一次共 4 次请求):

  • 传输层错误(超时 / 连接被拒)会重试
  • 状态码 408 / 429 / 500 / 502 / 503 / 504 会重试 —— 这些是服务端明确表示「这次没干成」
  • 间隔按指数退避(0.5s → 1s → 2s,封顶 10s);响应头带 Retry-After 时听服务端的(秒数 / HTTP-date 都认)
  • 4xx(除 429)不重试 —— 请求本身不对,再发一百次也一样
get("https://api.example.com/user", max_retries=0)   # 关闭重试

POST 也默认重试:429 / 503 这类失败里服务端根本没干活,重发是必要的。代价是服务端已经收了请求、只是回包断了时会重复执行一次 —— 有副作用的 POST 传 max_retries=0。

上传文件(files= / data={'字段名': 文件})重试时会自动把文件指针拨回原位,不会发空 body;定位不了的流(有 read 没 tell)则不重试。

数字转换

转不了给默认值,不抛异常。浮点向零截断,和 Java 的 intValue() 一个口径。

from abtbb.utils import to_int, to_float

to_int("3.9")        # 3
to_int("abc")        # 0      转不了给默认值
to_int("abc", -1)    # -1     默认值自己定
to_float(" 2.5 ")    # 2.5

JSON

转成 JSON 字符串,以及从一段文本里把 JSON 抠出来。

from abtbb.utils.json_utils import to_json, extract_json

to_json({"a": 1})                        # '{"a": 1}'(中文不转义)
extract_json('```json\n{"a": 1}\n```')    # '{"a": 1}'

to_json 的输出永远是一个合法 JSON 文档 —— pydantic 模型、dataclass、set、Enum 这些原生 json 转不了的对象也照样转得出结果。

extract_json 只做定位不做解析:它认 ```json 围栏、认对象优先的规则,从大模型输出里捞出那段 JSON。抠出来的东西不保证合法,对不对得自己 json.loads 验一遍;找不到返回空串。

日期时间

只用标准库 datetime。凡是「多种输入 → 统一类型」「跨格式解析」这种 stdlib 没有的活才包一层,datetime.now() / dt.strftime() 这类直接用。

from abtbb.utils.datetime_utils import to_datetime, to_timestamp, add_days

to_datetime("2024-01-01 10:00:00")      # datetime(2024, 1, 1, 10, 0)
to_datetime("2024年01月01日")            # datetime(2024, 1, 1, 0, 0)
to_datetime(1704084000)                 # 时间戳(自动认秒/毫秒, 按本地时区)
to_timestamp("2024-01-01T10:00:00+08:00")  # 1704074400
add_days("2024-01-31", 1)               # datetime(2024, 2, 1)

⚠️ 带时区信息的输入会保留 tzinfo,naive 的还是 naive —— 不做隐式本地化。

路径

不依赖当前工作目录 —— 换个地方启动,定位到的还是同一个项目。

from abtbb.utils.path_utils import script_dir, project_root, env_file

script_dir()      # 正在跑的入口脚本(main.py)所在目录
project_root()    # 往上第一个有 pyproject.toml 的目录
env_file()        # .env 的位置:脚本目录优先,没有就退回项目根

文件

只收「容易踩坑」的那部分封装 —— Path.read_text() / shutil.copy2() 这类 stdlib 能直接用的不包。

from abtbb.utils.file_utils import (
    read_text_safe, write_text, write_text_atomic, append_text,
    copy_file, move_file, delete_file, delete_dir, list_files, file_size,
    human_bytes, file_name, file_suffix,
)

read_text_safe("配置.ini", default="")     # 读不到(不存在/是目录/编码不对)就返回默认值
write_text("logs/app.log", "内容")          # 父目录不存在自动创建
write_text_atomic("cfg.json", '{"a": 1}')  # 原子写:先写临时文件再替换,不会留半截文件
append_text("logs/app.log", "又一行\n")     # 追加,文件不存在则新建
copy_file("a.txt", "out/b.txt")            # 目标是目录时直接报错,不会把文件塞进目录
move_file("a.txt", "out/b.txt")            # 同上
delete_file("out/b.txt")                   # 只删文件,目录不删,返回是否删掉了
delete_dir("out/build")                    # 删目录连同里面所有内容,返回是否删掉了
list_files("logs", pattern="*.log")        # 只列文件、顺序稳定
file_size("a.txt")                         # 字节数,拿不到给默认值
human_bytes(1000 ** 3)                     # '1.0 GB'(1000 进制,跟 Finder 一个口径)
file_name("/data/logs/app.log")            # 'app.log'(含后缀,不含目录)
file_suffix("/data/logs/app.log")          # '.log'(带点;没有后缀返回空串)

⚠️ write_text 是直接覆盖写 —— 写到一半进程被杀,文件会剩半截。配置文件这类用 write_text_atomic(目标文件要么是旧的完整内容,要么是新的完整内容;目标已有时会保留它原来的权限位)。

⚠️ delete_dir 会挡掉几个致命路径:文件系统根、home 目录、当前工作目录 —— 以及这两个连同它们的所有祖先。这几个删掉不是「清理临时目录」,是删机器 —— shutil.rmtree 自己不拦,得自己拦。

命令行

把当前项目的入口脚本放到后台跑起来,并管住它的生命周期:

abtbb start                          # 后台跑项目里的 main.py
abtbb start uvicorn app.main:app     # 或显式指定命令
abtbb stop                           # 停掉
abtbb restart
abtbb status                         # 看当前项目的状态
abtbb list                           # 看所有用 abtbb 跑过的项目

进程输出落在项目目录的 .abtbb.log,进程信息记在 ~/.abtbb/registry.json。

Schema

基于 pydantic v2。继承 BaseSchema 自动获得蛇形 ↔ 驼峰双向别名和 ORM 取值:

from abtbb.schemas import BaseSchema, PageReq

class UserSchema(BaseSchema):
    user_id: int
    user_name: str

UserSchema(user_id=1, user_name="alice")   # 原名构造
UserSchema(userId=2, userName="bob")       # 驼峰构造
UserSchema(user_id=3).model_dump(by_alias=True)   # {"userId": 3}

分页请求直接继承 PageReq,offset / limit 是现成的:

class UserListReq(PageReq):
    name: Optional[str] = None

UserListReq().offset   # 0

只支持 pydantic v2(Python 3.8+)。FastAPI 低于 0.100 的项目锁死在 pydantic v1,那边自己手写请求模型就好,不用装 abtbb[schemas]。

中间件

统一响应格式 + 请求 ID + 访问日志,三件套:

from fastapi import FastAPI
from abtbb.middlewares import add_middlewares

app = FastAPI()
add_middlewares(app)

响应统一成 {code, message, data},code=200 表示成功,异常直接抛,不用自己转响应:

from abtbb.exceptions import ApiError

raise ApiError("用户不存在", code=4040)
{"code": 200, "message": "成功", "data": {"id": 1}}
{"code": 4040, "message": "用户不存在", "data": null}

错误码是 5 位数业务码(exceptions/code.py 里定义),只有成功码是 200。

文件下载、纯文本、SSE 流式原样放行 —— 不会被读进内存缓冲,流式依然是流式。

装了 Swagger 的话要把 /openapi.json 排掉 —— 它被包成统一格式后 Swagger 打不开:

add_middlewares(app, json_response_exclude_paths=["/openapi.json"])

两个 exclude 参数各管各的:json_response_exclude_paths 管响应包装(排掉的路径不包成 {code, message, data}),logging_exclude_paths 管访问日志(排掉的路径连日志都不打,健康检查这种高频接口用得上):

add_middlewares(
    app,
    json_response_exclude_paths=["/docs", "/redoc", "/openapi.json"],
    logging_exclude_paths=["/health"],
)

匹配规则是精确 + 前缀(/api/llm 命中 /api/llm、/api/llm/chat),命中的响应路径整条链路跳过:不包装,异常也不捕获。

也可以只挑一个用:

from abtbb.middlewares import RequestIdMiddleware

app.add_middleware(RequestIdMiddleware)

MinerU 解析

调用部署好的 mineru-api 服务,把 PDF / 图片 / Office 文档解析成 markdown:

from abtbb.ocr.mineru import MinerU

client = MinerU("http://127.0.0.1:8017")
markdown = client.parse_file("报告.pdf", effort="high")

地址和参数走 .env(MINERU_URL / MINERU_BACKEND / MINERU_EFFORT / MINERU_TIMEOUT),也可以像上面这样直接传参覆盖。

⚠️ 这是同步客户端 —— FastAPI 里请把路由写成 def(不是 async def),否则解析大 PDF 会阻塞事件循环。

⚠️ 默认不重试 —— 上传是 POST,重发可能让服务端把同一个大 PDF 解析两遍(一次几分钟、还吃 GPU)。要重试就显式传 MinerU(url, max_retries=3)。

要结构化产物(content_list)或图片资源,用 parse_file_raw / parse_file_zip。

LLM

构造 chat model 和可流式对话的 Agent:

from abtbb.llm import ChatAgent, init_model

agent = ChatAgent(init_model())
result = agent.chat("你好")
# {"reasoning_content": None, "content": "..."}

流式逐块吐:

for chunk in agent.chat_stream("你好"):
    print(chunk["content"], end="")

异步版加 a 前缀(achat / achat_stream,返回值一样):

result = await agent.achat("你好")
async for chunk in agent.achat_stream("你好"):
    print(chunk["content"], end="")

同步版不是另写一套逻辑 —— langchain 的 agent 原生同时提供 invoke / stream 和 ainvoke / astream,两边形状一模一样。

模型和地址走 .env(LLM_MODEL / LLM_API_KEY / LLM_BASE_URL / LLM_PROVIDER / LLM_TIMEOUT),也可以直接传参覆盖:

llm = init_model(model="glm-5.3", base_url="https://api.chatfire.cn/v1", temperature=0.2)

init_model 默认走 openai 派发 —— 国内那批服务商(glm / qwen / deepseek / minimax)都是 OpenAI 兼容的 /v1 端点。

模型名可以带 provider 前缀(openai:gpt-4o,会被剥掉),也可以不带。其它带冒号的模型名(比如 ollama 的 llama3.1:8b)原样传给 provider。

失败重试默认 3 次(加上第一次共 4 次请求):连接失败 / 超时 / 429 / 5xx 都会重试。

llm = init_model(model="glm-5.3", max_retries=0)   # 关闭重试

重试由 provider 的 HTTP 客户端执行(OpenAI 兼容端点就是 openai SDK)—— 它认 Retry-After 响应头,限流时会按服务端说的等。

不是所有 provider 的 chat model 都认 max_retries 这个字段。碰上不认的,会退回它自己的重试策略(次数由 provider 定)并打一条 warning —— 不会静默假装重试开着。

流式只覆盖「响应还没开始」之前的失败 —— 已经开始吐内容之后中断不重试(吐出去的内容收不回来,重连只会重复一遍)。

要调工具(ReAct)就给 tools:

from langchain_core.tools import tool

@tool
def get_weather(city: str) -> str:
    """查天气"""
    return "晴"

agent = ChatAgent(init_model(), tools=[get_weather])

在 FastAPI 里跟同步代码混用

同步的阻塞 IO(mineru 解析 PDF)和异步的 LLM 调用混在一个接口里,关键是路由函数写 def 还是 async def:

# async 路由 —— 同步部分丢线程池,LLM 用 await
# 优点:等 LLM 返回时不占 FastAPI 的线程池线程
@app.post("/report")
async def report(file: UploadFile):
    md = await run_in_threadpool(mineru.parse_file, path)   # 同步阻塞 IO 挪出事件循环
    return await agent.achat(md)


# def 路由 —— 全程同步
# 注意是 def 不是 async def:FastAPI 会把它丢进线程池,阻塞不影响别的请求
# 代价:等 LLM 返回时一直占着一个线程池线程(默认池 40 个)
@app.post("/report2")
def report2(file: UploadFile):
    md = mineru.parse_file(path)
    return agent.chat(md)

⚠️ 别在 async def 里调同步方法 —— mineru.parse_file 或 agent.chat 都是阻塞 IO,跑在事件循环里会卡住整个服务的并发。

License

MIT

Metadata

Release files for abtbb 0.0.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for abtbb 0.0.4
File Size Uploaded Provenance Actions
abtbb-0.0.4.tar.gz 62.3 kB Without provenance Details for abtbb-0.0.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for abtbb 0.0.4
File Interpreter ABI Platform Actions
abtbb-0.0.4-py3-none-any.whl Python 3 none any Details for abtbb-0.0.4-py3-none-any.whl

Total release size: 143.0 kB

Release files / abtbb-0.0.4.tar.gz

Download URL abtbb-0.0.4.tar.gz
Size 62.3 kB
Tags Source
SHA-256 checksum
How to use checksums
43870a0c1100b78fd15adacd5125c2e0b5939c639e36ba67918c618ba4fd8142
BLAKE2b-256 checksum
How to use checksums
19294e8e5a088496a3bf4b8ff78c6580a5b0378705ff48445cd3aec40d0fbcb9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.13

Release files / abtbb-0.0.4-py3-none-any.whl

Download URL abtbb-0.0.4-py3-none-any.whl
Size 80.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
43db91d70b4905b4803cab3613681277d0df7cae6ec1a79d8826c565610f2722
BLAKE2b-256 checksum
How to use checksums
3bfae813b028647063fa9de54afd52a9a4de1209ed582138d40fe0ea97e90097
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.13

Security for abtbb 0.0.4

Provenance

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.

No provenance found

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page