backend/ai-service/README.md
AI Service is a comprehensive intelligent service platform built on FastAPI, integrating multiple AI capabilities and a complete points management system. The platform provides core functions including chat conversations, OCR text recognition, captcha recognition, and implements fine-grained service usage management through a points mechanism.
/v1/chat/completions)/v1/models)/ocr/general)/jfbym/customApi)/admin)| Component | Technology | Version Requirement |
|---|---|---|
| Backend Framework | FastAPI | >=0.115.12 |
| Python | Python | >=3.13 |
| Database | MySQL + SQLAlchemy | >=2.0.41 |
| Cache | Redis | >=6.1.0 |
| Async Support | asyncio + aiomysql | >=0.2.0 |
| Config Management | Pydantic Settings | >=2.9.1 |
| Containerization | Docker + Docker Compose | - |
| Testing Framework | pytest + pytest-asyncio | >=8.3.5 |
| Code Quality | Ruff | >=0.11.11 |
| Encryption Support | bcrypt + cryptography | >=4.3.0 |
ai-service/
โโโ app/ # Main application directory
โ โโโ main.py # FastAPI application entry point
โ โโโ config.py # Configuration management
โ โโโ database.py # Database connection and session management
โ โโโ redis_op.py # Redis connection pool management
โ โโโ logger.py # Logging configuration
โ โโโ dependencies/ # Dependency injection modules
โ โ โโโ __init__.py # Common dependencies
โ โ โโโ points.py # Points-related dependencies
โ โโโ models/ # Data models
โ โ โโโ __init__.py
โ โ โโโ point.py # Points-related models
โ โโโ schemas/ # Pydantic data schemas
โ โ โโโ chat.py # Chat interface schemas
โ โ โโโ ocr.py # OCR interface schemas
โ โ โโโ jfbym.py # Captcha interface schemas
โ โโโ routers/ # API routes
โ โ โโโ ocr.py # OCR routes
โ โ โโโ jfbym.py # Captcha routes
โ โ โโโ v1/
โ โ โโโ chat.py # Chat routes
โ โ โโโ models.py # Model management routes
โ โโโ services/ # Business logic services
โ โ โโโ point.py # Points management service
โ โโโ utils/ # Utility functions
โ โ โโโ ocr.py # OCR utilities
โ โ โโโ jfbym.py # Captcha utilities
โ โโโ middlewares/ # Middlewares
โ โ โโโ tracing.py # Request tracing middleware
โ โโโ internal/ # Internal management interfaces
โ โโโ admin.py # Admin interface
โโโ tests/ # Test code
โ โโโ conftest.py # Test configuration
โ โโโ test_main.py # Main application tests
โ โโโ routers/ # Route tests
โโโ logs/ # Log directory (e.g., app.log)
โโโ Dockerfile # Docker image build
โโโ pyproject.toml # Project dependency configuration
โโโ uv.lock # uv dependency lock file
โโโ README.md # Project documentation
git clone <repository-url>
cd ai-service
# Install using pip
pip install -e .
# Or use uv (recommended)
uv sync
It is recommended to use uv for dependency management. The
uv.lockfile has locked dependency versions to ensure environment consistency.
There are three configuration files, sorted by priority from low to high: .env.default < .env < .env.local, where .env.local is only used for local debugging and should never be used in production.
Edit the .env file and configure necessary environment variables:
# Database configuration
DATABASE_URL=mysql+aiomysql://username:password@localhost:3306/ai_service
DATABASE_USERNAME=your_db_username
DATABASE_PASSWORD=your_db_password
# Redis configuration
REDIS_URL=redis://localhost:6379/0
# AI chat service configuration
AICHAT_BASE_URL=https://api.deepseek.com/v1/
AICHAT_API_KEY=your_deepseek_api_key
# Xunfei OCR configuration
XFYUN_APP_ID=your_xfyun_app_id
XFYUN_API_SECRET=your_xfyun_api_secret
XFYUN_API_KEY=your_xfyun_api_key
# Yunma captcha configuration
JFBYM_API_TOKEN=your_jfbym_token
# Points strategy configuration (can also use default .env.default)
MONTHLY_GRANT_AMOUNT=100000
AICHAT_POINTS_COST=100
OCR_GENERAL_POINTS_COST=50
JFBYM_POINTS_COST=10
uv run python run.py dev
Visit http://localhost:8010/docs to view API documentation.
Configure Environment Variables
Create .env file and configure relevant environment variables.
Start Service
docker-compose up -d
Check Service Status
docker-compose ps
docker-compose logs -f app
Start Test Dependency Services
docker-compose -f docker-compose.test.yaml up -d
Run Tests
pytest
All API requests need to include user ID in request headers:
X-User-Id: 123
# or
user_id: 123
POST /v1/chat/completions
{
"model": "deepseek-chat",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
"stream": false,
"temperature": 0.7,
"max_tokens": 4096
}
POST /ocr/general
{
"image": "base64_encoded_image_string",
"encoding": "jpg",
"status": 3
}
POST /jfbym/customApi
{
"type": "captcha_type",
"image": "base64_encoded_image_string"
}
Response Format:
{
"code": 10000,
"message": "success",
"data": {
"code": 0,
"data": "recognition_result"
}
}
Error Response:
{
"code": 400,
"message": "Yunma captcha processing failed: specific error message",
"data": null
}
GET /admin/user/points?user_id=123
POST /admin/user/points?user_id=123&amount=1000
| Configuration | Default Value | Description |
|---|---|---|
MONTHLY_GRANT_AMOUNT | 100000 | Monthly automatic points distribution amount |
AICHAT_POINTS_COST | 100 | Points consumed per AI chat request |
OCR_GENERAL_POINTS_COST | 50 | Points consumed per OCR recognition |
JFBYM_POINTS_COST | 10 | Points consumed per captcha recognition |
| Configuration | Default Value | Description |
|---|---|---|
LOG_LEVEL | INFO | Log level (DEBUG, INFO, WARNING, ERROR) |
LOG_DIR | /var/log/ai_service | Log file storage directory |
# Start test database
docker-compose -f docker-compose.test.yaml up -d
# Run all tests
pytest
# Run specific test file
pytest tests/routers/test_chat.py
# Run tests with coverage
pytest --cov=app
# Format code
ruff format
# Check code quality
ruff check
# Fix auto-fixable issues
ruff check --fix
# Real-time view of application logs
tail -f logs/app.log
app/routers/app/schemas/app/utils/app/main.pyPointTransactionType enum in app/models/point.pyPointChecker dependency injection for points checking and deductionNote: After adding new points types, database needs to be manually upgraded. This is not recommended in production.
LOG_LEVEL environment variable (default: INFO)LOG_DIR environment variable (default: /var/log/ai_service)Each request is assigned a unique Request ID for easy troubleshooting:
2025-06-03 10:30:15 - app.main - [abc-123-def] - INFO - Root endpoint accessed!
A: You can manually deduct all current user points through admin interface, then re-add:
# 1. Query current user points
curl -X GET "http://localhost:8010/admin/user/points?user_id=123"
# 2. Deduct all points
curl -X POST "http://localhost:8010/admin/user/points/deduct?user_id=123&amount=current_points"
# 3. Add new points
curl -X POST "http://localhost:8010/admin/user/points?user_id=123&amount=new_points"
A: The system automatically checks user points. If insufficient, returns 403 status code. Users need to contact admin to add points or wait for monthly automatic distribution.
A: You can monitor through:
/ to check if service responds normallyA:
Backup:
# Backup MySQL data
docker exec mysql_container mysqldump -u root -p ai_service > backup.sql
# Backup Redis data
docker exec redis_container redis-cli BGSAVE
Restore:
# Restore MySQL data
docker exec -i mysql_container mysql -u root -p ai_service < backup.sql
A: When captcha recognition fails, the system returns detailed error information:
All error messages are in Chinese for easy user understanding.
A: Ensure:
RequestTracingMiddleware middlewareRequestIdFilter%(request_id)sIf problems persist, check if log configuration and middleware are correctly loaded.