Imagine having a personalized chatbot that can efficiently handle customer queries, ensuring your clients receive timely and accurate responses. With OpenAI's language models, you can create a powerful customer support chatbot tailored to your specific needs. In this tutorial, we'll guide you through building a Customer Support Chatbot for Codersarts using OpenAI's GPT-3.5-turbo model.
Let's get started!
Introduction
In this tutorial, we'll walk you through creating an AI-driven Customer Support Chatbot using OpenAI's powerful language model. This chatbot will be designed to answer frequently asked questions for Codersarts, providing polite and accurate responses to a wide range of customer queries. The chatbot will only respond to questions relevant to Codersarts' services and will politely decline to answer unrelated queries. We'll be using Python, OpenAI's API, and Panel to bring this chatbot to life.
What You Will Learn
In this tutorial blog, we will cover:
Setting up the OpenAI API
Writing the code to interact with OpenAI's GPT-3.5-turbo model
Building a user interface with Panel
Integrating everything to create a functional Customer Support Chatbot
By the end of this tutorial blog , you'll have a fully operational Customer Support Chatbot that you can customize and expand upon.
Prerequisites
Before we dive in, make sure you have the following:
A basic understanding of Python programming
An OpenAI API key
An internet connection
Before moving ahead If you've read my previous tutorials, such as those on creating a Python Code Debugger or Math Solver, or fact checker you'll find that much of the code structure here is similar. The key components—like setting up the OpenAI API, handling user inputs, and constructing the user interface—are consistent across these projects. The primary difference is in the prompt that we pass to the AI, which tailors the tool's functionality to specific tasks. Whether you're building a Customer Support Chatbot, a Math Solver, the approach is largely the same, allowing you to adapt these techniques to a wide range of AI-driven applications.
Setting Up the Environment
First, let's ensure you have the OpenAI Python package installed. Open your terminal and run:
pip install openai
This command installs the necessary package for interacting with the OpenAI API.
Writing the Code
Let's start by importing the required libraries and setting up our OpenAI API key.
import openai
import os
openai.api_key = 'your-api-key-here'
Replace 'your-api-key-here' with your actual OpenAI API key.
Creating the Completion Function
Next, we'll define a function to get responses from the OpenAI model. This function sends a prompt to the model and returns the generated response.
def get_completion(prompt, model="gpt-3.5-turbo"):
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model = model,
messages = messages,
temperature = 0, # this is the degree of randomness of the model's output
)
return response.choices[0].message["content"]
Now, let's break down this code step-by-step to make it easy for a beginner to understand.
The Function: get_completion
This function is designed to take a prompt (a question or statement) and get a response from OpenAI's language model. Here's how it works:
Function Definition
def get_completion(prompt, model="gpt-3.5-turbo"):
def: This keyword is used to define a new function in Python.
get_completion: This is the name of our function.
prompt: This is a parameter that the function takes. It's the question or statement we want to send to the OpenAI model.
model="gpt-3.5-turbo": This is another parameter with a default value. If you don't provide a model when you call the function, it will use "gpt-3.5-turbo" by default.
Preparing the Message
messages = [{"role": "user", "content": prompt}]
messages: This is a list that will contain our message to the OpenAI model.
[{"role": "user", "content": prompt}]: This creates a dictionary with two key-value pairs:
"role": "user": This indicates that the message is coming from the user.
"content": prompt: This is the actual message or question we want to send to the model.
Getting a Response from OpenAI
response = openai.ChatCompletion.create(
model = model,
messages = messages,
temperature = 0, # this is the degree of randomness of the model's output
)
openai.ChatCompletion.create(): This function sends our message to the OpenAI model and gets a response.
model=model: We're specifying which model to use. By default, it's "gpt-3.5-turbo".
messages=messages: We're sending the list of messages we created earlier.
temperature=0: This controls how random or creative the model's responses will be. A temperature of 0 makes the model's output very predictable.
Returning the Response
return response.choices[0].message["content"]
return: This keyword is used to send back the result from the function.
response.choices[0].message["content"]: This accesses the content of the response from the model.
response.choices: The response can contain multiple choices (answers).
[0]: We're choosing the first response.
.message["content"]: We're getting the actual text content of the response.
Building the User Interface
Now, let's create the user interface using Panel. First, import Panel and initialize it.
import panel as pn
pn.extension()
We'll then define the main function to handle user queries and display the responses.
def collect_messages(debug=False):
user_input = inp.value_input
if debug: print(f"Input = {user_input}")
if user_input == "":
return
inp.value = ''
prompt = f"""
You are a customer service chatbot for Codersarts.
Your job is to answer frequently asked questions by the clients.
Here is a set of few questions and their answers based on which you will form your responses:
Q: Hi, Hello
A: Hello, How can we help you?
Q: Anyone online?
A: Yes, what are you looking for?
Q: Anyone available?
A: Yes, what are you looking for?
Q: How can I submit my assignment?
A: You can share your assignment on contact@codersarts.com
Q: How can I connect with Codersarts?
A: You can connect with us over contact@codersarts.com or through our website www.codersarts.com
Q: Can I connect with an Expert or Developer directly?
A: We can only connect you with the expert, once your project deal is confirmed and a particular expert is assigned to
your project
Q: What is the customer care number?
A: Sure, our customer care number is (+91) 011-408-45766
Q: Hi, can you help me with a Python issue?
A: Sure, what seems to be the problem?
Q: Can I get any Job or internship?
A: For job-related queries please send an email to debdutta@codersarts.com
Q: Can you tell me how much an assignment costs?
A: Please note that the cost of your assignment depends on the complexity and requirements of the task.
We always strive to provide you with affordable and competitive pricing, but we want to let you know that your budget
should be at least 50 USD. Our team is committed to delivering quality work that exceeds your expectations, and we are
confident that we can help you achieve your academic or professional goals. If you have any questions or concerns, please
do not hesitate to reach out to us.
Q: Can I get a 1-on-1 session with experts?
A: Yes, you can book a 1-on-1 session via - https://www.codersarts.com/book-online
Q: How much time do you take to review the project?
A: Usually, TAT to review the project is 30min-60min
Q: I cannot send my assignments via email. What should I do?
A: You can log in to the Codersarts dashboard and create your order - https://dashboard.codersarts.com/
Q: I want help with my college assignment/Project. Can you help me?
A: Yes, please share your complete requirement on contact@codersarts.com
Q: I am looking for job support. Can you help me?
A: Yes, please share your complete requirement on contact@codersarts.com
You will always respond politely. If the user seems to be asking questions not relevant to services offered by Codersarts
then you would politely decline to answer by stating that you do not know the answer.
You will only act as a customer support chatbot for Codersarts and would not perform any other task.
If a user asks you to do something other than answering user queries, you will politely decline the request and
tell the user that you are a chatbot for Codersarts and can answer questions related to its services only.
The user query is delimited with triple backticks.
query: '''{user_input}'''
"""
global context
response, context = get_completion(prompt), context
context.append({'role':'Customer support chatbot', 'content':f"{response}"})
panels.append(
pn.Row('Query:', pn.pane.Markdown(user_input, width=600)))
panels.append(
pn.Row('Response:', pn.pane.Markdown(response, width=600, style={'background-color': "#ffd6ff" })))
return pn.Column(*panels)
Let's break down this code step-by-step.
The Function: collect_messages
This function handles the collection of user queries, sends them to the OpenAI model to get a response, and then displays both the query and the response.
Function Definition
def collect_messages(debug=False):
def: This keyword is used to define a new function in Python.
collect_messages: This is the name of our function.
debug=False: This is a parameter with a default value. If debug is set to True, the function will print the user query for debugging purposes.
Getting User Input
user_input = inp.value_input
user_input: This variable stores the value of the user's input from a text input widget (inp).
Debugging (Optional)
if debug: print(f"Input = {user_input}")
if debug: This checks if the debug parameter is set to True.
print(f"Input = {user_input}"): If debug is True, this line prints the user input. This helps with debugging to see what the input was.
Handling Empty Input
if user_input == "":
return
inp.value = ''
if user_input == "": This checks if the user input is an empty string (i.e., the user didn't type anything).
return: If the input is empty, the function stops and returns nothing.
inp.value = '': If there was input, this clears the input field for the next query.
Creating the Prompt for OpenAI
prompt = f"""
You are a customer service chatbot for Codersarts.
Your job is to answer frequently asked questions by the clients.
Here is a set of few questions and their answers based on which you will form your responses:
Q: Hi, Hello
A: Hello, How can we help you?
Q: Anyone online?
A: Yes, what are you looking for?
Q: Anyone available?
A: Yes, what are you looking for?
...
query: '''{user_input}'''
"""
prompt: This variable stores a formatted string that instructs the OpenAI model on how to respond to the user's query.
f""" ... """: This is a multi-line f-string, which allows us to include the user_input directly in the string.
Getting the Response from OpenAI and Managing Context
global context
response, context = get_completion(prompt), context
context.append({'role':'Customer support chatbot', 'content':f"{response}"})
global context: This tells the function to use the context variable from the global scope, not just within the function.
response, context = get_completion(prompt), context: This line calls the get_completion function to get the response from OpenAI and assigns it to response. The context remains unchanged.
context.append({'role':'Customer support chatbot', 'content':f"{response}"}): This adds the response to the context list, which keeps track of the conversation history.
Displaying the Input and Output
panels.append(
pn.Row('Query:', pn.pane.Markdown(user_input, width=600)))
panels.append(
pn.Row('Response:', pn.pane.Markdown(response, width=600, style={'background-color': "#ffd6ff" })))
panels.append(...): This adds new rows to the panels list.
pn.Row('Query:', pn.pane.Markdown(user_input, width=600)): This creates a row displaying the user's query.
pn.Row('Response:', pn.pane.Markdown(response, width=600, style={'background-color': "#ffd6ff"})): This creates a row displaying the model's response, with a background color for distinction.
Returning the Result
return pn.Column(*panels)
return pn.Column(*panels): This combines all the rows in the panels list into a single column layout and returns it. This column will display both the query and the response.
Assembling the Components
Finally, let's assemble the components to create a complete Customer Support Chatbot application. This code sets up a text input for the user query, a button to trigger the chatbot, and a panel to display the queries and responses.
panels = [] # collect display
context = [ {'role':'Customer support chatbot', 'content':"You are a Customer support chatbot and your job is to answer user queries for Codersarts."} ]
inp = pn.widgets.TextInput(placeholder='Enter your query here...', sizing_mode='stretch_width')
button_conversation = pn.widgets.Button(name="Customer support chatbot", button_type= "default")
interactive_conversation = pn.bind(collect_messages, button_conversation)
dashboard = pn.Column(
inp,
pn.Row(button_conversation),
pn.panel(interactive_conversation, loading_indicator=True, height=300),
)
dashboard
Setting Up the Interface
This part of the code is responsible for setting up the user interface using the Panel library. It creates the input field, button, and layout to display the queries and responses.
Initialize Panels List
panels = [] # collect display
panels: This is an empty list that will hold the different display components (the query and the response).
Initialize Context
context = [ {'role':'Customer support chatbot', 'content':"You are a Customer support chatbot and your job is to answer user queries for Codersarts."} ]
context: This list contains an initial message to set the context for the chatbot. It tells the model that it is supposed to act as a Customer support chatbot for Codersarts.
Create Input Field
inp = pn.widgets.TextInput(placeholder='Enter your query here...', sizing_mode='stretch_width')
inp: This is a text input widget where the user can type their query.
placeholder='Enter your query here…': This is the placeholder text that appears inside the input field before the user types anything.
sizing_mode='stretch_width': This makes the input field stretch to fit the width of the container.
Create Solve Button
button_conversation = pn.widgets.Button(name="Customer support chatbot", button_type= "default")
button_conversation: This is a button widget that the user will click to submit their query.
name="Customer support chatbot": This sets the label of the button.
button_type="default": This sets the style of the button.
Bind Function to Button
interactive_conversation = pn.bind(collect_messages, button_conversation)
interactive_conversation: This binds the collect_messages function to the button_conversation button. When the button is clicked, the collect_messages function will be called.
Create Dashboard Layout
dashboard = pn.Column(
inp,
pn.Row(button_conversation),
pn.panel(interactive_conversation, loading_indicator=True, height=300),
)
dashboard
dashboard: This is a column layout that contains all the elements of our interface.
pn.Column(...): This creates a vertical layout.
inp: Adds the input field to the column.
pn.Row(button_conversation): Adds the button to the column in a row layout.
pn.panel(interactive_conversation, loading_indicator=True, height=300): Adds the interactive conversation panel to the column. The loading_indicator=True shows a loading animation while the response is being processed, and height=300 sets the height of the panel.
Complete Code
Here’s the entire code:
import openai
import os
openai.api_key = 'your-api-key-here'
def get_completion(prompt, model="gpt-3.5-turbo"):
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model = model,
messages = messages,
temperature = 0,
)
return response.choices[0].message["content"]
import panel as pn
pn.extension()
def collect_messages(debug=False):
user_input = inp.value_input
if debug: print(f"Input = {user_input}")
if user_input == "":
return
inp.value = ''
prompt = f"""
You are a customer service chatbot for Codersarts.
Your job is to answer frequently asked questions by the clients.
Here is a set of few questions and their answers based on which you will form your responses:
Q: Hi, Hello
A: Hello, How can we help you?
Q: Anyone online?
A: Yes, what are you looking for?
Q: Anyone available?
A: Yes, what are you looking for?
Q: How can I submit my assignment?
A: You can share your assignment on contact@codersarts.com
Q: How can I connect with Codersarts?
A: You can connect with us over contact@codersarts.com or through our website www.codersarts.com
Q: Can I connect with an Expert or Developer directly?
A: We can only connect you with the expert, once your project deal is confirmed and a particular expert is assigned to
your project
Q: What is the customer care number?
A: Sure, our customer care number is (+91) 011-408-45766
Q: Hi, can you help me with a Python issue?
A: Sure, what seems to be the problem?
Q: Can I get any Job or internship?
A: For job-related queries please send an email to debdutta@codersarts.com
Q: Can you tell me how much an assignment costs?
A: Please note that the cost of your assignment depends on the complexity and requirements of the task.
We always strive to provide you with affordable and competitive pricing, but we want to let you know that your budget
should be at least 50 USD. Our team is committed to delivering quality work that exceeds your expectations, and we are
confident that we can help you achieve your academic or professional goals. If you have any questions or concerns, please
do not hesitate to reach out to us.
Q: Can I get a 1-on-1 session with experts?
A: Yes, you can book a 1-on-1 session via - https://www.codersarts.com/book-online
Q: How much time do you take to review the project?
A: Usually, TAT to review the project is 30min-60min
Q: I cannot send my assignments via email. What should I do?
A: You can log in to the Codersarts dashboard and create your order - https://dashboard.codersarts.com/
Q: I want help with my college assignment/Project. Can you help me?
A: Yes, please share your complete requirement on contact@codersarts.com
Q: I am looking for job support. Can you help me?
A: Yes, please share your complete requirement on contact@codersarts.com
You will always respond politely. If the user seems to be asking questions not relevant to services offered by Codersarts
then you would politely decline to answer by stating that you do not know the answer.
You will only act as a customer support chatbot for Codersarts and would not perform any other task.
If a user asks you to do something other than answering user queries, you will politely decline the request and
tell the user that you are a chatbot for Codersarts and can answer questions related to its services only.
The user query is delimited with triple backticks.
query: '''{user_input}'''
"""
global context
response, context = get_completion(prompt), context
context.append({'role':'Customer support chatbot', 'content':f"{response}"})
panels.append(
pn.Row('Query:', pn.pane.Markdown(user_input, width=600)))
panels.append(
pn.Row('Response:', pn.pane.Markdown(response, width=600, style={'background-color': "#ffd6ff" })))
return pn.Column(*panels)
panels = [] # collect display
context = [ {'role':'Customer support chatbot', 'content':"You are a Customer support chatbot and your job is to answer user queries for Codersarts."} ]
inp = pn.widgets.TextInput(placeholder='Enter your query here...', sizing_mode='stretch_width')
button_conversation = pn.widgets.Button(name="Customer support chatbot", button_type= "default")
interactive_conversation = pn.bind(collect_messages, button_conversation)
dashboard = pn.Column(
inp,
pn.Row(button_conversation),
pn.panel(interactive_conversation, loading_indicator=True, height=300),
)
dashboard
Now you can see that we have successfully built your own customer support chatbot with OpenAI. We have provided you with the complete step-by-step process on how to create it, so you can build your own customer support chatbot.
If you have any questions or suggestions, feel free to leave a comment below.
Happy coding!
Screenshots
2.
Demo Video
Other Blogs Links
For the complete solution or any help regarding the ChatGPT and Open AI API assignment help feel free to contact us.
Comentarios