Welcome Traveler..
Welcome back Traveler.. I hope you’ll enjoy today’s journey.
In today’s mission we will be exploring how to create your very own chat bot using the Python programming language and the OpenAI API.
Why? Well..
As a wildcard slasher, I have journeyed through countless worlds of and faced numerous demons on my quest to rid the multiverse of their malevolent influence. And in my travels, I have found that having a chat bot by my side can be a valuable ally.
Besides that.. it’s a fun journey.
This is limited quick and dirty command line chatbot. It doesn’t have all the features as fancy web Chat GPT but it will get the job done. With time I’ll be adding some enhancement and you can build on top that little script.
We’ll go over different sections of the script or you can skip all the way to the bottom and grab the script from GIT link.
Let’s look at the first few lines..
#!/usr/bin/env python3 import os from dotenv import load_dotenv import datetime import openai
.. the mysterious and arcane world of imports. Don’t worry, we won’t be delving too deep into this mystical realm. All you need to know is that these lines of code are bringing in some helpful libraries that we’ll be using to create our chat bot.
chat_log = None load_dotenv() openai.api_key = os.environ.get('OPENAI_KEY') completion = openai.Completion() start_chat_log = '''... '''
The chat_log
variable is initialized to None
, because at this point in the script, we’re not quite sure what we’re going to put in it yet (but we have high hopes).
We call the load_dotenv
function to load up all those sweet, sweet environment variables we talked about earlier. These bad boys are stored in a file called .env
, because who wants to have to remember all their API keys and stuff? Ain’t nobody got time for that.
Next, we set the OpenAI API key to the value of the OPENAI_KEY
environment variable using the os.environ.get
function. This way, we can keep our API key safe and sound without having to hardcode it into the script. Sneaky, sneaky.
We then create a Completion
object using the openai.Completion
function. This little guy is going to be responsible for generating all the chat bot responses we’ll be using later on in the script.
Finally, we initialize the start_chat_log
variable to a string of ...
, because every good chat needs a solid introduction (and three dots is about as solid as it gets).
def ask(question, chat_log=None): if chat_log is None: chat_log = start_chat_log prompt = f'{chat_log}Human: {question}\nChatBot:' response = completion.create( prompt=prompt, engine="text-davinci-003", stop=['\nHuman'], temperature=0.9, top_p=1, frequency_penalty=0, presence_penalty=0.6, best_of=1, max_tokens=1500) answer = response.choices[0].text.strip() return answer
Ah, the ask
function – the beating heart of our little chat bot. This is where all the magic happens.
First things first, we’ve got a default value for the chat_log
parameter set to None
. This means that if we don’t pass in a value for chat_log
when we call the function, it will default to None
. Handy, right?
Next, we have an if
statement that checks if chat_log
is equal to None
. If it is, then we set chat_log
equal to start_chat_log
, which will be our chat log’s opening message (remember those dots we talked about earlier?).
Then, we create a prompt
string using string interpolation. This string is going to be passed as an argument to the create
method of the completion
object we created earlier. The create
method is going to use this prompt to generate a chat bot response for the given question.
Finally, we call the create
method and pass in a bunch of arguments to customize the chat bot’s response. The engine
argument specifies which language model we want to use (in this case, it’s “text-davinci-003”). The stop
argument is a list of strings that tell the chat bot when to stop generating text. The temperature
, top_p
, frequency_penalty
, and presence_penalty
arguments all affect the randomness and creativity of the chat bot’s response. The best_of
argument specifies how many responses we want the chat bot to generate. And the max_tokens
argument specifies the maximum number of tokens (i.e. words) the chat bot can generate in its response.
Finally, we store the chat bot’s response in a variable called answer
, strip off any leading or trailing whitespace, and return it to the caller.
Many more information can be found at “Open AI Documentation” page.
def chat_interaction(question, answer, chat_log=None): if chat_log is None: chat_log = start_chat_log return f'{chat_log}\n\n\nHuman: {question}\n\nChatBot: {answer}\n\n\n'
Just like the ask
function, the chat_interaction
function has a default value for the chat_log
parameter set to None
. This means that if we don’t pass in a value for chat_log
when we call the function, it will default to None
.
We also have an if
statement that checks if chat_log
is equal to None
. If it is, then we set chat_log
equal to start_chat_log
, which will be our chat log’s opening message (those dots are pretty important, folks).
Next, we have a return statement that uses string interpolation to create a string containing the chat log, the human’s question, and the chat bot’s response. We use a bunch of \n
characters to create some nice, clean formatting for our chat log.
And that’s it! The chat_interaction
function takes in a question, an answer, and (optionally) a chat log, and returns a nicely formatted string containing all that juicy chat goodness.
while True: question = input("Ask a question traveler: ") answer = ask(question, chat_log) chat_log = chat_interaction(question, answer, chat_log) time_stamp = datetime.datetime.now().strftime("%Y_%m_%d-%H_%M") chat_log_file = 'archive-messages/output_'+time_stamp+'.log' with open(chat_log_file, 'w') as outfile: outfile.write(chat_log) print(str(chat_log)) if question == 'quit' or question == 'q': print(f"Bye, see ya later! ;)\n Remember.. our convo is saved in {chat_log_file} \nHasta la vista! Keep it wi break
First, we have the while True
loop, which will run indefinitely until we tell it to stop. Inside the loop, we have a question
variable that is set equal to the user’s input. Then, we call the ask
function and pass in the question
and chat_log
variables as arguments. The ask
function returns the chat bot’s response, which we store in the answer
variable.
Next, we call the chat_interaction
function and pass in the question
, answer
, and chat_log
variables as arguments. The chat_interaction
function returns a string containing the chat log, the human’s question, and the chat bot’s response, which we store in the chat_log
variable.
We then create a time_stamp
variable that contains the current date and time, formatted as a string. We use this time_stamp
to create a unique file name for our chat log.
Next, we open the chat log file in write mode and write the chat_log
string to the file. We then print the chat_log
string to the console.
Finally, we have an if
statement that checks if the question
variable is equal to “quit” or “q”. If it is, then we print a goodbye message, close the loop, and bid our little chat bot farewell.
Full code available on GITHUB:
https://github.com/wozoopa/python/blob/main/chat1.py
That’s all in this story..
Until next time Traveler..