AUXteam commited on
Commit
c8a667b
·
verified ·
1 Parent(s): 20d0ebf

Fix: Strip empty `stop` parameter for Google Gemini fallback

Browse files
Files changed (1) hide show
  1. tinytroupe/openai_utils.py +105 -105
tinytroupe/openai_utils.py CHANGED
@@ -31,6 +31,8 @@ class OpenAIClient:
31
  def __init__(self, cache_api_calls=default["cache_api_calls"], cache_file_name=default["cache_file_name"]) -> None:
32
  logger.debug("Initializing OpenAIClient")
33
 
 
 
34
  # should we cache api calls and reuse them?
35
  self.set_api_cache(cache_api_calls, cache_file_name)
36
 
@@ -52,7 +54,8 @@ class OpenAIClient:
52
  """
53
  Sets up the OpenAI API configurations for this client.
54
  """
55
- self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY", os.getenv("BLABLADOR_API_KEY", "dummy_token")), base_url=os.getenv("HELMHOLTZ_BLABLADOR_ENDPOINT", "https://api.helmholtz-blablador.fz-juelich.de/v1"))
 
56
 
57
  @config_manager.config_defaults(
58
  model="model",
@@ -141,7 +144,6 @@ class OpenAIClient:
141
  "messages": current_messages,
142
  "temperature": temperature,
143
  "max_tokens":max_tokens,
144
- "top_p": top_p,
145
  "frequency_penalty": frequency_penalty,
146
  "presence_penalty": presence_penalty,
147
  "stop": stop,
@@ -150,18 +152,40 @@ class OpenAIClient:
150
  "n": n,
151
  }
152
 
 
 
 
153
  if response_format is not None:
154
  chat_api_params["response_format"] = response_format
155
 
156
  i = 0
157
- while i < max_attempts:
158
  try:
159
  i += 1
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  try:
162
- logger.debug(f"Sending messages to OpenAI API. Token count={self._count_tokens(current_messages, model)}.")
163
  except NotImplementedError:
164
- logger.debug(f"Token count not implemented for model {model}.")
165
 
166
  start_time = time.monotonic()
167
  logger.debug(f"Calling model with client class {self.__class__.__name__}.")
@@ -169,15 +193,11 @@ class OpenAIClient:
169
  ###############################################################
170
  # call the model, either from the cache or from the API
171
  ###############################################################
172
- cache_key = str((model, chat_api_params)) # need string to be hashable
173
  if self.cache_api_calls and (cache_key in self.api_cache):
174
  response = self.api_cache[cache_key]
175
  else:
176
- if waiting_time > 0:
177
- logger.info(f"Waiting {waiting_time} seconds before next API request (to avoid throttling)...")
178
- time.sleep(waiting_time)
179
-
180
- response = self._raw_model_call(model, chat_api_params)
181
  if self.cache_api_calls:
182
  self.api_cache[cache_key] = response
183
  self._save_cache()
@@ -193,51 +213,23 @@ class OpenAIClient:
193
  else:
194
  return utils.sanitize_dict(self._raw_model_response_extractor(response))
195
 
196
- except InvalidRequestError as e:
197
  logger.error(f"[{i}] Invalid request error, won't retry: {e}")
198
-
199
- # there's no point in retrying if the request is invalid
200
- # so we return None right away
201
- return None
202
-
203
- except openai.BadRequestError as e:
204
- logger.error(f"[{i}] Invalid request error, won't retry: {e}")
205
-
206
- # there's no point in retrying if the request is invalid
207
- # so we return None right away
208
  return None
209
 
210
- except openai.RateLimitError:
211
- logger.warning(
212
- f"[{i}] Rate limit error, waiting a bit and trying again.")
213
- aux_exponential_backoff()
214
-
215
- except NonTerminalError as e:
216
- logger.error(f"[{i}] Non-terminal error: {e}")
217
- aux_exponential_backoff()
218
-
219
- except Exception as e:
220
- logger.error(f"[{i}] {type(e).__name__} Error: {e}")
221
- aux_exponential_backoff()
222
-
223
- logger.error(f"Failed to get response after {max_attempts} attempts.")
224
- return None
225
 
226
  def _raw_model_call(self, model, chat_api_params):
227
-
228
- # Ensure system message is strictly first
229
-
230
- if "messages" in chat_api_params:
231
- system_msgs = [m for m in chat_api_params["messages"] if m.get("role") == "system"]
232
- other_msgs = [m for m in chat_api_params["messages"] if m.get("role") != "system"]
233
-
234
- # Combine all system messages into one single system message block to satisfy strict ChatML
235
- if system_msgs:
236
- combined_content = "\n\n".join([m.get("content", "") for m in system_msgs])
237
- chat_api_params["messages"] = [{"role": "system", "content": combined_content}] + other_msgs
238
-
239
-
240
-
241
  """
242
  Calls the OpenAI API with the given parameters. Subclasses should
243
  override this method to implement their own API calls.
@@ -258,44 +250,34 @@ class OpenAIClient:
258
  chat_api_params["reasoning_effort"] = default["reasoning_effort"]
259
 
260
 
261
- # To make the log cleaner, we remove the messages from the logged parameters
262
- logged_params = {k: v for k, v in chat_api_params.items() if k != "messages"}
 
 
 
 
 
 
 
 
 
 
263
 
264
- # --- GOOGLE FALLBACK INJECTION ---
265
- import os
266
- from openai import OpenAI
 
 
 
 
 
 
267
 
268
- try:
269
- if "response_format" in chat_api_params:
270
- if "stream" in chat_api_params: del chat_api_params["stream"]
271
- result_message = self.client.beta.chat.completions.parse(**chat_api_params)
272
- return result_message
273
- else:
274
- return self.client.chat.completions.create(**chat_api_params)
275
-
276
- except Exception as e:
277
- logger.warning(f"Primary model call failed ({e}). Falling back to Google gemini-3-flash-preview...")
278
-
279
- google_client = OpenAI(
280
- api_key=os.environ.get("GOOGLE_API_KEY", "missing_google_key"),
281
- base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
282
- )
283
- chat_api_params["model"] = "gemini-3-flash-preview"
284
-
285
- # Remove parameters Google OpenAI compat endpoint might not support
286
- if "response_format" in chat_api_params:
287
- del chat_api_params["response_format"]
288
- if "reasoning_effort" in chat_api_params:
289
- del chat_api_params["reasoning_effort"]
290
- if "frequency_penalty" in chat_api_params:
291
- del chat_api_params["frequency_penalty"]
292
- if "presence_penalty" in chat_api_params:
293
- del chat_api_params["presence_penalty"]
294
- if "max_completion_tokens" in chat_api_params:
295
- chat_api_params["max_tokens"] = chat_api_params.pop("max_completion_tokens")
296
-
297
- return google_client.chat.completions.create(**chat_api_params)
298
- # ----------------------------------
299
 
300
  def _is_reasoning_model(self, model):
301
  return "o1" in model or "o3" in model
@@ -340,8 +322,8 @@ class OpenAIClient:
340
  elif "gpt-3.5-turbo" in model:
341
  logger.debug("Token count: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")
342
  return self._count_tokens(messages, model="gpt-3.5-turbo-0613")
343
- elif ("gpt-4" in model) or ("ppo" in model) or ("alias-" in model):
344
- logger.debug("Token count: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.")
345
  return self._count_tokens(messages, model="gpt-4-0613")
346
  else:
347
  raise NotImplementedError(
@@ -422,23 +404,40 @@ class AzureClient(OpenAIClient):
422
  Sets up the Azure OpenAI Service API configurations for this client,
423
  including the API endpoint and key.
424
  """
425
- if os.getenv("AZURE_OPENAI_KEY"):
426
- logger.info("Using Azure OpenAI Service API with key.")
427
- self.client = AzureOpenAI(azure_endpoint= os.getenv("AZURE_OPENAI_ENDPOINT"),
428
- api_version = config["OpenAI"]["AZURE_API_VERSION"],
429
- api_key = os.getenv("AZURE_OPENAI_KEY"))
430
- else: # Use Entra ID Auth
431
- logger.info("Using Azure OpenAI Service API with Entra ID Auth.")
432
- from azure.identity import DefaultAzureCredential, get_bearer_token_provider
433
-
434
- credential = DefaultAzureCredential()
435
- token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default")
436
- self.client = AzureOpenAI(
437
- azure_endpoint= os.getenv("AZURE_OPENAI_ENDPOINT"),
438
- api_version = config["OpenAI"]["AZURE_API_VERSION"],
439
- azure_ad_token_provider=token_provider
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
  )
441
-
442
 
443
  ###########################################################################
444
  # Exceptions
@@ -530,6 +529,7 @@ def force_api_cache(cache_api_calls, cache_file_name=default["cache_file_name"])
530
  # default client
531
  register_client("openai", OpenAIClient())
532
  register_client("azure", AzureClient())
 
533
 
534
 
535
 
 
31
  def __init__(self, cache_api_calls=default["cache_api_calls"], cache_file_name=default["cache_file_name"]) -> None:
32
  logger.debug("Initializing OpenAIClient")
33
 
34
+ self.client = None
35
+
36
  # should we cache api calls and reuse them?
37
  self.set_api_cache(cache_api_calls, cache_file_name)
38
 
 
54
  """
55
  Sets up the OpenAI API configurations for this client.
56
  """
57
+ if self.client is None:
58
+ self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
59
 
60
  @config_manager.config_defaults(
61
  model="model",
 
144
  "messages": current_messages,
145
  "temperature": temperature,
146
  "max_tokens":max_tokens,
 
147
  "frequency_penalty": frequency_penalty,
148
  "presence_penalty": presence_penalty,
149
  "stop": stop,
 
152
  "n": n,
153
  }
154
 
155
+ if top_p is not None and top_p > 0:
156
+ chat_api_params["top_p"] = top_p
157
+
158
  if response_format is not None:
159
  chat_api_params["response_format"] = response_format
160
 
161
  i = 0
162
+ while True:
163
  try:
164
  i += 1
165
 
166
+ #
167
+ # Model fallback and retry strategy requested by the user:
168
+ # 1. alias-fast for 3 attempts, 35s wait
169
+ # 2. alias-large for 2 attempts, 35s wait
170
+ # 3. alias-huge until success, 60s wait
171
+ #
172
+ # Model fallback strategy using config
173
+ if i <= 3:
174
+ current_model = config["OpenAI"].get("MODEL", "alias-large")
175
+ current_wait_time = 35
176
+ elif i <= 5:
177
+ current_model = config["OpenAI"].get("FALLBACK_MODEL_LARGE", "alias-large")
178
+ current_wait_time = 35
179
+ else:
180
+ current_model = config["OpenAI"].get("FALLBACK_MODEL_HUGE", "alias-huge")
181
+ current_wait_time = 60
182
+
183
+ chat_api_params["model"] = current_model
184
+
185
  try:
186
+ logger.debug(f"Sending messages to OpenAI API. Model={current_model}. Token count={self._count_tokens(current_messages, current_model)}.")
187
  except NotImplementedError:
188
+ logger.debug(f"Token count not implemented for model {current_model}.")
189
 
190
  start_time = time.monotonic()
191
  logger.debug(f"Calling model with client class {self.__class__.__name__}.")
 
193
  ###############################################################
194
  # call the model, either from the cache or from the API
195
  ###############################################################
196
+ cache_key = str((current_model, chat_api_params)) # need string to be hashable
197
  if self.cache_api_calls and (cache_key in self.api_cache):
198
  response = self.api_cache[cache_key]
199
  else:
200
+ response = self._raw_model_call(current_model, chat_api_params)
 
 
 
 
201
  if self.cache_api_calls:
202
  self.api_cache[cache_key] = response
203
  self._save_cache()
 
213
  else:
214
  return utils.sanitize_dict(self._raw_model_response_extractor(response))
215
 
216
+ except (InvalidRequestError, openai.BadRequestError) as e:
217
  logger.error(f"[{i}] Invalid request error, won't retry: {e}")
 
 
 
 
 
 
 
 
 
 
218
  return None
219
 
220
+ except (openai.RateLimitError,
221
+ openai.APITimeoutError,
222
+ openai.APIConnectionError,
223
+ openai.InternalServerError,
224
+ NonTerminalError,
225
+ Exception) as e:
226
+ msg = f"[{i}] {type(e).__name__} Error with {current_model}: {e}. Waiting {current_wait_time} seconds before next attempt..."
227
+ logger.warning(msg)
228
+
229
+ time.sleep(current_wait_time)
230
+ continue
 
 
 
 
231
 
232
  def _raw_model_call(self, model, chat_api_params):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  """
234
  Calls the OpenAI API with the given parameters. Subclasses should
235
  override this method to implement their own API calls.
 
250
  chat_api_params["reasoning_effort"] = default["reasoning_effort"]
251
 
252
 
253
+ # To make the log cleaner, we remove the messages from the logged parameters,
254
+ # unless we are in debug mode
255
+ if logger.getEffectiveLevel() <= logging.DEBUG:
256
+ logged_params = chat_api_params
257
+ else:
258
+ logged_params = {k: v for k, v in chat_api_params.items() if k != "messages"}
259
+
260
+ if "response_format" in chat_api_params:
261
+ # to enforce the response format via pydantic, we need to use a different method
262
+
263
+ if "stream" in chat_api_params:
264
+ del chat_api_params["stream"]
265
 
266
+ logger.debug(f"Calling LLM model (using .parse too) with these parameters: {logged_params}. Not showing 'messages' parameter.")
267
+ # complete message
268
+ logger.debug(f" --> Complete messages sent to LLM: {chat_api_params['messages']}")
269
+
270
+ result_message = self.client.beta.chat.completions.parse(
271
+ **chat_api_params
272
+ )
273
+
274
+ return result_message
275
 
276
+ else:
277
+ logger.debug(f"Calling LLM model with these parameters: {logged_params}. Not showing 'messages' parameter.")
278
+ return self.client.chat.completions.create(
279
+ **chat_api_params
280
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
 
282
  def _is_reasoning_model(self, model):
283
  return "o1" in model or "o3" in model
 
322
  elif "gpt-3.5-turbo" in model:
323
  logger.debug("Token count: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")
324
  return self._count_tokens(messages, model="gpt-3.5-turbo-0613")
325
+ elif ("gpt-4" in model) or ("ppo" in model) or ("alias-large" in model) or ("alias-huge" in model) or ("alias-large" in model):
326
+ logger.debug("Token count: gpt-4/alias-large may update over time. Returning num tokens assuming gpt-4-0613.")
327
  return self._count_tokens(messages, model="gpt-4-0613")
328
  else:
329
  raise NotImplementedError(
 
404
  Sets up the Azure OpenAI Service API configurations for this client,
405
  including the API endpoint and key.
406
  """
407
+ if self.client is None:
408
+ if os.getenv("AZURE_OPENAI_KEY"):
409
+ logger.info("Using Azure OpenAI Service API with key.")
410
+ self.client = AzureOpenAI(azure_endpoint= os.getenv("AZURE_OPENAI_ENDPOINT"),
411
+ api_version = config["OpenAI"]["AZURE_API_VERSION"],
412
+ api_key = os.getenv("AZURE_OPENAI_KEY"))
413
+ else: # Use Entra ID Auth
414
+ logger.info("Using Azure OpenAI Service API with Entra ID Auth.")
415
+ from azure.identity import DefaultAzureCredential, get_bearer_token_provider
416
+
417
+ credential = DefaultAzureCredential()
418
+ token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default")
419
+ self.client = AzureOpenAI(
420
+ azure_endpoint= os.getenv("AZURE_OPENAI_ENDPOINT"),
421
+ api_version = config["OpenAI"]["AZURE_API_VERSION"],
422
+ azure_ad_token_provider=token_provider
423
+ )
424
+
425
+
426
+ class HelmholtzBlabladorClient(OpenAIClient):
427
+
428
+ def __init__(self, cache_api_calls=default["cache_api_calls"], cache_file_name=default["cache_file_name"]) -> None:
429
+ logger.debug("Initializing HelmholtzBlabladorClient")
430
+ super().__init__(cache_api_calls, cache_file_name)
431
+
432
+ def _setup_from_config(self):
433
+ """
434
+ Sets up the Helmholtz Blablador API configurations for this client.
435
+ """
436
+ if self.client is None:
437
+ self.client = OpenAI(
438
+ base_url="https://api.helmholtz-blablador.fz-juelich.de/v1",
439
+ api_key=os.getenv("BLABLADOR_API_KEY", "dummy"),
440
  )
 
441
 
442
  ###########################################################################
443
  # Exceptions
 
529
  # default client
530
  register_client("openai", OpenAIClient())
531
  register_client("azure", AzureClient())
532
+ register_client("helmholtz-blablador", HelmholtzBlabladorClient())
533
 
534
 
535