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.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 算不算错误由你决定。

数字转换

转不了给默认值,不抛异常。浮点向零截断,和 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

日期时间

只用标准库 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 的位置:脚本目录优先,没有就退回项目根

命令行

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

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 会阻塞事件循环。

要结构化产物(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。

要调工具(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.3

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.3
File Size Uploaded Provenance Actions
abtbb-0.0.3.tar.gz 48.4 kB Without provenance Details for abtbb-0.0.3.tar.gz

Built distribution (wheel)

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

Total release size: 112.7 kB

Release files / abtbb-0.0.3.tar.gz

Download URL abtbb-0.0.3.tar.gz
Size 48.4 kB
Tags Source
SHA-256 checksum
How to use checksums
f0a05178a82d4f67454f65a03ae9410ca02020ab1a8218443a62d79443021052
BLAKE2b-256 checksum
How to use checksums
7f8a2cee436ed4487d61323697b837fd338e97c81480570fdf8f436c49e5520d
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.3-py3-none-any.whl

Download URL abtbb-0.0.3-py3-none-any.whl
Size 64.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ecfc3a7b88b2328b09c5037bd9a97afe3f33877d5a1f3f23542085327000e11d
BLAKE2b-256 checksum
How to use checksums
30519ada2c26b0a8a1a30afdee62681cc9f103fbbfaef6ca572ac68be3d5ca40
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.3

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