建立 get_response() 函式
本課程中大多數練習都會以使用者提示詞呼叫 OpenAI API 的 chat.completions 端點。這裡你將建立一個 get_response() 函式,接收一個提示詞作為輸入,並將回應作為輸出返回;在之後的練習中,這個函式會為你預先載入。
OpenAI 套件與 OpenAI API 的 Python 用戶端已預先載入。
本練習屬於課程
使用 OpenAI API 的提示工程
練習說明
- 在
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)