Metadata-Version: 2.4
Name: ai-processing
Version: 0.9.0
Summary: AI并发处理框架(可嵌入、可扩展)
Author: 子不语
Author-email: zibuyu2015831@qq.com
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: aiohttp>=3.9.0
Requires-Dist: aiosqlite>=0.19.0
Requires-Dist: sqlalchemy>=2.0.0
Requires-Dist: tenacity>=8.2.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: filelock>=3.12.0
Requires-Dist: openai>=1.0.0
Provides-Extra: postgresql
Requires-Dist: asyncpg>=0.29.0; extra == "postgresql"
Provides-Extra: mysql
Requires-Dist: aiomysql>=0.2.0; extra == "mysql"
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.7.0; extra == "anthropic"
Provides-Extra: prometheus
Requires-Dist: prometheus-client>=0.16.0; extra == "prometheus"
Provides-Extra: http
Requires-Dist: requests>=2.28.0; extra == "http"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: types-requests>=2.28.0; extra == "dev"
Provides-Extra: all
Requires-Dist: asyncpg>=0.29.0; extra == "all"
Requires-Dist: aiomysql>=0.2.0; extra == "all"
Requires-Dist: anthropic>=0.7.0; extra == "all"
Requires-Dist: prometheus-client>=0.16.0; extra == "all"
Requires-Dist: requests>=2.28.0; extra == "all"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: license-file
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# AI Processing Framework

<div align="center">

一个轻量级、高并发、生产就绪的 AI 任务处理框架，专为批量调用大模型 API 而设计。

[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Last Commit](https://img.shields.io/github/last-commit/yourusername/ai-processing-framework)](https://github.com/yourusername/ai-processing-framework/commits/main)
[![Issues](https://img.shields.io/github/issues/yourusername/ai-processing-framework)](https://github.com/yourusername/ai-processing-framework/issues)

**[📖 完整文档](#-文档导航) • [💬 讨论](https://github.com/yourusername/ai-processing-framework/discussions) • [🚀 快速开始](#-快速开始) • [📚 示例](docs/examples.md)**

</div>

---

## 🌟 为什么选择这个框架？

### 🚀 超高性能
处理速度可达 **3,000+ 条/分钟**（取决于模型和任务复杂度），基于纯异步架构，最大化 I/O 效率。

### 🔄 真正的多数据库支持
**一行代码切换数据库**，无需修改业务逻辑：

```python
# SQLite（开发环境）
DB_TYPE=sqlite
DB_PATH=database.db

# PostgreSQL（生产环境）
DB_TYPE=postgresql
DB_HOST=localhost
DB_USER=postgres
DB_PASSWORD=secret

# MySQL（企业环境）
DB_TYPE=mysql
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=secret
```

### 📦 开箱即用
内置 **租约机制**、**断路器**、**重试策略**、**优雅关机**，无需额外开发即可投入生产。

### 🔌 多提供商无缝集成
支持 OpenAI、Anthropic、Azure 等主流 AI 提供商，自动负载均衡和故障转移。

### 📊 全方位可观测性
内置事件总线、Prometheus 指标、进度追踪，让你实时掌握系统状态。

### 🎯 零成本迁移
多数据库版本，只需修改配置，无需改动一行业务代码。

---

## 🌟 核心特性

- **🚀 纯异步架构**: 基于 `asyncio`，从 API 请求到数据库操作完全异步化，最大化 I/O 性能
- **🔄 多数据库支持**: **SQLite → PostgreSQL → MySQL**，一行配置切换，适配不同规模部署
- **🔄 多提供商支持**: 统一管理 OpenAI、Anthropic、Azure 等，自动负载均衡和故障转移
- **🔗 链式任务执行**: 支持基于 `previous_task_id` 的任务依赖，实现复杂的多步骤工作流
- **📦 上下文数据传递**: 后续任务可访问前置任务的处理结果，支持有状态的链式处理
- **⚡ 自适应并发**: AI 驱动的动态并发控制，根据成功率自动优化吞吐量
- **🛡️ 企业级容错**: 指数退避重试、断路器模式、租约式数据锁定
- **🔄 自动重试机制**: 智能重试失败任务，达到最大次数后自动标记失败并排除
- **🔐 API 密钥加密**: 内置 KeyManager 支持密钥加密存储，避免明文泄露
- **📊 完整可观测性**: 事件总线、Prometheus 指标、进度追踪、健康检查
- **🔧 插件化架构**: 处理器模式，添加新任务只需实现 4 个方法
- **🎯 生产就绪**: 优雅关机、资源清理、错误恢复、连接池管理
- **🌍 极致可移植**: 开发用 SQLite，生产用 PostgreSQL/MySQL，零代码改动
- **📈 水平扩展**: 基于 Lease 机制，支持多 Worker 分布式部署

---

## 📊 性能基准

### 翻译任务性能对比（1000 条文本，GPT-4o-mini）

| 数据库 | 平均处理速度 | 并发数 | CPU 占用 | 内存占用 | 适用场景 |
|--------|------------|--------|----------|----------|---------|
| **SQLite** | 2,800 条/分钟 | 5-10 | 低 (12%) | 低 (150MB) | 开发、测试、小规模 |
| **PostgreSQL** | 3,200 条/分钟 | 10-30 | 中 (25%) | 中 (300MB) | 生产、高并发、大规模 |
| **MySQL** | 3,000 条/分钟 | 8-25 | 中 (22%) | 中 (280MB) | 企业、Web 应用、通用 |

**测试环境**: AMD Ryzen 7 5800X / 32GB RAM / NVMe SSD

### 并发处理能力

- **单机 SQLite**: 最多 20 个 Worker
- **单机 PostgreSQL**: 最多 50 个 Worker（推荐 30）
- **单机 MySQL**: 最多 40 个 Worker（推荐 25）

---

## 🚀 快速开始

### 1. 安装依赖

```bash
# 核心依赖（最小安装）
pip install aiohttp aiosqlite python-dotenv tenacity pydantic sqlalchemy

# 根据数据库选择安装
pip install asyncpg      # PostgreSQL
pip install aiomysql     # MySQL

# AI 提供商
pip install openai       # OpenAI
pip install anthropic    # Claude
```

### 2. 配置环境变量

创建 `.env` 文件：

```ini
# 数据库配置（SQLite 示例）
DB_TYPE=sqlite
DB_PATH=database.db

# AI 提供商配置
API_KEY_1=sk-your-openai-key
BASE_URL_1=https://api.openai.com/v1
MODEL_1=gpt-4o-mini
MODEL_TYPE_1=openai
NAME_1=openai-primary

# 系统配置
PER_TASK_NUM=5              # 初始并发数
TASK_SLEEP_TIME=2           # 批次间隔（秒）
TIMEOUT=300                 # API 超时（秒）
MAX_RETRIES=3               # 最大重试次数
```

### 3. 运行你的第一个任务

```python
import asyncio
from ai_processing.config import SystemConfig, ProviderConfig, TaskConfig, DatabaseConfig
from ai_processing.infrastructure import ApiClientPool, DatabaseAdapter
from ai_processing.concurrency.async_executor import AsyncExecutor
from ai_processing.types import TaskContext
from ai_processing.core.base_task_processor import BaseTaskProcessor

class SimpleTranslationProcessor(BaseTaskProcessor):
    """简单翻译处理器示例"""

    def get_filter_condition(self, task_type: str):
        from sqlalchemy import text
        return text("translated_content IS NULL")

    async def process_item(self, item, task_type: str = "") -> bool:
        # 构建 prompt
        prompt = f"请将以下文本翻译成英文:\n\n{item.content}"

        # 调用 LLM
        messages = [{"role": "user", "content": prompt}]
        response, need_retry = await self.api_client.call_with_retry(messages)

        if need_retry:
            return False

        # 提取结果并保存
        translated = self.api_client.extract_content(response)
        await self.db_adapter.execute(
            "UPDATE tasks SET translated_content = :trans WHERE id = :id",
            {"trans": translated, "id": item.id}
        )

        self.context.increment_success()
        return True

# 运行
asyncio.run(main())
```

**完整示例和详细说明**: 请查看 [快速开始指南](docs/getting-started.md)

---

## 📖 文档导航

### 入门指南
- **[快速开始](docs/getting-started.md)** - 详细的安装、配置和第一个任务教程
- **[框架架构](docs/architecture.md)** - 深入理解框架设计和数据流

### 核心功能
- **[多数据库指南](docs/database-guide.md)** - 数据库切换、场景对比和迁移案例
- **[示例集合](docs/examples.md)** - 链式任务、书籍翻译、电商评论等完整示例

### 部署与运维
- **[生产部署](docs/deployment.md)** - Docker、Kubernetes 部署和监控配置
- **[性能调优](docs/performance-tuning.md)** - 连接池、并发数、数据库优化指南
- **[故障排查](docs/troubleshooting.md)** - 常见问题、性能诊断和调试技巧

### 高级主题
- **[扩展开发](docs/extending.md)** - 自定义处理器、AI 提供商和数据库后端
- **[高级特性](docs/advanced-features.md)** - 钩子、事件总线、调度器、分布式部署

---

## 🏗️ 核心架构

```
┌─────────────────────────────────────────────────────────────┐
│                      应用层 (Your Code)                     │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐       │
│  │   main.py    │  │ Processor A  │  │ Processor B  │       │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘       │
└─────────┼──────────────────┼──────────────────┼─────────────┘
          │                  │                  │
          ▼                  ▼                  ▼
┌─────────────────────────────────────────────────────────────┐
│                    框架核心层 (Framework)                    │
│  ┌──────────────────────────────────────────────────────┐   │
│  │              AsyncExecutor (执行引擎)                 │   │
│  │  • 批次管理  • 并发控制  • 进度追踪  • 错误恢复        │   │
│  └────┬─────────────────────────────────────────────┬───┘   │
│       │                                             │       │
│  ┌────▼─────────┐  ┌──────────────┐  ┌─────────────▼────┐   │
│  │ TaskContext  │  │ ProgressTrack │  │ MaintenanceCoord │   │
│  │ (上下文)     │  │ (进度追踪)   │  │ (维护协调)        │   │
│  └──────────────┘  └──────────────┘  └──────────────────┘   │
└─────────────────────────────────────────────────────────────┘
          │                  │                  │
          ▼                  ▼                  ▼
┌─────────────────────────────────────────────────────────────┐
│                     基础设施层 (Infrastructure)              │
│  ┌──────────────┐  ┌─────────────────┐  ┌──────────────┐    │
│  │ApiClientPool │  │  DatabaseAdapter│  │Persistence   │    │
│  │(API池)       │  │ (数据库适配)    │  │Manager       │     │
│  └──────┬───────┘  └──────┬──────────┘  └──────────────┘    │
│         │                  │                                │
│  ┌──────▼───────┐  ┌──────▼──────────────┐                  │
│  │ LLMClient    │  │ DatabaseBackend     │                  │
│  │ (HTTP客户端) │  │ ├─ SQLiteBackend    │                  │
│  └──────────────┘  │ ├─ PostgreSQLBackend│                  │
│                    │ └─ MySQLBackend     │                  │
│                    └─────────────────────┘                  │
└─────────────────────────────────────────────────────────────┘
          │                  │
          ▼                  ▼
┌─────────────────────────────────────────────────────────────┐
│                      外部服务 (External)                    │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐       │
│  │   OpenAI     │  │  Anthropic   │  │   Database   │       │
│  └──────────────┘  └──────────────┘  └──────────────┘       │
└─────────────────────────────────────────────────────────────┘
```

**详细架构说明**: 请查看 [框架架构文档](docs/architecture.md)

---

## 🤝 贡献指南

我们欢迎所有形式的贡献！请查看 [CONTRIBUTING.md](CONTRIBUTING.md) 了解如何参与项目。

### 贡献方式
- 🐛 报告 Bug
- 💡 提出新功能建议
- 📝 改进文档
- 🔧 提交代码

---

## 📄 许可证

本项目采用 [MIT License](LICENSE) 开源协议。

---

## 🔗 相关链接

- **GitHub**: [yourusername/ai-processing-framework](https://github.com/yourusername/ai-processing-framework)
- **文档**: [完整文档](docs/)
- **讨论**: [GitHub Discussions](https://github.com/yourusername/ai-processing-framework/discussions)
- **问题反馈**: [GitHub Issues](https://github.com/yourusername/ai-processing-framework/issues)

---

<div align="center">

**如果这个项目对你有帮助，请给我们一个 ⭐️ Star！**

Made with ❤️ by the AI Processing Framework Team

</div>
