GPT-4 has disrupted the tech industry completely. From writing better code to explaining the already written code. GPT-4 is doing everything with much better performances than any other AI model available today in the market.
Tech industry is not the only field where GPT-4 is being widely used. Here are some of the following platforms where GPT-4 usage has topped the charts.
- Content Generation like writing blogs, mails, social media campaigns etc.
- Using GPT-4 to create prompts to use it create much better images using Dall-E, Midjourney etc.
- Creating Chatbots has never been this easier.
Today, we will learn how you can also use GPT-4 to power your application using the API provided by OPENAI in Python programming language.
Prerequisites
We will require the following items before we can start using the GPT-4 API in Python.
- Basic idea of Python programming language
- OpenAI account and API key: Simply create an account on openAI and they will provide you $18 worth of credits.
Code Section
Once you have generated the API key, Create a file and name it as gpt.py
and write the following code.
import openai
import os
openai.api_key = os.environ.get('OPENAI_API_KEY')
prompt = f"I am an AI language model."
def generate_response(user_input):
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": prompt},
{"role": "user", "content": user_input},
]
)
message = response.choices[0].message.content
return message
print("\n\nPython script to connect with GPT-4.\nTo exit, just type exit or press Ctrl + C\n\n")
while True:
user_input = input("User: ")
if user_input == "exit":
print("Conversation ended by user...")
break
gpt_response = generate_response(user_input)
print(f"GPT-4: {gpt_response}")
Code language: Python (python)
Let’s breakdown our code for better understanding.
- We are fetching our OpenAI API key from our env file. It is considered to be a healthy practise!
generate_response
function is the place where the interaction between user query and GPT-4 API takes place here. GPT-4 API has a particular format in which it understands the user query and responds back.- We have created a while loop so that user can interact with GPT-4 without re running the script again and again. To stop simply type in exit and the loop will break and the program will stop executing.
Run our code
To run our code, We simply need to run the python file by typing the command python gpt.py
in the terminal. Please make sure you are at the same path as that of the file otherwise you’ll get error like file not found.
In this step, we can connect with GPT-4 and have a conversation. However, it is currently unable to retain the previous conversation. We will be working on that problem in another article to see how developers are using it to develop new-age chatbots.
Happy coding Warriors!