AgentsforBedrockRuntime / Client / invoke_agent

invoke_agent#

AgentsforBedrockRuntime.Client.invoke_agent(**kwargs)#

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

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

    [REQUIRED]

    The alias of the agent to use.

  • agentId (string) –

    [REQUIRED]

    The unique identifier of the agent to use.

  • enableTrace (boolean) – Specifies whether to turn on the trace or not to track the agent’s reasoning process. For more information, see Trace enablement.

  • endSession (boolean) – Specifies whether to end the session with the agent or not.

  • inputText (string) –

    [REQUIRED]

    The prompt text to send the agent.

  • sessionId (string) –

    [REQUIRED]

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

  • sessionState (dict) –

    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) –

Return type:

dict

Returns:

The response of this operation contains an EventStream member. When iterated the 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': {...}|[...]|123|123.4|'string'|True|None
                                }
                            },
                        ]
                    },
                ]
            },
            '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': {...}|[...]|123|123.4|'string'|True|None
                                    }
                                },
                            ]
                        },
                        '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 (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.

          Note

          This is a Tagged Union structure. Only one of the following top level keys will be set: failureTrace, orchestrationTrace, postProcessingTrace, preProcessingTrace. If a client receives an unknown member it will set SDK_UNKNOWN_MEMBER as the top level key, which maps to the name or tag of the unknown member. The structure of SDK_UNKNOWN_MEMBER is as follows:

          'SDK_UNKNOWN_MEMBER': {'name': 'UnknownMemberName'}
          
          • 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.

            Note

            This is a Tagged Union structure. Only one of the following top level keys will be set: invocationInput, modelInvocationInput, observation, rationale. If a client receives an unknown member it will set SDK_UNKNOWN_MEMBER as the top level key, which maps to the name or tag of the unknown member. The structure of SDK_UNKNOWN_MEMBER is as follows:

            'SDK_UNKNOWN_MEMBER': {'name': 'UnknownMemberName'}
            
            • 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..

            Note

            This is a Tagged Union structure. Only one of the following top level keys will be set: modelInvocationInput, modelInvocationOutput. If a client receives an unknown member it will set SDK_UNKNOWN_MEMBER as the top level key, which maps to the name or tag of the unknown member. The structure of SDK_UNKNOWN_MEMBER is as follows:

            'SDK_UNKNOWN_MEMBER': {'name': 'UnknownMemberName'}
            
            • 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.

            Note

            This is a Tagged Union structure. Only one of the following top level keys will be set: modelInvocationInput, modelInvocationOutput. If a client receives an unknown member it will set SDK_UNKNOWN_MEMBER as the top level key, which maps to the name or tag of the unknown member. The structure of SDK_UNKNOWN_MEMBER is as follows:

            'SDK_UNKNOWN_MEMBER': {'name': 'UnknownMemberName'}
            
            • 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.

Exceptions