66import logging
77from pathlib import Path
88from typing import Optional
9- from threading import Lock
109from fastapi import FastAPI , HTTPException
1110from fastapi .middleware .cors import CORSMiddleware
1211from pydantic import BaseModel
1817app = FastAPI (title = 'Lab68Dev AI API' , version = '1.0.0' )
1918
2019# CORS configuration - use environment variable for allowed origins
21- allowed_origins = os .getenv ('ALLOWED_ORIGINS' , 'http://localhost:3000' ).split (',' )
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 ()]
2222app .add_middleware (
2323 CORSMiddleware ,
2424 allow_origins = allowed_origins ,
2727 allow_headers = ['*' ]
2828)
2929
30- # Global variables with thread safety
30+ # Global variables - set once during startup, read-only during inference
3131model , tokenizer = None , None
32- model_lock = Lock ()
3332
3433class GenerateRequest (BaseModel ):
3534 prompt : str
@@ -50,21 +49,20 @@ def load_config():
5049@app .on_event ('startup' )
5150async def startup ():
5251 global model , tokenizer
53- with model_lock :
54- config = load_config ()
55- model_path = config .get ('training' , {}).get ('output_dir' , './models/lab68dev-assistant' )
56- base_model = config .get ('model' , {}).get ('name' , 'TinyLlama/TinyLlama-1.1B-Chat-v1.0' )
57- logging .info ('Loading model...' )
58- if Path (model_path ).exists ():
59- tokenizer = AutoTokenizer .from_pretrained (model_path )
60- model = AutoModelForCausalLM .from_pretrained (base_model , torch_dtype = torch .float16 , device_map = 'auto' )
61- model = PeftModel .from_pretrained (model , model_path )
62- else :
63- tokenizer = AutoTokenizer .from_pretrained (base_model )
64- model = AutoModelForCausalLM .from_pretrained (base_model , torch_dtype = torch .float16 , device_map = 'auto' )
65- tokenizer .pad_token = tokenizer .eos_token
66- model .eval ()
67- logging .info ('Model loaded successfully!' )
52+ config = load_config ()
53+ model_path = config .get ('training' , {}).get ('output_dir' , './models/lab68dev-assistant' )
54+ base_model = config .get ('model' , {}).get ('name' , 'TinyLlama/TinyLlama-1.1B-Chat-v1.0' )
55+ logging .info ('Loading model...' )
56+ if Path (model_path ).exists ():
57+ tokenizer = AutoTokenizer .from_pretrained (model_path )
58+ model = AutoModelForCausalLM .from_pretrained (base_model , torch_dtype = torch .float16 , device_map = 'auto' )
59+ model = PeftModel .from_pretrained (model , model_path )
60+ else :
61+ tokenizer = AutoTokenizer .from_pretrained (base_model )
62+ model = AutoModelForCausalLM .from_pretrained (base_model , torch_dtype = torch .float16 , device_map = 'auto' )
63+ tokenizer .pad_token = tokenizer .eos_token
64+ model .eval ()
65+ logging .info ('Model loaded successfully!' )
6866
6967@app .get ('/health' )
7068async def health ():
0 commit comments