Skip to main content

How to use ChatGPT with Python

In our previous Python tutorial, we have explained how to Make ChatBot using Python. In this tutorial, we will explain how to use ChatGPT using Python.

ChatGPT is a popular artificial-intelligence(AI) chatbot developed by OpenAI. It’s developed on top of OpenAI’s GPT-3 language model for conversational language generation. The ChatGPT can be use for may purpose such as writing essays, stories, solve coding related problems, debugging code and all sorts of scripts etc.

Due to importance of ChatGPT, developers started thiinking about it to use in their applications. So no need to be panic about this, It’s really very easy to use ChatGPT in your Python applications.

So let’s proceed to use ChatGPT with Python.

Application Setup

We will create application directory chatgpt-python using below command.

$ mkdir chatgpt-python

we moved to the project direcotry

$ cd chatgpt-python

Install Required Module

We will use openai module to use ChatGPT API. We will install it using the below command

pip install openai

Use ChatGPT API with Python

After installing openai module. We will create Python file main.py and import openai module.

import openai

We will get OPENAI API key and pass to openai.api_key.

openai.api_key = "OPENAI_API_KEY"

We will get user input text to get answer text.

# Get user text
promptText = input("You: ")

We will setup API and pass the model engine.

modelEngine = "text-davinci-003"

We will make the API request by passing model engine and prompt text to make API request and get the response.

completion = openai.Completion.create(
    engine=modelEngine,
    prompt=promptText,
    max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5,
)

Finally, we will get the response and print it.

response = completion.choices[0].text
print(response)

Here is complete code of main.py file.

import openai

# Pass OpenAI API key
openai.api_key = "OPENAI_API_KEY"

# Get user text
promptText = input("You: ")

# Pass the model and prompt text
modelEngine = "text-davinci-003"

# Generate a response
completion = openai.Completion.create(
    engine=modelEngine,
    prompt=promptText,
    max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5,
)

# Get response and print it
response = completion.choices[0].text
print("Bot Say :", response)

Ouput: