Agents for Amazon Bedrock Runtime

2024/03/27 - Agents for Amazon Bedrock Runtime - 3 updated api methods

Changes  This release introduces filtering support on Retrieve and RetrieveAndGenerate APIs.

InvokeAgent (updated) Link ¶
Changes (response)
{'completion': {'chunk': {'attribution': {'citations': {'retrievedReferences': {'metadata': {'string': {}}}}}},
                'trace': {'trace': {'orchestrationTrace': {'observation': {'knowledgeBaseLookupOutput': {'retrievedReferences': {'metadata': {'string': {}}}}}}}}}}

Sends a prompt for the agent to process and respond to.

Note

The CLI doesn't support InvokeAgent .

  • To continue the same conversation with an agent, use the same sessionId value in the request.

  • To activate trace enablement, turn enableTrace to true . Trace enablement helps you follow the agent's reasoning process that led it to the information it processed, the actions it took, and the final result it yielded. For more information, see Trace enablement .

  • End a conversation by setting endSession to true .

  • Include attributes for the session or prompt in the sessionState object.

The response is returned in the bytes field of the chunk object.

  • The attribution object contains citations for parts of the response.

  • If you set enableTrace to true in the request, you can trace the agent's steps and reasoning process that led it to the response.

  • Errors are also surfaced in the response.

See also: AWS API Documentation

Request Syntax

client.invoke_agent(
    agentAliasId='string',
    agentId='string',
    enableTrace=True|False,
    endSession=True|False,
    inputText='string',
    sessionId='string',
    sessionState={
        'promptSessionAttributes': {
            'string': 'string'
        },
        'sessionAttributes': {
            'string': 'string'
        }
    }
)
type agentAliasId

string

param agentAliasId

[REQUIRED]

The alias of the agent to use.

type agentId

string

param agentId

[REQUIRED]

The unique identifier of the agent to use.

type enableTrace

boolean

param enableTrace

Specifies whether to turn on the trace or not to track the agent's reasoning process. For more information, see Trace enablement .

type endSession

boolean

param endSession

Specifies whether to end the session with the agent or not.

type inputText

string

param inputText

[REQUIRED]

The prompt text to send the agent.

type sessionId

string

param sessionId

[REQUIRED]

The unique identifier of the session. Use the same value across requests to continue the same conversation.

type sessionState

dict

param sessionState

Contains parameters that specify various attributes of the session. For more information, see Control session context .

  • promptSessionAttributes (dict) --

    Contains attributes that persist across a prompt and the values of those attributes. These attributes replace the $prompt_session_attributes$ placeholder variable in the orchestration prompt template. For more information, see Prompt template placeholder variables .

    • (string) --

      • (string) --

  • sessionAttributes (dict) --

    Contains attributes that persist across a session and the values of those attributes.

    • (string) --

      • (string) --

rtype

dict

returns

The response of this operation contains an :class:`.EventStream` member. When iterated the :class:`.EventStream` will yield events based on the structure below, where only one of the top level keys will be present for any given event.

Response Syntax

{
    'completion': EventStream({
        'accessDeniedException': {
            'message': 'string'
        },
        'badGatewayException': {
            'message': 'string',
            'resourceName': 'string'
        },
        'chunk': {
            'attribution': {
                'citations': [
                    {
                        'generatedResponsePart': {
                            'textResponsePart': {
                                'span': {
                                    'end': 123,
                                    'start': 123
                                },
                                'text': 'string'
                            }
                        },
                        'retrievedReferences': [
                            {
                                'content': {
                                    'text': 'string'
                                },
                                'location': {
                                    's3Location': {
                                        'uri': 'string'
                                    },
                                    'type': 'S3'
                                },
                                'metadata': {
                                    'string': {}
                                }
                            },
                        ]
                    },
                ]
            },
            'bytes': b'bytes'
        },
        'conflictException': {
            'message': 'string'
        },
        'dependencyFailedException': {
            'message': 'string',
            'resourceName': 'string'
        },
        'internalServerException': {
            'message': 'string'
        },
        'resourceNotFoundException': {
            'message': 'string'
        },
        'serviceQuotaExceededException': {
            'message': 'string'
        },
        'throttlingException': {
            'message': 'string'
        },
        'trace': {
            'agentAliasId': 'string',
            'agentId': 'string',
            'sessionId': 'string',
            'trace': {
                'failureTrace': {
                    'failureReason': 'string',
                    'traceId': 'string'
                },
                'orchestrationTrace': {
                    'invocationInput': {
                        'actionGroupInvocationInput': {
                            'actionGroupName': 'string',
                            'apiPath': 'string',
                            'parameters': [
                                {
                                    'name': 'string',
                                    'type': 'string',
                                    'value': 'string'
                                },
                            ],
                            'requestBody': {
                                'content': {
                                    'string': [
                                        {
                                            'name': 'string',
                                            'type': 'string',
                                            'value': 'string'
                                        },
                                    ]
                                }
                            },
                            'verb': 'string'
                        },
                        'invocationType': 'ACTION_GROUP'|'KNOWLEDGE_BASE'|'FINISH',
                        'knowledgeBaseLookupInput': {
                            'knowledgeBaseId': 'string',
                            'text': 'string'
                        },
                        'traceId': 'string'
                    },
                    'modelInvocationInput': {
                        'inferenceConfiguration': {
                            'maximumLength': 123,
                            'stopSequences': [
                                'string',
                            ],
                            'temperature': ...,
                            'topK': 123,
                            'topP': ...
                        },
                        'overrideLambda': 'string',
                        'parserMode': 'DEFAULT'|'OVERRIDDEN',
                        'promptCreationMode': 'DEFAULT'|'OVERRIDDEN',
                        'text': 'string',
                        'traceId': 'string',
                        'type': 'PRE_PROCESSING'|'ORCHESTRATION'|'KNOWLEDGE_BASE_RESPONSE_GENERATION'|'POST_PROCESSING'
                    },
                    'observation': {
                        'actionGroupInvocationOutput': {
                            'text': 'string'
                        },
                        'finalResponse': {
                            'text': 'string'
                        },
                        'knowledgeBaseLookupOutput': {
                            'retrievedReferences': [
                                {
                                    'content': {
                                        'text': 'string'
                                    },
                                    'location': {
                                        's3Location': {
                                            'uri': 'string'
                                        },
                                        'type': 'S3'
                                    },
                                    'metadata': {
                                        'string': {}
                                    }
                                },
                            ]
                        },
                        'repromptResponse': {
                            'source': 'ACTION_GROUP'|'KNOWLEDGE_BASE'|'PARSER',
                            'text': 'string'
                        },
                        'traceId': 'string',
                        'type': 'ACTION_GROUP'|'KNOWLEDGE_BASE'|'FINISH'|'ASK_USER'|'REPROMPT'
                    },
                    'rationale': {
                        'text': 'string',
                        'traceId': 'string'
                    }
                },
                'postProcessingTrace': {
                    'modelInvocationInput': {
                        'inferenceConfiguration': {
                            'maximumLength': 123,
                            'stopSequences': [
                                'string',
                            ],
                            'temperature': ...,
                            'topK': 123,
                            'topP': ...
                        },
                        'overrideLambda': 'string',
                        'parserMode': 'DEFAULT'|'OVERRIDDEN',
                        'promptCreationMode': 'DEFAULT'|'OVERRIDDEN',
                        'text': 'string',
                        'traceId': 'string',
                        'type': 'PRE_PROCESSING'|'ORCHESTRATION'|'KNOWLEDGE_BASE_RESPONSE_GENERATION'|'POST_PROCESSING'
                    },
                    'modelInvocationOutput': {
                        'parsedResponse': {
                            'text': 'string'
                        },
                        'traceId': 'string'
                    }
                },
                'preProcessingTrace': {
                    'modelInvocationInput': {
                        'inferenceConfiguration': {
                            'maximumLength': 123,
                            'stopSequences': [
                                'string',
                            ],
                            'temperature': ...,
                            'topK': 123,
                            'topP': ...
                        },
                        'overrideLambda': 'string',
                        'parserMode': 'DEFAULT'|'OVERRIDDEN',
                        'promptCreationMode': 'DEFAULT'|'OVERRIDDEN',
                        'text': 'string',
                        'traceId': 'string',
                        'type': 'PRE_PROCESSING'|'ORCHESTRATION'|'KNOWLEDGE_BASE_RESPONSE_GENERATION'|'POST_PROCESSING'
                    },
                    'modelInvocationOutput': {
                        'parsedResponse': {
                            'isValid': True|False,
                            'rationale': 'string'
                        },
                        'traceId': 'string'
                    }
                }
            }
        },
        'validationException': {
            'message': 'string'
        }
    }),
    'contentType': 'string',
    'sessionId': 'string'
}

Response Structure

  • (dict) --

    • completion (:class:`.EventStream`) --

      The agent's response to the user prompt.

      • accessDeniedException (dict) --

        The request is denied because of missing access permissions. Check your permissions and retry your request.

        • message (string) --

      • badGatewayException (dict) --

        There was an issue with a dependency due to a server issue. Retry your request.

        • message (string) --

        • resourceName (string) --

          The name of the dependency that caused the issue, such as Amazon Bedrock, Lambda, or STS.

      • chunk (dict) --

        Contains a part of an agent response and citations for it.

        • attribution (dict) --

          Contains citations for a part of an agent response.

          • citations (list) --

            A list of citations and related information for a part of an agent response.

            • (dict) --

              An object containing a segment of the generated response that is based on a source in the knowledge base, alongside information about the source.

              This data type is used in the following API operations:

              • generatedResponsePart (dict) --

                Contains the generated response and metadata

                • textResponsePart (dict) --

                  Contains metadata about a textual part of the generated response that is accompanied by a citation.

                  • span (dict) --

                    Contains information about where the text with a citation begins and ends in the generated output.

                    • end (integer) --

                      Where the text with a citation ends in the generated output.

                    • start (integer) --

                      Where the text with a citation starts in the generated output.

                  • text (string) --

                    The part of the generated text that contains a citation.

              • retrievedReferences (list) --

                Contains metadata about the sources cited for the generated response.

                • (dict) --

                  Contains metadata about a source cited for the generated response.

                  This data type is used in the following API operations:

                  • content (dict) --

                    Contains the cited text from the data source.

                    • text (string) --

                      The cited text from the data source.

                  • location (dict) --

                    Contains information about the location of the data source.

                    • s3Location (dict) --

                      Contains the S3 location of the data source.

                      • uri (string) --

                        The S3 URI of the data source.

                    • type (string) --

                      The type of the location of the data source.

                  • metadata (dict) --

                    Contains metadata attributes and their values for the file in the data source. For more information, see Metadata and filtering .

        • bytes (bytes) --

          A part of the agent response in bytes.

      • conflictException (dict) --

        There was a conflict performing an operation. Resolve the conflict and retry your request.

        • message (string) --

      • dependencyFailedException (dict) --

        There was an issue with a dependency. Check the resource configurations and retry the request.

        • message (string) --

        • resourceName (string) --

          The name of the dependency that caused the issue, such as Amazon Bedrock, Lambda, or STS.

      • internalServerException (dict) --

        An internal server error occurred. Retry your request.

        • message (string) --

      • resourceNotFoundException (dict) --

        The specified resource ARN was not found. Check the ARN and try your request again.

        • message (string) --

      • serviceQuotaExceededException (dict) --

        The number of requests exceeds the service quota. Resubmit your request later.

        • message (string) --

      • throttlingException (dict) --

        The number of requests exceeds the limit. Resubmit your request later.

        • message (string) --

      • trace (dict) --

        Contains information about the agent and session, alongside the agent's reasoning process and results from calling API actions and querying knowledge bases and metadata about the trace. You can use the trace to understand how the agent arrived at the response it provided the customer. For more information, see Trace events .

        • agentAliasId (string) --

          The unique identifier of the alias of the agent.

        • agentId (string) --

          The unique identifier of the agent.

        • sessionId (string) --

          The unique identifier of the session with the agent.

        • trace (dict) --

          Contains one part of the agent's reasoning process and results from calling API actions and querying knowledge bases. You can use the trace to understand how the agent arrived at the response it provided the customer. For more information, see Trace enablement .

          • failureTrace (dict) --

            Contains information about the failure of the interaction.

            • failureReason (string) --

              The reason the interaction failed.

            • traceId (string) --

              The unique identifier of the trace.

          • orchestrationTrace (dict) --

            Details about the orchestration step, in which the agent determines the order in which actions are executed and which knowledge bases are retrieved.

            • invocationInput (dict) --

              Contains information pertaining to the action group or knowledge base that is being invoked.

              • actionGroupInvocationInput (dict) --

                Contains information about the action group to be invoked.

                • actionGroupName (string) --

                  The name of the action group.

                • apiPath (string) --

                  The path to the API to call, based off the action group.

                • parameters (list) --

                  The parameters in the Lambda input event.

                  • (dict) --

                    A parameter in the Lambda input event.

                    • name (string) --

                      The name of the parameter.

                    • type (string) --

                      The type of the parameter.

                    • value (string) --

                      The value of the parameter.

                • requestBody (dict) --

                  The parameters in the request body for the Lambda input event.

                  • content (dict) --

                    The content in the request body.

                    • (string) --

                      • (list) --

                        • (dict) --

                          A parameter in the Lambda input event.

                          • name (string) --

                            The name of the parameter.

                          • type (string) --

                            The type of the parameter.

                          • value (string) --

                            The value of the parameter.

                • verb (string) --

                  The API method being used, based off the action group.

              • invocationType (string) --

                Specifies whether the agent is invoking an action group or a knowledge base.

              • knowledgeBaseLookupInput (dict) --

                Contains details about the knowledge base to look up and the query to be made.

                • knowledgeBaseId (string) --

                  The unique identifier of the knowledge base to look up.

                • text (string) --

                  The query made to the knowledge base.

              • traceId (string) --

                The unique identifier of the trace.

            • modelInvocationInput (dict) --

              The input for the orchestration step.

              • The type is ORCHESTRATION .

              • The text contains the prompt.

              • The inferenceConfiguration , parserMode , and overrideLambda values are set in the PromptOverrideConfiguration object that was set when the agent was created or updated.

              • inferenceConfiguration (dict) --

                Specifications about the inference parameters that were provided alongside the prompt. These are specified in the PromptOverrideConfiguration object that was set when the agent was created or updated. For more information, see Inference parameters for foundation models .

                • maximumLength (integer) --

                  The maximum number of tokens allowed in the generated response.

                • stopSequences (list) --

                  A list of stop sequences. A stop sequence is a sequence of characters that causes the model to stop generating the response.

                  • (string) --

                • temperature (float) --

                  The likelihood of the model selecting higher-probability options while generating a response. A lower value makes the model more likely to choose higher-probability options, while a higher value makes the model more likely to choose lower-probability options.

                • topK (integer) --

                  While generating a response, the model determines the probability of the following token at each point of generation. The value that you set for topK is the number of most-likely candidates from which the model chooses the next token in the sequence. For example, if you set topK to 50, the model selects the next token from among the top 50 most likely choices.

                • topP (float) --

                  While generating a response, the model determines the probability of the following token at each point of generation. The value that you set for Top P determines the number of most-likely candidates from which the model chooses the next token in the sequence. For example, if you set topP to 80, the model only selects the next token from the top 80% of the probability distribution of next tokens.

              • overrideLambda (string) --

                The ARN of the Lambda function to use when parsing the raw foundation model output in parts of the agent sequence.

              • parserMode (string) --

                Specifies whether to override the default parser Lambda function when parsing the raw foundation model output in the part of the agent sequence defined by the promptType .

              • promptCreationMode (string) --

                Specifies whether the default prompt template was OVERRIDDEN . If it was, the basePromptTemplate that was set in the PromptOverrideConfiguration object when the agent was created or updated is used instead.

              • text (string) --

                The text that prompted the agent at this step.

              • traceId (string) --

                The unique identifier of the trace.

              • type (string) --

                The step in the agent sequence.

            • observation (dict) --

              Details about the observation (the output of the action group Lambda or knowledge base) made by the agent.

              • actionGroupInvocationOutput (dict) --

                Contains the JSON-formatted string returned by the API invoked by the action group.

                • text (string) --

                  The JSON-formatted string returned by the API invoked by the action group.

              • finalResponse (dict) --

                Contains details about the response to the user.

                • text (string) --

                  The text in the response to the user.

              • knowledgeBaseLookupOutput (dict) --

                Contains details about the results from looking up the knowledge base.

                • retrievedReferences (list) --

                  Contains metadata about the sources cited for the generated response.

                  • (dict) --

                    Contains metadata about a source cited for the generated response.

                    This data type is used in the following API operations:

                    • content (dict) --

                      Contains the cited text from the data source.

                      • text (string) --

                        The cited text from the data source.

                    • location (dict) --

                      Contains information about the location of the data source.

                      • s3Location (dict) --

                        Contains the S3 location of the data source.

                        • uri (string) --

                          The S3 URI of the data source.

                      • type (string) --

                        The type of the location of the data source.

                    • metadata (dict) --

                      Contains metadata attributes and their values for the file in the data source. For more information, see Metadata and filtering .

              • repromptResponse (dict) --

                Contains details about the response to reprompt the input.

                • source (string) --

                  Specifies what output is prompting the agent to reprompt the input.

                • text (string) --

                  The text reprompting the input.

              • traceId (string) --

                The unique identifier of the trace.

              • type (string) --

                Specifies what kind of information the agent returns in the observation. The following values are possible.

                • ACTION_GROUP – The agent returns the result of an action group.

                • KNOWLEDGE_BASE – The agent returns information from a knowledge base.

                • FINISH – The agent returns a final response to the user with no follow-up.

                • ASK_USER – The agent asks the user a question.

                • REPROMPT – The agent prompts the user again for the same information.

            • rationale (dict) --

              Details about the reasoning, based on the input, that the agent uses to justify carrying out an action group or getting information from a knowledge base.

              • text (string) --

                The reasoning or thought process of the agent, based on the input.

              • traceId (string) --

                The unique identifier of the trace step.

          • postProcessingTrace (dict) --

            Details about the post-processing step, in which the agent shapes the response..

            • modelInvocationInput (dict) --

              The input for the post-processing step.

              • The type is POST_PROCESSING .

              • The text contains the prompt.

              • The inferenceConfiguration , parserMode , and overrideLambda values are set in the PromptOverrideConfiguration object that was set when the agent was created or updated.

              • inferenceConfiguration (dict) --

                Specifications about the inference parameters that were provided alongside the prompt. These are specified in the PromptOverrideConfiguration object that was set when the agent was created or updated. For more information, see Inference parameters for foundation models .

                • maximumLength (integer) --

                  The maximum number of tokens allowed in the generated response.

                • stopSequences (list) --

                  A list of stop sequences. A stop sequence is a sequence of characters that causes the model to stop generating the response.

                  • (string) --

                • temperature (float) --

                  The likelihood of the model selecting higher-probability options while generating a response. A lower value makes the model more likely to choose higher-probability options, while a higher value makes the model more likely to choose lower-probability options.

                • topK (integer) --

                  While generating a response, the model determines the probability of the following token at each point of generation. The value that you set for topK is the number of most-likely candidates from which the model chooses the next token in the sequence. For example, if you set topK to 50, the model selects the next token from among the top 50 most likely choices.

                • topP (float) --

                  While generating a response, the model determines the probability of the following token at each point of generation. The value that you set for Top P determines the number of most-likely candidates from which the model chooses the next token in the sequence. For example, if you set topP to 80, the model only selects the next token from the top 80% of the probability distribution of next tokens.

              • overrideLambda (string) --

                The ARN of the Lambda function to use when parsing the raw foundation model output in parts of the agent sequence.

              • parserMode (string) --

                Specifies whether to override the default parser Lambda function when parsing the raw foundation model output in the part of the agent sequence defined by the promptType .

              • promptCreationMode (string) --

                Specifies whether the default prompt template was OVERRIDDEN . If it was, the basePromptTemplate that was set in the PromptOverrideConfiguration object when the agent was created or updated is used instead.

              • text (string) --

                The text that prompted the agent at this step.

              • traceId (string) --

                The unique identifier of the trace.

              • type (string) --

                The step in the agent sequence.

            • modelInvocationOutput (dict) --

              The foundation model output from the post-processing step.

              • parsedResponse (dict) --

                Details about the response from the Lambda parsing of the output of the post-processing step.

                • text (string) --

                  The text returned by the parser.

              • traceId (string) --

                The unique identifier of the trace.

          • preProcessingTrace (dict) --

            Details about the pre-processing step, in which the agent contextualizes and categorizes user inputs.

            • modelInvocationInput (dict) --

              The input for the pre-processing step.

              • The type is PRE_PROCESSING .

              • The text contains the prompt.

              • The inferenceConfiguration , parserMode , and overrideLambda values are set in the PromptOverrideConfiguration object that was set when the agent was created or updated.

              • inferenceConfiguration (dict) --

                Specifications about the inference parameters that were provided alongside the prompt. These are specified in the PromptOverrideConfiguration object that was set when the agent was created or updated. For more information, see Inference parameters for foundation models .

                • maximumLength (integer) --

                  The maximum number of tokens allowed in the generated response.

                • stopSequences (list) --

                  A list of stop sequences. A stop sequence is a sequence of characters that causes the model to stop generating the response.

                  • (string) --

                • temperature (float) --

                  The likelihood of the model selecting higher-probability options while generating a response. A lower value makes the model more likely to choose higher-probability options, while a higher value makes the model more likely to choose lower-probability options.

                • topK (integer) --

                  While generating a response, the model determines the probability of the following token at each point of generation. The value that you set for topK is the number of most-likely candidates from which the model chooses the next token in the sequence. For example, if you set topK to 50, the model selects the next token from among the top 50 most likely choices.

                • topP (float) --

                  While generating a response, the model determines the probability of the following token at each point of generation. The value that you set for Top P determines the number of most-likely candidates from which the model chooses the next token in the sequence. For example, if you set topP to 80, the model only selects the next token from the top 80% of the probability distribution of next tokens.

              • overrideLambda (string) --

                The ARN of the Lambda function to use when parsing the raw foundation model output in parts of the agent sequence.

              • parserMode (string) --

                Specifies whether to override the default parser Lambda function when parsing the raw foundation model output in the part of the agent sequence defined by the promptType .

              • promptCreationMode (string) --

                Specifies whether the default prompt template was OVERRIDDEN . If it was, the basePromptTemplate that was set in the PromptOverrideConfiguration object when the agent was created or updated is used instead.

              • text (string) --

                The text that prompted the agent at this step.

              • traceId (string) --

                The unique identifier of the trace.

              • type (string) --

                The step in the agent sequence.

            • modelInvocationOutput (dict) --

              The foundation model output from the pre-processing step.

              • parsedResponse (dict) --

                Details about the response from the Lambda parsing of the output of the pre-processing step.

                • isValid (boolean) --

                  Whether the user input is valid or not. If false , the agent doesn't proceed to orchestration.

                • rationale (string) --

                  The text returned by the parsing of the pre-processing step, explaining the steps that the agent plans to take in orchestration, if the user input is valid.

              • traceId (string) --

                The unique identifier of the trace.

      • validationException (dict) --

        Input validation failed. Check your request parameters and retry the request.

        • message (string) --

    • contentType (string) --

      The MIME type of the input data in the request. The default value is application/json .

    • sessionId (string) --

      The unique identifier of the session with the agent.

Retrieve (updated) Link ¶
Changes (request, response)
Request
{'retrievalConfiguration': {'vectorSearchConfiguration': {'filter': {'andAll': [()],
                                                                     'equals': {'key': 'string',
                                                                                'value': {}},
                                                                     'greaterThan': {'key': 'string',
                                                                                     'value': {}},
                                                                     'greaterThanOrEquals': {'key': 'string',
                                                                                             'value': {}},
                                                                     'in': {'key': 'string',
                                                                            'value': {}},
                                                                     'lessThan': {'key': 'string',
                                                                                  'value': {}},
                                                                     'lessThanOrEquals': {'key': 'string',
                                                                                          'value': {}},
                                                                     'notEquals': {'key': 'string',
                                                                                   'value': {}},
                                                                     'notIn': {'key': 'string',
                                                                               'value': {}},
                                                                     'orAll': [()],
                                                                     'startsWith': {'key': 'string',
                                                                                    'value': {}}}}}}
Response
{'retrievalResults': {'metadata': {'string': {}}}}

Queries a knowledge base and retrieves information from it.

See also: AWS API Documentation

Request Syntax

client.retrieve(
    knowledgeBaseId='string',
    nextToken='string',
    retrievalConfiguration={
        'vectorSearchConfiguration': {
            'filter': {
                'andAll': [
                    {'... recursive ...'},
                ],
                'equals': {
                    'key': 'string',
                    'value': {}

                },
                'greaterThan': {
                    'key': 'string',
                    'value': {}

                },
                'greaterThanOrEquals': {
                    'key': 'string',
                    'value': {}

                },
                'in': {
                    'key': 'string',
                    'value': {}

                },
                'lessThan': {
                    'key': 'string',
                    'value': {}

                },
                'lessThanOrEquals': {
                    'key': 'string',
                    'value': {}

                },
                'notEquals': {
                    'key': 'string',
                    'value': {}

                },
                'notIn': {
                    'key': 'string',
                    'value': {}

                },
                'orAll': [
                    {'... recursive ...'},
                ],
                'startsWith': {
                    'key': 'string',
                    'value': {}

                }
            },
            'numberOfResults': 123,
            'overrideSearchType': 'HYBRID'|'SEMANTIC'
        }
    },
    retrievalQuery={
        'text': 'string'
    }
)
type knowledgeBaseId

string

param knowledgeBaseId

[REQUIRED]

The unique identifier of the knowledge base to query.

type nextToken

string

param nextToken

If there are more results than can fit in the response, the response returns a nextToken . Use this token in the nextToken field of another request to retrieve the next batch of results.

type retrievalConfiguration

dict

param retrievalConfiguration

Contains configurations for the knowledge base query and retrieval process. For more information, see Query configurations .

  • vectorSearchConfiguration (dict) -- [REQUIRED]

    Contains details about how the results from the vector search should be returned. For more information, see Query configurations .

    • filter (dict) --

      Specifies the filters to use on the metadata in the knowledge base data sources before returning results. For more information, see Query configurations .

      • andAll (list) --

        Knowledge base data sources whose metadata attributes fulfill all the filter conditions inside this list are returned.

        • (dict) --

          Specifies the filters to use on the metadata attributes in the knowledge base data sources before returning results. For more information, see Query configurations .

          This data type is used in the following API operations:

      • equals (dict) --

        Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value matches the value in this object are returned.

        • key (string) -- [REQUIRED]

          The name that the metadata attribute must match.

        • value (dict) -- [REQUIRED]

          The value to whcih to compare the value of the metadata attribute.

      • greaterThan (dict) --

        Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value is greater than the value in this object are returned.

        • key (string) -- [REQUIRED]

          The name that the metadata attribute must match.

        • value (dict) -- [REQUIRED]

          The value to whcih to compare the value of the metadata attribute.

      • greaterThanOrEquals (dict) --

        Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value is greater than or equal to the value in this object are returned.

        • key (string) -- [REQUIRED]

          The name that the metadata attribute must match.

        • value (dict) -- [REQUIRED]

          The value to whcih to compare the value of the metadata attribute.

      • in (dict) --

        Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value is in the list specified in the value in this object are returned.

        • key (string) -- [REQUIRED]

          The name that the metadata attribute must match.

        • value (dict) -- [REQUIRED]

          The value to whcih to compare the value of the metadata attribute.

      • lessThan (dict) --

        Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value is less than the value in this object are returned.

        • key (string) -- [REQUIRED]

          The name that the metadata attribute must match.

        • value (dict) -- [REQUIRED]

          The value to whcih to compare the value of the metadata attribute.

      • lessThanOrEquals (dict) --

        Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value is less than or equal to the value in this object are returned.

        • key (string) -- [REQUIRED]

          The name that the metadata attribute must match.

        • value (dict) -- [REQUIRED]

          The value to whcih to compare the value of the metadata attribute.

      • notEquals (dict) --

        Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value doesn't match the value in this object are returned.

        • key (string) -- [REQUIRED]

          The name that the metadata attribute must match.

        • value (dict) -- [REQUIRED]

          The value to whcih to compare the value of the metadata attribute.

      • notIn (dict) --

        Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value isn't in the list specified in the value in this object are returned.

        • key (string) -- [REQUIRED]

          The name that the metadata attribute must match.

        • value (dict) -- [REQUIRED]

          The value to whcih to compare the value of the metadata attribute.

      • orAll (list) --

        Knowledge base data sources whose metadata attributes fulfill at least one of the filter conditions inside this list are returned.

        • (dict) --

          Specifies the filters to use on the metadata attributes in the knowledge base data sources before returning results. For more information, see Query configurations .

          This data type is used in the following API operations:

      • startsWith (dict) --

        Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value starts with the value in this object are returned. This filter is currently only supported for Amazon OpenSearch Serverless vector stores.

        • key (string) -- [REQUIRED]

          The name that the metadata attribute must match.

        • value (dict) -- [REQUIRED]

          The value to whcih to compare the value of the metadata attribute.

    • numberOfResults (integer) --

      The number of source chunks to retrieve.

    • overrideSearchType (string) --

      By default, Amazon Bedrock decides a search strategy for you. If you're using an Amazon OpenSearch Serverless vector store that contains a filterable text field, you can specify whether to query the knowledge base with a HYBRID search using both vector embeddings and raw text, or SEMANTIC search using only vector embeddings. For other vector store configurations, only SEMANTIC search is available. For more information, see Test a knowledge base .

type retrievalQuery

dict

param retrievalQuery

[REQUIRED]

Contains the query to send the knowledge base.

  • text (string) -- [REQUIRED]

    The text of the query made to the knowledge base.

rtype

dict

returns

Response Syntax

{
    'nextToken': 'string',
    'retrievalResults': [
        {
            'content': {
                'text': 'string'
            },
            'location': {
                's3Location': {
                    'uri': 'string'
                },
                'type': 'S3'
            },
            'metadata': {
                'string': {}
            },
            'score': 123.0
        },
    ]
}

Response Structure

  • (dict) --

    • nextToken (string) --

      If there are more results than can fit in the response, the response returns a nextToken . Use this token in the nextToken field of another request to retrieve the next batch of results.

    • retrievalResults (list) --

      A list of results from querying the knowledge base.

      • (dict) --

        Details about a result from querying the knowledge base.

        This data type is used in the following API operations:

        • content (dict) --

          Contains a chunk of text from a data source in the knowledge base.

          • text (string) --

            The cited text from the data source.

        • location (dict) --

          Contains information about the location of the data source.

          • s3Location (dict) --

            Contains the S3 location of the data source.

            • uri (string) --

              The S3 URI of the data source.

          • type (string) --

            The type of the location of the data source.

        • metadata (dict) --

          Contains metadata attributes and their values for the file in the data source. For more information, see Metadata and filtering .

          • (string) --

            • (dict) --

        • score (float) --

          The level of relevance of the result to the query.

RetrieveAndGenerate (updated) Link ¶
Changes (request, response)
Request
{'retrieveAndGenerateConfiguration': {'knowledgeBaseConfiguration': {'retrievalConfiguration': {'vectorSearchConfiguration': {'filter': {'andAll': [()],
                                                                                                                                         'equals': {'key': 'string',
                                                                                                                                                    'value': {}},
                                                                                                                                         'greaterThan': {'key': 'string',
                                                                                                                                                         'value': {}},
                                                                                                                                         'greaterThanOrEquals': {'key': 'string',
                                                                                                                                                                 'value': {}},
                                                                                                                                         'in': {'key': 'string',
                                                                                                                                                'value': {}},
                                                                                                                                         'lessThan': {'key': 'string',
                                                                                                                                                      'value': {}},
                                                                                                                                         'lessThanOrEquals': {'key': 'string',
                                                                                                                                                              'value': {}},
                                                                                                                                         'notEquals': {'key': 'string',
                                                                                                                                                       'value': {}},
                                                                                                                                         'notIn': {'key': 'string',
                                                                                                                                                   'value': {}},
                                                                                                                                         'orAll': [()],
                                                                                                                                         'startsWith': {'key': 'string',
                                                                                                                                                        'value': {}}}}}}}}
Response
{'citations': {'retrievedReferences': {'metadata': {'string': {}}}}}

Queries a knowledge base and generates responses based on the retrieved results. The response only cites sources that are relevant to the query.

See also: AWS API Documentation

Request Syntax

client.retrieve_and_generate(
    input={
        'text': 'string'
    },
    retrieveAndGenerateConfiguration={
        'knowledgeBaseConfiguration': {
            'generationConfiguration': {
                'promptTemplate': {
                    'textPromptTemplate': 'string'
                }
            },
            'knowledgeBaseId': 'string',
            'modelArn': 'string',
            'retrievalConfiguration': {
                'vectorSearchConfiguration': {
                    'filter': {
                        'andAll': [
                            {'... recursive ...'},
                        ],
                        'equals': {
                            'key': 'string',
                            'value': {}

                        },
                        'greaterThan': {
                            'key': 'string',
                            'value': {}

                        },
                        'greaterThanOrEquals': {
                            'key': 'string',
                            'value': {}

                        },
                        'in': {
                            'key': 'string',
                            'value': {}

                        },
                        'lessThan': {
                            'key': 'string',
                            'value': {}

                        },
                        'lessThanOrEquals': {
                            'key': 'string',
                            'value': {}

                        },
                        'notEquals': {
                            'key': 'string',
                            'value': {}

                        },
                        'notIn': {
                            'key': 'string',
                            'value': {}

                        },
                        'orAll': [
                            {'... recursive ...'},
                        ],
                        'startsWith': {
                            'key': 'string',
                            'value': {}

                        }
                    },
                    'numberOfResults': 123,
                    'overrideSearchType': 'HYBRID'|'SEMANTIC'
                }
            }
        },
        'type': 'KNOWLEDGE_BASE'
    },
    sessionConfiguration={
        'kmsKeyArn': 'string'
    },
    sessionId='string'
)
type input

dict

param input

[REQUIRED]

Contains the query to be made to the knowledge base.

  • text (string) -- [REQUIRED]

    The query made to the knowledge base.

type retrieveAndGenerateConfiguration

dict

param retrieveAndGenerateConfiguration

Contains configurations for the knowledge base query and retrieval process. For more information, see Query configurations .

  • knowledgeBaseConfiguration (dict) --

    Contains details about the resource being queried.

    • generationConfiguration (dict) --

      Contains configurations for response generation based on the knowwledge base query results.

      • promptTemplate (dict) --

        Contains the template for the prompt that's sent to the model for response generation.

        • textPromptTemplate (string) --

          The template for the prompt that's sent to the model for response generation. You can include prompt placeholders, which become replaced before the prompt is sent to the model to provide instructions and context to the model. In addition, you can include XML tags to delineate meaningful sections of the prompt template.

          For more information, see the following resources:

    • knowledgeBaseId (string) -- [REQUIRED]

      The unique identifier of the knowledge base that is queried and the foundation model used for generation.

    • modelArn (string) -- [REQUIRED]

      The ARN of the foundation model used to generate a response.

    • retrievalConfiguration (dict) --

      Contains configurations for how to retrieve and return the knowledge base query.

      • vectorSearchConfiguration (dict) -- [REQUIRED]

        Contains details about how the results from the vector search should be returned. For more information, see Query configurations .

        • filter (dict) --

          Specifies the filters to use on the metadata in the knowledge base data sources before returning results. For more information, see Query configurations .

          • andAll (list) --

            Knowledge base data sources whose metadata attributes fulfill all the filter conditions inside this list are returned.

            • (dict) --

              Specifies the filters to use on the metadata attributes in the knowledge base data sources before returning results. For more information, see Query configurations .

              This data type is used in the following API operations:

          • equals (dict) --

            Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value matches the value in this object are returned.

            • key (string) -- [REQUIRED]

              The name that the metadata attribute must match.

            • value (dict) -- [REQUIRED]

              The value to whcih to compare the value of the metadata attribute.

          • greaterThan (dict) --

            Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value is greater than the value in this object are returned.

            • key (string) -- [REQUIRED]

              The name that the metadata attribute must match.

            • value (dict) -- [REQUIRED]

              The value to whcih to compare the value of the metadata attribute.

          • greaterThanOrEquals (dict) --

            Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value is greater than or equal to the value in this object are returned.

            • key (string) -- [REQUIRED]

              The name that the metadata attribute must match.

            • value (dict) -- [REQUIRED]

              The value to whcih to compare the value of the metadata attribute.

          • in (dict) --

            Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value is in the list specified in the value in this object are returned.

            • key (string) -- [REQUIRED]

              The name that the metadata attribute must match.

            • value (dict) -- [REQUIRED]

              The value to whcih to compare the value of the metadata attribute.

          • lessThan (dict) --

            Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value is less than the value in this object are returned.

            • key (string) -- [REQUIRED]

              The name that the metadata attribute must match.

            • value (dict) -- [REQUIRED]

              The value to whcih to compare the value of the metadata attribute.

          • lessThanOrEquals (dict) --

            Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value is less than or equal to the value in this object are returned.

            • key (string) -- [REQUIRED]

              The name that the metadata attribute must match.

            • value (dict) -- [REQUIRED]

              The value to whcih to compare the value of the metadata attribute.

          • notEquals (dict) --

            Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value doesn't match the value in this object are returned.

            • key (string) -- [REQUIRED]

              The name that the metadata attribute must match.

            • value (dict) -- [REQUIRED]

              The value to whcih to compare the value of the metadata attribute.

          • notIn (dict) --

            Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value isn't in the list specified in the value in this object are returned.

            • key (string) -- [REQUIRED]

              The name that the metadata attribute must match.

            • value (dict) -- [REQUIRED]

              The value to whcih to compare the value of the metadata attribute.

          • orAll (list) --

            Knowledge base data sources whose metadata attributes fulfill at least one of the filter conditions inside this list are returned.

            • (dict) --

              Specifies the filters to use on the metadata attributes in the knowledge base data sources before returning results. For more information, see Query configurations .

              This data type is used in the following API operations:

          • startsWith (dict) --

            Knowledge base data sources that contain a metadata attribute whose name matches the key and whose value starts with the value in this object are returned. This filter is currently only supported for Amazon OpenSearch Serverless vector stores.

            • key (string) -- [REQUIRED]

              The name that the metadata attribute must match.

            • value (dict) -- [REQUIRED]

              The value to whcih to compare the value of the metadata attribute.

        • numberOfResults (integer) --

          The number of source chunks to retrieve.

        • overrideSearchType (string) --

          By default, Amazon Bedrock decides a search strategy for you. If you're using an Amazon OpenSearch Serverless vector store that contains a filterable text field, you can specify whether to query the knowledge base with a HYBRID search using both vector embeddings and raw text, or SEMANTIC search using only vector embeddings. For other vector store configurations, only SEMANTIC search is available. For more information, see Test a knowledge base .

  • type (string) -- [REQUIRED]

    The type of resource that is queried by the request.

type sessionConfiguration

dict

param sessionConfiguration

Contains details about the session with the knowledge base.

  • kmsKeyArn (string) -- [REQUIRED]

    The ARN of the KMS key encrypting the session.

type sessionId

string

param sessionId

The unique identifier of the session. Reuse the same value to continue the same session with the knowledge base.

rtype

dict

returns

Response Syntax

{
    'citations': [
        {
            'generatedResponsePart': {
                'textResponsePart': {
                    'span': {
                        'end': 123,
                        'start': 123
                    },
                    'text': 'string'
                }
            },
            'retrievedReferences': [
                {
                    'content': {
                        'text': 'string'
                    },
                    'location': {
                        's3Location': {
                            'uri': 'string'
                        },
                        'type': 'S3'
                    },
                    'metadata': {
                        'string': {}
                    }
                },
            ]
        },
    ],
    'output': {
        'text': 'string'
    },
    'sessionId': 'string'
}

Response Structure

  • (dict) --

    • citations (list) --

      A list of segments of the generated response that are based on sources in the knowledge base, alongside information about the sources.

      • (dict) --

        An object containing a segment of the generated response that is based on a source in the knowledge base, alongside information about the source.

        This data type is used in the following API operations:

        • generatedResponsePart (dict) --

          Contains the generated response and metadata

          • textResponsePart (dict) --

            Contains metadata about a textual part of the generated response that is accompanied by a citation.

            • span (dict) --

              Contains information about where the text with a citation begins and ends in the generated output.

              • end (integer) --

                Where the text with a citation ends in the generated output.

              • start (integer) --

                Where the text with a citation starts in the generated output.

            • text (string) --

              The part of the generated text that contains a citation.

        • retrievedReferences (list) --

          Contains metadata about the sources cited for the generated response.

          • (dict) --

            Contains metadata about a source cited for the generated response.

            This data type is used in the following API operations:

            • content (dict) --

              Contains the cited text from the data source.

              • text (string) --

                The cited text from the data source.

            • location (dict) --

              Contains information about the location of the data source.

              • s3Location (dict) --

                Contains the S3 location of the data source.

                • uri (string) --

                  The S3 URI of the data source.

              • type (string) --

                The type of the location of the data source.

            • metadata (dict) --

              Contains metadata attributes and their values for the file in the data source. For more information, see Metadata and filtering .

              • (string) --

                • (dict) --

    • output (dict) --

      Contains the response generated from querying the knowledge base.

      • text (string) --

        The response generated from querying the knowledge base.

    • sessionId (string) --

      The unique identifier of the session. Reuse the same value to continue the same session with the knowledge base.