Workshop context
Before this workshop
- In the previous series , we set up a route handler that returned a random quote, and contacted the route handler from the client.
This workshop
- This workshop will set up the OpenAI Node SDK in the route handler.
After this workshop
- In future workshops, we will use the OpenAI Node SDK to generate a color and font appropriate to the quote, and use those styles in the UI quote presentation. We’ll also correct grammar and genered language in the quote. An example of a styled quote in the final application:
Please note: The quotes in data/quotes.ts were assembled from Kaggle datasets , and do not necessarily reflect the views of the instructor.
Setup
Follow the setup instructions under “Getting started” in this GitHub repo README . Be sure to:
- clone or fork the repository
- generate an OpenAI API key
Workshop goal
By the end of this workshop you should have an updated route handler in src/app/api/get-quote-styles/route.ts that:
- contacts OpenAI via the Node SDK
- prints the OpenAI response to the terminal
Notes on the prompt:
- This workshop is about setting up the OpenAI Node SDK for the app. The actual prompt and response are not important for this workshop (we’ll get to the prompt / response for our app in the next workshop).
- You will want to send a prompt that will generate a short response, as longer output costs more .
- you can limit the response tokens with the max_tokens options
- A suggestion for a prompt to test your OpenAI SDK setup:
Describe <your favorite celebrity> in three words
(for example:Describe Dolly Parton in three words
)
Hints
Hint 1
You will need to install the OpenAI SDK; this package doesn’t come with the scaffolding project.
Hint 2
To make your OpenAPI key available as an environment variable:
- create a file at the top of your project called .env.local
- make sure this file is excluded from git in .gitignore
- Add a line to the .env.local file with these contents (replace
sk-proj-xxx
with your API key):
.env.local
Hint 3
You can add your OpenAI SDK code in src/app/api/get-quote-styles/route.ts. You’ll want to use the Chat Completions API . Here are some tips to get started:
- model your code on this example from the Usage docs.
- you might also look at this Chat Completions API example
- I recommend using
gpt-3.5-turbo
as the model . It’s inexpensive and plenty powerful for our app.
Hint 4
In the Chat Completions response , you can use completion.choices[0].message.content
to get the text response.
Hint 5
To trigger the route handler, start the server using (“npm run dev”), access http://localhost:3000 from a browser, and click the ‘use random quote’ button.
Alternatively, you could access the route handler URL directly from a browser: http://localhost:3000/api/get-quote-styles .
Resources
- OpenAI Node SDK
- OpenAI Chat Completions API example
- Open AI Chat Completions response format
- Next.js environment variables