Spaces:
Sleeping
Sleeping
| from llama_index.llms.openai import OpenAI | |
| from llama_index.core.agent import ReActAgent | |
| from tools import TOOLS | |
| import os | |
| #from llama_index.agent.openai import OpenAIAgent | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| # 🔑 Variables d'environnement | |
| openai_api_key = os.getenv("OPENAI_API_KEY") | |
| os.environ["OPENAI_API_KEY"] = openai_api_key | |
| with open("prompt.txt", "r", encoding="utf-8") as f: | |
| my_prompt = f.read() | |
| # 🧠 Création de l'agent | |
| llm = OpenAI( | |
| model="gpt-3.5-turbo", | |
| system_prompt=(my_prompt), | |
| max_tokens=1500, | |
| temperature=0.1 | |
| ) | |
| agent = ReActAgent.from_tools( | |
| tools=TOOLS, | |
| llm=llm, | |
| verbose=True, | |
| max_iterations = 10 | |
| ) | |
| # 🚀 Point d'entrée principal | |
| def run_agent(question: str) -> str: | |
| """Interface principale pour l'agent avec nettoyage de format""" | |
| try: | |
| response = agent.chat(question) | |
| answer = str(response).strip() | |
| # Nettoyer les préfixes | |
| prefixes_to_remove = [ | |
| "La réponse est :", "Réponse :", "FINAL ANSWER:", "Answer:" | |
| ] | |
| for prefix in prefixes_to_remove: | |
| if answer.startswith(prefix): | |
| answer = answer[len(prefix):].strip() | |
| # CORRECTION CRITIQUE : Nettoyer les formats JSON/liste | |
| if answer.startswith('["') and answer.endswith('"]'): | |
| # Convertir ["a", "b", "c"] en a, b, c | |
| import json | |
| try: | |
| list_items = json.loads(answer) | |
| answer = ', '.join(list_items) | |
| except (json.JSONDecodeError, TypeError, ValueError): | |
| # Si le parsing JSON échoue, on garde la réponse originale | |
| pass | |
| # Supprimer les guillemets autour des listes | |
| if answer.startswith('"') and answer.endswith('"'): | |
| answer = answer[1:-1] | |
| return answer | |
| except Exception as e: | |
| return f"Erreur: {str(e)}" |