IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Developing AI Systems with the OpenAI API

Visualizza il corso

Istruzioni dell'esercizio

  • 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.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

# 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(____)
Modifica ed esegui il codice