/
ramqwo
/
devup
Обзор
Документация
Войти
/
ramqwo
/
devup
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
main.py
123 строки
4 KB
ramqwo
upload files
01 дек 2025, 19:49
01 дек 2025, 19:49
9abc608
Код
Авторство
О чём код?
import os import asyncio from typing import Dict, Any from fastapi import FastAPI, HTTPException, BackgroundTasks from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse, JSONResponse from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Field from leasing_agent.leasing_valuator import LeasingValuator import logging # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) app = FastAPI( title="AI Leasing Valuator API", description="Automated market assessment and risk analysis for leased assets", version="2.0.0" ) # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # In production, specify exact origins allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Mount static files app.mount("/static", StaticFiles(directory="static"), name="static") class AssessmentRequest(BaseModel): """Request model for asset assessment.""" description: str = Field(..., min_length=5, description="Asset description") client_cost: str | None = Field(None, description="Optional client-provided cost") class AssessmentResponse(BaseModel): """Response model for assessment results.""" status: str message: str data: Dict[str, Any] | None = None # Initialize valuator with credentials from environment CREDENTIALS = os.getenv( "GIGACHAT_CREDENTIALS", "MDE5YWJhMzAtNjlkMC03OTlkLWJkZTYtNmExY2NmMTNlOTYwOmQ1MTc1Y2E0LTc0ZjYtNGM3MS04YWNlLTAxM2UzNWFhNzRjNg==" ) # Global valuator instance (reusable) valuator = LeasingValuator(CREDENTIALS) @app.get("/") async def read_root(): """Serve the main application page.""" return FileResponse('static/index.html') @app.get("/health") async def health_check(): """Health check endpoint.""" return {"status": "healthy", "service": "AI Leasing Valuator"} @app.post("/api/assess", response_model=AssessmentResponse) async def assess(request: AssessmentRequest): """ Assess the market value of a leasing object. This endpoint performs web scraping and LLM analysis to determine the market value of the provided asset description. """ try: logger.info(f"Starting assessment for: {request.description}") # Call the agent (runs in thread pool to avoid blocking) result = await asyncio.to_thread( valuator.assess_object, request.description, client_cost=request.client_cost ) logger.info("Assessment completed successfully") return AssessmentResponse( status="success", message="Assessment completed", data=result ) except ValueError as e: logger.error(f"Validation error: {e}") raise HTTPException(status_code=400, detail=str(e)) except Exception as e: logger.error(f"Assessment failed: {e}", exc_info=True) raise HTTPException( status_code=500, detail=f"Assessment failed: {str(e)}" ) @app.exception_handler(Exception) async def global_exception_handler(request, exc): """Global exception handler for better error reporting.""" logger.error(f"Unhandled exception: {exc}", exc_info=True) return JSONResponse( status_code=500, content={ "status": "error", "message": "An internal error occurred", "detail": str(exc) } ) if __name__ == "__main__": import uvicorn uvicorn.run( "main:app", host="0.0.0.0", port=8000, reload=True, log_level="info" )