開始使用免費開始

建立對話歷史

一家名為 Easy as Pi 的線上數學學習平台委託你協助開發 AI 家教。你立刻看出可以運用 OpenAI API 來打造這個應用,並開始為公司內部的主要利害關係人設計一個簡單的概念驗證(POC)。

首先,你要示範如何把對學生訊息的回應儲存在訊息歷史中,讓系統能進行完整的對話。

本練習屬於課程

Working with the OpenAI API

檢視課程

練習說明

  • 在聊天請求中將 messages 傳給模型。
  • response 擷取助理訊息,轉換為訊息字典,並將其加入 messages

動手互動練習

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

client = OpenAI(api_key="")

messages = [
    {"role": "system", "content": "You are a helpful math tutor that speaks concisely."},
    {"role": "user", "content": "Explain what pi is."}
]

# Send the chat messages to the model
response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=____,
    max_completion_tokens=100
)

# Extract the assistant message from the response
assistant_dict = {"role": "____", "content": ____}

# Add assistant_dict to the messages dictionary
messages.____(assistant_dict)
print(messages)
編輯並執行程式碼