開始使用免費開始

建立 AI 聊天機器人

為了完成你的 POC,你將把訊息歷史與 for 迴圈整合,這樣就能重複將提示送到模型,並將每次的回應依序儲存在訊息歷史中。

本練習屬於課程

使用 Python 操作 DeepSeek

檢視課程

練習說明

  • 針對使用者訊息(user_msgs)進行迴圈。
  • 在每次迭代中建立該使用者訊息的字典,並將其加入 messages
  • 在聊天請求中將 messages 傳送給模型。
  • 將助理的訊息字典加入 messages

動手互動練習

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

client = OpenAI(api_key="", base_url="https://api.together.xyz/v1")

messages = [{"role": "system", "content": "You are a helpful math tutor that generates concise, one-sentence responses."}]
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="deepseek-ai/DeepSeek-V4.1-Flash",
        ____,
        max_tokens=500
    )
    
    # 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")
編輯並執行程式碼