Shreya Pal commited on
Commit
aace552
·
1 Parent(s): ada3dd4

Lazy load OpenAI client

Browse files
Files changed (1) hide show
  1. server/app.py +9 -2
server/app.py CHANGED
@@ -12,7 +12,14 @@ load_dotenv()
12
  from fastapi.responses import FileResponse
13
  from fastapi.staticfiles import StaticFiles
14
 
15
- openai_client = OpenAI()
 
 
 
 
 
 
 
16
 
17
  app = FastAPI(docs_url=None, redoc_url=None)
18
 
@@ -125,7 +132,7 @@ remove = clear hate speech, credible threats, targeted harassment, highly toxic
125
  user_prompt = f"Text to moderate: {text}\n\nToxicity Scores:\n{json.dumps(hf_scores, indent=2)}"
126
 
127
  try:
128
- response = openai_client.chat.completions.create(
129
  model="gpt-4o-mini",
130
  messages=[
131
  {"role": "system", "content": system_prompt},
 
12
  from fastapi.responses import FileResponse
13
  from fastapi.staticfiles import StaticFiles
14
 
15
+ _openai_client = None
16
+
17
+ def get_openai_client():
18
+ global _openai_client
19
+ if _openai_client is None:
20
+ api_key = os.getenv("API_KEY") or os.getenv("OPENAI_API_KEY")
21
+ _openai_client = OpenAI(api_key=api_key)
22
+ return _openai_client
23
 
24
  app = FastAPI(docs_url=None, redoc_url=None)
25
 
 
132
  user_prompt = f"Text to moderate: {text}\n\nToxicity Scores:\n{json.dumps(hf_scores, indent=2)}"
133
 
134
  try:
135
+ response = get_openai_client().chat.completions.create(
136
  model="gpt-4o-mini",
137
  messages=[
138
  {"role": "system", "content": system_prompt},