将模型响应格式化为 JSON
作为一名负责编目新书的图书管理员,您希望借助 OpenAI API,把同事提供的文本笔记自动转换为 JSON 文件。您的任务是提取书名、作者等关键信息。为此,您将使用 OpenAI API,把包含书名与作者的文本笔记转换为结构化的 JSON 文件。
在本题及后续所有练习中,openai 库已为您加载。在本课程中,您无需输入自己的 API 密钥即可发起请求并完成练习;当然,如果您愿意,也可以自行提供。
本练习是课程的一部分
使用 OpenAI API 构建 AI 系统
练习说明
- 创建一个 OpenAI API 客户端。
- 向 Chat Completions 端点创建请求。
- 指定该请求应使用
json_object响应格式。 - 提取并打印模型的响应。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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(____)