管理 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 入门

¡Vamos a practicar!

Amazon Bedrock 入门

Preparing Video For Download...