Spaces:
Runtime error
Runtime error
Download utils/utils.py from Resaofd/resao-chat: direct link, hf CLI and curl.
- Browser
- Download file 5.69 kB
-
https://huggingface.co/spaces/Resaofd/resao-chat/resolve/main/utils/utils.py
- Command line
-
hf download hf://spaces/Resaofd/resao-chat/utils/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/Resaofd/resao-chat/resolve/main/utils/utils.py
5.69 kB
| import json | |
| import os | |
| from uuid import uuid4 | |
| from datetime import datetime | |
| from httpx import HTTPStatusError | |
| import time | |
| import asyncio | |
| # Gestion des sessions | |
| sessions = {} | |
| # HISTORY_FILE = 'E:\work\Vocal-Telma\TMSpeechTextML\chat\chat_history.json' | |
| HISTORY_FILE = "chat_history.json" | |
| # Fonction pour charger les données historiques au démarrage de l'application | |
| def load_history(): | |
| """Charge les sessions existantes depuis le fichier JSON.""" | |
| global sessions | |
| if os.path.exists(HISTORY_FILE): | |
| try: | |
| with open(HISTORY_FILE, "r") as f: | |
| sessions = json.load(f) | |
| except json.JSONDecodeError: | |
| # Si le fichier est corrompu ou invalide, on initialise avec un dictionnaire vide | |
| sessions = {} | |
| else: | |
| sessions = {} # Si le fichier n'existe pas, on crée un dictionnaire vide | |
| # Initialisation du fichier JSON si non existant | |
| def initialize_history_file(): | |
| """Initialise le fichier historique s'il n'existe pas.""" | |
| if not os.path.exists(HISTORY_FILE): | |
| with open(HISTORY_FILE, "w") as f: | |
| json.dump({}, f) | |
| # Fonction pour créer une nouvelle session | |
| def create_session(): | |
| session_id = str(uuid4()) | |
| sessions[session_id] = {"created_at": str(datetime.now()), "history": []} | |
| _save_history() # Toujours sauvegarder après avoir créé une session | |
| return session_id | |
| # Fonction pour obtenir une session existante | |
| def get_session(session_id): | |
| return sessions.get(session_id, None) | |
| # Fonction pour ajouter des entrées dans l'historique | |
| def add_to_history(session_id, user_input, response, result): | |
| session = get_session(session_id) | |
| if session: | |
| session["history"].append({ | |
| "timestamp": str(datetime.now()), | |
| "input": user_input, | |
| "output": response, | |
| "Offer": result | |
| }) | |
| _save_history() # Toujours sauvegarder après avoir ajouté des données | |
| # Sauvegarde de l'historique dans le fichier JSON | |
| def _save_history(): | |
| """Sauvegarde l'état actuel des sessions dans le fichier JSON sans écraser l'historique.""" | |
| try: | |
| with open(HISTORY_FILE, "w") as f: | |
| json.dump(sessions, f, indent=4) | |
| except Exception as e: | |
| print(f"Erreur lors de la sauvegarde de l'historique: {e}") | |
| # Fonction pour obtenir la valeur d'une clé par ordre de priorité | |
| def get_priority_value(json_data, priority_keys): | |
| if isinstance(json_data, dict): | |
| for key in priority_keys: | |
| if key in json_data: | |
| return json_data[key] # Renvoie la valeur de la première clé trouvée | |
| if isinstance(json_data, str): | |
| try: | |
| # Convertir la chaîne JSON en dictionnaire | |
| json_data = json.loads(json_data) | |
| for key in priority_keys: | |
| if key in json_data: | |
| return json_data[key] | |
| except json.JSONDecodeError as e: | |
| print(f"Erreur lors de la conversion du JSON: {e}") | |
| json_data = {} | |
| else: | |
| print("Erreur: json_data n'est pas un dictionnaire.") | |
| return None | |
| # Retry logic for API calls | |
| async def invoke_with_retry(retrieval_chain, input_query, max_retries=3, wait_time=5): | |
| for attempt in range(max_retries): | |
| try: | |
| response = retrieval_chain.invoke({"input": input_query}) | |
| return response | |
| except HTTPStatusError as e: | |
| if e.response.status_code == 429: | |
| print(f"Rate limit exceeded. Retrying in {wait_time} seconds... (Attempt {attempt + 1}/{max_retries})") | |
| # time.sleep(wait_time) | |
| await asyncio.sleep(wait_time) | |
| else: | |
| raise e | |
| raise Exception("Max retries exceeded. Could not process the request due to repeated rate limiting.") | |
| async def invoke_with_retry_payment(model, formatted_input, max_retries=3, wait_time=5): | |
| """ | |
| Attempts to invoke the model. If a rate limit (429) error occurs, | |
| waits for a specified time and retries the request. | |
| Parameters: | |
| model: The language model responsible for processing the input query. | |
| formatted_input: The formatted input query to process. | |
| max_retries: The maximum number of retries allowed (default is 3). | |
| wait_time: Time in seconds to wait before retrying after a 429 error (default is 40 seconds). | |
| Returns: | |
| The response from the model or raises an exception if retries are exhausted. | |
| """ | |
| for attempt in range(max_retries): | |
| try: | |
| # Attempt to invoke the model | |
| response = model.invoke(formatted_input) | |
| return response # Return the response if successful | |
| except HTTPStatusError as e: | |
| # Check for the rate limit error (429) | |
| if e.response.status_code == 429: | |
| print(f"Rate limit exceeded. Retrying in {wait_time} seconds... (Attempt {attempt + 1}/{max_retries})") | |
| # time.sleep(wait_time) # Wait for the specified time before retrying | |
| await asyncio.sleep(wait_time) | |
| else: | |
| # Raise the exception if it's not a rate limit error | |
| raise e | |
| # If all retries are exhausted, raise an exception | |
| raise Exception("Max retries exceeded. Could not process the request due to repeated rate limiting.") | |
| # Initialisation au démarrage de l'application | |
| initialize_history_file() # Vérifie et initialise le fichier JSON si nécessaire | |
| load_history() # Charge l'historique existant lors du démarrage | |