建立 AI 聊天機器人
為了完成你的 POC,你將把訊息歷程與 for 迴圈整合,這樣就能反覆將提示送給模型,並把每次的回應依序儲存在訊息歷程中。
本練習屬於課程
Working with the OpenAI API
練習說明
- 迭代使用者訊息(
user_msgs)。 - 在每次迭代中建立一個使用者訊息的字典,並將它加入
messages。 - 在聊天請求中將
messages送給模型。 - 將助理的訊息字典加入
messages。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
client = OpenAI(api_key="")
messages = [{"role": "system", "content": "You are a helpful math tutor that speaks concisely."}]
user_msgs = ["Explain what pi is.", "Summarize this in two bullet points."]
# Loop over the user questions
for q in ____:
print("User: ", q)
# Create a dictionary for the user message from q and append to messages
user_dict = {"role": ____, "content": ____}
messages.append(____)
# Create the API request
response = client.chat.completions.create(
model="gpt-4o-mini",
____,
max_completion_tokens=100
)
# Append the assistant's message to messages
assistant_dict = {"role": "assistant", "content": response.choices[0].message.content}
messages.append(____)
print("Assistant: ", response.choices[0].message.content, "\n")