Skip to main content

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-orm MySQL、Redis 缓存、Litellm、NATS、Qdrant/Milvus 的集成入口,易于按需扩展。
  • AI/LLM 辅助infoman.llm.LLM 提供问答、对话、流式输出、翻译、总结、代码审查等常用封装。
  • 实用工具集:日志系统、缓存/重试/计时装饰器、AES/RSA、异步 HTTP、文本结构化提取、Feishu Bot 等常用基建。
  • 细粒度模块化:可单独安装 webdatabasellmvectormessaging 等 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 将被装饰器自动读取
        ...

返回值可以是 BaseModellist[BaseModel] 或普通 dict,装饰器会自动序列化/反序列化。

5. 消息队列与事件路由

from infoman.service.mq.nats.nats_event_router 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 ClientHttpAsyncClient 支持表单/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_PORTMILVUS_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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

infomankit-0.2.1.tar.gz (51.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

infomankit-0.2.1-py3-none-any.whl (79.7 kB view details)

Uploaded Python 3

File details

Details for the file infomankit-0.2.1.tar.gz.

File metadata

  • Download URL: infomankit-0.2.1.tar.gz
  • Upload date:
  • Size: 51.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.13

File hashes

Hashes for infomankit-0.2.1.tar.gz
Algorithm Hash digest
SHA256 59469c9064de232d8c0099e74e0f32c2a75e2012e15fe89bf9411e92d4e57d43
MD5 39560390476b936f0d1881c0a1b7e9e9
BLAKE2b-256 4eaf2a383323cf0776686268c6d04de78eed8a62227b712c1cf00e5565019121

See more details on using hashes here.

File details

Details for the file infomankit-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: infomankit-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 79.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.13

File hashes

Hashes for infomankit-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 cac1242e155b579a12f928532d5a0dc76a66781d222b38e64013360aa6e7fb20
MD5 6828bc46cb315895b10dc6db00d882fd
BLAKE2b-256 65a611bf5a8d616c356b9e493581b2f69356eafb41bd569343e6e7f6fb8d7d7b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page