Formatting model response as JSON
As a librarian cataloging new books, you aim to leverage the OpenAI API to automate the creation of a JSON file from text notes you received from a colleague. Your task is to extract relevant information such as book titles and authors and to do this, you use the OpenAI API to convert the text notes, that include book titles and authors, into structured JSON files.
In this and all the following exercises, the openai
library has already been loaded. Entering your own API key is not necessary to create requests and complete the exercises in this course; however, you may do so if you prefer.
This exercise is part of the course
Developing AI Systems with the OpenAI API
Exercise instructions
- Create an OpenAI API client.
- Create a request to the Chat Completions endpoint.
- Specify that the request should use the
json_object
response format. - Extract and print the model response.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create the OpenAI client
client = ____(api_key="")
# Create the request
response = ____(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "I have these notes with book titles and authors: New releases this week! The Beholders by Hester Musson, The Mystery Guest by Nita Prose. Please organize the titles and authors in a json file."}
],
# Specify the response format
____
)
# Print the response
print(____)