開始使用免費開始

建立用於寫程式的推理聊天機器人

現在把前面學到的全部串起來,打造一個能協助寫程式的推理聊天機器人!

你會拿到兩則使用者訊息:第一則請求針對特定任務撰寫 Python 程式碼,第二則追問要求改用特定的函式庫撰寫。

V4-Pro 預設會推理,因此你只需要迴圈處理對話,並將正確的欄位附加到歷史紀錄即可。

本練習屬於課程

使用 Python 操作 DeepSeek

檢視課程

練習說明

  • 迴圈處理所有使用者問題。
  • 將每個使用者問題 q 傳送給 deepseek-ai/DeepSeek-V4.1-Flash 模型。
  • 將助理的最終答案(.content,不是推理過程)附加到 messages,讓對話歷史保持精簡。

動手互動練習

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

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

messages = []
user_msgs = ["Write some Python code to generate a list of numbers from 1-10.", "Update the code to use the NumPy library."]

# Loop over the user questions
for q in ____:
    print("User: ", q)
    user_dict = {"role": "user", "content": q}
    messages.append(user_dict)
    
    # Create the API request — V4-Pro reasons by default
    response = client.chat.completions.create(
        model="deepseek-ai/____",
        messages=____,
        max_tokens=500
    )
    
    # Append only the final answer to the conversation history
    assistant_dict = {"role": "assistant", "content": response.choices[0].message.____}
    messages.append(assistant_dict)
    print("Assistant: ", response.choices[0].message.content, "\n")
編輯並執行程式碼