Using Python to connect with ChatGPTs API

Using Python to connect with ChatGPTs API

Original YouTube Logo

Article have related YouTube video

ChatGPT is the new big thing, and extremely powerful when connecting to it with a programming language. In this article i will show you how to make a request to ChatGPT's API using Python.

24-01-2023 |

Python
ChatGPT

To connect to ChatGPT using Python is very easy, just like a lot of other stuff in Python. All you need is the code in this article and the API key from OpenAI.com.

This code is in short importing the libraries requests and json. Saving an API key to the variable api_key. Making a post request to https://api.openai.com/v1/completions with a header that is the API key as a bearer token, telling it is json we send and making a json object with prompt, model and max_tokens inside.

prompt is the request text we want to send. Just like when typing it directly at ChatGPT's own website. This is what the model will make a response to.

model is the engine-model that we will connect to. In this moment the Da Vinci 003 is the most powerful model we can connect to, but also the most expensive.

max_token Token is roughly words you want in return of the request. When sending requests it cost money, and a 1000 token will be approx. 1000 words in return but to a cost of $0.02 with the Da Vinci 003 model. There is other models that is cheaper to connect to though, down to $0.0004 for 1000 tokens in return.

The last thing we do is to get the response text and then display the response value from the returned object. So we basically just print the response that we expected to come back out.

This is the response i got from my request using this code:

Using Python to connect to an API is an extremely easy and intuitive process. All that is necessary is to create an appropriate request, which can then be sent using the Python Requests library. Depending on the type of API, some other packages may be required, such as json for working with JSON data. After making the request, you can then access the returned data and use it as you desire.


Like what you see?


New C# Learning Area - Free!

Our website now offers a new section on C# theory, including code examples and related video tutorials.

ZetBit

Subscribe to ZetBits Newsletter