开始使用免费开始使用

添加防护栏

您正在开发一个为前往罗马的游客提供建议的聊天机器人。要求仅限讨论以下主题:餐饮、景点、历史,以及在城市里可以做的事。对于任何其他主题,聊天机器人应先致歉,并回复:"Apologies, but I am not allowed to discuss this topic."。

本练习是课程的一部分

使用 OpenAI API 构建 AI 系统

查看课程

练习说明

  • 使用给定的 user_request 编写一条 user 消息,并编写一条 system 消息,提示模型先评估问题:若允许则给出回复,否则返回消息:"Apologies, but I am not allowed to discuss this topic."。
  • 打印响应。

交互式实操练习

通过完成这段示例代码来试试这个练习。

client = OpenAI(api_key="")

user_request = "Can you recommend a good restaurant in Berlin?"

# Write the system and user message
messages = ____

response = client.chat.completions.create(
    model="gpt-4o-mini", messages=messages
)

# Print the response
____
编辑并运行代码