DEV Community

jbxamora
jbxamora

Posted on

ChatGPT Bot

Chatbot

This Python script uses OpenAI's GPT-3 language model to create an advanced chatbot that can assist users by answering questions, providing helpful information, or completing tasks based on user input.
The script prompts the user for input and then uses the OpenAI API to get a response from the GPT-3 model.
The script then prints the chatbot response and updates the conversation history with the user's input and the chatbot's response.

To use the script, you will need to set your OpenAI API key and model engine in the script. You can then run the script in a terminal or command prompt by typing python chatbot.py and pressing Enter.

The script uses the openai Python package to access the OpenAI API and the input() function to prompt the user for input. The script defines a get_response() function that takes the conversation history and user input as arguments,
replaces the placeholders in the chatbot prompt with the conversation history and user input, and then uses the OpenAI API to get a response from the GPT-3 model. The script then defines a main() function that initializes the conversation
history to an empty string, prompts the user for input, gets the chatbot response using the get_response() function, prints the chatbot response, and updates the conversation history with the user's input and the chatbot's response.
The main() function continues looping until the user types "exit" to exit the program.

import openai

# Set your OpenAI API key and model engine
openai.api_key = "YOUR API KEY HERE"
model_engine = "text-davinci-003"

# Set the prompt for the chatbot
chatbot_prompt = """
As an advanced chatbot, your primary goal is to assist users to the best of your ability. This may involve answering questions, providing helpful information, or completing tasks based on user input. In order to effectively assist users, it is important to be detailed and thorough in your responses. Use examples and evidence to support your points and justify your recommendations or solutions.
<conversation history>
User: <user input>
Chatbot:"""

# Define a function to get the chatbot response given the conversation history and user input
def get_response(conversation_history, user_input):
    # Replace the placeholders in the prompt with the conversation history and user input
    prompt = chatbot_prompt.replace(
        "<conversation_history>", conversation_history).replace("<user input>", user_input)

    # Get the response from GPT-3 using the OpenAI API
    response = openai.Completion.create(
        engine=model_engine, prompt=prompt, max_tokens=2048, n=1, stop=None, temperature=0.5)

    # Extract the response text from the response object
    response_text = response["choices"][0]["text"]

    # Remove any leading or trailing whitespace from the response text
    chatbot_response = response_text.strip()

    return chatbot_response

# Define the main function to run the chatbot
def main():
    conversation_history = ""

    while True:
        # Prompt the user for input and check if they want to exit
        user_input = input("> ")
        if user_input == "exit":
            break

        # Get the chatbot response given the conversation history and user input
        chatbot_response = get_response(conversation_history, user_input)

        # Print the chatbot response and update the conversation history
        print(f"Chatbot: {chatbot_response}")
        conversation_history += f"User: {user_input}\nChatbot: {chatbot_response}\n"

# Call the main function to start the chatbot
main()
Enter fullscreen mode Exit fullscreen mode

Important

You will need to modify the script to include your own OpenAI API key. You can replace "YOUR API KEY HERE" on line 4 with your actual API key.

Additionally, you may want to modify the chatbot prompt to better suit your use case. The current prompt is a general prompt that can work for a variety of chatbot applications, but you may want to customize it to better fit your specific use case.

Finally, you may want to adjust the parameters passed to openai.Completion.create() on line 20 to fine-tune the behavior of the GPT-3 model. For example, you could adjust the max_tokens parameter to control the length of the response, or the temperature parameter to control the creativity of the response. You can find more information about these parameters in the OpenAI API documentation.

API KEY

here are the steps to obtain an OpenAI API key:

  1. Go to the OpenAI website (https://openai.com/) and click the "Sign up" button in the top right corner of the page.

  2. Follow the on-screen prompts to create a new OpenAI account. You will need to provide your name, email address, and a password to create an account.

  3. Once you have created an account, you will be taken to the OpenAI dashboard. Click the "API keys" link in the left sidebar to manage your API keys.

  4. Click the "Create new API key" button to generate a new API key. You can give your API key a name to help you identify it later.

  5. Once your API key has been generated, copy the key to your clipboard or save it in a secure location.

Hiding your API key

Two Methods in Python

Using Environment Variables

One common method to hide API keys is to use environment variables. This involves setting the API key as an environment variable on your local machine, and then accessing the variable in your Python code.

To set an environment variable, open a terminal or command prompt and enter the following command, replacing API_KEY with the name of your API key and SECRET_VALUE with the actual value of your API key:

export API_KEY="SECRET_VALUE"
Enter fullscreen mode Exit fullscreen mode

In your Python code, you can then access the API key using the os module:

import os
api_key = os.environ.get('API_KEY')
Enter fullscreen mode Exit fullscreen mode

This will retrieve the value of the API_KEY environment variable and assign it to the api_key variable in your Python code. Note that you should never hardcode API keys directly in your code, as this can make them vulnerable to being accessed by unauthorized users.

Using a Configuration File

Another method to hide API keys is to use a configuration file. This involves storing the API key in a separate configuration file that is not included in your code repository.

To create a configuration file, create a new file in your project directory called config.ini. In this file, add a section for your API key with a key-value pair for the actual value of your key, like this:

[API]
key = SECRET_VALUE
Enter fullscreen mode Exit fullscreen mode

In your Python code, you can then read the API key from the configuration file using the configparser module:

import configparser

config = configparser.ConfigParser()
config.read('config.ini')

api_key = config['API']['key']
Enter fullscreen mode Exit fullscreen mode

This will retrieve the value of the key key in the API section of the config.ini file and assign it to the api_key variable in your Python code. Note that you should add config.ini to your .gitignore file to prevent it from being included in your code repository.

Thanks for reading.

Top comments (1)

Collapse
 
acode123 profile image
acode123

Nice Job!