Spaces:
Paused
Paused
Upload folder using huggingface_hub
Browse files- tinytroupe/config.ini +6 -6
- tinytroupe/openai_utils.py +57 -85
tinytroupe/config.ini
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
# OpenAI or Azure OpenAI Service
|
| 4 |
#
|
| 5 |
|
| 6 |
-
# Default options: openai, azure
|
| 7 |
API_TYPE=openai
|
| 8 |
|
| 9 |
# Check Azure's documentation for updates here:
|
|
@@ -15,10 +15,10 @@ AZURE_API_VERSION=2023-05-15
|
|
| 15 |
#
|
| 16 |
|
| 17 |
# The main text generation model, used for agent responses
|
| 18 |
-
MODEL=
|
| 19 |
|
| 20 |
# Reasoning model is used when precise reasoning is required, such as when computing detailed analyses of simulation properties.
|
| 21 |
-
REASONING_MODEL=
|
| 22 |
|
| 23 |
# Embedding model is used for text similarity tasks
|
| 24 |
EMBEDDING_MODEL=text-embedding-3-small
|
|
@@ -31,8 +31,8 @@ TEMPERATURE=1.5
|
|
| 31 |
FREQ_PENALTY=0.1
|
| 32 |
PRESENCE_PENALTY=0.1
|
| 33 |
TIMEOUT=480
|
| 34 |
-
MAX_ATTEMPTS=
|
| 35 |
-
WAITING_TIME=
|
| 36 |
EXPONENTIAL_BACKOFF_FACTOR=5
|
| 37 |
|
| 38 |
REASONING_EFFORT=high
|
|
@@ -90,7 +90,7 @@ QUALITY_THRESHOLD = 5
|
|
| 90 |
|
| 91 |
|
| 92 |
[Logging]
|
| 93 |
-
LOGLEVEL=
|
| 94 |
# ERROR
|
| 95 |
# WARNING
|
| 96 |
# INFO
|
|
|
|
| 3 |
# OpenAI or Azure OpenAI Service
|
| 4 |
#
|
| 5 |
|
| 6 |
+
# Default options: openai, azure
|
| 7 |
API_TYPE=openai
|
| 8 |
|
| 9 |
# Check Azure's documentation for updates here:
|
|
|
|
| 15 |
#
|
| 16 |
|
| 17 |
# The main text generation model, used for agent responses
|
| 18 |
+
MODEL=gpt-4.1-mini
|
| 19 |
|
| 20 |
# Reasoning model is used when precise reasoning is required, such as when computing detailed analyses of simulation properties.
|
| 21 |
+
REASONING_MODEL=o3-mini
|
| 22 |
|
| 23 |
# Embedding model is used for text similarity tasks
|
| 24 |
EMBEDDING_MODEL=text-embedding-3-small
|
|
|
|
| 31 |
FREQ_PENALTY=0.1
|
| 32 |
PRESENCE_PENALTY=0.1
|
| 33 |
TIMEOUT=480
|
| 34 |
+
MAX_ATTEMPTS=5
|
| 35 |
+
WAITING_TIME=1
|
| 36 |
EXPONENTIAL_BACKOFF_FACTOR=5
|
| 37 |
|
| 38 |
REASONING_EFFORT=high
|
|
|
|
| 90 |
|
| 91 |
|
| 92 |
[Logging]
|
| 93 |
+
LOGLEVEL=ERROR
|
| 94 |
# ERROR
|
| 95 |
# WARNING
|
| 96 |
# INFO
|
tinytroupe/openai_utils.py
CHANGED
|
@@ -31,8 +31,6 @@ 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 |
-
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,8 +52,7 @@ class OpenAIClient:
|
|
| 54 |
"""
|
| 55 |
Sets up the OpenAI API configurations for this client.
|
| 56 |
"""
|
| 57 |
-
|
| 58 |
-
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 59 |
|
| 60 |
@config_manager.config_defaults(
|
| 61 |
model="model",
|
|
@@ -144,6 +141,7 @@ class OpenAIClient:
|
|
| 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,40 +150,18 @@ class OpenAIClient:
|
|
| 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
|
| 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.
|
| 187 |
except NotImplementedError:
|
| 188 |
-
logger.debug(f"Token count not implemented for model {
|
| 189 |
|
| 190 |
start_time = time.monotonic()
|
| 191 |
logger.debug(f"Calling model with client class {self.__class__.__name__}.")
|
|
@@ -193,11 +169,15 @@ class OpenAIClient:
|
|
| 193 |
###############################################################
|
| 194 |
# call the model, either from the cache or from the API
|
| 195 |
###############################################################
|
| 196 |
-
cache_key = str((
|
| 197 |
if self.cache_api_calls and (cache_key in self.api_cache):
|
| 198 |
response = self.api_cache[cache_key]
|
| 199 |
else:
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
if self.cache_api_calls:
|
| 202 |
self.api_cache[cache_key] = response
|
| 203 |
self._save_cache()
|
|
@@ -213,21 +193,35 @@ class OpenAIClient:
|
|
| 213 |
else:
|
| 214 |
return utils.sanitize_dict(self._raw_model_response_extractor(response))
|
| 215 |
|
| 216 |
-
except
|
| 217 |
logger.error(f"[{i}] Invalid request error, won't retry: {e}")
|
|
|
|
|
|
|
|
|
|
| 218 |
return None
|
| 219 |
|
| 220 |
-
except
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
def _raw_model_call(self, model, chat_api_params):
|
| 233 |
"""
|
|
@@ -250,12 +244,8 @@ class OpenAIClient:
|
|
| 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 |
-
|
| 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
|
|
@@ -322,8 +312,8 @@ class OpenAIClient:
|
|
| 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)
|
| 326 |
-
logger.debug("Token count: gpt-4
|
| 327 |
return self._count_tokens(messages, model="gpt-4-0613")
|
| 328 |
else:
|
| 329 |
raise NotImplementedError(
|
|
@@ -404,40 +394,23 @@ class AzureClient(OpenAIClient):
|
|
| 404 |
Sets up the Azure OpenAI Service API configurations for this client,
|
| 405 |
including the API endpoint and key.
|
| 406 |
"""
|
| 407 |
-
if
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 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,7 +502,6 @@ def force_api_cache(cache_api_calls, cache_file_name=default["cache_file_name"])
|
|
| 529 |
# default client
|
| 530 |
register_client("openai", OpenAIClient())
|
| 531 |
register_client("azure", AzureClient())
|
| 532 |
-
register_client("helmholtz-blablador", HelmholtzBlabladorClient())
|
| 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 |
# should we cache api calls and reuse them?
|
| 35 |
self.set_api_cache(cache_api_calls, cache_file_name)
|
| 36 |
|
|
|
|
| 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 |
"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 |
"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 |
###############################################################
|
| 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 |
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 |
"""
|
|
|
|
| 244 |
chat_api_params["reasoning_effort"] = default["reasoning_effort"]
|
| 245 |
|
| 246 |
|
| 247 |
+
# To make the log cleaner, we remove the messages from the logged parameters
|
| 248 |
+
logged_params = {k: v for k, v in chat_api_params.items() if k != "messages"}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
if "response_format" in chat_api_params:
|
| 251 |
# to enforce the response format via pydantic, we need to use a different method
|
|
|
|
| 312 |
elif "gpt-3.5-turbo" in model:
|
| 313 |
logger.debug("Token count: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")
|
| 314 |
return self._count_tokens(messages, model="gpt-3.5-turbo-0613")
|
| 315 |
+
elif ("gpt-4" in model) or ("ppo" in model) :
|
| 316 |
+
logger.debug("Token count: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.")
|
| 317 |
return self._count_tokens(messages, model="gpt-4-0613")
|
| 318 |
else:
|
| 319 |
raise NotImplementedError(
|
|
|
|
| 394 |
Sets up the Azure OpenAI Service API configurations for this client,
|
| 395 |
including the API endpoint and key.
|
| 396 |
"""
|
| 397 |
+
if os.getenv("AZURE_OPENAI_KEY"):
|
| 398 |
+
logger.info("Using Azure OpenAI Service API with key.")
|
| 399 |
+
self.client = AzureOpenAI(azure_endpoint= os.getenv("AZURE_OPENAI_ENDPOINT"),
|
| 400 |
+
api_version = config["OpenAI"]["AZURE_API_VERSION"],
|
| 401 |
+
api_key = os.getenv("AZURE_OPENAI_KEY"))
|
| 402 |
+
else: # Use Entra ID Auth
|
| 403 |
+
logger.info("Using Azure OpenAI Service API with Entra ID Auth.")
|
| 404 |
+
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
|
| 405 |
+
|
| 406 |
+
credential = DefaultAzureCredential()
|
| 407 |
+
token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default")
|
| 408 |
+
self.client = AzureOpenAI(
|
| 409 |
+
azure_endpoint= os.getenv("AZURE_OPENAI_ENDPOINT"),
|
| 410 |
+
api_version = config["OpenAI"]["AZURE_API_VERSION"],
|
| 411 |
+
azure_ad_token_provider=token_provider
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
)
|
| 413 |
+
|
| 414 |
|
| 415 |
###########################################################################
|
| 416 |
# Exceptions
|
|
|
|
| 502 |
# default client
|
| 503 |
register_client("openai", OpenAIClient())
|
| 504 |
register_client("azure", AzureClient())
|
|
|
|
| 505 |
|
| 506 |
|
| 507 |
|