ChatGPT API is not free, here's an alternative.
Tags: python, ai, chatgpt, programming
Published: 2023-09-04 17:37:35

If you have a natural curiosity, much like myself, you've probably always been eager to experiment with ChatGPT, I mean, to explore its capabilities by creating something with it.

> To get the API Key, developers need to log in to OpenAI’s website and select ‘View API Keys’. Although the API Key is not free, OpenAI provides a free credit of about $18 upon account creation. After the free credit expires, the cost is $0.002 per 1000 tokens. If the API Key is not working, it might be due to technical issues or the exhaustion of free tokens.

As a developer interested in utilizing the ChatGPT API, you need to obtain an API key which is available on OpenAI’s website, but unfortunately, it comes at a price. In this article, we’ll be discussing a very simple alternative I use instead of investing in OpenAI's API.

The OpenAI’s API was made available to developers on 1st of March 2023. At this time, they released a one month free trial to all API key holders where each user gets an $18.00 credit on their account which will be valid until 1st of April 2023. If you were able to benefit from the free trial, well congratulations to you, but I’m sure after the expiration date, your API key no longer works, and now you’re being asked to pay.

Interestingly, you can generate an API key for free. However, when you attempt to use it, you'll encounter a `rate limit reached` error, prompting you to purchase credits (a very clever selling strategy by OpenAI, lol 😁).

![OpenAI dashboard showing expired API credits](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dr1o6r1wrtro3jjh7wfk.png)

## What’s the way around this?
While searching for a cost-effective alternative to OpenAI's API, I came across numerous open-source ChatGPT alternatives. However, one particular option that caught my attention is GPT4Free.

## What is GPT4Free?
GPT4Free is a project developed by **xtekky** on GitHub, that has integrated the structure of ChatGPT to create a revolutionary, user-friendly platform. I won’t take too much time giving details about the project,  you can check it out the GitHub repository [here](https://github.com/xtekky/gpt4free).

### How to use GPT4free.
Now, let's delve into the coding part of this article. We'll write a basic Python script to illustrate how you can integrate GPT4Free into your upcoming project.

There are two ways to this;

- You can clone the GitHub repository, set up a virtual environment, and create your Python script. 

- Or you can simply install the official GPT4Free Python package.

However, for the purposes of this tutorial, we will utilize the second option, so, lets go!

First and foremost, let's create a virtual environment. I can't emphasize enough how crucial it is to establish a virtual environment for your Python projects. It aids in isolating your project's dependencies from your system's global dependencies.

```py
# On macOS and Linux
$ python3 -m venv env

# On windows
$ python -m venv env
```

Now that we have our virtual environment setup, lets activate it
```py
# On macOS and Linux
$ source venv/bin/activate

# On windows
$ .\venv\Scripts\activate
```
Now, it’s time to install the gpt4free package `g4f`
```
$ pip install g4f
```

Once the package is done installing, create a new file, I'll name mine `gpt4free.py`

```py
import g4f

messages = []

while True:
    userInput = input("\nUser: ")
    messages.append({"role": "user", "content": userInput})

    response = g4f.ChatCompletion.create(
        model=g4f.models.gpt_4,
        provider=g4f.Provider.DeepAi,
        messages=messages,
    )

    print(f"\n{response}")
```

Now, let's break the code down.

Firstly, we imported the `g4f` package that we installed earlier. Then, we created a `messages` list to hold the message, which will serve as a parameter for the `create` function from `g4f`.

Next, we established a `while` loop. Although this step isn't strictly necessary, it only allows us to continue a chat with the chosen model.

We then request `user input`, which will serve as the prompt for the model. This input is added to the `messages` list.

Afterward, we invoke `g4f.ChatCompletion.create` with three parameters:

1. `model`: this parameter specifies the model to be used for the chat. `g4f` supports various models, and in this example, we selected the `gpt_4` model. You can find other supported models on the official GitHub page.

2. `provider`: here, we specify the provider to be used for this chat. Multiple providers are available, including `OpenaiChat`, `Bard`, `Bing`, and others. In this case, we've chosen `DeepAi`. 
**Note**: Not all providers may be operational, you can refer to the GitHub page for additional information.)
3. `messages`: this parameter takes our `messages` list.

Finally, we `print` the response received.

**Let’s run our code.**

```py
# On macOS and Linux
$ python3 gpt4free.py

# On windows
$ python gpt4free.py
```
The result;

```
(env) C:\Users\hameed\ai_test>python gpt4free.py

User: give me 5 tips to become a better developer

1. Continuous Learning: Technology is constantly evolving and as a developer, you should always be striving to learn new things. Take advantage of resources like online courses, tutorials, and other learning
materials to keep yourself up-to-date with the latest trends and best practices.

2. Write Clean and Efficient Code: Writing clean and efficient code is essential for becoming a good developer. This ensures that your code is easy to read, understand, modify, and maintain. Keep in mind the
SOLID principles and try to implement them in your code.

3. Collaborate with other Developers: Working with other developers on projects or open source repositories can provide valuable feedback, guidance, and help you learn from their experience. Consider joining
local developer groups or attending meetups to collaborate and learn from others in the industry.  	 

4. Adopt Best Practices: Adopting best practices for software development can improve the quality of your code and development process. Learn about software development methodologies, testing frameworks, and
version control to help ensure your code meets quality standards.

5. Experiment with New Technologies: Experimenting with new technologies and frameworks allows you to expand your knowledge and skill set as a developer. This helps you stay ahead of the curve and stay relevant in the ever-changing industry. Keep experimenting with new technologies and implementing interesting
concepts.


User: give me 3 more extra tips


Sure, here are three extra tips to become a better developer:

1. Practice regularly: Just like any skill, programming requires consistent practice to develop. Regular coding exercises and personal projects help you to learn new concepts and apply what you've learned in
practical settings.

2. Learn from others: Joining online communities, attending meetups and conferences, and collaborating with fellow developers will expose you to new ideas and perspectives. Learn from experienced developers and seek their feedback on your code.

3. Keep up with evolving technology: Technology is constantly evolving, and being able to stay up-to-date with new trends and tools is vital in the tech industry. Participate in online forums and subscribe to tech blogs and newsletters to stay informed about the latest developments in your field.

User: Traceback (most recent call last):
  File "C:\Users\USER\Desktop\CRAP\ai_test\test_g4f.py", line 7, in <module>
	userInput = input("\nUser: ")
KeyboardInterrupt
^C
(env) C:\Users\hameed\ai_test>
```

**Wow, amazing isn't it?**

We first got a prompt asking us to enter an input (exactly what we asked the python script to do earlier), which I asked it to "give me 5 tips to become a better developer", then on clicking enter, our input was submitted to the `g4f` chat completion model, then **voila!!!**, we got our response printed out. I even went ahead to ask it to give me three more, and it did. Then finally exit the while loop using `CTRL + c`.

## Conclusion.
Now that you have the power of using AI in any of your projects, feel free to explore more possibilities with the g4f package. Keep building amazing projects.

Happy coding ✨.