AIの会話管理

Amazon Bedrock入門

Nikhil Rangarajan

Data Scientist

Bedrockでの会話状態管理

  • 会話管理: 自然で一貫したAI対話に必須
  • 会話コンテキスト: 履歴とメタデータを含む
  • Claudeは文脈を考慮可能

各要素(メッセージ、履歴、メタデータ)を示す円のイラスト。

Amazon Bedrock入門

会話管理の実装

  • ConversationManagerクラスが会話の中核機能を担当
  • メッセージ履歴はユーザー/アシスタント両方を役割付きで保存
  • 構造化により拡張性と保守性を確保
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の実践的な使い方

  • 新規メッセージを会話ログに追加
  • ユーザー入力を必ず記録
  • モデルが文脈を維持できるようにする

 

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...