Infoman base library - A comprehensive toolkit for modern Python applications
Project description
infomankit
现代化 Python/AI 服务脚手架与工具箱。封装了配置加载、日志、FastAPI 服务、LLM 调用、缓存、消息队列、加解密等常用能力,帮助你快速把 idea 变成可部署的生产级服务。
特性亮点
- 统一配置体系:
.env+config.py支持多环境加载,覆盖应用、数据库、缓存、LLM、MQ、向量库等关键参数。 - FastAPI 微服务基线:开箱即可运行的
infoman.service.app,内置 CORS、GZip、链路日志、中英文错误码、请求 ID、健康/监控接口。 - 异步基础设施:
tortoise-ormMySQL、Redis 缓存、Litellm、NATS、Qdrant/Milvus 的集成入口,易于按需扩展。 - AI/LLM 辅助:
infoman.llm.LLM提供问答、对话、流式输出、翻译、总结、代码审查等常用封装。 - 实用工具集:日志系统、缓存/重试/计时装饰器、AES/RSA、异步 HTTP、文本结构化提取、Feishu Bot 等常用基建。
- 细粒度模块化:可单独安装
web、database、llm、vector、messaging等 extra,仅引入所需依赖。
目录速览
infoman/
├── config/ # 环境变量加载与全局配置
├── llm/ # Litellm 包装,提供 Chat/Stream/API
├── service/
│ ├── app.py # FastAPI Application 入口
│ ├── routers/ # 健康检查与监控 API
│ ├── core/ # 事件、响应、认证
│ ├── infrastructure/ # 数据库,消息队列
│ ├── exception/ # 错误码、异常处理
│ ├── middleware/ # Logging、RequestID、RateLimit、中间件基类
│ ├── models/ # Tortoise 模型基类 & Embedding 配置
│ └── utils/ # redis 缓存装饰器、解析/转换
└── utils/
├── log/ # Loguru 配置与上下文
├── decorators/ # cache、retry、timing 等装饰器
├── encryption/ # AES/RSA/ECC
├── http/ # aiohttp 客户端、请求信息提取
├── notification/ # 飞书机器人通知
└── text/ # JSON 结构提取等
安装
# Python >= 3.11
pip install -U infomankit
pip install -U "infomankit[web]" # FastAPI 服务必备
pip install -U "infomankit[full]" # web + http + database + cache + llm + vector + messaging
常用 extra 组合:
| Extra | 说明 |
|---|---|
web |
FastAPI/uvicorn/gunicorn/uvloop |
http |
aiohttp/httpx |
database |
tortoise-orm + aiomysql |
cache |
redis + fastapi-cache2 |
llm |
litellm |
vector |
qdrant-client |
messaging |
nats-py |
webapp |
web + cache + http |
aikit |
llm + vector + http |
本地开发推荐:
git clone https://github.com/yourusername/infoman-pykit.git
cd infomankit
pip install -e ".[dev,full]" # 安装所有依赖和 lint/test 工具
快速上手
1. 配置环境变量
创建 .env.dev,并设置 ENV=dev (默认 dev)。可根据 infoman/config/config.py 填写常用变量:
APP_NAME=Infoman Service
APP_HOST=0.0.0.0
APP_PORT=8808
MYSQL_HOST=127.0.0.1
MYSQL_DB=infoman
MYSQL_USER=root
MYSQL_PASSWORD=secret
REDIS_HOST=127.0.0.1
QDRANT_HOST=127.0.0.1
LLM_PROXY=litellm_proxy
JWT_SECRET_KEY=change-me
运行时会依次加载 .env 与 .env.{ENV},缺省值可在 config.py 中找到。
2. 启动 FastAPI 服务
export ENV=dev
uvicorn infoman.service.app:application --host ${APP_HOST:-0.0.0.0} --port ${APP_PORT:-8808} --reload
# or
python -m infoman.service.launch --mode gunicorn
应用启动后默认提供:
/api/health:健康检查,返回{code:200}。/api/monitor:进程 & 系统指标、环境信息。- 启动事件中会自动注册 MySQL、Redis 缓存、NATS、Qdrant 等(根据配置是否填写)。
3. 调用 LLM
import asyncio
from infoman.llm import LLM
async def main():
resp = await LLM.ask(
model="gpt-4o-mini",
prompt="请用一句话介绍 infoman-pykit。",
system_prompt="You are a concise assistant."
)
if resp.success:
print(resp.content, resp.total_tokens)
asyncio.run(main())
LLM.ask/chat/stream会自动补全LLM_PROXY前缀并返回 token 统计。LLM.quick_*返回字符串,LLM.translate/summarize/code_review内置常用 system prompt。
4. 使用 Redis 缓存装饰器
from pydantic import BaseModel
from infoman.service.utils.cache import redis_cache
class ConfigSchema(BaseModel):
key: str
value: str
class ConfigService:
@redis_cache(prefix="config", ttl=600)
async def get_config(self, request, key: str) -> ConfigSchema:
# request.app.state.redis_client 将被装饰器自动读取
...
返回值可以是 BaseModel、list[BaseModel] 或普通 dict,装饰器会自动序列化/反序列化。
5. 消息队列与事件路由
from infoman.service.infrastructure.mq.nats import event_router
@event_router.on("topic.user.created", queue="worker")
async def handle_user_created(msg, nats_cli):
payload = msg.data.decode()
...
# 启动时在 startup 事件中执行:
# await event_router.register(app.state.nats_client)
NATSClient 支持 publish/request/subscribe/close,并在 events.startup 中自动连接(配置 NATS_SERVER 后生效)。
日志与中间件
infoman.utils.log.logger基于 Loguru,自动创建多种文件(all/info/error/debug)并支持 JSON 日志、请求上下文(RequestID)。LoggingMiddleware:记录请求耗时、客户端信息;RequestIDMiddleware为每次请求注入X-Request-ID。RateLimitMiddleware:IP/用户/路径多策略限流,内存或 Redis 持久化。BaseMiddleware为自定义中间件提供 session / 处理耗时写入示例。
统一错误与响应
infoman.service.exception.error定义系统、请求、数据库、业务、安全、外部服务等错误码枚举,可中英文提示。AppException+handler.py将数据库、Pydantic、HTTP 异常统一转换为{code, message, details}。infoman.service.core.response.success/failed提供标准响应结构。
更多工具箱
- 装饰器:
retry(支持 async/sync 指数退避)、cache(内存缓存)、timing(执行耗时)。 - 加密:AES(自动填充/随机 IV)、RSA(4096/自定义序列化)。
- HTTP Client:
HttpAsyncClient支持表单/JSON/文件上传,返回HttpResult。 - 文本处理:
utils.text.extractor.extract_json_from_string可从非结构化文本中提取 JSON。 - 通知:
notification.feishu.RobotManager发送飞书机器人消息。 - Embedding 配置:
service.models.type.embed统一管理不同向量模型的维度/长度、集合命名。
配置清单速查
| 分类 | 重点变量 |
|---|---|
| 应用 | APP_NAME, APP_HOST, APP_PORT, APP_BASE_URI, APP_DEBUG |
| 安全 | JWT_SECRET_KEY, JWT_ALGORITHM, JWT_ACCESS_TOKEN_EXPIRE_MINUTES, OAUTH2_REDIRECT_URL |
| 数据库 | MYSQL_HOST, MYSQL_PORT, MYSQL_DB, MYSQL_USER, MYSQL_PASSWORD, MYSQL_TABLE_MODELS |
| 缓存 / Redis | REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_PASSWORD |
| 向量数据库 | QDRANT_HOST/API_KEY/HTTP_PORT/GRPC_PORT、MILVUS_HOST 等(Milvus 需实现 AsyncMilvusClient) |
| MQ | NATS_SERVER(逗号分隔多实例), NATS_NAME |
| LLM | LLM_PROXY(litellm 代理地址) |
| 日志 | LOG_LEVEL, LOG_FORMAT, LOG_DIR, LOG_RETENTION, LOG_ENABLE_* |
开发 & 测试
# Lint / 格式化
ruff check infoman
black infoman
isort infoman
# 类型检查
mypy infoman
# 测试
pytest
License
MIT License © Infoman Contributors
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file infomankit-0.2.5.tar.gz.
File metadata
- Download URL: infomankit-0.2.5.tar.gz
- Upload date:
- Size: 70.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ad13b273fb0994b4e209b54607f708bfc8ae6a2f95d7538da0a654d3aaa3833f
|
|
| MD5 |
3b8cefb06cac33c699c2f48a9fd2bfe3
|
|
| BLAKE2b-256 |
92f31f140c68e6a496377cd2b5c4750822b01cc36dc420f90ebc734e90796845
|
File details
Details for the file infomankit-0.2.5-py3-none-any.whl.
File metadata
- Download URL: infomankit-0.2.5-py3-none-any.whl
- Upload date:
- Size: 101.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3ca8f96a5b71053ef3df5f8df00727d4fe5f958bdf6102582ef3f21c52249cd4
|
|
| MD5 |
6745b85350a66635788617a13c5a11c5
|
|
| BLAKE2b-256 |
5d22fe66647758c81cc1f61fb8770de5e9447c38d2fd99a6a1206cf15ced01de
|