GenAI with Stock Trading Website (Module 5)

Hui Yee Leong
2 min readJul 10, 2024

--

Module 5: Create Chatbot

In this module, we will create a simple chatbot using a Python script that interacts with the API Gateway we set up in the previous module. The chatbot will send user queries to the API Gateway and return responses to the user.

Step 1: Create the Chatbot Script

5.1 Introduction

We will write a Python script to create a basic command-line chatbot that interacts with our API Gateway. The chatbot will send user queries to the API Gateway, which will invoke the Lambda function to process the queries and return responses.

5.2 Write the Chatbot Script

Here is the Python script for the chatbot:

import requests
import re
import json

class APIGatewayChatbot:
def __init__(self, api_url):
self.api_url = api_url

def get_response(self, user_input):
payload = {
"inputTranscript": user_input,
"sessionState": {
"sessionAttributes": {},
"intent": {
"state": "InProgress"
}
},
"sessionId": "test-session",
"requestAttributes": {}
}
try:
response = requests.post(self.api_url, json=payload)
if response.status_code == 200:
response_json = response.json()
if 'messages' in response_json and response_json['messages']:
return response_json['messages'][0].get("content", "I don't understand.")
else:
return "I don't understand."
else:
return "I'm having trouble connecting to the API."
except Exception as e:
return f"An error occurred: {e}"

def main():
api_url = "https://<api-id>.execute-api.<region>.amazonaws.com/prod/chatbot" # Your API Gateway endpoint
bot = APIGatewayChatbot(api_url)
print("Chatbot: Hi! How can I help you today?")
while True:
user_input = input("You: ")
if re.search("bye|goodbye", user_input, re.IGNORECASE):
print("Chatbot: Goodbye!")
break
response = bot.get_response(user_input)
print(f"Chatbot: {response}")

if __name__ == "__main__":
main()

Step 2: Test the Chatbot

5.3 Run the Script

To test the chatbot:

a. Install Required Packages:

  • Ensure you have the requests module installed. You can install it using pip:
pip3 install requests

b. Run the Script:

  • Save the script to a file, for example, chatbot.py.
  • Run the script:
 python3 chatbot.py 

c. Interact with the Chatbot:

  • Enter queries and verify that the chatbot returns the correct responses from the API Gateway.
  • Test various scenarios to ensure the chatbot handles different inputs appropriately.

Summary

In this module, we created a simple Python script to implement a chatbot that interacts with the API Gateway. The chatbot sends user queries to the API Gateway, which invokes the Lambda function to process the queries and return responses. We tested the chatbot to ensure it works correctly. In the next module, we will perform end-to-end testing to ensure all components work seamlessly together.

Final Module: GenAI with Stock Trading Website (Module 6)

--

--