ITI109-SectionB-English / Web-Chatbot-app.py
wookimchye's picture
Upload 6 files
aca2437 verified
from flask import Flask, render_template, request, jsonify
import requests
from dotenv import load_dotenv
import os
# import namespaces
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering import QuestionAnsweringClient
app = Flask(__name__)
# Azure Bot Service configuration
AZURE_BOT_ENDPOINT = "https://iti109-sectionb.cognitiveservices.azure.com/"
AZURE_BOT_KEY = "2ou0CMAjUutj0D4In8U8AkxEIXtCrvYFOBMhqSW4rZ7x6yZ033GdJQQJ99ALACqBBLyXJ3w3AAAaACOGtVJj"
# Get Configuration Settings
load_dotenv()
ai_endpoint = os.getenv('AI_SERVICE_ENDPOINT')
ai_key = os.getenv('AI_SERVICE_KEY')
ai_project_name = os.getenv('QA_PROJECT_NAME')
ai_deployment_name = os.getenv('QA_DEPLOYMENT_NAME')
# Create client using endpoint and key
credential = AzureKeyCredential(ai_key)
ai_client = QuestionAnsweringClient(endpoint=ai_endpoint, credential=credential)
@app.route('/')
def home():
return render_template('index.html') # HTML file for the web interface
@app.route('/ask', methods=['POST'])
def ask_bot():
user_question = request.json.get("question", "")
if not user_question:
return jsonify({"error": "No question provided"}), 400
# Call Azure QnA
#response = ai_client.get_answers(question=user_question,project_name=ai_project_name,deployment_name=ai_deployment_name)
try:
response = ai_client.get_answers(question=user_question,
project_name=ai_project_name,
deployment_name=ai_deployment_name)
#response = requests.post(AZURE_BOT_ENDPOINT, headers=headers, json=data)
#@response.raise_for_status()
bot_response = response.answers[0].answer if response.answers else "No response from bot"
return jsonify({"answer": bot_response})
except requests.exceptions.RequestException as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)