import os os.system("pip install mistralai") import os import gradio as gr from mistralai import Mistral import requests import logging import html import time # Configure logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') # Get API key and agent ID from environment variables api_key = os.environ.get("Mistral_API_Key") agent_id = os.environ.get("Agent_API_Key") # Environment Variable Validation if not api_key: logging.error("Mistral API Key not found.") def error_response(message, history): yield "Mistral API Key not found. Please set the MISTRAL_API_KEY environment variable." demo = gr.ChatInterface(error_response, title="Error", description="Error") demo.launch() exit() if not agent_id: logging.error("Agent API Key not found.") def error_response(message, history): yield "Agent API Key not found. Please set the Agent_API_Key environment variable." demo = gr.ChatInterface(error_response, title="Error", description="Error") demo.launch() exit() logging.info("API keys found.") # Initialize the Mistral client client = Mistral(api_key=api_key) def sanitize_input(input_string): """Sanitize user input to prevent XSS attacks.""" return html.escape(input_string) def get_mistral_response(message, history, session_id): message = sanitize_input(message) if not message.strip(): yield "Please enter a message." return yield "Thinking..." logging.info(f"Session {session_id}: Sending message to Mistral agent: {message[:30]}...") messages = [] limited_history = history[-5:] if len(history) > 5 else history for human, assistant in limited_history: messages.append({"role": "user", "content": human}) messages.append({"role": "assistant", "content": assistant}) messages.append({"role": "user", "content": message}) retries = 3 for attempt in range(retries): try: chat_response = client.agents.complete( agent_id=agent_id, messages=messages ) response = chat_response.choices[0].message.content logging.info(f"Session {session_id}: Received response from Mistral agent: {response[:30]}...") yield response break # Break out of retry loop if successful except requests.exceptions.RequestException as e: if attempt < retries - 1 and e.response is not None and e.response.status_code == 429: #rate limit logging.warning(f"Session {session_id}: Rate limit exceeded. Retrying in {2**attempt} seconds.") time.sleep(2**attempt) #exponential backoff. elif e.response is not None: logging.error(f"Session {session_id}: API Error: {e.response.status_code} - {e.response.text}") yield f"API Error: {e.response.status_code} - {e.response.text}" break else: logging.error(f"Session {session_id}: Network Error: {e}") yield f"Network Error: {e}" break except Exception as e: logging.error(f"Session {session_id}: An unexpected error occurred: {e}") yield f"An unexpected error occurred: {e}" break # Create Gradio Interface with session_id demo = gr.ChatInterface( get_mistral_response, title="My Mistral AI Agent", description="Ask me anything and I'll respond using my custom Mistral AI Agent", theme="soft", additional_inputs=[gr.Textbox(label="Session ID", value="default")] ) # Launch the app if __name__ == "__main__": demo.launch()