Interact with ChatGPT via Python: Simple 1 Minute Setup ??
Konstantin Borimechkov
Senior Software Engineer at Tide | Intern To Senior In 3 Years ??
ChatGPT has gained significant popularity in recent months, and for good reason! It offers substantial value, and the best part is, it’s entirely FREE! In my view, it’s a valuable tool for anyone, especially engineers aiming to enhance their skills and productivity.
Given my interest in working with APIs, I decided to explore the process of connecting to OpenAI’s API and interacting with ChatGPT programmatically! ??
To my pleasant surprise (although, not entirely unexpected, given OpenAI reputation for having top-notch engineers ??), integrating the API into a Python script turned out to be a remarkably smooth process.
That’s why I wanted to share this experience with you!
So, enough with the chatter — let’s dive into the code! ????
Prerequisites
Python - refer to this DigitalOcean doc, if you don’t have it installed on your machine. If you have HomeBrew and you use Mac:
brew install python
openai library
pip3 install openai
An API Key for interacting with ChatGPT - get it for FREE from OpenAI’s website here (you would need to login to your account)
领英推荐
?? Let's do some coding ??
Firstly, run the pip command and install openai. Define the api_key like so ??
Secondly, let’s define a function that will call ChatGPT and give us the result in the command line ??
Finally, we will call this function with appropriate messages shown to the command line runner ??
Run the script and play with Mr. GPT! ??
?? Important to note is that once you sign-up for OpenAI, you will receive 5$ worth of credits that will expire in 3 months! You can use these credits to play around with the API, test it out and make a decision as to is it worth it!
The code for you to simply copy/paste ??
import openai
openai.api_key = "<your-api-key>"
def call_gpt(message):
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role":"user", "content": message}]
)
return response.choices[0].message.content.strip()
if __name__ == "__main__":
while True:
user_message = input("You: ")
if user_message.lower() in ["quit", "q", "exit", "bye"]:
break
print ("ChatGPT: ", call_gpt(user_message))
?? Just replace the <your-api-key> with the one you generated!
?? I hope you found this tutorial helpful! Build something awesome! ??
Here is OpenAI’s API documentation! There are a lot of endpoints to explore so feel free to do so and comment if you found something interesting! ??
Hey Konstantin Borimechkov, interested in creating custom LLM models with drag & drop components (with API export) ? Check out our platform intellithing.tech :) we are launching soon but you can drop us a message for quick access. ??