

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 存储会话中的对话历史记录和上下文
<a name="sessions-store-coversation"></a>

创建会话后，使用 [CreateInvocation](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_CreateInvocation.html)API 在会话中创建一组互动。对于每个分组，使用 [PutInvocationStep](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_PutInvocationStep.html)API 操作存储每个交互的状态检查点，包括文本和图像。

如何组织调用中的调用步骤取决于您的使用案例。例如，如果您提供代理来帮助客户预订旅行行程，那么调用和调用步骤可能如下所示：
+ 调用可以用来对源自对话的文本进行分组，在该对话中，代理与客户核实特定酒店在不同日期的空房情况。
+ 每个调用步骤可以是代理与用户之间的每条消息，以及代理为检索空房而采取的每个步骤。

在您[PutInvocationStep](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_PutInvocationStep.html)的 API 中，您可以导入与对话相关的图像。
+ 您最多可以包含 20 个图像。每个图像的大小、高度和宽度必须分别不超过 3.75 MB、8000 像素和 8000 像素。
+ 您可以导入以下类型的图像：
  + PNG
  + JPEG
  + GIF
  + WEBP

**Topics**
+ [CreateInvocation 示例](#session-create-invocation)
+ [PutInvocationSteps 示例](#session-put-invocation-step)

## CreateInvocation 示例
<a name="session-create-invocation"></a>

以下代码示例说明如何使用 适用于 Python (Boto3) 的 AWS SDK将调用添加到活动会话。对于 `sessionIdentifier`，您可以指定会话的 sessionId 或其 Amazon 资源名称（ARN）。有关 API 的更多信息，请参阅 [CreateInvocation](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_CreateInvocation.html)。

```
def create_invocation(session_identifier):
try:
    invocationId = client.create_invocation(
        sessionIdentifier=session_identifier,
        description="User asking about weather in Seattle",
        invocationId="12345abc-1234-abcd-1234-abcdef123456"
    )["invocationId"]
    print("invocation created")
    return invocationId
except ClientError as e:
    print(f"Error: {e}")
```

## PutInvocationSteps 示例
<a name="session-put-invocation-step"></a>

以下代码示例说明如何使用 适用于 Python (Boto3) 的 AWS SDK将调用步骤添加到活动会话。代码从工作目录中将文本和图像添加进来。对于 `sessionIdentifier`，您可以指定会话的 sessionId 或其 Amazon 资源名称（ARN）。对于调用标识符，请指定要将调用步骤添加到的调用的唯一标识符（采用 UUID 格式）。有关 API 的更多信息，请参阅 [PutInvocationStep](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_PutInvocationStep.html)。

```
def put_invocation_step(invocation_identifier, session_identifier):
with open('weather.png', 'rb') as image_file:
    weather_image = image_file.read()

try:
    client.put_invocation_step(
        sessionIdentifier=session_identifier,
        invocationIdentifier=invocation_identifier,
        invocationStepId="12345abc-1234-abcd-1234-abcdef123456",
        invocationStepTime="2023-08-08T12:00:00Z",
        payload={
            'contentBlocks': [
                {
                    'text': 'What\'s the weather in Seattle?',

                },
                {
                    'image': {
                        'format': 'png',
                        'source': {'bytes': weather_image}
                    }
                }

            ]
        }
    )
    print("invocation step created")
except ClientError as e:
    print(f"Error: {e}")
```