ChatGPT clone with OpenAi API

Omar Mohammad
2 min readApr 10, 2023

--

ChatGPT clone
!pip install - upgrade pip
!pip install openai

Create an account on beta.openai.com and generate an api key. Save the api key in a variable as follows:-

OPENAI_API_KEY = "**********************************************"

Import the OpenAI library and set the API key required to access OpenAI resources.

import openai
openai.api_key = OPENAI_API_KEY

Define a function named “chat” that uses the GPT-3.5 model to generate a response to a user’s question. The consolidated code should look like as follows:-

import openai
OPENAI_API_KEY = "**********************************************"
openai.api_key = OPENAI_API_KEY

def chat(question):
response = openai.ChatCompletion.create(
model = "gpt-3.5-turbo",
messages = [
{
"role": "user",
"content": question
}
]
)

return response

Save the response in a variable and print it as follows.

response = chat("Write a poem on Python's zen ?")
answer = response.choices[0].message.content
print(answer)

Python’s zen is a thing of grace,

A philosophy birthed in code’s embrace,

A set of rules to guide a way,

Ensuring elegance in every display.

This language of Monty’s creation,

A designer’s tool for exploration,

Embraces simplicity with ease,

Granting power to code with breeze.

It teaches us to strive for clarity,

In our coding, in our proclivity,

To craft programs that are readable,

Ensuring they’re reusable, and not disposable.

Beautiful code is art in motion,

And Python’s zen is the ultimate potion,

To bring forth the best in our design,

And write solutions that are sublime.

So let’s embrace the Python way,

And code with grace and skill each day,

For Python’s zen is the heart of it all,

And its magic weaves a lasting thrall.

--

--

Omar Mohammad

Full Stack Software Developer - Blockchain Solution Architect