สร้าง AI Chatbot
เพื่อให้ POC สมบูรณ์ ให้นำประวัติข้อความมาผสานกับลูป for เพื่อส่งคำถามซ้ำไปยังโมเดลได้หลายครั้ง โดยแต่ละคำตอบจะถูกบันทึกลงในประวัติข้อความตามลำดับ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทำงานกับ OpenAI API
คำแนะนำการฝึกหัด
- วนลูปผ่านข้อความของผู้ใช้ (
user_msgs) - สร้าง dictionary สำหรับข้อความผู้ใช้ในแต่ละรอบ แล้ว append เข้าไปใน
messages - ส่ง
messagesไปยังโมเดลผ่านคำขอแชท - Append dictionary ของข้อความ assistant เข้าไปใน
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")