Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
OpenAI Whisper
Next article icon

How to Use ChatGPT API in Python?

Last Updated : 21 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

ChatGPT and its inevitable applications. Day by Day everything around us seems to be getting automated by several AI models using different AI and Machine learning techniques and Chatbot with Python , there are numerous uses of Chat GPT and one of its useful applications we will be discussing today. So, before moving to its application let's know a little about what Chat GPT is.

ChatGPT is developed by OpenAI . It is a large language model based on the GPT-3.5 architecture. It is a type of AI chatbot that can take input from users and generate solutions similar to humans. ChatGPT is well trained AI that is trained on a large dataset , using that training it can able to perform a wide range of tasks. It is designed to simulate a conversation with a human, making it a valuable tool for customer service, personal assistants, and other applications where natural language processing is required. There are several applications of Chat GPT such as Content Creation , Customer Service , Assistance , and Automation .

To learn more about ChatGPT and explore its applications, you might also be interested in deepening your understanding of Python, which is essential for working with APIs. For a solid foundation in Python, consider the comprehensive Python Foundation Course offered by us. This course covers all the basics and advanced concepts necessary to become proficient in Python, making it an invaluable resource for both beginners and experienced developers.

How to use ChatGPT API with Python?

How to Use ChatGPT API in Python?

Here we are going to see all steps required to use ChatGPT API in Python . Using ChatGPT API we are able to use the features of ChatGPT using Python code which means we are not required to go to the site of ChatGPT to ask any questions.

Step 1: Create an account on OpenAI and log into an account.

Step 2: After login click on ' Personal ' on the top-right side and then click on ' View API keys ' as seen in the below image.

View API Keys

Step 3: After following step 2 a page of API keys is opened and we can see the button 'Create new secret key' click on that and a secret key is generated copy that key and save it on Notepad or anywhere else because it is required in upcoming steps.

API key generated

Step 4: Now, open any code editor or online notebooks such as Google Colab or Jupyter Notebook . Here, we are using Google Colab notebook and installing the Open Ai library in Python using the below command.

!pip install -q openai

If you are using any other code editor you can install the openai library in Python by executing the below command in the terminal or command prompt.

pip install openai

Step 5: Import openai library and Store the key in a variable that we have generated in Step 3 as given below.

Python
import openai  openai.my_api_key = 'YOUR_API_KEY' 

Step 6: Set a context for the ChatGPT API that is used to tell the API what is it supposed to do using the JSON file. In this, we have defined the role as a system because we are creating this for users and this ChatGPT is a system and also defined the content.

Python
messages = [ {"role": "system", "content": "You are a intelligent assistant."} ] 

Step 7: Here is the rest of the code where

  • We are using an infinite while loop so that we can chat with the ChatGPT API repeatedly without executing the code again and again.
  • In the second line we a taking input from the user and store it in a variable 'message'.
  • If a user inputs any question then only we enter the if condition and make a JSON of file and append it to the JSON file that we have created in step 6 after that generate the chat using openai.ChatCompletion.create()
  • Store the answer in the variable 'reply' and print that reply using the print() function.
Python
while True:     message = input("User : ")     if message:         messages.append(             {"role": "user", "content": message},         )         chat = openai.ChatCompletion.create(             model="gpt-3.5-turbo", messages=messages         )          reply = chat.choices[0].message.content     print(f"ChatGPT: {reply}")     messages.append({"role": "assistant", "content": reply}) 

Below is the Complete Implementation :

Python
import openai openai.api_key = 'YOUR_API_KEY' messages = [ {"role": "system", "content":                "You are a intelligent assistant."} ] while True:     message = input("User : ")     if message:         messages.append(             {"role": "user", "content": message},         )         chat = openai.ChatCompletion.create(             model="gpt-3.5-turbo", messages=messages         )     reply = chat.choices[0].message.content     print(f"ChatGPT: {reply}")     messages.append({"role": "assistant", "content": reply}) 

Output: After running the above code we have to input any query as in the below output query is 'What is geeks for geeks',' Which is best DSA course on gfg ' and we are getting the output from ChatGPT and as the while loop is infinite it again asks input from the user.

OpenAI API With Python
OpenAI API with Python

ChatGPT Output:

We can also check the output from OpenAI (Chatgpt) it will same as our Python code output.

Chat GPT output

Conclusion

We covered several steps in the whole article for integrating ChatGPT API using Python which would definitely help you in successfully achieving the final outcome. There are countless uses of Chat GPT of which some we are aware and some we aren't.

To learn more about Chat GPT, you can refer to:

  • ChatGPT vs Google BARD

Next Article
OpenAI Whisper
author
sagar99
Improve
Article Tags :
  • Python
  • ChatGPT
  • AI Chatbot
Practice Tags :
  • python

Similar Reads

  • OpenAI Python API - Complete Guide
    OpenAI is the leading company in the field of AI. With the public release of software like ChatGPT, DALL-E, GPT-3, and Whisper, the company has taken the entire AI industry by storm. Everyone has incorporated ChatGPT to do their work more efficiently and those who failed to do so have lost their job
    15+ min read
  • Extract keywords from text with ChatGPT
    In this article, we will learn how to extract keywords from text with ChatGPT using Python. ChatGPT is developed by OpenAI. It is an extensive language model based on the GPT-3.5 architecture. It is a type of AI chatbot that can take input from users and generate solutions similar to humans. ChatGPT
    4 min read
  • Pandas AI: The Generative AI Python Library
    In the age of AI, many of our tasks have been automated especially after the launch of ChatGPT. One such tool that uses the power of ChatGPT to ease data manipulation task in Python is PandasAI. It leverages the power of ChatGPT to generate Python code and executes it. The output of the generated co
    9 min read
  • Text Manipulation using OpenAI
    Open AI is a leading organization in the field of Artificial Intelligence and Machine Learning, they have provided the developers with state-of-the-art innovations like ChatGPT, WhisperAI, DALL-E, and many more to work on the vast unstructured data available. For text manipulation, OpenAI has compil
    11 min read
  • OpenAI Whisper
    In today's time, data is available in many forms, like tables, images, text, audio, or video. We use this data to gain insights and make predictions for certain events using various machine learning and deep learning techniques. There are many techniques that help us work on tables, images, texts, a
    9 min read
  • Spam Classification using OpenAI
    The majority of people in today's society own a mobile phone, and they all frequently get communications (SMS/email) on their phones. But the key point is that some of the messages you get may be spam, with very few being genuine or important interactions. You may be tricked into providing your pers
    6 min read
  • How to Use chatgpt on Linux
    OpenAI has developed an AI-powered chatbot named `ChatGPT`, which is used by users to have their answers to questions and queries. One can access ChatGPT on searchingness easily. But some users want to access this chatbot on their Linux System. It can be accessed as a Desktop application on Ubuntu o
    6 min read
  • PandasAI Library from OpenAI
    We spend a lot of time editing, cleaning, and analyzing data using various methodologies in today's data-driven environment. Pandas is a well-known Python module that aids with data manipulation. It keeps data in structures known as dataframes and enables you to alter, clean up, or analyze data by c
    9 min read
  • ChatGPT Prompt to get Datasets for Machine Learning
    With the development of machine learning, access to high-quality datasets is becoming increasingly important. Datasets are crucial for assessing the accuracy and effectiveness of the final model, which is a prerequisite for any machine learning project. In this article, we'll learn how to use a Chat
    7 min read
  • How To Implement ChatGPT In Django
    Integrating ChatGPT into a Django application allows you to create dynamic and interactive chat interfaces. By following the steps outlined in this article, you can implement ChatGPT in your Django project and provide users with engaging conversational experiences. Experiment with different prompts,
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences