from flask import Flask, render_template, request, jsonify from gradio_client import Client app = Flask(__name__) # Initialize Gradio Client once for efficiency try: client = Client("Gopikanth123/llama2") # Replace with your Gradio model URL except Exception as e: print(f"Error initializing Gradio client: {str(e)}") client = None # Function to fetch the response from Gradio model def generate_response(query): if client is None: return "Model is unavailable at the moment. Please try again later." try: result = client.predict(query=query, api_name="/predict") return result except Exception as e: return f"Error fetching the response: {str(e)}" # Route for the homepage @app.route('/') def index(): return render_template('index.html') # Route to handle chatbot messages @app.route('/chat', methods=['POST']) def chat(): try: user_message = request.json.get("message") if not user_message: return jsonify({"response": "Please say something!"}) bot_response = generate_response(user_message) return jsonify({"response": bot_response}) except Exception as e: return jsonify({"response": f"An error occurred: {str(e)}"}) if __name__ == '__main__': app.run(debug=True)