Using an API to calculate OpenAI tokens and pricing

Avi W
2 min readMay 29, 2023

--

Introduction

As developers are becoming more and more aware of the OpenAI API, there is something they have started to notice — the pricing is not that cheap and calculating the price for an API request is not easy.

With that said, a new service named AiPrice.dev allows you to implement their API easily and for free. AiPrice allows you to calculate how many tokens are being used and what the price is for those tokens. Is supports all OpenAI LLM models and the different types of requests.

AiPrice.dev homepage

Using the API

To start using the API, you can sign up for free by entering your email on the home page. You will then get an API key that you can use. For this example, we will use Python with the requests library to make the API calls. The full documentation can be viewed at the docs page.

After we have obtained the API key, lets test to see if it works by requesting our credit count at the credits endpoint:

import requests
API_ENDPOINT = "https://api.aiprice.dev"
API_KEY = "API_KEY_GOES_HERE"
headers = {"X-API-KEY": API_KEY}
content = requests.get(API_ENDPOINT + "/credits", headers=headers).json()
print(content) // {"credits": 50}

We can see we have 50 free credits! Let’s give it a shot by querying the /chat endpoint. For this example we will use the gpt-3.5-turbo model.

Let’s assume we wanted to calculate how many tokens were in the following text:

This is some text we would like to calculate. Let's see!

We would make the request as follows:

import requests
API_ENDPOINT = "https://api.aiprice.dev"
API_KEY = "API_KEY_GOES_HERE"
headers = {"X-API-KEY": API_KEY}
json_data = {"model": "gpt-3.5-turbo", "content": "This is some text we would like to calculate. Let's see!"}
content = requests.get(API_ENDPOINT + "/chat", json=json_data, headers=headers).json()
print(content) // {"price": 0.000028, "token_count": 14}

The price is in USD which means this prompt would cost $0.000028. The token count is 14.

Conclusions

Using the AiPrice API is super easy to integrate with any programming lanaguge and supports all models available by OpenAI. The pricing and token account is accurate and allows you to estimate your pricing before making a request to the OpenAI API.

You can get started for free without any credit card on their website at any time by just entering your email at — https://aiprice.dev.

--

--