|
| 1 | +# A FastAPI server to run the safety pipeline |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from concurrent.futures import ThreadPoolExecutor |
| 5 | + |
| 6 | +import fastapi |
| 7 | +import uvicorn |
| 8 | +from blade2blade import Blade2Blade |
| 9 | +from loguru import logger |
| 10 | +from oasst_shared.schemas import inference |
| 11 | +from settings import settings |
| 12 | + |
| 13 | +app = fastapi.FastAPI() |
| 14 | + |
| 15 | + |
| 16 | +@app.middleware("http") |
| 17 | +async def log_exceptions(request: fastapi.Request, call_next): |
| 18 | + try: |
| 19 | + response = await call_next(request) |
| 20 | + except Exception: |
| 21 | + logger.exception("Exception in request") |
| 22 | + raise |
| 23 | + return response |
| 24 | + |
| 25 | + |
| 26 | +pipeline_loaded: bool = False |
| 27 | +pipeline: Blade2Blade |
| 28 | +executor = ThreadPoolExecutor() |
| 29 | + |
| 30 | + |
| 31 | +@app.on_event("startup") |
| 32 | +async def load_pipeline(): |
| 33 | + global pipeline_loaded, pipeline |
| 34 | + pipeline = Blade2Blade(settings.safety_model_name) |
| 35 | + # warmup |
| 36 | + input = "|prompter|Hey,how are you?|endoftext|" |
| 37 | + _ = pipeline.predict(input) |
| 38 | + pipeline_loaded = True |
| 39 | + logger.info("Pipeline loaded") |
| 40 | + |
| 41 | + |
| 42 | +async def async_predict(pipeline: Blade2Blade, inputs: str): |
| 43 | + return await asyncio.get_event_loop().run_in_executor(executor, pipeline.predict, inputs) |
| 44 | + |
| 45 | + |
| 46 | +@app.post("/safety", response_model=inference.SafetyResponse) |
| 47 | +async def safety(request: inference.SafetyRequest): |
| 48 | + global pipeline_loaded, pipeline |
| 49 | + while not pipeline_loaded: |
| 50 | + await asyncio.sleep(1) |
| 51 | + outputs = await async_predict(pipeline, request.inputs) |
| 52 | + return inference.SafetyResponse(outputs=outputs) |
| 53 | + |
| 54 | + |
| 55 | +@app.get("/health") |
| 56 | +async def health(): |
| 57 | + if not pipeline_loaded: |
| 58 | + raise fastapi.HTTPException(status_code=503, detail="Server not fully loaded") |
| 59 | + return {"status": "ok"} |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + uvicorn.run(app, host="0.0.0.0", port=8008) |
0 commit comments