Workshop context
Before this workshop
- In the last workshop, we set up the OpenAI Node SDK for our app and made a sample chat completion call.
This workshop
- In this workshop, we’ll create a chat completion to get colors (text and background) appropriate for the quote.
After this workshop
- In the next workshop, we’ll apply the colors to the UI when displaying the quote.
Workshop goal
By the end of this workshop, you will have an updated api/get-quote-styles route that:
- asks OpenAI to generate a background color appropriate for the text of the quote
- asks OpenAI to generate a text color that contrasts well with the background color
- returns both the quote text and the colors
Hints
Hint 1
Use JSON mode to request a JSON response (JSON responses are easy to parse).
Hint 2
It takes some experimentation to get the prompt right. I’d recommend reading OpenAI’s prompt engineering tips and then trying different prompts in the ChatGPT interface until you find a prompt that consistently produces the output you want.
The more spcific you are about the output you want, the better. For example, try specifying the exact keys you want in the JSON output, and specifying a format for the color. You might ask for a color that matches the “mood” of the quote.
It may seem difficult to figure out what to ask now; the more you play around with prompt engineering, the easier it will get.
Hint 3
In route.ts, try specifying two messages (click “show possible types” for details after following the link) for the chat completion request:
- a
system
message with instructions that would apply to any quote - a
user
message that supplies the specific quote for this request
Hint 4
For the role
value in the messages, you’ll have to add as const
after the value (for example: role: "system" as const
) to satisfy TypeScript. See this GitHub issue for more details.
Hint 5
To find a good constrasting text color, ask for “black” or “white” – whichever has the higher WCAG contrast ratio with the background color.
Hint 6
Add a color
object to the returned JSON. The color
object should have two keys: text
and background
. The JSON currently contains a quote
value, so the final return value will have both color
and quote
as the top-level properties.
You can access http://localhost:3000/api/get-quote-styles to see the JSON response. Keep in mind that every request to OpenAI costs (a very small amount of) money. You might want to keep an eye on your usage to make sure your monthly spend is not getting too high.
Resources
- OpenAI Prompt Engineering
- OpenAI Chat Completions JSON mode
- OpenAI chat completion request options
- OpenAI Node SDK GitHub issue that requires
as const
when defining a message role to avoid a confusingTypeError
. (See also the TypeScript docs on literal inference .) - MDN on contrast ratio