Caching OpenAI API Responses with Upstash Redis
If you used the OpenAI API, you might have noticed that it’s pretty slow and sometimes doesn’t even respond. Especially the GPT-4 model is prone to high latency responses. Also, you pay for every answer you get. Those are all reasons to avoid serving responses directly.
You can store your responses in Upstash Redis to get around these issues. If you’re serving the same response to many clients, this can save you quite some money, and with global deployments, you can be sure users get the info as quickly as possible.
This article will guide you through caching OpenAI API responses to an Upstash Redis database.
Features
We will build a web app showing visitors a list of history jokes.
- Query the OpenAI API daily to get a history joke related to the current date
- Cache the joke for future delivery
- Display all jokes
Technology
We will use the following technologies to build the app:
- Node.js as HTTP server
- The OpenAI API to generate history jokes
- Upstash QStash to trigger a new joke request from the HTTP server to the OpenAI API
- Upstash Redis to store the joke for later use
Prerequisites
- An OpenAI account with API access to get access to an AI
- An Upstash account to send the request to the OpenAI API and cache the AI responses in Upstash Redis
- A Node.js installation to call the OpenAI and Upstash APIs
Implementation
Let’s start by creating the HTTP server to fetch the jokes, store them in Upstash Redis, and display them to visitors.
Setting Up the Project
First, we create a new Node.js project and install the dependencies.
Implementing the Server
To implement the server, create an index.js
file and copy the following code into it:
Let’s go through the important parts of this code.
We use the redisClient
to save our responses into Upstash Redis and load them for display.
The qstashReceiver
is responsible for verifying the daily calls from Upstash QStash; this way, we ensure that only QStash calls our /generate
endpoint.
We use Axios to create a client for the OpenAI API, so we don’t have to pass the baseUrl
and Authentication
header whenever we call the API.
Next, we create an Express middleware that uses the qstashReceiver
to verify all requests to the /generate
endpoint. Since we use QStash only to trigger the endpoint and don’t pass any values, we can use an empty string as the body
.
Note: The middleware allows all requests if you un-comment the line with "
// return next()
". You can use this to test the/generate
endpoint onlocalhost
.
The /generate
endpoint listens for POST
requests and creates and stores the actual jokes. It calculates the current month
and day
and uses it to create two prompts for the AI. One tells the AI to behave like a comedian, and the second asks to tell a history joke about the current month and day.
We call the OpenAI API with the prompts and save the result into a LIST
in Upstash Redis.
The /
endpoint listens for GET
requests and displays the saved jokes. It loads the LIST
from Upstash Redis, formats it as HTML list elements, and sends it to the client.
Deployment
Now that the server is set up, we must create the cloud resources and fill in the API credentials to access them.
Creating a Credential File
To store the credentials, create a .env
file with the following content:
In the next steps, we will fill each of these empty strings.
Creating an OpenAI API Token
Let’s start with the OpenAI API because we only need a key for the existing API; we don’t have to deploy anything.
Go to the OpenAI web console and click the “create new secret key” button. Give the key a name, click “Create secret key”, copy the new key, and paste it into the .env file as the value of OPENAI_TOKEN
.
Deploying a Recurring Request with QStash
To tell QStash that it should send a request to the /generate
endpoint once a day, you use the “Request Builder”. You find it in the Upstash console. Figure 1 shows the configuration details.
Figure 1: QStash Request Builder
Replace the <HOSTNAME>
with the domain that hosts your server. You need a publicly accessible hostname for QStash to work.
You find the singing keys QStash uses in the Upstash console in the “Request Builder” section. Click on the grey “Singing Keys” drop-down, copy each key and paste them in the right places of the .env
file.
Deploying an Upstash Redis Database
To create an Upstash Redis database, go to the Upstash console and click the “Create Database” button.
This will prompt you with a dialog to fill in the database configuration. Figure 2 shows the values you should use.
Figure 2: Upstash Redis Configuration
After the creation is completed, you can scroll down to the “REST API” section, which has two buttons, “UPSTASH_REDIS_REST_URL” and “UPSTASH_REDIS_REST_TOKEN”. Click each of these buttons to copy the corresponding credentials and paste them into the correct place in the .env
file.
Testing the Website
To test the website on your local machine, deactivate the QStash validation middleware by un-commenting the “// return next()
” line in the index.js
file.
Run the server with the following command:
If you open the / route in the browser, you should only see “History Jokes for Every Day” since no jokes have been generated.
You must send a POST
request to the /generate
endpoint to generate a joke. You can do so with this command:
If you refresh the browser page, you should see a joke like in Figure 3.
Figure 3: Joke website
This joke is now cached in Upstash Redis, so no OpenAI API requests will happen when someone visits the website. This gives you sub-second response times while saving you quite some money.
Summary
AI APIs are versatile tools that will transform the Internet as we know it, but right now, they’re slow and expensive. Caching is vital when using these APIs, and Upstash Redis is the easiest way to add it to your stack with just a few clicks.