111/app.py

136 lines
3.9 KiB
Python
Raw Permalink Normal View History

2026-01-08 21:48:24 +08:00
"""
Code Explainer & Fixer - AI编程学习助手主应用
"""
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from contextlib import asynccontextmanager
from config import config
from models.schemas import CodeRequest, CodeResponse
from agents import code_explainer, bug_fixer
from utils import detect_language
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
app = FastAPI(
title="代码解释与修复助手",
description="帮助编程学习者理解代码并提供修复建议的AI工具",
version="1.0.0",
lifespan=lifespan
)
# 配置静态文件服务
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/", response_class=HTMLResponse)
async def root():
return open("static/index.html", "r", encoding="utf-8").read()
@app.get("/health")
async def health_check():
return {"status": "healthy", "service": "code-explainer-fixer"}
@app.post("/explain", response_model=CodeResponse)
async def explain_code(request: CodeRequest):
"""解释代码功能"""
try:
if request.language not in config.SUPPORTED_LANGUAGES:
raise HTTPException(status_code=400, detail=f"不支持的语言: {request.language}")
explanation = code_explainer.explain(
code=request.code,
language=request.language,
depth=request.depth
)
return CodeResponse(
success=True,
task_type="explain",
result=explanation
)
except Exception as e:
return CodeResponse(
success=False,
task_type="explain",
result=None,
error=str(e)
)
@app.post("/fix", response_model=CodeResponse)
async def fix_code(request: CodeRequest):
"""修复代码问题"""
try:
if request.language not in config.SUPPORTED_LANGUAGES:
raise HTTPException(status_code=400, detail=f"不支持的语言: {request.language}")
fix_result = bug_fixer.fix(
code=request.code,
language=request.language
)
return CodeResponse(
success=True,
task_type="fix",
result=fix_result
)
except Exception as e:
return CodeResponse(
success=False,
task_type="fix",
result=None,
error=str(e)
)
@app.post("/auto", response_model=CodeResponse)
async def auto_process(request: CodeRequest):
"""自动检测并处理代码"""
try:
language = request.language
if language == "auto":
language = detect_language(request.code)
if language == "unknown":
raise HTTPException(status_code=400, detail="无法自动检测语言,请指定语言类型")
if request.task_type == "explain":
return await explain_code(CodeRequest(
code=request.code,
language=language,
task_type="explain",
depth=request.depth
))
else:
return await fix_code(CodeRequest(
code=request.code,
language=language,
task_type="fix"
))
except HTTPException:
raise
except Exception as e:
return CodeResponse(
success=False,
task_type=request.task_type,
result=None,
error=str(e)
)
def main():
"""主入口函数"""
print("🚀 启动代码解释与修复助手...")
print(f"🌐 服务地址: http://{config.APP_HOST}:{config.APP_PORT}")
print("📚 API文档: http://localhost:8000/docs")
uvicorn.run(
"app:app",
host=config.APP_HOST,
port=config.APP_PORT,
reload=True
)
if __name__ == "__main__":
main()