Spaces:
Paused
Paused
Upload folder using huggingface_hub
Browse filesFiles changed (2)
2 unmodified lines34567895 unmodified lines151617181920212223246 unmodified lines313233343536373851 unmodified lines909192939495962 unmodified lines# OpenAI or Azure OpenAI Service## Default options: openai, azure, helmholtz-blabladorAPI_TYPE=openai# Check Azure's documentation for updates here:5 unmodified lines## The main text generation model, used for agent responsesMODEL=alias-large# Reasoning model is used when precise reasoning is required, such as when computing detailed analyses of simulation properties.REASONING_MODEL=alias-large# Embedding model is used for text similarity tasksEMBEDDING_MODEL=text-embedding-3-small6 unmodified linesFREQ_PENALTY=0.1PRESENCE_PENALTY=0.1TIMEOUT=480MAX_ATTEMPTS=999WAITING_TIME=35EXPONENTIAL_BACKOFF_FACTOR=5REASONING_EFFORT=high51 unmodified lines[Logging]LOGLEVEL=DEBUG# ERROR# WARNING# INFO2 unmodified lines34567895 unmodified lines151617181920212223246 unmodified lines313233343536373851 unmodified lines909192939495962 unmodified lines# OpenAI or Azure OpenAI Service## Default options: openai, azureAPI_TYPE=openai# Check Azure's documentation for updates here:5 unmodified lines## The main text generation model, used for agent responsesMODEL=gpt-4.1-mini# Reasoning model is used when precise reasoning is required, such as when computing detailed analyses of simulation properties.REASONING_MODEL=o3-mini# Embedding model is used for text similarity tasksEMBEDDING_MODEL=text-embedding-3-small6 unmodified linesFREQ_PENALTY=0.1PRESENCE_PENALTY=0.1TIMEOUT=480MAX_ATTEMPTS=5WAITING_TIME=1EXPONENTIAL_BACKOFF_FACTOR=5REASONING_EFFORT=high51 unmodified lines[Logging]LOGLEVEL=ERROR# ERROR# WARNING# INFO
30 unmodified lines313233343536373815 unmodified lines545556575859606182 unmodified lines1441451461471481492 unmodified lines1521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911 unmodified line1931941951961971981992002012022039 unmodified lines21321421521621721821922022122222322422522622722822923023123223316 unmodified lines25025125225325425525625725825926026160 unmodified lines32232332432532632732832974 unmodified lines40440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244385 unmodified lines52953053153253353453530 unmodified linesdef __init__(self, cache_api_calls=default["cache_api_calls"], cache_file_name=default["cache_file_name"]) -> None:logger.debug("Initializing OpenAIClient")self.client = None# should we cache api calls and reuse them?self.set_api_cache(cache_api_calls, cache_file_name)15 unmodified lines"""Sets up the OpenAI API configurations for this client."""if self.client is None:self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))@config_manager.config_defaults(model="model",82 unmodified lines"messages": current_messages,"temperature": temperature,"max_tokens":max_tokens,"frequency_penalty": frequency_penalty,"presence_penalty": presence_penalty,"stop": stop,2 unmodified lines"n": n,}if top_p is not None and top_p > 0:chat_api_params["top_p"] = top_pif response_format is not None:chat_api_params["response_format"] = response_formati = 0while True:try:i += 1## Model fallback and retry strategy requested by the user:# 1. alias-fast for 3 attempts, 35s wait# 2. alias-large for 2 attempts, 35s wait# 3. alias-huge until success, 60s wait## Model fallback strategy using configif i <= 3:current_model = config["OpenAI"].get("MODEL", "alias-large")current_wait_time = 35elif i <= 5:current_model = config["OpenAI"].get("FALLBACK_MODEL_LARGE", "alias-large")current_wait_time = 35else:current_model = config["OpenAI"].get("FALLBACK_MODEL_HUGE", "alias-huge")current_wait_time = 60chat_api_params["model"] = current_modeltry:logger.debug(f"Sending messages to OpenAI API. Model={current_model}. Token count={self._count_tokens(current_messages, current_model)}.")except NotImplementedError:logger.debug(f"Token count not implemented for model {current_model}.")start_time = time.monotonic()logger.debug(f"Calling model with client class {self.__class__.__name__}.")1 unmodified line################################################################ call the model, either from the cache or from the API###############################################################cache_key = str((current_model, chat_api_params)) # need string to be hashableif self.cache_api_calls and (cache_key in self.api_cache):response = self.api_cache[cache_key]else:response = self._raw_model_call(current_model, chat_api_params)if self.cache_api_calls:self.api_cache[cache_key] = responseself._save_cache()9 unmodified lineselse:return utils.sanitize_dict(self._raw_model_response_extractor(response))except (InvalidRequestError, openai.BadRequestError) as e:logger.error(f"[{i}] Invalid request error, won't retry: {e}")return Noneexcept (openai.RateLimitError,openai.APITimeoutError,openai.APIConnectionError,openai.InternalServerError,NonTerminalError,Exception) as e:msg = f"[{i}] {type(e).__name__} Error with {current_model}: {e}. Waiting {current_wait_time} seconds before next attempt..."logger.warning(msg)time.sleep(current_wait_time)continuedef _raw_model_call(self, model, chat_api_params):"""16 unmodified lineschat_api_params["reasoning_effort"] = default["reasoning_effort"]# To make the log cleaner, we remove the messages from the logged parameters,# unless we are in debug modeif logger.getEffectiveLevel() <= logging.DEBUG:logged_params = chat_api_paramselse:logged_params = {k: v for k, v in chat_api_params.items() if k != "messages"}if "response_format" in chat_api_params:# to enforce the response format via pydantic, we need to use a different method60 unmodified lineselif "gpt-3.5-turbo" in model:logger.debug("Token count: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")return self._count_tokens(messages, model="gpt-3.5-turbo-0613")elif ("gpt-4" in model) or ("ppo" in model) or ("alias-large" in model) or ("alias-huge" in model) or ("alias-large" in model):logger.debug("Token count: gpt-4/alias-large may update over time. Returning num tokens assuming gpt-4-0613.")return self._count_tokens(messages, model="gpt-4-0613")else:raise NotImplementedError(74 unmodified linesSets up the Azure OpenAI Service API configurations for this client,including the API endpoint and key."""if self.client is None:if os.getenv("AZURE_OPENAI_KEY"):logger.info("Using Azure OpenAI Service API with key.")self.client = AzureOpenAI(azure_endpoint= os.getenv("AZURE_OPENAI_ENDPOINT"),api_version = config["OpenAI"]["AZURE_API_VERSION"],api_key = os.getenv("AZURE_OPENAI_KEY"))else: # Use Entra ID Authlogger.info("Using Azure OpenAI Service API with Entra ID Auth.")from azure.identity import DefaultAzureCredential, get_bearer_token_providercredential = DefaultAzureCredential()token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default")self.client = AzureOpenAI(azure_endpoint= os.getenv("AZURE_OPENAI_ENDPOINT"),api_version = config["OpenAI"]["AZURE_API_VERSION"],azure_ad_token_provider=token_provider)class HelmholtzBlabladorClient(OpenAIClient):def __init__(self, cache_api_calls=default["cache_api_calls"], cache_file_name=default["cache_file_name"]) -> None:logger.debug("Initializing HelmholtzBlabladorClient")super().__init__(cache_api_calls, cache_file_name)def _setup_from_config(self):"""Sets up the Helmholtz Blablador API configurations for this client."""if self.client is None:self.client = OpenAI(base_url="https://api.helmholtz-blablador.fz-juelich.de/v1",api_key=os.getenv("BLABLADOR_API_KEY", "dummy"),)############################################################################ Exceptions85 unmodified lines# default clientregister_client("openai", OpenAIClient())register_client("azure", AzureClient())register_client("helmholtz-blablador", HelmholtzBlabladorClient())30 unmodified lines31323334353615 unmodified lines5253545556575882 unmodified lines1411421431441451461472 unmodified lines1501511521531541551561571581591601611621631641651661671 unmodified line1691701711721731741751761771781791801811821839 unmodified lines19319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622716 unmodified lines24424524624724824925025160 unmodified lines31231331431531631731831974 unmodified lines39439539639739839940040140240340440540640740840941041141241341441541685 unmodified lines50250350450550650730 unmodified linesdef __init__(self, cache_api_calls=default["cache_api_calls"], cache_file_name=default["cache_file_name"]) -> None:logger.debug("Initializing OpenAIClient")# should we cache api calls and reuse them?self.set_api_cache(cache_api_calls, cache_file_name)15 unmodified lines"""Sets up the OpenAI API configurations for this client."""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"))@config_manager.config_defaults(model="model",82 unmodified lines"messages": current_messages,"temperature": temperature,"max_tokens":max_tokens,"top_p": top_p,"frequency_penalty": frequency_penalty,"presence_penalty": presence_penalty,"stop": stop,2 unmodified lines"n": n,}if response_format is not None:chat_api_params["response_format"] = response_formati = 0while i < max_attempts:try:i += 1try:logger.debug(f"Sending messages to OpenAI API. Token count={self._count_tokens(current_messages, model)}.")except NotImplementedError:logger.debug(f"Token count not implemented for model {model}.")start_time = time.monotonic()logger.debug(f"Calling model with client class {self.__class__.__name__}.")1 unmodified line################################################################ call the model, either from the cache or from the API###############################################################cache_key = str((model, chat_api_params)) # need string to be hashableif self.cache_api_calls and (cache_key in self.api_cache):response = self.api_cache[cache_key]else:if waiting_time > 0:logger.info(f"Waiting {waiting_time} seconds before next API request (to avoid throttling)...")time.sleep(waiting_time)response = self._raw_model_call(model, chat_api_params)if self.cache_api_calls:self.api_cache[cache_key] = responseself._save_cache()9 unmodified lineselse:return utils.sanitize_dict(self._raw_model_response_extractor(response))except InvalidRequestError as e:logger.error(f"[{i}] Invalid request error, won't retry: {e}")# there's no point in retrying if the request is invalid# so we return None right awayreturn Noneexcept openai.BadRequestError as e:logger.error(f"[{i}] Invalid request error, won't retry: {e}")# there's no point in retrying if the request is invalid# so we return None right awayreturn Noneexcept openai.RateLimitError:logger.warning(f"[{i}] Rate limit error, waiting a bit and trying again.")aux_exponential_backoff()except NonTerminalError as e:logger.error(f"[{i}] Non-terminal error: {e}")aux_exponential_backoff()except Exception as e:logger.error(f"[{i}] {type(e).__name__} Error: {e}")aux_exponential_backoff()logger.error(f"Failed to get response after {max_attempts} attempts.")return Nonedef _raw_model_call(self, model, chat_api_params):"""16 unmodified lineschat_api_params["reasoning_effort"] = default["reasoning_effort"]# To make the log cleaner, we remove the messages from the logged parameterslogged_params = {k: v for k, v in chat_api_params.items() if k != "messages"}if "response_format" in chat_api_params:# to enforce the response format via pydantic, we need to use a different method60 unmodified lineselif "gpt-3.5-turbo" in model:logger.debug("Token count: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")return self._count_tokens(messages, model="gpt-3.5-turbo-0613")elif ("gpt-4" in model) or ("ppo" in model) :logger.debug("Token count: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.")return self._count_tokens(messages, model="gpt-4-0613")else:raise NotImplementedError(74 unmodified linesSets up the Azure OpenAI Service API configurations for this client,including the API endpoint and key."""if os.getenv("AZURE_OPENAI_KEY"):logger.info("Using Azure OpenAI Service API with key.")self.client = AzureOpenAI(azure_endpoint= os.getenv("AZURE_OPENAI_ENDPOINT"),api_version = config["OpenAI"]["AZURE_API_VERSION"],api_key = os.getenv("AZURE_OPENAI_KEY"))else: # Use Entra ID Authlogger.info("Using Azure OpenAI Service API with Entra ID Auth.")from azure.identity import DefaultAzureCredential, get_bearer_token_providercredential = DefaultAzureCredential()token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default")self.client = AzureOpenAI(azure_endpoint= os.getenv("AZURE_OPENAI_ENDPOINT"),api_version = config["OpenAI"]["AZURE_API_VERSION"],azure_ad_token_provider=token_provider)############################################################################ Exceptions85 unmodified lines# default clientregister_client("openai", OpenAIClient())register_client("azure", AzureClient())
tinytroupe/config.ini+6-6
tinytroupe/openai_utils.py+57-85