Files
AI_Translator/CLAUDE.md
2026-01-09 17:28:20 +08:00

100 lines
3.4 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## 项目概述
AI 翻译网站 - Monorepo 架构,前端 Next.js 14 + 后端 FastAPI支持流式输出SSE、Redis 缓存/限流、MySQL 数据存储。
## 常用命令
### 后端开发 (apps/api)
```bash
cd apps/api
pip install -e . # 安装依赖
pip install -e ".[dev]" # 安装开发依赖
uvicorn app.main:app --reload --port 8030 # 启动开发服务器 (localhost:8030)
python scripts/init_db.py [用户名] [密码] # 初始化数据库管理员账户(默认 admin/admin123
# 测试与代码检查
pytest # 运行测试
pytest tests/test_xxx.py::test_name # 运行单个测试
ruff check . # 代码检查
ruff format . # 代码格式化
```
### 前端开发 (apps/web)
```bash
cd apps/web
npm install # 安装依赖
npm run dev # 启动开发服务器 (localhost:3030)
npm run build # 构建生产版本
npm run lint # ESLint 检查
npm run clean:next # 清理 .next 缓存(遇到 404 或缓存问题时使用)
```
### Docker 部署 (infra)
```bash
cd infra
cp .env.example .env # 配置环境变量(必须设置 LLM_API_KEY
docker-compose up -d # 启动所有服务web:3030, api:8030, redis:6379, mysql:3306
```
## 架构概览
```
apps/
web/ # Next.js 14 前端 (TypeScript + Tailwind CSS + shadcn/ui)
api/ # FastAPI 后端 (Python 3.11+, 全异步)
infra/ # Docker Compose 配置
```
### 后端结构 (apps/api/app)
- `main.py` - FastAPI 应用入口lifespan 管理各服务连接
- `core/` - 配置(config.py)、日志(logging.py)、数据库(database.py)
- `api/` - 路由层translate.py、admin.py、ai_provider.py、stats.py
- `services/` - 业务逻辑单例模式llm.py、cache.py、rate_limit.py、auth.py、stats.py
- `schemas/` - Pydantic 请求/响应模型
- `models/` - SQLAlchemy ORM 模型AIProvider、Admin、UsageStats
### 前端结构 (apps/web)
- `app/` - Next.js App Router 页面
- `page.tsx` - 翻译主页
- `login/` - 管理员登录
- `admin/` - 后台管理providers、stats、settings
- `components/` - React 组件TranslatorForm 等)
### 核心 API 端点
- `POST /api/v1/translate` - 非流式翻译
- `POST /api/v1/translate/stream` - SSE 流式翻译event: meta → chunk → done
- `GET /health` - 健康检查
### 数据流
1. 请求 → IP 限流检查(Redis) → 缓存查询(Redis)
2. 缓存命中 → 直接返回(流式模式下一次性返回完整翻译)
3. 缓存未命中 → LLM 调用 → 异步写入缓存 → 返回
### AI Provider 配置优先级
1. 数据库中 `is_active=True && is_default=True` 的 AIProvider
2. 回退到环境变量 `LLM_API_KEY``LLM_BASE_URL``LLM_MODEL`
## 环境变量
后端 `.env` 关键配置:
- `LLM_API_KEY` - LLM 服务 API Key必需
- `LLM_MODEL` - 模型名称(默认 gpt-4o-mini
- `LLM_BASE_URL` - 自定义 API 地址(可选,默认 OpenAI
- `DATABASE_URL` - MySQL 连接串格式mysql+aiomysql://user:pass@host:3306/db
- `REDIS_URL` - Redis 连接串
前端 `.env.local`
- `NEXT_PUBLIC_API_BASE_URL` - 后端 API 地址(如 http://localhost:8030