Tạo chatbot AI
Để hoàn tất POC của bạn, bạn sẽ tích hợp lịch sử hội thoại với một vòng lặp for, để có thể gửi nhiều prompt lặp lại tới mô hình, và lưu từng phản hồi vào lịch sử hội thoại theo thứ tự.
Bài tập này là một phần của khóa học
Làm việc với DeepSeek bằng Python
Hướng dẫn bài tập
- Lặp qua các tin nhắn của người dùng (
user_msgs). - Tạo một dictionary cho tin nhắn người dùng ở mỗi vòng lặp và nối nó vào
messages. - Gửi
messagestới mô hình trong một yêu cầu chat. - Nối 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="", 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-V3",
____,
max_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")