讓對話具備記憶能力
在 ChargeNet 繼續開發 ChargeBot 時,你將把每一輪對話都保存下來,並只將最新的訊息發送給 Claude,以透過 Amazon Bedrock 的 Claude 模型維持對話脈絡。這個機器人會管理訊息歷程,並用 Claude 能理解的格式來組織對話,只使用最新的脈絡。
boto3 與 json 函式庫,以及你在前一個練習中定義的 ConversationManager 類別,都已預先載入。
本練習屬於課程
Amazon Bedrock 入門
練習說明
- 使用
add_message()方法來儲存使用者輸入。 - 只將歷程中最後兩則訊息,依正確的訊息格式發送給 Claude。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
conversation = ConversationManager()
user_input = "What is the charging speed of your Highway Max station?"
# Add the user input
conversation.____
# Send only the last two messages from conversation history
messages = ____
request_body = json.dumps({"anthropic_version": "bedrock-2023-05-31", "max_tokens": 200, "temperature": 0.2, "messages": messages})
response = conversation.bedrock.invoke_model(modelId="us.anthropic.claude-sonnet-4-5-20250929-v1:0", body=request_body)
completion = json.loads(response['body'].read().decode())["content"][0]["text"]
conversation.add_message("assistant", completion)
print(completion)