# 环境要求：Python 3.8+
# 依赖包：pip install fastapi uvicorn python-multipart

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
import uvicorn

# 创建FastAPI应用实例
app = FastAPI(
    title="AI模型服务",
    description="统一的AI模型API服务",
    version="1.0.0"
)

# 定义请求和响应模型
class TextRequest(BaseModel):
    text: str
    max_length: Optional[int] = 100

class TextResponse(BaseModel):
    result: str
    status: str
    processing_time: float

# 健康检查端点
@app.get("/")
async def root():
    """服务根路径，返回基本信息"""
    return {
        "message": "AI模型服务正在运行",
        "version": "1.0.0",
        "status": "healthy"
    }

# 健康检查端点
@app.get("/health")
async def health_check():
    """健康检查端点，用于负载均衡器检查"""
    return {"status": "healthy"}

# 简单的文本处理端点
@app.post("/process-text", response_model=TextResponse)
async def process_text(request: TextRequest):
    """
    处理文本请求的示例端点
    
    Args:
        request: 包含文本和参数的请求对象
        
    Returns:
        处理后的文本结果
    """
    import time
    start_time = time.time()
    
    try:
        # 模拟文本处理逻辑
        processed_text = f"已处理: {request.text[:request.max_length]}"
        
        processing_time = time.time() - start_time
        
        return TextResponse(
            result=processed_text,
            status="success",
            processing_time=processing_time
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")

if __name__ == "__main__":
    # 启动服务
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True  # 开发环境启用热重载
    )
