Creating a Simple Diet Bot in Your Terminal with OpenAI’s API

4/5 - (3 votes)

In this article, we will use OpenAI’s API to build a simple diet bot, a virtual assistant that can guide users through their dietary needs and choices.

Setting up OpenAI API

To get started, first, you need to create an account on OpenAI. Here’s how you do it:

  1. Visit the OpenAI platform’s website.
  2. Create an account by providing the necessary details.
  3. Once you’ve signed up, navigate to your profile on the top right side of the platform.
  4. Click on ‘View API keys’ from the drop-down menu.
  5. Generate a new secret API key by clicking on ‘Create new secret key’.
  6. Store the generated API key safely in a notepad file πŸ˜‚, as you’ll need it later.

πŸ’‘ Recommended: OpenAI Python API – A Helpful Illustrated Guide in 5 Steps

Developing the Diet Bot using OpenAI’s API

We’ll use Google Colab to develop our chatbot as it is a user-friendly and efficient platform.

Start by installing OpenAI’s Python client library using the command !pip install openai in a Jupyter notebook and pip install openai in your normal Python environment (not Jupyter).

πŸ’‘ Recommended: How to Install OpenAI

Now, we can proceed with the code (thanks to Ashutosh Roy for providing an initial version of this code β™₯️):

import openai

openai.api_key = "YOUR API KEY"  # Substitute "YOUR API KEY" with the key you generated earlier

def dietchatbot():
  messages = [
    {"role": "system", "content": "You are a diet planner."},
  ]

  while True:
    user_message = input("User: ")

    if user_message.lower() == "quit":
      break

    messages.append({"role": "user", "content": user_message})

    response = openai.ChatCompletion.create(
      model="gpt-3.5-turbo",
      messages=messages
    )

    result = response['choices'][0]['message']['content']
    print(f"Diet_Bot: {result}")
    messages.append({"role": "assistant", "content": result})

print("Chatting with the Diet bot")
dietchatbot()

Let’s delve into how this code works:

  1. We start by importing the openai module and initializing our OpenAI API key.
  2. We define a function dietchatbot(), which houses the main logic for our chatbot.
  3. The messages list is initialized with a system message defining the bot’s role as a diet planner. This serves as the bot’s initial understanding and sets the context for all future interactions. The list will eventually store all the dialog exchanges between the user and the bot.
  4. We then enter a while loop, which continues running until the user types 'quit'. Inside the loop, the bot takes the user’s input, appends it to the messages list, and passes the updated list to the model.
  5. The openai.ChatCompletion.create() function then generates a response based on the user’s query and the previously recorded messages. This function uses the GPT-3.5-turbo model.
  6. The response is extracted from the response object, displayed to the user, and appended back to the messages list.

In summary, this simple diet bot takes in user queries, processes them using OpenAI’s ChatGPT model, and provides appropriate dietary advice.

The conversation continues until the user decides to exit by typing 'quit'. The code is quite flexible and can be easily customized to develop chatbots for different roles by changing the initial system message.

More Ideas for Initial System Messages (Alternative Bots)

The initial system message sets the context and role for the AI model. Here are five different ideas for the initial system message that can result in entirely different chatbots:

Personal Fitness Trainer

{"role": "system", "content": "You are a personal fitness trainer."}

This sets up the model as a fitness trainer, giving advice on exercise routines, workout plans, and general fitness guidance.

Mental Health Counselor

{"role": "system", "content": "You are a mental health counselor."}

This would prompt the model to act as a mental health counselor, providing help for stress management, mindfulness techniques, and positive thinking.

Financial Advisor

{"role": "system", "content": "You are a financial advisor."}

With this, the bot would offer advice on financial matters, such as investments, budgeting, retirement planning, and more.

Recipe Advisor

{"role": "system", "content": "You are a recipe advisor."}

This context would enable the chatbot to offer culinary advice, suggest recipes, and provide tips on cooking and baking.

Language Tutor

{"role": "system", "content": "You are a language tutor."}

The bot would act as a language tutor in this case, assisting with vocabulary, grammar rules, and language learning tips.

Also check out our free Finxter cheat sheet on OpenAI API: πŸ‘‡

πŸ”— Recommended: Python OpenAI API Cheat Sheet (Free)