MulaiMulai sekarang secara 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.

Latihan ini adalah bagian dari kursus

Developing AI Systems with the OpenAI API

Lihat Kursus

Petunjuk latihan

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

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# 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(____)
Edit dan Jalankan Kode