

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

# 控制代理会话上下文
<a name="agents-session-state"></a>

为了更好地控制会话上下文，您可以修改代理中的 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_SessionState.html#bedrock-Type-agent-runtime_SessionState](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_SessionState.html#bedrock-Type-agent-runtime_SessionState) 对象。[https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_SessionState.html#bedrock-Type-agent-runtime_SessionState](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_SessionState.html#bedrock-Type-agent-runtime_SessionState) 对象包含可以跨多个回合维护的信息（单独的 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 请求和响应）。在用户对话过程中，您可以利用这些信息为代理提供对话上下文。

[https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_SessionState.html#bedrock-Type-agent-runtime_SessionState](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_SessionState.html#bedrock-Type-agent-runtime_SessionState) 对象的一般格式如下。

```
{
    "sessionAttributes": {
        "{{<attributeName1>}}": "{{<attributeValue1>"}},
        "{{<attributeName2>}}": "{{<attributeValue2>"}},
        ...
    },
     "conversationHistory": {
          "messages": [{
              "role": "user | assistant",
              "content": [{
                  "text": "string"
              }]
          }],
               },
    "promptSessionAttributes": {
        "{{<attributeName3>}}": "{{<attributeValue3>"}},
        "{{<attributeName4>}}": "{{<attributeValue4>"}},
        ...
    },
    "invocationId": "string",
    "returnControlInvocationResults": [
        [ApiResult](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_ApiResult.html) or [FunctionResult](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_FunctionResult.html),
        ...
    ],
    "knowledgeBases": [
       {
        "knowledgeBaseId": "string",
        "retrievalConfiguration": {
            "vectorSearchConfiguration": {
                "overrideSearchType": "HYBRID | SEMANTIC",
                "numberOfResults": int,
                "filter": [RetrievalFilter](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RetrievalFilter.html) object
            }
        }
       },
       ...
    ]
}
```

选择一个主题，进一步了解 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_SessionState.html#bedrock-Type-agent-runtime_SessionState](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_SessionState.html#bedrock-Type-agent-runtime_SessionState) 对象中的字段。

**Topics**
+ [会话和提示会话属性](#session-state-attributes)
+ [会话属性示例](#session-attribute-ex)
+ [提示会话属性示例](#prompt-session-attribute-ex)
+ [操作组调用结果](#session-state-return-control)
+ [知识库检索配置](#session-state-kb)

## 会话和提示会话属性
<a name="session-state-attributes"></a>

Amazon Bedrock 代理让您能够定义以下类型的上下文属性，这些属性将在会话的不同部分中持续存在：
+ **sessionAttributes** – 在用户和代理之间的[会话](advanced-prompts.md#advanced-prompts-terminology)期间持续存在的属性。只要未超过会话时间限制（即 `idleSessionTTLinSeconds`），所有使用相同 `sessionId` 发出的 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 请求都属于同一会话。
+ **conversationHistory** – 对于多代理协作，如果为协作者代理启用了 `conversationalHistorySharing` 功能，则接受用于处理运行时请求的其他上下文。默认情况下，该字段由主管代理在调用协作者代理时自动构建。您可以选择使用此字段来提供其他上下文。有关更多信息，请参阅 [结合使用多代理协作与 Amazon Bedrock 代理](agents-multi-agent-collaboration.md)。
+ **promptSessionAttributes** – 在一个[回合](advanced-prompts.md#advanced-prompts-terminology)（即一次 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 调用）中持续存在的属性。在编辑编排基础提示模板时，您可以使用 $prompt\_session\_attributes$ [占位符](prompt-placeholders.md)。系统将在运行时使用您在 `promptSessionAttributes` 字段中指定的属性来填充该占位符。

您可以在两个不同的步骤中定义会话状态属性：
+ 当您设置操作组并[编写 Lambda 函数](agents-lambda.md)时，将 `sessionAttributes` 或 `promptSessionAttributes` 包含在返回给 Amazon Bedrock 的[响应事件](agents-lambda.md#agents-lambda-response)中。
+ 在运行时，当您发送 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 请求时，将 `sessionState` 对象包含在请求正文中，以便在对话中动态地更改会话状态属性。

## 会话属性示例
<a name="session-attribute-ex"></a>

以下示例使用会话属性对发送给用户的消息进行个性化设置。

1. 编写您的应用程序代码，要求用户提供他们的名字和他们想要向代理发出的请求，并将答案存储为变量 {{<first\_name>}} 和 {{<request>}}。

1. 编写您的应用程序代码，发送带有以下正文的 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 请求：

   ```
   {
       "inputText": "{{<request>}}",
       "sessionState": {
           "sessionAttributes": {
               "firstName": "{{<first_name>}}"
           }
       }
   }
   ```

1. 当用户使用您的应用程序并提供他们的名字时，您的代码将发送名字作为会话属性，代理将在[会话](advanced-prompts.md#advanced-prompts-terminology)期间存储他们的名字。

1. 由于会话属性是在 [Lambda 输入事件](agents-lambda.md#agents-lambda-input)中发送的，因此您可以在 Lambda 函数中引用这些会话属性，以供操作组使用。例如，如果操作 [API 架构](agents-api-schema.md)要求在请求正文中使用名字，那么您可以在编写操作组的 Lambda 函数时使用 `firstName` 会话属性，以便在发送 API 请求时自动填充该字段。

## 提示会话属性示例
<a name="prompt-session-attribute-ex"></a>

以下一般示例使用提示会话属性为代理提供时间上下文。

1. 编写应用程序代码，将用户请求存储在名为 {{<request>}} 的变量中。

1. 编写应用程序代码，如果用户在 {{<request>}} 中使用了表示相对时间的词语（例如“明天”），则检索用户所在位置的时区，并将其存储在一个名为 {{<timezone>}} 的变量中。

1. 编写应用程序，发送带有以下正文的 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 请求：

   ```
   {
       "inputText": "{{<request>}}",
       "sessionState": {
           "promptSessionAttributes": {
               "timeZone": "{{<timezone>}}"
           }
       }
   }
   ```

1. 如果用户使用表示相对时间的词语，您的代码将发送 `timeZone` 提示会话属性，代理会在[回合](advanced-prompts.md#advanced-prompts-terminology)内将其存储。

1. 例如，如果用户询问 **I need to book a hotel for tomorrow**，您的代码会将用户的时区发送给代理，代理可以确定“明天”所指的确切日期。

1. 您可以在以下步骤中使用提示会话属性。
   + 如果您在编排提示模板中包含 $prompt\_session\_attributes$ [占位符](prompt-placeholders.md)，则发送给 FM 的编排提示将包含提示会话属性。
   + 提示会话属性在 [Lambda 输入事件](agents-lambda.md#agents-lambda-input)中发送，可以用于帮助填充 API 请求或在[响应](agents-lambda.md#agents-lambda-response)中返回。

## 操作组调用结果
<a name="session-state-return-control"></a>

如果您将操作组配置为[在 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 响应中交还控制权](agents-returncontrol.md)，则可以通过包含以下字段，在后续 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 响应的 `sessionState` 中发送调用操作组的结果：
+ `invocationId` – 此 ID 必须与 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 响应中的 `returnControl` 字段的 [ReturnControlPayload](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_ReturnControlPayload.html) 对象中返回的 `invocationId` 一致。
+ `returnControlInvocationResults` – 包含通过调用操作获得的结果。您可以将应用程序设置为传递 [ReturnControlPayload](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_ReturnControlPayload.html) 对象，以便执行 API 请求或调用您定义的函数。然后，您可以在此处提供该操作的结果。`returnControlInvocationResults` 列表中的每一项都是以下几项之一：
  + 一个 [ApiResult](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_ApiResult.html) 对象，其中包含代理在之前的 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 流程中预测应该调用的 API 操作，以及在您的系统中调用该操作后的结果。一般格式如下：

    ```
    {
        "actionGroup": "string",
        "agentId" : :string",
        "apiPath": "string",
        "confirmationState" : "CONFIRM | DENY",
        "httpMethod": "string",
        "httpStatusCode": integer,
        "responseBody": {
            "TEXT": {
                "body": "string"
            }
        }
    }
    ```
  + 一个 [FunctionResult](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_FunctionResult.html) 对象，其中包含代理在之前的 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 流程中预测应该调用的函数，以及在您的系统中调用该操作后的结果。一般格式如下：

    ```
    {
        "actionGroup": "string",
        "agentId" : :string",
        "confirmationState" : "CONFIRM | DENY",
        "function": "string",
        "responseBody": {
            "TEXT": {
                "body": "string"
            }
        }
    }
    ```

系统提供的结果可用作进一步编排的上下文，发送到后处理阶段，以便代理对响应进行格式化，或者直接用于代理对用户的响应。

## 知识库检索配置
<a name="session-state-kb"></a>

要修改附加到代理的知识库的检索配置，您需要在 `knowledgeBaseConfigurations` 字段中包含要指定其配置的每个知识库的配置列表。请指定 `knowledgeBaseId`。在 `vectorSearchConfiguration` 字段中，您可以指定以下查询配置（有关这些配置的更多信息，请参阅[配置和自定义查询与响应生成](kb-test-config.md)）：
+ **搜索类型** – 知识库是仅搜索向量嵌入（`SEMANTIC`）还是同时搜索向量嵌入和原始文本（`HYBRID`）。使用 `overrideSearchType` 字段。
+ **最大检索结果数量** – 要在响应中使用的查询检索结果的最大数量。
+ **元数据和筛选** – 您可以配置的筛选条件，用于根据数据来源文件中的元数据属性筛选结果。