การจัดการบทสนทนา AI

Amazon Bedrock เบื้องต้น

Nikhil Rangarajan

Data Scientist

การจัดการสถานะบทสนทนาใน Bedrock

  • การจัดการบทสนทนา: สำคัญสำหรับการโต้ตอบ AI ที่เป็นธรรมชาติ
  • บริบทของบทสนทนา: ประกอบด้วยประวัติและ metadata
  • โมเดล Claude สามารถนำบริบทมาพิจารณาได้

ภาพประกอบแสดงวงกลมที่แต่ละวงแทนองค์ประกอบหนึ่งของบทสนทนา ได้แก่ ข้อความ ประวัติ และ metadata

Amazon Bedrock เบื้องต้น

การสร้างระบบจัดการบทสนทนา

  • คลาส ConversationManager จัดการฟังก์ชันหลักของบทสนทนา
  • ประวัติข้อความเก็บทั้งข้อความของผู้ใช้และ assistant พร้อม role
  • แนวทางที่มีโครงสร้างช่วยให้ขยายและดูแลรักษาได้ง่าย
class ConversationManager:

def __init__(self): self.bedrock = boto3.client('bedrock-runtime')
self.conversation_history = [] self.max_tokens = 8000
def add_message(self, role, content): self.conversation_history .append({"role": role,
"content": content
})
Amazon Bedrock เบื้องต้น

การใช้ ConversationManager ในทางปฏิบัติ

  • เพิ่มข้อความใหม่ลงในบันทึกบทสนทนา
  • บันทึก input ของผู้ใช้ไว้เสมอ
  • ช่วยให้โมเดลรักษาบริบทได้

 

conversation_manager = ConversationManager()
conversation_manager.add_message("user", "What's the weather like?")
Amazon Bedrock เบื้องต้น

การใช้ ConversationManager ในทางปฏิบัติ

  • จัดรูปแบบเป็นข้อความ
  • จำกัดปริมาณข้อความที่ส่ง
  • ส่งบทสนทนาที่จัดรูปแบบแล้วไปยังโมเดล
# Send the latest context to the model
conversation_history = conversation_manager.conversation_history
messages = "\n\n".join(
    f"{msg['role']}: {msg['content']}" 
    for msg in conversation_history[-2:]) # Only most recent exchanges


# Send the full message to the model response = conversation_manager.bedrock.invoke_model( modelId="amazon.nova-micro-v1:0", body=messages)
Amazon Bedrock เบื้องต้น

มาฝึกกันเถอะ!

Amazon Bedrock เบื้องต้น

Preparing Video For Download...