11#!/usr/bin/env python3
22'''FastAPI Inference Server for Lab68Dev AI Model'''
3+ import os
34import yaml
45import torch
6+ import logging
57from pathlib import Path
68from typing import Optional
79from fastapi import FastAPI , HTTPException
1012from transformers import AutoModelForCausalLM , AutoTokenizer
1113from peft import PeftModel
1214
15+ logging .basicConfig (level = logging .INFO )
16+
1317app = FastAPI (title = 'Lab68Dev AI API' , version = '1.0.0' )
14- app .add_middleware (CORSMiddleware , allow_origins = ['*' ], allow_credentials = True , allow_methods = ['*' ], allow_headers = ['*' ])
1518
19+ # CORS configuration - use environment variable for allowed origins
20+ allowed_origins_str = os .getenv ('ALLOWED_ORIGINS' , 'http://localhost:3000' )
21+ allowed_origins = [origin .strip () for origin in allowed_origins_str .split (',' ) if origin .strip ()]
22+ app .add_middleware (
23+ CORSMiddleware ,
24+ allow_origins = allowed_origins ,
25+ allow_credentials = True ,
26+ allow_methods = ['*' ],
27+ allow_headers = ['*' ]
28+ )
29+
30+ # Global variables - set once during startup, read-only during inference
1631model , tokenizer = None , None
1732
1833class GenerateRequest (BaseModel ):
@@ -28,6 +43,7 @@ def load_config():
2843 config_path = Path (__file__ ).parent .parent / 'config' / 'training_config.yaml'
2944 if config_path .exists ():
3045 with open (config_path ) as f : return yaml .safe_load (f )
46+ logging .warning (f'Configuration file not found at { config_path } , using default values' )
3147 return {}
3248
3349@app .on_event ('startup' )
@@ -36,7 +52,7 @@ async def startup():
3652 config = load_config ()
3753 model_path = config .get ('training' , {}).get ('output_dir' , './models/lab68dev-assistant' )
3854 base_model = config .get ('model' , {}).get ('name' , 'TinyLlama/TinyLlama-1.1B-Chat-v1.0' )
39- print ('Loading model...' )
55+ logging . info ('Loading model...' )
4056 if Path (model_path ).exists ():
4157 tokenizer = AutoTokenizer .from_pretrained (model_path )
4258 model = AutoModelForCausalLM .from_pretrained (base_model , torch_dtype = torch .float16 , device_map = 'auto' )
@@ -46,7 +62,7 @@ async def startup():
4662 model = AutoModelForCausalLM .from_pretrained (base_model , torch_dtype = torch .float16 , device_map = 'auto' )
4763 tokenizer .pad_token = tokenizer .eos_token
4864 model .eval ()
49- print ('Model loaded!' )
65+ logging . info ('Model loaded successfully !' )
5066
5167@app .get ('/health' )
5268async def health ():
0 commit comments