Wednesday, December 25, 2024
Google search engine
HomeLanguagesHow to Use ChatGPT API in Python?

How to Use ChatGPT API in Python?

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.

How to Use ChatGPT API in Python?

 

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

How to use ChatGPT API with 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.

Python3




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.

Python3




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.

Python3




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:

Python3




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 Lazyroar for Lazyroar’,’ 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:

FAQs

1. Can you use ChatGPT as an API?

Chat GPT API is now available for commercial and research purposes by Open Ai. To access it you need to follow these steps:

  • Create an account on OpenAI
  • After login, click on ‘Personal‘ and then click on ‘View API keys‘.
  • ‘Create new secret key’
  • Open any code editor
  • Import the Openai library and Store the key in a variable 
  • Follow the above steps 

2. Is ChatGPT provided for free?

Sure, Chat GPT is an Open Source application that is completely free for normal usage, anyone can use Chat GPT for an unlimited period of time on a particular day. There is a subscription to Chat GPT known as Chat GPT Plus which costs $20 per user monthly.

3. What is the difference between Chat GPT and ChatGPT API?

Basically, Chat GPT is an application that can be directly used by the user from the browser. Whereas, ChatGPT API is an Application Programming Interface that can be fetched using any programming language by developers in their code.

RELATED ARTICLES

Most Popular

Recent Comments