-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathmain.py
77 lines (63 loc) · 2.36 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import time
from typing import List
from fastapi import FastAPI, HTTPException, Request, Response
from pydantic import HttpUrl
from schemas.request import PredictionRequest, PredictionResponse
from utils.logger import setup_logger
# Initialize
app = FastAPI()
logger = None
@app.on_event("startup")
async def startup_event():
global logger
logger = await setup_logger()
@app.middleware("http")
async def log_requests(request: Request, call_next):
start_time = time.time()
body = await request.body()
await logger.info(
f"Incoming request: {request.method} {request.url}\n"
f"Request body: {body.decode()}"
)
response = await call_next(request)
process_time = time.time() - start_time
response_body = b""
async for chunk in response.body_iterator:
response_body += chunk
await logger.info(
f"Request completed: {request.method} {request.url}\n"
f"Status: {response.status_code}\n"
f"Response body: {response_body.decode()}\n"
f"Duration: {process_time:.3f}s"
)
return Response(
content=response_body,
status_code=response.status_code,
headers=dict(response.headers),
media_type=response.media_type,
)
@app.post("/api/request", response_model=PredictionResponse)
async def predict(body: PredictionRequest):
try:
await logger.info(f"Processing prediction request with id: {body.id}")
# Здесь будет вызов вашей модели
answer = 1 # Замените на реальный вызов модели
sources: List[HttpUrl] = [
HttpUrl("https://itmo.ru/ru/"),
HttpUrl("https://abit.itmo.ru/"),
]
response = PredictionResponse(
id=body.id,
answer=answer,
reasoning="Из информации на сайте",
sources=sources,
)
await logger.info(f"Successfully processed request {body.id}")
return response
except ValueError as e:
error_msg = str(e)
await logger.error(f"Validation error for request {body.id}: {error_msg}")
raise HTTPException(status_code=400, detail=error_msg)
except Exception as e:
await logger.error(f"Internal error processing request {body.id}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")