This publication was originally written in Portuguese. You're viewing an automated translation into English.
This is a simple Python- based chatbot project that uses Azure LUIS (Language Understanding Intelligent Service) to identify intents and extract entities from messages provided by users.
The chatbot is designed to interpret messages and identify user intent based on a model trained in Azure LUIS. It displays the identified intent, as well as the detected entities, and records all interactions in a log file.
The chatbot receives a text message from the user.
The message is sent to the LUIS service, which returns:
The information is displayed to the user and recorded in a log file.
<div align="center">
</div>
This is a simple Python- based chatbot project that uses Azure LUIS (Language Understanding Intelligent Service) to identify intents and extract entities from messages provided by users.
The chatbot is designed to interpret messages and identify user intent based on a model trained in Azure LUIS. It displays the identified intent, as well as the detected entities, and records all interactions in a log file.
The chatbot receives a text message from the user.
The message is sent to the LUIS service, which returns:
The information is displayed to the user and recorded in a log file.
pip install -r requirements.txt`
.env
in the project root:APP_ID=seu-app-id-aqui PREDICTION_KEY=sua-chave-de-api-aqui ENDPOINT=seu-endpoint-aqui
Run the main script:
python app.py
Você: Qual será o tempo amanhã?
sair
.Log Configuration:
logs/logChatbot.log
.Integration with LUIS:
.env
settings.obter_intencao
function processes messages in LUIS and returns the intents and entities.Main Chatbot:
app.py
The file app.py
is the chatbot's main code. It integrates Azure LUIS with Python, manages user input, and records interactions in a log file. Let's explore the main parts of the code:
`LOG_DIR = "logs"` `LOG_FILE = os.path.join(LOG_DIR, "logChatbot.log")` `os.makedirs(LOG_DIR, exist_ok=True)` `logging.basicConfig(` `level=logging.INFO,` `format="%(asctime)s - %(levelname)s - %(message)s",` `handlers=[` `logging.FileHandler(LOG_FILE, encoding="utf-8"),` `logging.StreamHandler() # Também exibe logs no console` `]` `)` `logger = logging.getLogger(__name__)`
Objective : Configure the logging system.
Details :
logs
to store the log files if it does not exist.logChatbot.log
is generated inside this folder, and it logs all messages (info, error, etc.).`if load_dotenv():` `logger.info("Variáveis de ambiente carregadas com sucesso.")` `else:` `logger.error("Erro ao carregar as variáveis de ambiente. Verifique o arquivo .env.")`
.env
..env
file contains sensitive settings such as the APP_ID , PREDICTION_KEY , and ENDPOINT of the LUIS service. The code uses the python-dotenv
library to load these variables.`APP_ID = os.getenv("APP_ID")` `PREDICTION_KEY = os.getenv("PREDICTION_KEY")` `ENDPOINT = os.getenv("ENDPOINT")` `if not all([APP_ID, PREDICTION_KEY, ENDPOINT]):` `logger.critical("Uma ou mais variáveis do .env não foram encontradas. Verifique o arquivo .env.")` `exit(1)`
`try:` `client = LUISRuntimeClient(endpoint=ENDPOINT, credentials=CognitiveServicesCredentials(PREDICTION_KEY))` `logger.info("Cliente LUIS inicializado com sucesso.")` `except Exception as e:` `logger.critical(f"Erro ao inicializar o cliente LUIS: {e}")` `exit(1)`
`def obter_intencao(mensagem):` `try:` `response = client.prediction.resolve(APP_ID, query=mensagem)` `intent = response.top_scoring_intent.intent` `entities = [(e.entity, e.type) for e in response.entities]` `logger.info(f"Mensagem processada com sucesso. Intenção: {intent}, Entidades: {entities}")` `return intent, entities` `except Exception as e:` `logger.error(f"Erro ao processar a mensagem no LUIS: {e}")` `return "Erro", []`
Objective : Send a message to LUIS and get the intent and entities.
Details :
resolve()
method.`if __name__ == "__main__":` `logger.info("Chatbot iniciado. Digite sua mensagem ou 'sair' para encerrar.")` `while True:` `user_input = input("Você: ")` `if user_input.lower() == "sair":` `logger.info("Chatbot encerrado pelo usuário.")` `break` `intent, entities = obter_intencao(user_input)` `print(f"Intenção: {intent}")` `print(f"Entidades: {entities}")`
Objective : Control user interaction.
Details :
obter_intencao
function to process the input and returns the intent and entities.Language Understanding Intelligent Service (LUIS) is a Microsoft artificial intelligence API that uses natural language processing (NLP) to identify intent and extract information from natural language messages.
Greeting
might indicate a greeting, such as "Hello!".All events, successes and errors are logged in the file:
logs/logChatbot.log * **Exemplo de Log:** 2024-12-23 10:30:00 - INFO - Cliente LUIS inicializado com sucesso. 2024-12-23 10:31:00 - INFO - Mensagem processada com sucesso. Intenção: WeatherQuery, Entidades: [('tempo', 'consulta')]` *
This project is licensed under the MIT License - see the LICENSE file for more details.