finyx_data_ai/DEVELOPMENT.md
2026-01-11 07:48:19 +08:00

321 lines
8.7 KiB
Markdown
Raw 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.

# 开发指南
## 📋 接口开发清单
本框架已经构建完成包含了所有7个接口的路由占位符。后续需要逐个实现每个接口的具体功能。
### 待开发接口列表
#### 模块一:数据盘点智能分析服务
1. **`/api/v1/inventory/parse-document`** - 文档解析接口
- 文件位置: `app/api/v1/inventory/routes.py`
- 状态: ⏳ 待实现
- 优先级: 中
- 工作量: 5 人日
- 参考文档: `docs/01-parse-document.md`
2. **`/api/v1/inventory/parse-sql-result`** - SQL 结果解析接口
- 文件位置: `app/api/v1/inventory/routes.py`
- 状态: ⏳ 待实现
- 优先级: 低
- 工作量: 2 人日
- 参考文档: `docs/02-parse-sql-result.md`
3. **`/api/v1/inventory/parse-business-tables`** - 业务表解析接口
- 文件位置: `app/api/v1/inventory/routes.py`
- 状态: ⏳ 待实现
- 优先级: 中
- 工作量: 3 人日
- 参考文档: `docs/03-parse-business-tables.md`
4. **`/api/v1/inventory/ai-analyze`** - 数据资产智能识别接口 ⭐⭐⭐
- 文件位置: `app/api/v1/inventory/routes.py`
- 状态: ⏳ 待实现
- 优先级: **高**
- 工作量: **15 人日**
- 参考文档: `docs/04-ai-analyze.md`
- 需要: 大模型集成
#### 模块二:场景挖掘智能推荐服务
5. **`/api/v1/value/scenario-recommendation`** - 潜在场景推荐接口 ⭐⭐
- 文件位置: `app/api/v1/value/routes.py`
- 状态: ⏳ 待实现
- 优先级: **高**
- 工作量: **12 人日**
- 参考文档: `docs/05-scenario-recommendation.md`
- 需要: 大模型集成
6. **`/api/v1/value/scenario-optimization`** - 存量场景优化建议接口
- 文件位置: `app/api/v1/value/routes.py`
- 状态: ⏳ 待实现
- 优先级: 中
- 工作量: 8 人日
- 参考文档: `docs/06-scenario-optimization.md`
- 需要: 大模型集成、OCR
#### 模块三:数据资产盘点报告生成服务
7. **`/api/v1/delivery/generate-report`** - 完整报告生成接口 ⭐⭐⭐
- 文件位置: `app/api/v1/delivery/routes.py`
- 状态: ⏳ 待实现
- 优先级: **高**
- 工作量: **20 人日**
- 参考文档: `docs/07-generate-report.md``docs/数据资产盘点报告-大模型接口设计文档.md`
- 需要: 大模型集成、分阶段生成
## 🛠️ 框架使用说明
### 1. 配置管理
所有配置都在 `app/core/config.py` 中管理,通过环境变量加载。
```python
from app.core.config import settings
# 使用配置
api_key = settings.DASHSCOPE_API_KEY
max_upload_size = settings.MAX_UPLOAD_SIZE
```
### 2. 统一响应格式
使用 `app/core/response.py` 中的响应格式:
```python
from app.core.response import success_response, error_response
# 成功响应
return success_response(
data={"result": "..."},
message="操作成功"
)
# 错误响应
return error_response(
message="操作失败",
code=400,
error_code="ERROR_CODE",
error_detail="详细信息"
)
```
### 3. 异常处理
使用 `app/core/exceptions.py` 中的自定义异常:
```python
from app.core.exceptions import FileUploadException, LLMAPIException
# 抛出异常
raise FileUploadException("文件上传失败", error_detail="具体错误信息")
```
### 4. 大模型调用
使用 `app/utils/llm_client.py` 中的 LLM 客户端:
```python
from app.utils.llm_client import llm_client
# 调用大模型
response = await llm_client.call(
prompt="你的提示词",
system_prompt="系统提示词",
temperature=0.3,
model="qwen-max"
)
# 解析 JSON 响应
result = llm_client.parse_json_response(response)
```
### 5. 文件处理
使用 `app/utils/file_handler.py` 中的文件处理工具:
```python
from app.utils.file_handler import save_upload_file, detect_file_type, cleanup_temp_file
# 保存上传文件
file_path = await save_upload_file(file, project_id="project_001")
# 检测文件类型
file_type = detect_file_type(file.filename)
# 清理临时文件
cleanup_temp_file(file_path)
```
### 6. 日志记录
使用 `app/utils/logger.py` 中的日志工具:
```python
from app.utils.logger import logger
logger.info("信息日志")
logger.warning("警告日志")
logger.error("错误日志")
logger.exception("异常日志(带堆栈)")
```
## 📝 开发步骤示例
以开发 `parse-document` 接口为例:
### 步骤 1: 定义请求和响应模型
`app/schemas/` 目录下创建或更新模型文件:
```python
# app/schemas/inventory.py
from pydantic import BaseModel
from typing import Optional, List
from app.schemas.common import TableInfo
class ParseDocumentRequest(BaseModel):
project_id: str
file_type: Optional[str] = None # 可选,自动识别
class ParseDocumentResponse(BaseModel):
tables: List[TableInfo]
total_tables: int
total_fields: int
parse_time: float
file_info: dict
```
### 步骤 2: 实现业务逻辑
`app/services/` 目录下创建服务类:
```python
# app/services/document_parser.py
from app.utils.file_handler import detect_file_type
import pandas as pd
class DocumentParser:
@staticmethod
async def parse_excel(file_path: str) -> List[TableInfo]:
# 实现 Excel 解析逻辑
pass
@staticmethod
async def parse_word(file_path: str) -> List[TableInfo]:
# 实现 Word 解析逻辑
pass
```
### 步骤 3: 实现路由处理函数
`app/api/v1/inventory/routes.py` 中实现:
```python
from fastapi import UploadFile, File, Form
from app.schemas.inventory import ParseDocumentRequest, ParseDocumentResponse
from app.services.document_parser import DocumentParser
from app.core.response import success_response
from app.utils.file_handler import save_upload_file, detect_file_type
@router.post("/parse-document", response_model=ParseDocumentResponse)
async def parse_document(
file: UploadFile = File(...),
project_id: str = Form(...),
file_type: Optional[str] = Form(None)
):
"""文档解析接口"""
try:
# 保存文件
file_path = await save_upload_file(file, project_id)
# 检测文件类型
if not file_type:
file_type = detect_file_type(file.filename)
# 解析文件
parser = DocumentParser()
if file_type == "excel":
tables = await parser.parse_excel(file_path)
elif file_type == "word":
tables = await parser.parse_word(file_path)
else:
raise ValueError(f"不支持的文件类型: {file_type}")
# 返回结果
return success_response(
data={
"tables": [table.dict() for table in tables],
"total_tables": len(tables),
"total_fields": sum(t.field_count for t in tables),
"parse_time": 0.0, # 实际计算耗时
"file_info": {
"file_name": file.filename,
"file_type": file_type
}
},
message="文档解析成功"
)
except Exception as e:
# 异常已在全局异常处理器中处理
raise
```
### 步骤 4: 编写测试
`tests/` 目录下创建测试文件:
```python
# tests/test_inventory.py
import pytest
from fastapi.testclient import TestClient
def test_parse_document(client: TestClient):
with open("test_data/sample.xlsx", "rb") as f:
response = client.post(
"/api/v1/inventory/parse-document",
files={"file": ("test.xlsx", f, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
data={"project_id": "test_project"}
)
assert response.status_code == 200
data = response.json()
assert data["success"] is True
assert "tables" in data["data"]
```
## 🎯 开发建议
### 优先级顺序
1. **第一阶段MVP**:
- 数据资产智能识别接口 (`ai-analyze`)
- 完整报告生成接口 (`generate-report`)
- 文档解析接口 (`parse-document`)
2. **第二阶段**:
- 潜在场景推荐接口 (`scenario-recommendation`)
- 业务表解析接口 (`parse-business-tables`)
- 存量场景优化建议接口 (`scenario-optimization`)
3. **第三阶段**:
- SQL 结果解析接口 (`parse-sql-result`)
### 代码规范
- 使用类型注解
- 添加文档字符串docstring
- 遵循 PEP 8 代码风格
- 编写单元测试
- 添加日志记录
- 处理异常情况
### 注意事项
1. **大模型接口**: 注意 Token 消耗和 API 限流
2. **文件处理**: 及时清理临时文件,限制文件大小
3. **错误处理**: 提供清晰的错误信息和错误码
4. **性能优化**: 对于耗时操作,考虑异步处理或任务队列
5. **安全性**: 验证文件类型和大小,防止路径遍历攻击