開始使用免費開始

建立雙提示的 get_response() 函式

接下來的練習會以兩個提示詞(system 提示與 user 提示)呼叫 OpenAI API 的 chat.completions 端點。為了準備這件事,在本練習中你將建立一個雙提示的 get_response() 函式,接收兩個提示詞作為輸入(system_promptuser_prompt),並回傳模型的回應作為輸出。接著,將這個函式套用到你自行選擇的任何範例上。

OpenAI 套件已為你預先載入。

本練習屬於課程

使用 OpenAI API 的提示工程

檢視課程

練習說明

  • messages 清單中為每則訊息指定角色與內容。
  • 傳入你選擇的 system_promptuser_prompt,試用這個函式。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

client = OpenAI(api_key="")

def get_response(system_prompt, user_prompt):
  # Assign the role and content for each message
  messages = [{"role": ____, "content": ____},
      		  {"role": ____, "content": ____}]  
  response = client.chat.completions.create(
      model="gpt-4o-mini", messages= messages, temperature=0)
  
  return response.choices[0].message.content

# Try the function with a system and user prompts of your choice 
response = get_response("____", "____")
print(response)
編輯並執行程式碼