创建 get_response() 函数
本课程的大多数练习都会使用用户提示调用 OpenAI API 的 chat.completions 端点。这里,您将创建一个 get_response() 函数,它接收一个提示作为输入,并返回模型的响应作为输出。在后续练习中,我们会为您预先加载它。
OpenAI 包和 OpenAI API 的 Python 客户端已预先加载。
本练习是课程的一部分
使用 OpenAI API 的 Prompt Engineering
练习说明
- 在
get_response()函数内向chat.completions端点发起请求。 - 使用一个提示来试运行该函数,请模型写一首关于 ChatGPT 的诗。
交互式实操练习
通过完成这段示例代码来试试这个练习。
def get_response(prompt):
# Create a request to the chat completions endpoint
response = client.____.____.____(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
temperature = 0)
return response.choices[0].message.content
# Test the function with your prompt
response = get_response("____")
print(response)