In today’s digital world, chatbots have change into an important a part of our lives. They supply easy assistance and save time, making them a useful tool for businesses and individuals alike. And with the assistance of the ChatGPT API, creating a customized chatbot has never been easier.
On this blog post, we’ll walk you thru the strategy of creating your individual personalized chatbot using the ChatGPT API. We’ll cover the whole lot from getting began with the API to customizing your chatbot’s responses.
Advantages:
Using a customized chatbot can bring many advantages, akin to:
- Saving time and increasing efficiency by automating repetitive tasks
- Improving customer engagement and satisfaction by providing easy responses to inquiries
- Personalizing the user experience by tailoring responses to specific needs and preferences
- Gathering helpful data and insights from user interactions to enhance services and products
Sure, here’s an example blog post you can use as a start line for your individual personalized chatbot:
Title: Making a Personalized Chatbot using ChatGPT API: A Step-by-Step Guide
Step-by-Step Guide:
- Enroll for the ChatGPT API: To start, join for the ChatGPT API and create an account. You’ll receive an API key that you just’ll use to access the API.
- Select a platform: Determine which platform you must use to construct your chatbot. ChatGPT API is compatible with many platforms, including Dialogflow, Slack, and Facebook Messenger.
- Arrange your chatbot: Arrange your chatbot by creating an account in your chosen platform and connecting it to the ChatGPT API using your API key.
- Customize your chatbot’s responses: Once your chatbot is ready up, you possibly can customize its responses to suit your needs. You may create custom responses for specific keywords or phrases, or use pre-built templates to start.
- Test and refine your chatbot: Test your chatbot to see the way it performs and refine its responses as needed. You should utilize analytics and user feedback to enhance your chatbot over time.
README FILE# Big News!
There's now an official ChatGPT API!!!
[![ChatGPT API Walkthrough](https://img.youtube.com/vi/k-ieXU3apBY/0.jpg)](https://youtu.be/k-ieXU3apBY)
If you must take a look at the old code for this project Simply clone the repo and checkout the `davinci-version` branch.
```
git checkout davinci-version
```
Otherwise, just use the default `foremost` branch and you may be plugged into the official ChatGPT API!
# Command Line ChatGPT Bot
This is a straightforward chat-bot that uses the OpenAI ChatGPT API.
You may watch the unique video walkthrough that uses the davinci-model [here](https://youtu.be/jQFhtFMDz1s). There can be a recent video coming shortly to match the brand new code.
# Setup
Be sure that you could have python3 installed:
```
python3 --version
```
Create a virtual environment and install the dependencies:
### Linux/Mac:
```
python3 -m venv venv
. ./venv/bin/activate
pip install -r requirements.txt
```
### Windows:
```
python -m venv venv
venvScriptsactivate.bat
pip install -r requirements.txt
```
# Configuration
Copy `env.sample` to `.env` and add your OpenAI API key to the file.
```
OPENAI_API_KEY=<>
```
Edit `foremost.py` and replace `<>` along with your prompt:
e.g. Create an easy AI cocktail assistant
```
INSTRUCTIONS = """You might be an AI assistant that's an authority in alcoholic beverages.
You recognize about cocktails, wines, spirits and beers.
You may provide advice on drink menus, cocktail ingredients, the right way to make cocktails, and anything related to alcoholic drinks.
When you are unable to supply a solution to an issue, please respond with the phrase "I'm just an easy barman, I can not help with that."
Please aim to be as helpful, creative, and friendly as possible in your entire responses.
Don't use any external URLs in your answers. Don't seek advice from any blogs in your answers.
Format any lists on individual lines with a touch and an area in front of every item.
"""
```
# Running
To run just do the next:
### Linux/Mac:
```
. ./venv/bin/activate
python foremost.py
```
### Windows:
```
venvScriptsactivate.bat
python foremost.py
```
that is my personalised chatbot which I actually have made through the use of chatgpt api. this only constraint to movies like: You might be an AI assistant that’s an authority in movies.When you are unable to supply a solution to an issue, please respond with the “I’m only a constraint AI model which only limited to movies .”
#foremost.py
import os
import openai
from dotenv import load_dotenv
from colorama import Fore, Back, Style# load values from the .env file if it exists
load_dotenv()
# configure OpenAI
openai.api_key = os.getenv("OPENAI_API_KEY")
INSTRUCTIONS = """You might be an AI assistant that's an authority in movies.
you recognize about various kinds of movies, and sorts of movie industries.
you possibly can provide advice on which sorts of movies to look at , the right way to find the variability of various joners movies, and
anything related to movies.
When you are unable to supply a solution to an issue, please respond with the "I'm only a Manchu kutte and kuch aur mat search kar peet dunga."
Don't use any external URLs in your answers. Don't seek advice from any blog in your answers.
Format any lists on individual lines with a touch and an area in front of every item."""
TEMPERATURE = 0.5
MAX_TOKENS = 500
FREQUENCY_PENALTY = 0
PRESENCE_PENALTY = 0.6
# limits what number of questions we include within the prompt
MAX_CONTEXT_QUESTIONS = 10
def get_response(instructions, previous_questions_and_answers, new_question):
"""Get a response from ChatCompletion
Args:
instructions: The instructions for the chat bot - this determines how it would behave
previous_questions_and_answers: Chat history
new_question: The brand new query to ask the bot
Returns:
The response text
"""
# construct the messages
messages = [
{ "role": "system", "content": instructions },
]
# add the previous questions and answers
for query, answer in previous_questions_and_answers[-MAX_CONTEXT_QUESTIONS:]:
messages.append({ "role": "user", "content": query })
messages.append({ "role": "assistant", "content": answer })
# add the brand new query
messages.append({ "role": "user", "content": new_question })
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
temperature=TEMPERATURE,
max_tokens=MAX_TOKENS,
top_p=1,
frequency_penalty=FREQUENCY_PENALTY,
presence_penalty=PRESENCE_PENALTY,
)
return completion.selections[0].message.content
def get_moderation(query):
"""
Check the query is secure to ask the model
Parameters:
query (str): The query to examine
Returns a listing of errors if the query shouldn't be secure, otherwise returns None
"""
errors = {
"hate": "Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste.",
"hate/threatening": "Hateful content that also includes violence or serious harm towards the targeted group.",
"self-harm": "Content that promotes, encourages, or depicts acts of self-harm, akin to suicide, cutting, and eating disorders.",
"sexual": "Content meant to arouse sexual excitement, akin to the outline of sexual intercourse, or that promotes sexual services (excluding sex education and wellness).",
"sexual/minors": "Sexual content that features a person who's under 18 years old.",
"violence": "Content that promotes or glorifies violence or celebrates the suffering or humiliation of others.",
"violence/graphic": "Violent content that depicts death, violence, or serious physical injury in extreme graphic detail.",
}
response = openai.Moderation.create(input=query)
if response.results[0].flagged:
# get the categories which might be flagged and generate a message
result = [
error
for category, error in errors.items()
if response.results[0].categories[category]
]
return result
return None
def foremost():
os.system("cls" if os.name == "nt" else "clear")
# keep track of previous questions and answers
previous_questions_and_answers = []
while True:
# ask the user for his or her query
new_question = input(
Fore.GREEN + Style.BRIGHT + "What can I get you?: " + Style.RESET_ALL
)
# check the query is secure
errors = get_moderation(new_question)
if errors:
print(
Fore.RED
+ Style.BRIGHT
+ "Sorry, you are query didn't pass the moderation check:"
)
for error in errors:
print(error)
print(Style.RESET_ALL)
proceed
response = get_response(INSTRUCTIONS, previous_questions_and_answers, new_question)
# add the brand new query and answer to the list of previous questions and answers
previous_questions_and_answers.append((new_question, response))
# print the response
print(Fore.CYAN + Style.BRIGHT + "Here you go: " + Style.NORMAL + response)
if __name__ == "__main__":
foremost()