Bắt đầu ngayBắt đầu miễn phí

Tạo một chatbot AI

Để hoàn thiện POC của bạn, bạn sẽ tích hợp lịch sử tin nhắn với một vòng lặp for, để có thể gửi nhiều lời nhắc lặp lại cho mô hình, và lần lượt lưu từng phản hồi vào lịch sử tin nhắn.

Bài tập này là một phần của khóa học

Làm việc với OpenAI API

Xem khóa học

Hướng dẫn bài tập

  • Lặp qua các tin nhắn của người dùng (user_msgs).
  • Ở mỗi vòng lặp, tạo một dictionary cho tin nhắn người dùng và thêm nó vào messages.
  • Gửi messages tới mô hình trong một yêu cầu chat.
  • Thêm dictionary tin nhắn của assistant vào messages.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

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")
Chỉnh sửa và Chạy Mã