SDK for PHP 3.x

Client: Aws\BedrockRuntime\BedrockRuntimeClient
Service ID: bedrock-runtime
Version: 2023-09-30

This page describes the parameters and results for the operations of the Amazon Bedrock Runtime (2023-09-30), and shows how to use the Aws\BedrockRuntime\BedrockRuntimeClient object to call the described operations. This documentation is specific to the 2023-09-30 API version of the service.

Operation Summary

Each of the following operations can be created from a client using $client->getCommand('CommandName'), where "CommandName" is the name of one of the following operations. Note: a command is a value that encapsulates an operation and the parameters used to create an HTTP request.

You can also create and send a command immediately using the magic methods available on a client object: $client->commandName(/* parameters */). You can send the command asynchronously (returning a promise) by appending the word "Async" to the operation name: $client->commandNameAsync(/* parameters */).

ApplyGuardrail ( array $params = [] )
The action to apply a guardrail.
Converse ( array $params = [] )
Sends messages to the specified Amazon Bedrock model.
ConverseStream ( array $params = [] )
Sends messages to the specified Amazon Bedrock model and returns the response in a stream.
GetAsyncInvoke ( array $params = [] )
Retrieve information about an asynchronous invocation.
InvokeModel ( array $params = [] )
Invokes the specified Amazon Bedrock model to run inference using the prompt and inference parameters provided in the request body.
InvokeModelWithResponseStream ( array $params = [] )
Invoke the specified Amazon Bedrock model to run inference using the prompt and inference parameters provided in the request body.
ListAsyncInvokes ( array $params = [] )
Lists asynchronous invocations.
StartAsyncInvoke ( array $params = [] )
Starts an asynchronous invocation.

Paginators

Paginators handle automatically iterating over paginated API results. Paginators are associated with specific API operations, and they accept the parameters that the corresponding API operation accepts. You can get a paginator from a client class using getPaginator($paginatorName, $operationParameters). This client supports the following paginators:

ListAsyncInvokes

Operations

ApplyGuardrail

$result = $client->applyGuardrail([/* ... */]);
$promise = $client->applyGuardrailAsync([/* ... */]);

The action to apply a guardrail.

For troubleshooting some of the common errors you might encounter when using the ApplyGuardrail API, see Troubleshooting Amazon Bedrock API Error Codes in the Amazon Bedrock User Guide

Parameter Syntax

$result = $client->applyGuardrail([
    'content' => [ // REQUIRED
        [
            'image' => [
                'format' => 'png|jpeg', // REQUIRED
                'source' => [ // REQUIRED
                    'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                ],
            ],
            'text' => [
                'qualifiers' => ['<string>', ...],
                'text' => '<string>', // REQUIRED
            ],
        ],
        // ...
    ],
    'guardrailIdentifier' => '<string>', // REQUIRED
    'guardrailVersion' => '<string>', // REQUIRED
    'source' => 'INPUT|OUTPUT', // REQUIRED
]);

Parameter Details

Members
content
Required: Yes
Type: Array of GuardrailContentBlock structures

The content details used in the request to apply the guardrail.

guardrailIdentifier
Required: Yes
Type: string

The guardrail identifier used in the request to apply the guardrail.

guardrailVersion
Required: Yes
Type: string

The guardrail version used in the request to apply the guardrail.

source
Required: Yes
Type: string

The source of data used in the request to apply the guardrail.

Result Syntax

[
    'action' => 'NONE|GUARDRAIL_INTERVENED',
    'assessments' => [
        [
            'contentPolicy' => [
                'filters' => [
                    [
                        'action' => 'BLOCKED',
                        'confidence' => 'NONE|LOW|MEDIUM|HIGH',
                        'filterStrength' => 'NONE|LOW|MEDIUM|HIGH',
                        'type' => 'INSULTS|HATE|SEXUAL|VIOLENCE|MISCONDUCT|PROMPT_ATTACK',
                    ],
                    // ...
                ],
            ],
            'contextualGroundingPolicy' => [
                'filters' => [
                    [
                        'action' => 'BLOCKED|NONE',
                        'score' => <float>,
                        'threshold' => <float>,
                        'type' => 'GROUNDING|RELEVANCE',
                    ],
                    // ...
                ],
            ],
            'invocationMetrics' => [
                'guardrailCoverage' => [
                    'images' => [
                        'guarded' => <integer>,
                        'total' => <integer>,
                    ],
                    'textCharacters' => [
                        'guarded' => <integer>,
                        'total' => <integer>,
                    ],
                ],
                'guardrailProcessingLatency' => <integer>,
                'usage' => [
                    'contentPolicyUnits' => <integer>,
                    'contextualGroundingPolicyUnits' => <integer>,
                    'sensitiveInformationPolicyFreeUnits' => <integer>,
                    'sensitiveInformationPolicyUnits' => <integer>,
                    'topicPolicyUnits' => <integer>,
                    'wordPolicyUnits' => <integer>,
                ],
            ],
            'sensitiveInformationPolicy' => [
                'piiEntities' => [
                    [
                        'action' => 'ANONYMIZED|BLOCKED',
                        'match' => '<string>',
                        'type' => 'ADDRESS|AGE|AWS_ACCESS_KEY|AWS_SECRET_KEY|CA_HEALTH_NUMBER|CA_SOCIAL_INSURANCE_NUMBER|CREDIT_DEBIT_CARD_CVV|CREDIT_DEBIT_CARD_EXPIRY|CREDIT_DEBIT_CARD_NUMBER|DRIVER_ID|EMAIL|INTERNATIONAL_BANK_ACCOUNT_NUMBER|IP_ADDRESS|LICENSE_PLATE|MAC_ADDRESS|NAME|PASSWORD|PHONE|PIN|SWIFT_CODE|UK_NATIONAL_HEALTH_SERVICE_NUMBER|UK_NATIONAL_INSURANCE_NUMBER|UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER|URL|USERNAME|US_BANK_ACCOUNT_NUMBER|US_BANK_ROUTING_NUMBER|US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER|US_PASSPORT_NUMBER|US_SOCIAL_SECURITY_NUMBER|VEHICLE_IDENTIFICATION_NUMBER',
                    ],
                    // ...
                ],
                'regexes' => [
                    [
                        'action' => 'ANONYMIZED|BLOCKED',
                        'match' => '<string>',
                        'name' => '<string>',
                        'regex' => '<string>',
                    ],
                    // ...
                ],
            ],
            'topicPolicy' => [
                'topics' => [
                    [
                        'action' => 'BLOCKED',
                        'name' => '<string>',
                        'type' => 'DENY',
                    ],
                    // ...
                ],
            ],
            'wordPolicy' => [
                'customWords' => [
                    [
                        'action' => 'BLOCKED',
                        'match' => '<string>',
                    ],
                    // ...
                ],
                'managedWordLists' => [
                    [
                        'action' => 'BLOCKED',
                        'match' => '<string>',
                        'type' => 'PROFANITY',
                    ],
                    // ...
                ],
            ],
        ],
        // ...
    ],
    'guardrailCoverage' => [
        'images' => [
            'guarded' => <integer>,
            'total' => <integer>,
        ],
        'textCharacters' => [
            'guarded' => <integer>,
            'total' => <integer>,
        ],
    ],
    'outputs' => [
        [
            'text' => '<string>',
        ],
        // ...
    ],
    'usage' => [
        'contentPolicyUnits' => <integer>,
        'contextualGroundingPolicyUnits' => <integer>,
        'sensitiveInformationPolicyFreeUnits' => <integer>,
        'sensitiveInformationPolicyUnits' => <integer>,
        'topicPolicyUnits' => <integer>,
        'wordPolicyUnits' => <integer>,
    ],
]

Result Details

Members
action
Required: Yes
Type: string

The action taken in the response from the guardrail.

assessments
Required: Yes
Type: Array of GuardrailAssessment structures

The assessment details in the response from the guardrail.

guardrailCoverage
Type: GuardrailCoverage structure

The guardrail coverage details in the apply guardrail response.

outputs
Required: Yes
Type: Array of GuardrailOutputContent structures

The output details in the response from the guardrail.

usage
Required: Yes
Type: GuardrailUsage structure

The usage details in the response from the guardrail.

Errors

AccessDeniedException:

The request is denied because you do not have sufficient permissions to perform the requested action. For troubleshooting this error, see AccessDeniedException in the Amazon Bedrock User Guide

ResourceNotFoundException:

The specified resource ARN was not found. For troubleshooting this error, see ResourceNotFound in the Amazon Bedrock User Guide

ThrottlingException:

Your request was denied due to exceeding the account quotas for Amazon Bedrock. For troubleshooting this error, see ThrottlingException in the Amazon Bedrock User Guide

InternalServerException:

An internal server error occurred. For troubleshooting this error, see InternalFailure in the Amazon Bedrock User Guide

ValidationException:

The input fails to satisfy the constraints specified by Amazon Bedrock. For troubleshooting this error, see ValidationError in the Amazon Bedrock User Guide

ServiceQuotaExceededException:

Your request exceeds the service quota for your account. You can view your quotas at Viewing service quotas. You can resubmit your request later.

Converse

$result = $client->converse([/* ... */]);
$promise = $client->converseAsync([/* ... */]);

Sends messages to the specified Amazon Bedrock model. Converse provides a consistent interface that works with all models that support messages. This allows you to write code once and use it with different models. If a model has unique inference parameters, you can also pass those unique parameters to the model.

Amazon Bedrock doesn't store any text, images, or documents that you provide as content. The data is only used to generate the response.

You can submit a prompt by including it in the messages field, specifying the modelId of a foundation model or inference profile to run inference on it, and including any other fields that are relevant to your use case.

You can also submit a prompt from Prompt management by specifying the ARN of the prompt version and including a map of variables to values in the promptVariables field. You can append more messages to the prompt by using the messages field. If you use a prompt from Prompt management, you can't include the following fields in the request: additionalModelRequestFields, inferenceConfig, system, or toolConfig. Instead, these fields must be defined through Prompt management. For more information, see Use a prompt from Prompt management.

For information about the Converse API, see Use the Converse API in the Amazon Bedrock User Guide. To use a guardrail, see Use a guardrail with the Converse API in the Amazon Bedrock User Guide. To use a tool with a model, see Tool use (Function calling) in the Amazon Bedrock User Guide

For example code, see Converse API examples in the Amazon Bedrock User Guide.

This operation requires permission for the bedrock:InvokeModel action.

To deny all inference access to resources that you specify in the modelId field, you need to deny access to the bedrock:InvokeModel and bedrock:InvokeModelWithResponseStream actions. Doing this also denies access to the resource through the base inference actions (InvokeModel and InvokeModelWithResponseStream). For more information see Deny access for inference on specific models.

For troubleshooting some of the common errors you might encounter when using the Converse API, see Troubleshooting Amazon Bedrock API Error Codes in the Amazon Bedrock User Guide

Parameter Syntax

$result = $client->converse([
    'additionalModelRequestFields' => [
    ],
    'additionalModelResponseFieldPaths' => ['<string>', ...],
    'guardrailConfig' => [
        'guardrailIdentifier' => '<string>', // REQUIRED
        'guardrailVersion' => '<string>', // REQUIRED
        'trace' => 'enabled|disabled',
    ],
    'inferenceConfig' => [
        'maxTokens' => <integer>,
        'stopSequences' => ['<string>', ...],
        'temperature' => <float>,
        'topP' => <float>,
    ],
    'messages' => [
        [
            'content' => [ // REQUIRED
                [
                    'document' => [
                        'format' => 'pdf|csv|doc|docx|xls|xlsx|html|txt|md', // REQUIRED
                        'name' => '<string>', // REQUIRED
                        'source' => [ // REQUIRED
                            'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                        ],
                    ],
                    'guardContent' => [
                        'image' => [
                            'format' => 'png|jpeg', // REQUIRED
                            'source' => [ // REQUIRED
                                'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                            ],
                        ],
                        'text' => [
                            'qualifiers' => ['<string>', ...],
                            'text' => '<string>', // REQUIRED
                        ],
                    ],
                    'image' => [
                        'format' => 'png|jpeg|gif|webp', // REQUIRED
                        'source' => [ // REQUIRED
                            'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                        ],
                    ],
                    'text' => '<string>',
                    'toolResult' => [
                        'content' => [ // REQUIRED
                            [
                                'document' => [
                                    'format' => 'pdf|csv|doc|docx|xls|xlsx|html|txt|md', // REQUIRED
                                    'name' => '<string>', // REQUIRED
                                    'source' => [ // REQUIRED
                                        'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                                    ],
                                ],
                                'image' => [
                                    'format' => 'png|jpeg|gif|webp', // REQUIRED
                                    'source' => [ // REQUIRED
                                        'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                                    ],
                                ],
                                'json' => [
                                ],
                                'text' => '<string>',
                                'video' => [
                                    'format' => 'mkv|mov|mp4|webm|flv|mpeg|mpg|wmv|three_gp', // REQUIRED
                                    'source' => [ // REQUIRED
                                        'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                                        's3Location' => [
                                            'bucketOwner' => '<string>',
                                            'uri' => '<string>', // REQUIRED
                                        ],
                                    ],
                                ],
                            ],
                            // ...
                        ],
                        'status' => 'success|error',
                        'toolUseId' => '<string>', // REQUIRED
                    ],
                    'toolUse' => [
                        'input' => [ // REQUIRED
                        ],
                        'name' => '<string>', // REQUIRED
                        'toolUseId' => '<string>', // REQUIRED
                    ],
                    'video' => [
                        'format' => 'mkv|mov|mp4|webm|flv|mpeg|mpg|wmv|three_gp', // REQUIRED
                        'source' => [ // REQUIRED
                            'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                            's3Location' => [
                                'bucketOwner' => '<string>',
                                'uri' => '<string>', // REQUIRED
                            ],
                        ],
                    ],
                ],
                // ...
            ],
            'role' => 'user|assistant', // REQUIRED
        ],
        // ...
    ],
    'modelId' => '<string>', // REQUIRED
    'performanceConfig' => [
        'latency' => 'standard|optimized',
    ],
    'promptVariables' => [
        '<String>' => [
            'text' => '<string>',
        ],
        // ...
    ],
    'requestMetadata' => ['<string>', ...],
    'system' => [
        [
            'guardContent' => [
                'image' => [
                    'format' => 'png|jpeg', // REQUIRED
                    'source' => [ // REQUIRED
                        'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                    ],
                ],
                'text' => [
                    'qualifiers' => ['<string>', ...],
                    'text' => '<string>', // REQUIRED
                ],
            ],
            'text' => '<string>',
        ],
        // ...
    ],
    'toolConfig' => [
        'toolChoice' => [
            'any' => [
            ],
            'auto' => [
            ],
            'tool' => [
                'name' => '<string>', // REQUIRED
            ],
        ],
        'tools' => [ // REQUIRED
            [
                'toolSpec' => [
                    'description' => '<string>',
                    'inputSchema' => [ // REQUIRED
                        'json' => [
                        ],
                    ],
                    'name' => '<string>', // REQUIRED
                ],
            ],
            // ...
        ],
    ],
]);

Parameter Details

Members
additionalModelRequestFields
Type: document (null|bool|string|numeric) or an (array|associative array) whose members are all valid documents

Additional inference parameters that the model supports, beyond the base set of inference parameters that Converse and ConverseStream support in the inferenceConfig field. For more information, see Model parameters.

additionalModelResponseFieldPaths
Type: Array of strings

Additional model parameters field paths to return in the response. Converse and ConverseStream return the requested fields as a JSON Pointer object in the additionalModelResponseFields field. The following is example JSON for additionalModelResponseFieldPaths.

[ "/stop_sequence" ]

For information about the JSON Pointer syntax, see the Internet Engineering Task Force (IETF) documentation.

Converse and ConverseStream reject an empty JSON Pointer or incorrectly structured JSON Pointer with a 400 error code. if the JSON Pointer is valid, but the requested field is not in the model response, it is ignored by Converse.

guardrailConfig
Type: GuardrailConfiguration structure

Configuration information for a guardrail that you want to use in the request. If you include guardContent blocks in the content field in the messages field, the guardrail operates only on those messages. If you include no guardContent blocks, the guardrail operates on all messages in the request body and in any included prompt resource.

inferenceConfig
Type: InferenceConfiguration structure

Inference parameters to pass to the model. Converse and ConverseStream support a base set of inference parameters. If you need to pass additional parameters that the model supports, use the additionalModelRequestFields request field.

messages
Type: Array of Message structures

The messages that you want to send to the model.

modelId
Required: Yes
Type: string

Specifies the model or throughput with which to run inference, or the prompt resource to use in inference. The value depends on the resource that you use:

The Converse API doesn't support imported models.

performanceConfig
Type: PerformanceConfiguration structure

Model performance settings for the request.

promptVariables
Type: Associative array of custom strings keys (String) to PromptVariableValues structures

Contains a map of variables in a prompt from Prompt management to objects containing the values to fill in for them when running model invocation. This field is ignored if you don't specify a prompt resource in the modelId field.

requestMetadata
Type: Associative array of custom strings keys (RequestMetadataKeyString) to strings

Key-value pairs that you can use to filter invocation logs.

system
Type: Array of SystemContentBlock structures

A prompt that provides instructions or context to the model about the task it should perform, or the persona it should adopt during the conversation.

toolConfig
Type: ToolConfiguration structure

Configuration information for the tools that the model can use when generating a response.

For information about models that support tool use, see Supported models and model features.

Result Syntax

[
    'additionalModelResponseFields' => [
    ],
    'metrics' => [
        'latencyMs' => <integer>,
    ],
    'output' => [
        'message' => [
            'content' => [
                [
                    'document' => [
                        'format' => 'pdf|csv|doc|docx|xls|xlsx|html|txt|md',
                        'name' => '<string>',
                        'source' => [
                            'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                        ],
                    ],
                    'guardContent' => [
                        'image' => [
                            'format' => 'png|jpeg',
                            'source' => [
                                'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                            ],
                        ],
                        'text' => [
                            'qualifiers' => ['<string>', ...],
                            'text' => '<string>',
                        ],
                    ],
                    'image' => [
                        'format' => 'png|jpeg|gif|webp',
                        'source' => [
                            'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                        ],
                    ],
                    'text' => '<string>',
                    'toolResult' => [
                        'content' => [
                            [
                                'document' => [
                                    'format' => 'pdf|csv|doc|docx|xls|xlsx|html|txt|md',
                                    'name' => '<string>',
                                    'source' => [
                                        'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                                    ],
                                ],
                                'image' => [
                                    'format' => 'png|jpeg|gif|webp',
                                    'source' => [
                                        'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                                    ],
                                ],
                                'json' => [
                                ],
                                'text' => '<string>',
                                'video' => [
                                    'format' => 'mkv|mov|mp4|webm|flv|mpeg|mpg|wmv|three_gp',
                                    'source' => [
                                        'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                                        's3Location' => [
                                            'bucketOwner' => '<string>',
                                            'uri' => '<string>',
                                        ],
                                    ],
                                ],
                            ],
                            // ...
                        ],
                        'status' => 'success|error',
                        'toolUseId' => '<string>',
                    ],
                    'toolUse' => [
                        'input' => [
                        ],
                        'name' => '<string>',
                        'toolUseId' => '<string>',
                    ],
                    'video' => [
                        'format' => 'mkv|mov|mp4|webm|flv|mpeg|mpg|wmv|three_gp',
                        'source' => [
                            'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                            's3Location' => [
                                'bucketOwner' => '<string>',
                                'uri' => '<string>',
                            ],
                        ],
                    ],
                ],
                // ...
            ],
            'role' => 'user|assistant',
        ],
    ],
    'performanceConfig' => [
        'latency' => 'standard|optimized',
    ],
    'stopReason' => 'end_turn|tool_use|max_tokens|stop_sequence|guardrail_intervened|content_filtered',
    'trace' => [
        'guardrail' => [
            'inputAssessment' => [
                '<String>' => [
                    'contentPolicy' => [
                        'filters' => [
                            [
                                'action' => 'BLOCKED',
                                'confidence' => 'NONE|LOW|MEDIUM|HIGH',
                                'filterStrength' => 'NONE|LOW|MEDIUM|HIGH',
                                'type' => 'INSULTS|HATE|SEXUAL|VIOLENCE|MISCONDUCT|PROMPT_ATTACK',
                            ],
                            // ...
                        ],
                    ],
                    'contextualGroundingPolicy' => [
                        'filters' => [
                            [
                                'action' => 'BLOCKED|NONE',
                                'score' => <float>,
                                'threshold' => <float>,
                                'type' => 'GROUNDING|RELEVANCE',
                            ],
                            // ...
                        ],
                    ],
                    'invocationMetrics' => [
                        'guardrailCoverage' => [
                            'images' => [
                                'guarded' => <integer>,
                                'total' => <integer>,
                            ],
                            'textCharacters' => [
                                'guarded' => <integer>,
                                'total' => <integer>,
                            ],
                        ],
                        'guardrailProcessingLatency' => <integer>,
                        'usage' => [
                            'contentPolicyUnits' => <integer>,
                            'contextualGroundingPolicyUnits' => <integer>,
                            'sensitiveInformationPolicyFreeUnits' => <integer>,
                            'sensitiveInformationPolicyUnits' => <integer>,
                            'topicPolicyUnits' => <integer>,
                            'wordPolicyUnits' => <integer>,
                        ],
                    ],
                    'sensitiveInformationPolicy' => [
                        'piiEntities' => [
                            [
                                'action' => 'ANONYMIZED|BLOCKED',
                                'match' => '<string>',
                                'type' => 'ADDRESS|AGE|AWS_ACCESS_KEY|AWS_SECRET_KEY|CA_HEALTH_NUMBER|CA_SOCIAL_INSURANCE_NUMBER|CREDIT_DEBIT_CARD_CVV|CREDIT_DEBIT_CARD_EXPIRY|CREDIT_DEBIT_CARD_NUMBER|DRIVER_ID|EMAIL|INTERNATIONAL_BANK_ACCOUNT_NUMBER|IP_ADDRESS|LICENSE_PLATE|MAC_ADDRESS|NAME|PASSWORD|PHONE|PIN|SWIFT_CODE|UK_NATIONAL_HEALTH_SERVICE_NUMBER|UK_NATIONAL_INSURANCE_NUMBER|UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER|URL|USERNAME|US_BANK_ACCOUNT_NUMBER|US_BANK_ROUTING_NUMBER|US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER|US_PASSPORT_NUMBER|US_SOCIAL_SECURITY_NUMBER|VEHICLE_IDENTIFICATION_NUMBER',
                            ],
                            // ...
                        ],
                        'regexes' => [
                            [
                                'action' => 'ANONYMIZED|BLOCKED',
                                'match' => '<string>',
                                'name' => '<string>',
                                'regex' => '<string>',
                            ],
                            // ...
                        ],
                    ],
                    'topicPolicy' => [
                        'topics' => [
                            [
                                'action' => 'BLOCKED',
                                'name' => '<string>',
                                'type' => 'DENY',
                            ],
                            // ...
                        ],
                    ],
                    'wordPolicy' => [
                        'customWords' => [
                            [
                                'action' => 'BLOCKED',
                                'match' => '<string>',
                            ],
                            // ...
                        ],
                        'managedWordLists' => [
                            [
                                'action' => 'BLOCKED',
                                'match' => '<string>',
                                'type' => 'PROFANITY',
                            ],
                            // ...
                        ],
                    ],
                ],
                // ...
            ],
            'modelOutput' => ['<string>', ...],
            'outputAssessments' => [
                '<String>' => [
                    [
                        'contentPolicy' => [
                            'filters' => [
                                [
                                    'action' => 'BLOCKED',
                                    'confidence' => 'NONE|LOW|MEDIUM|HIGH',
                                    'filterStrength' => 'NONE|LOW|MEDIUM|HIGH',
                                    'type' => 'INSULTS|HATE|SEXUAL|VIOLENCE|MISCONDUCT|PROMPT_ATTACK',
                                ],
                                // ...
                            ],
                        ],
                        'contextualGroundingPolicy' => [
                            'filters' => [
                                [
                                    'action' => 'BLOCKED|NONE',
                                    'score' => <float>,
                                    'threshold' => <float>,
                                    'type' => 'GROUNDING|RELEVANCE',
                                ],
                                // ...
                            ],
                        ],
                        'invocationMetrics' => [
                            'guardrailCoverage' => [
                                'images' => [
                                    'guarded' => <integer>,
                                    'total' => <integer>,
                                ],
                                'textCharacters' => [
                                    'guarded' => <integer>,
                                    'total' => <integer>,
                                ],
                            ],
                            'guardrailProcessingLatency' => <integer>,
                            'usage' => [
                                'contentPolicyUnits' => <integer>,
                                'contextualGroundingPolicyUnits' => <integer>,
                                'sensitiveInformationPolicyFreeUnits' => <integer>,
                                'sensitiveInformationPolicyUnits' => <integer>,
                                'topicPolicyUnits' => <integer>,
                                'wordPolicyUnits' => <integer>,
                            ],
                        ],
                        'sensitiveInformationPolicy' => [
                            'piiEntities' => [
                                [
                                    'action' => 'ANONYMIZED|BLOCKED',
                                    'match' => '<string>',
                                    'type' => 'ADDRESS|AGE|AWS_ACCESS_KEY|AWS_SECRET_KEY|CA_HEALTH_NUMBER|CA_SOCIAL_INSURANCE_NUMBER|CREDIT_DEBIT_CARD_CVV|CREDIT_DEBIT_CARD_EXPIRY|CREDIT_DEBIT_CARD_NUMBER|DRIVER_ID|EMAIL|INTERNATIONAL_BANK_ACCOUNT_NUMBER|IP_ADDRESS|LICENSE_PLATE|MAC_ADDRESS|NAME|PASSWORD|PHONE|PIN|SWIFT_CODE|UK_NATIONAL_HEALTH_SERVICE_NUMBER|UK_NATIONAL_INSURANCE_NUMBER|UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER|URL|USERNAME|US_BANK_ACCOUNT_NUMBER|US_BANK_ROUTING_NUMBER|US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER|US_PASSPORT_NUMBER|US_SOCIAL_SECURITY_NUMBER|VEHICLE_IDENTIFICATION_NUMBER',
                                ],
                                // ...
                            ],
                            'regexes' => [
                                [
                                    'action' => 'ANONYMIZED|BLOCKED',
                                    'match' => '<string>',
                                    'name' => '<string>',
                                    'regex' => '<string>',
                                ],
                                // ...
                            ],
                        ],
                        'topicPolicy' => [
                            'topics' => [
                                [
                                    'action' => 'BLOCKED',
                                    'name' => '<string>',
                                    'type' => 'DENY',
                                ],
                                // ...
                            ],
                        ],
                        'wordPolicy' => [
                            'customWords' => [
                                [
                                    'action' => 'BLOCKED',
                                    'match' => '<string>',
                                ],
                                // ...
                            ],
                            'managedWordLists' => [
                                [
                                    'action' => 'BLOCKED',
                                    'match' => '<string>',
                                    'type' => 'PROFANITY',
                                ],
                                // ...
                            ],
                        ],
                    ],
                    // ...
                ],
                // ...
            ],
        ],
        'promptRouter' => [
            'invokedModelId' => '<string>',
        ],
    ],
    'usage' => [
        'inputTokens' => <integer>,
        'outputTokens' => <integer>,
        'totalTokens' => <integer>,
    ],
]

Result Details

Members
additionalModelResponseFields
Type: document (null|bool|string|numeric) or an (array|associative array) whose members are all valid documents

Additional fields in the response that are unique to the model.

metrics
Required: Yes
Type: ConverseMetrics structure

Metrics for the call to Converse.

output
Required: Yes
Type: ConverseOutput structure

The result from the call to Converse.

performanceConfig
Type: PerformanceConfiguration structure

Model performance settings for the request.

stopReason
Required: Yes
Type: string

The reason why the model stopped generating output.

trace
Type: ConverseTrace structure

A trace object that contains information about the Guardrail behavior.

usage
Required: Yes
Type: TokenUsage structure

The total number of tokens used in the call to Converse. The total includes the tokens input to the model and the tokens generated by the model.

Errors

AccessDeniedException:

The request is denied because you do not have sufficient permissions to perform the requested action. For troubleshooting this error, see AccessDeniedException in the Amazon Bedrock User Guide

ResourceNotFoundException:

The specified resource ARN was not found. For troubleshooting this error, see ResourceNotFound in the Amazon Bedrock User Guide

ThrottlingException:

Your request was denied due to exceeding the account quotas for Amazon Bedrock. For troubleshooting this error, see ThrottlingException in the Amazon Bedrock User Guide

ModelTimeoutException:

The request took too long to process. Processing time exceeded the model timeout length.

InternalServerException:

An internal server error occurred. For troubleshooting this error, see InternalFailure in the Amazon Bedrock User Guide

ServiceUnavailableException:

The service isn't currently available. For troubleshooting this error, see ServiceUnavailable in the Amazon Bedrock User Guide

ValidationException:

The input fails to satisfy the constraints specified by Amazon Bedrock. For troubleshooting this error, see ValidationError in the Amazon Bedrock User Guide

ModelNotReadyException:

The model specified in the request is not ready to serve inference requests. The AWS SDK will automatically retry the operation up to 5 times. For information about configuring automatic retries, see Retry behavior in the AWS SDKs and Tools reference guide.

ModelErrorException:

The request failed due to an error while processing the model.

ConverseStream

$result = $client->converseStream([/* ... */]);
$promise = $client->converseStreamAsync([/* ... */]);

Sends messages to the specified Amazon Bedrock model and returns the response in a stream. ConverseStream provides a consistent API that works with all Amazon Bedrock models that support messages. This allows you to write code once and use it with different models. Should a model have unique inference parameters, you can also pass those unique parameters to the model.

To find out if a model supports streaming, call GetFoundationModel and check the responseStreamingSupported field in the response.

The CLI doesn't support streaming operations in Amazon Bedrock, including ConverseStream.

Amazon Bedrock doesn't store any text, images, or documents that you provide as content. The data is only used to generate the response.

You can submit a prompt by including it in the messages field, specifying the modelId of a foundation model or inference profile to run inference on it, and including any other fields that are relevant to your use case.

You can also submit a prompt from Prompt management by specifying the ARN of the prompt version and including a map of variables to values in the promptVariables field. You can append more messages to the prompt by using the messages field. If you use a prompt from Prompt management, you can't include the following fields in the request: additionalModelRequestFields, inferenceConfig, system, or toolConfig. Instead, these fields must be defined through Prompt management. For more information, see Use a prompt from Prompt management.

For information about the Converse API, see Use the Converse API in the Amazon Bedrock User Guide. To use a guardrail, see Use a guardrail with the Converse API in the Amazon Bedrock User Guide. To use a tool with a model, see Tool use (Function calling) in the Amazon Bedrock User Guide

For example code, see Conversation streaming example in the Amazon Bedrock User Guide.

This operation requires permission for the bedrock:InvokeModelWithResponseStream action.

To deny all inference access to resources that you specify in the modelId field, you need to deny access to the bedrock:InvokeModel and bedrock:InvokeModelWithResponseStream actions. Doing this also denies access to the resource through the base inference actions (InvokeModel and InvokeModelWithResponseStream). For more information see Deny access for inference on specific models.

For troubleshooting some of the common errors you might encounter when using the ConverseStream API, see Troubleshooting Amazon Bedrock API Error Codes in the Amazon Bedrock User Guide

Parameter Syntax

$result = $client->converseStream([
    'additionalModelRequestFields' => [
    ],
    'additionalModelResponseFieldPaths' => ['<string>', ...],
    'guardrailConfig' => [
        'guardrailIdentifier' => '<string>', // REQUIRED
        'guardrailVersion' => '<string>', // REQUIRED
        'streamProcessingMode' => 'sync|async',
        'trace' => 'enabled|disabled',
    ],
    'inferenceConfig' => [
        'maxTokens' => <integer>,
        'stopSequences' => ['<string>', ...],
        'temperature' => <float>,
        'topP' => <float>,
    ],
    'messages' => [
        [
            'content' => [ // REQUIRED
                [
                    'document' => [
                        'format' => 'pdf|csv|doc|docx|xls|xlsx|html|txt|md', // REQUIRED
                        'name' => '<string>', // REQUIRED
                        'source' => [ // REQUIRED
                            'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                        ],
                    ],
                    'guardContent' => [
                        'image' => [
                            'format' => 'png|jpeg', // REQUIRED
                            'source' => [ // REQUIRED
                                'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                            ],
                        ],
                        'text' => [
                            'qualifiers' => ['<string>', ...],
                            'text' => '<string>', // REQUIRED
                        ],
                    ],
                    'image' => [
                        'format' => 'png|jpeg|gif|webp', // REQUIRED
                        'source' => [ // REQUIRED
                            'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                        ],
                    ],
                    'text' => '<string>',
                    'toolResult' => [
                        'content' => [ // REQUIRED
                            [
                                'document' => [
                                    'format' => 'pdf|csv|doc|docx|xls|xlsx|html|txt|md', // REQUIRED
                                    'name' => '<string>', // REQUIRED
                                    'source' => [ // REQUIRED
                                        'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                                    ],
                                ],
                                'image' => [
                                    'format' => 'png|jpeg|gif|webp', // REQUIRED
                                    'source' => [ // REQUIRED
                                        'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                                    ],
                                ],
                                'json' => [
                                ],
                                'text' => '<string>',
                                'video' => [
                                    'format' => 'mkv|mov|mp4|webm|flv|mpeg|mpg|wmv|three_gp', // REQUIRED
                                    'source' => [ // REQUIRED
                                        'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                                        's3Location' => [
                                            'bucketOwner' => '<string>',
                                            'uri' => '<string>', // REQUIRED
                                        ],
                                    ],
                                ],
                            ],
                            // ...
                        ],
                        'status' => 'success|error',
                        'toolUseId' => '<string>', // REQUIRED
                    ],
                    'toolUse' => [
                        'input' => [ // REQUIRED
                        ],
                        'name' => '<string>', // REQUIRED
                        'toolUseId' => '<string>', // REQUIRED
                    ],
                    'video' => [
                        'format' => 'mkv|mov|mp4|webm|flv|mpeg|mpg|wmv|three_gp', // REQUIRED
                        'source' => [ // REQUIRED
                            'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                            's3Location' => [
                                'bucketOwner' => '<string>',
                                'uri' => '<string>', // REQUIRED
                            ],
                        ],
                    ],
                ],
                // ...
            ],
            'role' => 'user|assistant', // REQUIRED
        ],
        // ...
    ],
    'modelId' => '<string>', // REQUIRED
    'performanceConfig' => [
        'latency' => 'standard|optimized',
    ],
    'promptVariables' => [
        '<String>' => [
            'text' => '<string>',
        ],
        // ...
    ],
    'requestMetadata' => ['<string>', ...],
    'system' => [
        [
            'guardContent' => [
                'image' => [
                    'format' => 'png|jpeg', // REQUIRED
                    'source' => [ // REQUIRED
                        'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
                    ],
                ],
                'text' => [
                    'qualifiers' => ['<string>', ...],
                    'text' => '<string>', // REQUIRED
                ],
            ],
            'text' => '<string>',
        ],
        // ...
    ],
    'toolConfig' => [
        'toolChoice' => [
            'any' => [
            ],
            'auto' => [
            ],
            'tool' => [
                'name' => '<string>', // REQUIRED
            ],
        ],
        'tools' => [ // REQUIRED
            [
                'toolSpec' => [
                    'description' => '<string>',
                    'inputSchema' => [ // REQUIRED
                        'json' => [
                        ],
                    ],
                    'name' => '<string>', // REQUIRED
                ],
            ],
            // ...
        ],
    ],
]);

Parameter Details

Members
additionalModelRequestFields
Type: document (null|bool|string|numeric) or an (array|associative array) whose members are all valid documents

Additional inference parameters that the model supports, beyond the base set of inference parameters that Converse and ConverseStream support in the inferenceConfig field. For more information, see Model parameters.

additionalModelResponseFieldPaths
Type: Array of strings

Additional model parameters field paths to return in the response. Converse and ConverseStream return the requested fields as a JSON Pointer object in the additionalModelResponseFields field. The following is example JSON for additionalModelResponseFieldPaths.

[ "/stop_sequence" ]

For information about the JSON Pointer syntax, see the Internet Engineering Task Force (IETF) documentation.

Converse and ConverseStream reject an empty JSON Pointer or incorrectly structured JSON Pointer with a 400 error code. if the JSON Pointer is valid, but the requested field is not in the model response, it is ignored by Converse.

guardrailConfig

Configuration information for a guardrail that you want to use in the request. If you include guardContent blocks in the content field in the messages field, the guardrail operates only on those messages. If you include no guardContent blocks, the guardrail operates on all messages in the request body and in any included prompt resource.

inferenceConfig
Type: InferenceConfiguration structure

Inference parameters to pass to the model. Converse and ConverseStream support a base set of inference parameters. If you need to pass additional parameters that the model supports, use the additionalModelRequestFields request field.

messages
Type: Array of Message structures

The messages that you want to send to the model.

modelId
Required: Yes
Type: string

Specifies the model or throughput with which to run inference, or the prompt resource to use in inference. The value depends on the resource that you use:

The Converse API doesn't support imported models.

performanceConfig
Type: PerformanceConfiguration structure

Model performance settings for the request.

promptVariables
Type: Associative array of custom strings keys (String) to PromptVariableValues structures

Contains a map of variables in a prompt from Prompt management to objects containing the values to fill in for them when running model invocation. This field is ignored if you don't specify a prompt resource in the modelId field.

requestMetadata
Type: Associative array of custom strings keys (RequestMetadataKeyString) to strings

Key-value pairs that you can use to filter invocation logs.

system
Type: Array of SystemContentBlock structures

A prompt that provides instructions or context to the model about the task it should perform, or the persona it should adopt during the conversation.

toolConfig
Type: ToolConfiguration structure

Configuration information for the tools that the model can use when generating a response.

For information about models that support streaming tool use, see Supported models and model features.

Result Syntax

[
    'stream' => [ // EventParsingIterator
        'contentBlockDelta' => [
            'contentBlockIndex' => <integer>,
            'delta' => [
                'text' => '<string>',
                'toolUse' => [
                    'input' => '<string>',
                ],
            ],
        ],
        'contentBlockStart' => [
            'contentBlockIndex' => <integer>,
            'start' => [
                'toolUse' => [
                    'name' => '<string>',
                    'toolUseId' => '<string>',
                ],
            ],
        ],
        'contentBlockStop' => [
            'contentBlockIndex' => <integer>,
        ],
        'internalServerException' => [
            'message' => '<string>',
        ],
        'messageStart' => [
            'role' => 'user|assistant',
        ],
        'messageStop' => [
            'additionalModelResponseFields' => [
            ],
            'stopReason' => 'end_turn|tool_use|max_tokens|stop_sequence|guardrail_intervened|content_filtered',
        ],
        'metadata' => [
            'metrics' => [
                'latencyMs' => <integer>,
            ],
            'performanceConfig' => [
                'latency' => 'standard|optimized',
            ],
            'trace' => [
                'guardrail' => [
                    'inputAssessment' => [
                        '<String>' => [
                            'contentPolicy' => [
                                'filters' => [
                                    [
                                        'action' => 'BLOCKED',
                                        'confidence' => 'NONE|LOW|MEDIUM|HIGH',
                                        'filterStrength' => 'NONE|LOW|MEDIUM|HIGH',
                                        'type' => 'INSULTS|HATE|SEXUAL|VIOLENCE|MISCONDUCT|PROMPT_ATTACK',
                                    ],
                                    // ...
                                ],
                            ],
                            'contextualGroundingPolicy' => [
                                'filters' => [
                                    [
                                        'action' => 'BLOCKED|NONE',
                                        'score' => <float>,
                                        'threshold' => <float>,
                                        'type' => 'GROUNDING|RELEVANCE',
                                    ],
                                    // ...
                                ],
                            ],
                            'invocationMetrics' => [
                                'guardrailCoverage' => [
                                    'images' => [
                                        'guarded' => <integer>,
                                        'total' => <integer>,
                                    ],
                                    'textCharacters' => [
                                        'guarded' => <integer>,
                                        'total' => <integer>,
                                    ],
                                ],
                                'guardrailProcessingLatency' => <integer>,
                                'usage' => [
                                    'contentPolicyUnits' => <integer>,
                                    'contextualGroundingPolicyUnits' => <integer>,
                                    'sensitiveInformationPolicyFreeUnits' => <integer>,
                                    'sensitiveInformationPolicyUnits' => <integer>,
                                    'topicPolicyUnits' => <integer>,
                                    'wordPolicyUnits' => <integer>,
                                ],
                            ],
                            'sensitiveInformationPolicy' => [
                                'piiEntities' => [
                                    [
                                        'action' => 'ANONYMIZED|BLOCKED',
                                        'match' => '<string>',
                                        'type' => 'ADDRESS|AGE|AWS_ACCESS_KEY|AWS_SECRET_KEY|CA_HEALTH_NUMBER|CA_SOCIAL_INSURANCE_NUMBER|CREDIT_DEBIT_CARD_CVV|CREDIT_DEBIT_CARD_EXPIRY|CREDIT_DEBIT_CARD_NUMBER|DRIVER_ID|EMAIL|INTERNATIONAL_BANK_ACCOUNT_NUMBER|IP_ADDRESS|LICENSE_PLATE|MAC_ADDRESS|NAME|PASSWORD|PHONE|PIN|SWIFT_CODE|UK_NATIONAL_HEALTH_SERVICE_NUMBER|UK_NATIONAL_INSURANCE_NUMBER|UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER|URL|USERNAME|US_BANK_ACCOUNT_NUMBER|US_BANK_ROUTING_NUMBER|US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER|US_PASSPORT_NUMBER|US_SOCIAL_SECURITY_NUMBER|VEHICLE_IDENTIFICATION_NUMBER',
                                    ],
                                    // ...
                                ],
                                'regexes' => [
                                    [
                                        'action' => 'ANONYMIZED|BLOCKED',
                                        'match' => '<string>',
                                        'name' => '<string>',
                                        'regex' => '<string>',
                                    ],
                                    // ...
                                ],
                            ],
                            'topicPolicy' => [
                                'topics' => [
                                    [
                                        'action' => 'BLOCKED',
                                        'name' => '<string>',
                                        'type' => 'DENY',
                                    ],
                                    // ...
                                ],
                            ],
                            'wordPolicy' => [
                                'customWords' => [
                                    [
                                        'action' => 'BLOCKED',
                                        'match' => '<string>',
                                    ],
                                    // ...
                                ],
                                'managedWordLists' => [
                                    [
                                        'action' => 'BLOCKED',
                                        'match' => '<string>',
                                        'type' => 'PROFANITY',
                                    ],
                                    // ...
                                ],
                            ],
                        ],
                        // ...
                    ],
                    'modelOutput' => ['<string>', ...],
                    'outputAssessments' => [
                        '<String>' => [
                            [
                                'contentPolicy' => [
                                    'filters' => [
                                        [
                                            'action' => 'BLOCKED',
                                            'confidence' => 'NONE|LOW|MEDIUM|HIGH',
                                            'filterStrength' => 'NONE|LOW|MEDIUM|HIGH',
                                            'type' => 'INSULTS|HATE|SEXUAL|VIOLENCE|MISCONDUCT|PROMPT_ATTACK',
                                        ],
                                        // ...
                                    ],
                                ],
                                'contextualGroundingPolicy' => [
                                    'filters' => [
                                        [
                                            'action' => 'BLOCKED|NONE',
                                            'score' => <float>,
                                            'threshold' => <float>,
                                            'type' => 'GROUNDING|RELEVANCE',
                                        ],
                                        // ...
                                    ],
                                ],
                                'invocationMetrics' => [
                                    'guardrailCoverage' => [
                                        'images' => [
                                            'guarded' => <integer>,
                                            'total' => <integer>,
                                        ],
                                        'textCharacters' => [
                                            'guarded' => <integer>,
                                            'total' => <integer>,
                                        ],
                                    ],
                                    'guardrailProcessingLatency' => <integer>,
                                    'usage' => [
                                        'contentPolicyUnits' => <integer>,
                                        'contextualGroundingPolicyUnits' => <integer>,
                                        'sensitiveInformationPolicyFreeUnits' => <integer>,
                                        'sensitiveInformationPolicyUnits' => <integer>,
                                        'topicPolicyUnits' => <integer>,
                                        'wordPolicyUnits' => <integer>,
                                    ],
                                ],
                                'sensitiveInformationPolicy' => [
                                    'piiEntities' => [
                                        [
                                            'action' => 'ANONYMIZED|BLOCKED',
                                            'match' => '<string>',
                                            'type' => 'ADDRESS|AGE|AWS_ACCESS_KEY|AWS_SECRET_KEY|CA_HEALTH_NUMBER|CA_SOCIAL_INSURANCE_NUMBER|CREDIT_DEBIT_CARD_CVV|CREDIT_DEBIT_CARD_EXPIRY|CREDIT_DEBIT_CARD_NUMBER|DRIVER_ID|EMAIL|INTERNATIONAL_BANK_ACCOUNT_NUMBER|IP_ADDRESS|LICENSE_PLATE|MAC_ADDRESS|NAME|PASSWORD|PHONE|PIN|SWIFT_CODE|UK_NATIONAL_HEALTH_SERVICE_NUMBER|UK_NATIONAL_INSURANCE_NUMBER|UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER|URL|USERNAME|US_BANK_ACCOUNT_NUMBER|US_BANK_ROUTING_NUMBER|US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER|US_PASSPORT_NUMBER|US_SOCIAL_SECURITY_NUMBER|VEHICLE_IDENTIFICATION_NUMBER',
                                        ],
                                        // ...
                                    ],
                                    'regexes' => [
                                        [
                                            'action' => 'ANONYMIZED|BLOCKED',
                                            'match' => '<string>',
                                            'name' => '<string>',
                                            'regex' => '<string>',
                                        ],
                                        // ...
                                    ],
                                ],
                                'topicPolicy' => [
                                    'topics' => [
                                        [
                                            'action' => 'BLOCKED',
                                            'name' => '<string>',
                                            'type' => 'DENY',
                                        ],
                                        // ...
                                    ],
                                ],
                                'wordPolicy' => [
                                    'customWords' => [
                                        [
                                            'action' => 'BLOCKED',
                                            'match' => '<string>',
                                        ],
                                        // ...
                                    ],
                                    'managedWordLists' => [
                                        [
                                            'action' => 'BLOCKED',
                                            'match' => '<string>',
                                            'type' => 'PROFANITY',
                                        ],
                                        // ...
                                    ],
                                ],
                            ],
                            // ...
                        ],
                        // ...
                    ],
                ],
                'promptRouter' => [
                    'invokedModelId' => '<string>',
                ],
            ],
            'usage' => [
                'inputTokens' => <integer>,
                'outputTokens' => <integer>,
                'totalTokens' => <integer>,
            ],
        ],
        'modelStreamErrorException' => [
            'message' => '<string>',
            'originalMessage' => '<string>',
            'originalStatusCode' => <integer>,
        ],
        'serviceUnavailableException' => [
            'message' => '<string>',
        ],
        'throttlingException' => [
            'message' => '<string>',
        ],
        'validationException' => [
            'message' => '<string>',
        ],
    ],
]

Result Details

Using an EventParsingIterator

To use an EventParsingIterator, you will need to loop over the events it will generate and check the top-level field to determine which type of event it is.

foreach($result['stream'] as $event) {
    if (isset($event['contentBlockDelta'])) {
        // Handle the 'contentBlockDelta' event.
    } else if (isset($event['contentBlockStart'])) {
        // Handle the 'contentBlockStart' event.
    } else if (isset($event['contentBlockStop'])) {
        // Handle the 'contentBlockStop' event.
    } else if (isset($event['internalServerException'])) {
        // Handle the 'internalServerException' event.
    } else if (isset($event['messageStart'])) {
        // Handle the 'messageStart' event.
    } else if (isset($event['messageStop'])) {
        // Handle the 'messageStop' event.
    } else if (isset($event['metadata'])) {
        // Handle the 'metadata' event.
    } else if (isset($event['modelStreamErrorException'])) {
        // Handle the 'modelStreamErrorException' event.
    } else if (isset($event['serviceUnavailableException'])) {
        // Handle the 'serviceUnavailableException' event.
    } else if (isset($event['throttlingException'])) {
        // Handle the 'throttlingException' event.
    } else if (isset($event['validationException'])) {
        // Handle the 'validationException' event.
    }
}

Errors

AccessDeniedException:

The request is denied because you do not have sufficient permissions to perform the requested action. For troubleshooting this error, see AccessDeniedException in the Amazon Bedrock User Guide

ResourceNotFoundException:

The specified resource ARN was not found. For troubleshooting this error, see ResourceNotFound in the Amazon Bedrock User Guide

ThrottlingException:

Your request was denied due to exceeding the account quotas for Amazon Bedrock. For troubleshooting this error, see ThrottlingException in the Amazon Bedrock User Guide

ModelTimeoutException:

The request took too long to process. Processing time exceeded the model timeout length.

InternalServerException:

An internal server error occurred. For troubleshooting this error, see InternalFailure in the Amazon Bedrock User Guide

ServiceUnavailableException:

The service isn't currently available. For troubleshooting this error, see ServiceUnavailable in the Amazon Bedrock User Guide

ValidationException:

The input fails to satisfy the constraints specified by Amazon Bedrock. For troubleshooting this error, see ValidationError in the Amazon Bedrock User Guide

ModelNotReadyException:

The model specified in the request is not ready to serve inference requests. The AWS SDK will automatically retry the operation up to 5 times. For information about configuring automatic retries, see Retry behavior in the AWS SDKs and Tools reference guide.

ModelErrorException:

The request failed due to an error while processing the model.

GetAsyncInvoke

$result = $client->getAsyncInvoke([/* ... */]);
$promise = $client->getAsyncInvokeAsync([/* ... */]);

Retrieve information about an asynchronous invocation.

Parameter Syntax

$result = $client->getAsyncInvoke([
    'invocationArn' => '<string>', // REQUIRED
]);

Parameter Details

Members
invocationArn
Required: Yes
Type: string

The invocation's ARN.

Result Syntax

[
    'clientRequestToken' => '<string>',
    'endTime' => <DateTime>,
    'failureMessage' => '<string>',
    'invocationArn' => '<string>',
    'lastModifiedTime' => <DateTime>,
    'modelArn' => '<string>',
    'outputDataConfig' => [
        's3OutputDataConfig' => [
            'bucketOwner' => '<string>',
            'kmsKeyId' => '<string>',
            's3Uri' => '<string>',
        ],
    ],
    'status' => 'InProgress|Completed|Failed',
    'submitTime' => <DateTime>,
]

Result Details

Members
clientRequestToken
Type: string

The invocation's idempotency token.

endTime
Type: timestamp (string|DateTime or anything parsable by strtotime)

When the invocation ended.

failureMessage
Type: string

An error message.

invocationArn
Required: Yes
Type: string

The invocation's ARN.

lastModifiedTime
Type: timestamp (string|DateTime or anything parsable by strtotime)

The invocation's last modified time.

modelArn
Required: Yes
Type: string

The invocation's model ARN.

outputDataConfig
Required: Yes
Type: AsyncInvokeOutputDataConfig structure

Output data settings.

status
Required: Yes
Type: string

The invocation's status.

submitTime
Required: Yes
Type: timestamp (string|DateTime or anything parsable by strtotime)

When the invocation request was submitted.

Errors

AccessDeniedException:

The request is denied because you do not have sufficient permissions to perform the requested action. For troubleshooting this error, see AccessDeniedException in the Amazon Bedrock User Guide

ThrottlingException:

Your request was denied due to exceeding the account quotas for Amazon Bedrock. For troubleshooting this error, see ThrottlingException in the Amazon Bedrock User Guide

InternalServerException:

An internal server error occurred. For troubleshooting this error, see InternalFailure in the Amazon Bedrock User Guide

ValidationException:

The input fails to satisfy the constraints specified by Amazon Bedrock. For troubleshooting this error, see ValidationError in the Amazon Bedrock User Guide

InvokeModel

$result = $client->invokeModel([/* ... */]);
$promise = $client->invokeModelAsync([/* ... */]);

Invokes the specified Amazon Bedrock model to run inference using the prompt and inference parameters provided in the request body. You use model inference to generate text, images, and embeddings.

For example code, see Invoke model code examples in the Amazon Bedrock User Guide.

This operation requires permission for the bedrock:InvokeModel action.

To deny all inference access to resources that you specify in the modelId field, you need to deny access to the bedrock:InvokeModel and bedrock:InvokeModelWithResponseStream actions. Doing this also denies access to the resource through the Converse API actions (Converse and ConverseStream). For more information see Deny access for inference on specific models.

For troubleshooting some of the common errors you might encounter when using the InvokeModel API, see Troubleshooting Amazon Bedrock API Error Codes in the Amazon Bedrock User Guide

Parameter Syntax

$result = $client->invokeModel([
    'accept' => '<string>',
    'body' => <string || resource || Psr\Http\Message\StreamInterface>,
    'contentType' => '<string>',
    'guardrailIdentifier' => '<string>',
    'guardrailVersion' => '<string>',
    'modelId' => '<string>', // REQUIRED
    'performanceConfigLatency' => 'standard|optimized',
    'trace' => 'ENABLED|DISABLED',
]);

Parameter Details

Members
accept
Type: string

The desired MIME type of the inference body in the response. The default value is application/json.

body
Type: blob (string|resource|Psr\Http\Message\StreamInterface)

The prompt and inference parameters in the format specified in the contentType in the header. You must provide the body in JSON format. To see the format and content of the request and response bodies for different models, refer to Inference parameters. For more information, see Run inference in the Bedrock User Guide.

contentType
Type: string

The MIME type of the input data in the request. You must specify application/json.

guardrailIdentifier
Type: string

The unique identifier of the guardrail that you want to use. If you don't provide a value, no guardrail is applied to the invocation.

An error will be thrown in the following situations.

  • You don't provide a guardrail identifier but you specify the amazon-bedrock-guardrailConfig field in the request body.

  • You enable the guardrail but the contentType isn't application/json.

  • You provide a guardrail identifier, but guardrailVersion isn't specified.

guardrailVersion
Type: string

The version number for the guardrail. The value can also be DRAFT.

modelId
Required: Yes
Type: string

The unique identifier of the model to invoke to run inference.

The modelId to provide depends on the type of model or throughput that you use:

performanceConfigLatency
Type: string

Model performance settings for the request.

trace
Type: string

Specifies whether to enable or disable the Bedrock trace. If enabled, you can see the full Bedrock trace.

Result Syntax

[
    'body' => <string || resource || Psr\Http\Message\StreamInterface>,
    'contentType' => '<string>',
    'performanceConfigLatency' => 'standard|optimized',
]

Result Details

Members
body
Required: Yes
Type: blob (string|resource|Psr\Http\Message\StreamInterface)

Inference response from the model in the format specified in the contentType header. To see the format and content of the request and response bodies for different models, refer to Inference parameters.

contentType
Required: Yes
Type: string

The MIME type of the inference result.

performanceConfigLatency
Type: string

Model performance settings for the request.

Errors

AccessDeniedException:

The request is denied because you do not have sufficient permissions to perform the requested action. For troubleshooting this error, see AccessDeniedException in the Amazon Bedrock User Guide

ResourceNotFoundException:

The specified resource ARN was not found. For troubleshooting this error, see ResourceNotFound in the Amazon Bedrock User Guide

ThrottlingException:

Your request was denied due to exceeding the account quotas for Amazon Bedrock. For troubleshooting this error, see ThrottlingException in the Amazon Bedrock User Guide

ModelTimeoutException:

The request took too long to process. Processing time exceeded the model timeout length.

InternalServerException:

An internal server error occurred. For troubleshooting this error, see InternalFailure in the Amazon Bedrock User Guide

ServiceUnavailableException:

The service isn't currently available. For troubleshooting this error, see ServiceUnavailable in the Amazon Bedrock User Guide

ValidationException:

The input fails to satisfy the constraints specified by Amazon Bedrock. For troubleshooting this error, see ValidationError in the Amazon Bedrock User Guide

ModelNotReadyException:

The model specified in the request is not ready to serve inference requests. The AWS SDK will automatically retry the operation up to 5 times. For information about configuring automatic retries, see Retry behavior in the AWS SDKs and Tools reference guide.

ServiceQuotaExceededException:

Your request exceeds the service quota for your account. You can view your quotas at Viewing service quotas. You can resubmit your request later.

ModelErrorException:

The request failed due to an error while processing the model.

InvokeModelWithResponseStream

$result = $client->invokeModelWithResponseStream([/* ... */]);
$promise = $client->invokeModelWithResponseStreamAsync([/* ... */]);

Invoke the specified Amazon Bedrock model to run inference using the prompt and inference parameters provided in the request body. The response is returned in a stream.

To see if a model supports streaming, call GetFoundationModel and check the responseStreamingSupported field in the response.

The CLI doesn't support streaming operations in Amazon Bedrock, including InvokeModelWithResponseStream.

For example code, see Invoke model with streaming code example in the Amazon Bedrock User Guide.

This operation requires permissions to perform the bedrock:InvokeModelWithResponseStream action.

To deny all inference access to resources that you specify in the modelId field, you need to deny access to the bedrock:InvokeModel and bedrock:InvokeModelWithResponseStream actions. Doing this also denies access to the resource through the Converse API actions (Converse and ConverseStream). For more information see Deny access for inference on specific models.

For troubleshooting some of the common errors you might encounter when using the InvokeModelWithResponseStream API, see Troubleshooting Amazon Bedrock API Error Codes in the Amazon Bedrock User Guide

Parameter Syntax

$result = $client->invokeModelWithResponseStream([
    'accept' => '<string>',
    'body' => <string || resource || Psr\Http\Message\StreamInterface>,
    'contentType' => '<string>',
    'guardrailIdentifier' => '<string>',
    'guardrailVersion' => '<string>',
    'modelId' => '<string>', // REQUIRED
    'performanceConfigLatency' => 'standard|optimized',
    'trace' => 'ENABLED|DISABLED',
]);

Parameter Details

Members
accept
Type: string

The desired MIME type of the inference body in the response. The default value is application/json.

body
Type: blob (string|resource|Psr\Http\Message\StreamInterface)

The prompt and inference parameters in the format specified in the contentType in the header. You must provide the body in JSON format. To see the format and content of the request and response bodies for different models, refer to Inference parameters. For more information, see Run inference in the Bedrock User Guide.

contentType
Type: string

The MIME type of the input data in the request. You must specify application/json.

guardrailIdentifier
Type: string

The unique identifier of the guardrail that you want to use. If you don't provide a value, no guardrail is applied to the invocation.

An error is thrown in the following situations.

  • You don't provide a guardrail identifier but you specify the amazon-bedrock-guardrailConfig field in the request body.

  • You enable the guardrail but the contentType isn't application/json.

  • You provide a guardrail identifier, but guardrailVersion isn't specified.

guardrailVersion
Type: string

The version number for the guardrail. The value can also be DRAFT.

modelId
Required: Yes
Type: string

The unique identifier of the model to invoke to run inference.

The modelId to provide depends on the type of model or throughput that you use:

performanceConfigLatency
Type: string

Model performance settings for the request.

trace
Type: string

Specifies whether to enable or disable the Bedrock trace. If enabled, you can see the full Bedrock trace.

Result Syntax

[
    'body' => [ // EventParsingIterator
        'chunk' => [
            'bytes' => <string || resource || Psr\Http\Message\StreamInterface>,
        ],
        'internalServerException' => [
            'message' => '<string>',
        ],
        'modelStreamErrorException' => [
            'message' => '<string>',
            'originalMessage' => '<string>',
            'originalStatusCode' => <integer>,
        ],
        'modelTimeoutException' => [
            'message' => '<string>',
        ],
        'serviceUnavailableException' => [
            'message' => '<string>',
        ],
        'throttlingException' => [
            'message' => '<string>',
        ],
        'validationException' => [
            'message' => '<string>',
        ],
    ],
    'contentType' => '<string>',
    'performanceConfigLatency' => 'standard|optimized',
]

Result Details

Members
body

Inference response from the model in the format specified by the contentType header. To see the format and content of this field for different models, refer to Inference parameters.

contentType
Required: Yes
Type: string

The MIME type of the inference result.

performanceConfigLatency
Type: string

Model performance settings for the request.

Using an EventParsingIterator

To use an EventParsingIterator, you will need to loop over the events it will generate and check the top-level field to determine which type of event it is.

foreach($result['body'] as $event) {
    if (isset($event['chunk'])) {
        // Handle the 'chunk' event.
    } else if (isset($event['internalServerException'])) {
        // Handle the 'internalServerException' event.
    } else if (isset($event['modelStreamErrorException'])) {
        // Handle the 'modelStreamErrorException' event.
    } else if (isset($event['modelTimeoutException'])) {
        // Handle the 'modelTimeoutException' event.
    } else if (isset($event['serviceUnavailableException'])) {
        // Handle the 'serviceUnavailableException' event.
    } else if (isset($event['throttlingException'])) {
        // Handle the 'throttlingException' event.
    } else if (isset($event['validationException'])) {
        // Handle the 'validationException' event.
    }
}

Errors

AccessDeniedException:

The request is denied because you do not have sufficient permissions to perform the requested action. For troubleshooting this error, see AccessDeniedException in the Amazon Bedrock User Guide

ResourceNotFoundException:

The specified resource ARN was not found. For troubleshooting this error, see ResourceNotFound in the Amazon Bedrock User Guide

ThrottlingException:

Your request was denied due to exceeding the account quotas for Amazon Bedrock. For troubleshooting this error, see ThrottlingException in the Amazon Bedrock User Guide

ModelTimeoutException:

The request took too long to process. Processing time exceeded the model timeout length.

InternalServerException:

An internal server error occurred. For troubleshooting this error, see InternalFailure in the Amazon Bedrock User Guide

ServiceUnavailableException:

The service isn't currently available. For troubleshooting this error, see ServiceUnavailable in the Amazon Bedrock User Guide

ModelStreamErrorException:

An error occurred while streaming the response. Retry your request.

ValidationException:

The input fails to satisfy the constraints specified by Amazon Bedrock. For troubleshooting this error, see ValidationError in the Amazon Bedrock User Guide

ModelNotReadyException:

The model specified in the request is not ready to serve inference requests. The AWS SDK will automatically retry the operation up to 5 times. For information about configuring automatic retries, see Retry behavior in the AWS SDKs and Tools reference guide.

ServiceQuotaExceededException:

Your request exceeds the service quota for your account. You can view your quotas at Viewing service quotas. You can resubmit your request later.

ModelErrorException:

The request failed due to an error while processing the model.

ListAsyncInvokes

$result = $client->listAsyncInvokes([/* ... */]);
$promise = $client->listAsyncInvokesAsync([/* ... */]);

Lists asynchronous invocations.

Parameter Syntax

$result = $client->listAsyncInvokes([
    'maxResults' => <integer>,
    'nextToken' => '<string>',
    'sortBy' => 'SubmissionTime',
    'sortOrder' => 'Ascending|Descending',
    'statusEquals' => 'InProgress|Completed|Failed',
    'submitTimeAfter' => <integer || string || DateTime>,
    'submitTimeBefore' => <integer || string || DateTime>,
]);

Parameter Details

Members
maxResults
Type: int

The maximum number of invocations to return in one page of results.

nextToken
Type: string

Specify the pagination token from a previous request to retrieve the next page of results.

sortBy
Type: string

How to sort the response.

sortOrder
Type: string

The sorting order for the response.

statusEquals
Type: string

Filter invocations by status.

submitTimeAfter
Type: timestamp (string|DateTime or anything parsable by strtotime)

Include invocations submitted after this time.

submitTimeBefore
Type: timestamp (string|DateTime or anything parsable by strtotime)

Include invocations submitted before this time.

Result Syntax

[
    'asyncInvokeSummaries' => [
        [
            'clientRequestToken' => '<string>',
            'endTime' => <DateTime>,
            'failureMessage' => '<string>',
            'invocationArn' => '<string>',
            'lastModifiedTime' => <DateTime>,
            'modelArn' => '<string>',
            'outputDataConfig' => [
                's3OutputDataConfig' => [
                    'bucketOwner' => '<string>',
                    'kmsKeyId' => '<string>',
                    's3Uri' => '<string>',
                ],
            ],
            'status' => 'InProgress|Completed|Failed',
            'submitTime' => <DateTime>,
        ],
        // ...
    ],
    'nextToken' => '<string>',
]

Result Details

Members
asyncInvokeSummaries
Type: Array of AsyncInvokeSummary structures

A list of invocation summaries.

nextToken
Type: string

Specify the pagination token from a previous request to retrieve the next page of results.

Errors

AccessDeniedException:

The request is denied because you do not have sufficient permissions to perform the requested action. For troubleshooting this error, see AccessDeniedException in the Amazon Bedrock User Guide

ThrottlingException:

Your request was denied due to exceeding the account quotas for Amazon Bedrock. For troubleshooting this error, see ThrottlingException in the Amazon Bedrock User Guide

InternalServerException:

An internal server error occurred. For troubleshooting this error, see InternalFailure in the Amazon Bedrock User Guide

ValidationException:

The input fails to satisfy the constraints specified by Amazon Bedrock. For troubleshooting this error, see ValidationError in the Amazon Bedrock User Guide

StartAsyncInvoke

$result = $client->startAsyncInvoke([/* ... */]);
$promise = $client->startAsyncInvokeAsync([/* ... */]);

Starts an asynchronous invocation.

This operation requires permission for the bedrock:InvokeModel action.

To deny all inference access to resources that you specify in the modelId field, you need to deny access to the bedrock:InvokeModel and bedrock:InvokeModelWithResponseStream actions. Doing this also denies access to the resource through the Converse API actions (Converse and ConverseStream). For more information see Deny access for inference on specific models.

Parameter Syntax

$result = $client->startAsyncInvoke([
    'clientRequestToken' => '<string>',
    'modelId' => '<string>', // REQUIRED
    'modelInput' => [ // REQUIRED
    ],
    'outputDataConfig' => [ // REQUIRED
        's3OutputDataConfig' => [
            'bucketOwner' => '<string>',
            'kmsKeyId' => '<string>',
            's3Uri' => '<string>', // REQUIRED
        ],
    ],
    'tags' => [
        [
            'key' => '<string>', // REQUIRED
            'value' => '<string>', // REQUIRED
        ],
        // ...
    ],
]);

Parameter Details

Members
clientRequestToken
Type: string

Specify idempotency token to ensure that requests are not duplicated.

modelId
Required: Yes
Type: string

The model to invoke.

modelInput
Required: Yes
Type: document (null|bool|string|numeric) or an (array|associative array) whose members are all valid documents

Input to send to the model.

outputDataConfig
Required: Yes
Type: AsyncInvokeOutputDataConfig structure

Where to store the output.

tags
Type: Array of Tag structures

Tags to apply to the invocation.

Result Syntax

[
    'invocationArn' => '<string>',
]

Result Details

Members
invocationArn
Required: Yes
Type: string

The ARN of the invocation.

Errors

AccessDeniedException:

The request is denied because you do not have sufficient permissions to perform the requested action. For troubleshooting this error, see AccessDeniedException in the Amazon Bedrock User Guide

ResourceNotFoundException:

The specified resource ARN was not found. For troubleshooting this error, see ResourceNotFound in the Amazon Bedrock User Guide

ThrottlingException:

Your request was denied due to exceeding the account quotas for Amazon Bedrock. For troubleshooting this error, see ThrottlingException in the Amazon Bedrock User Guide

InternalServerException:

An internal server error occurred. For troubleshooting this error, see InternalFailure in the Amazon Bedrock User Guide

ServiceUnavailableException:

The service isn't currently available. For troubleshooting this error, see ServiceUnavailable in the Amazon Bedrock User Guide

ValidationException:

The input fails to satisfy the constraints specified by Amazon Bedrock. For troubleshooting this error, see ValidationError in the Amazon Bedrock User Guide

ServiceQuotaExceededException:

Your request exceeds the service quota for your account. You can view your quotas at Viewing service quotas. You can resubmit your request later.

ConflictException:

Error occurred because of a conflict while performing an operation.

Shapes

AccessDeniedException

Description

The request is denied because you do not have sufficient permissions to perform the requested action. For troubleshooting this error, see AccessDeniedException in the Amazon Bedrock User Guide

Members
message
Type: string

AnyToolChoice

Description

The model must request at least one tool (no text is generated). For example, {"any" : {}}.

Members

AsyncInvokeOutputDataConfig

Description

Asynchronous invocation output data settings.

Members
s3OutputDataConfig

A storage location for the output data in an S3 bucket

AsyncInvokeS3OutputDataConfig

Description

Asynchronous invocation output data settings.

Members
bucketOwner
Type: string

If the bucket belongs to another AWS account, specify that account's ID.

kmsKeyId
Type: string

A KMS encryption key ID.

s3Uri
Required: Yes
Type: string

An object URI starting with s3://.

AsyncInvokeSummary

Description

A summary of an asynchronous invocation.

Members
clientRequestToken
Type: string

The invocation's idempotency token.

endTime
Type: timestamp (string|DateTime or anything parsable by strtotime)

When the invocation ended.

failureMessage
Type: string

An error message.

invocationArn
Required: Yes
Type: string

The invocation's ARN.

lastModifiedTime
Type: timestamp (string|DateTime or anything parsable by strtotime)

When the invocation was last modified.

modelArn
Required: Yes
Type: string

The invoked model's ARN.

outputDataConfig
Required: Yes
Type: AsyncInvokeOutputDataConfig structure

The invocation's output data settings.

status
Type: string

The invocation's status.

submitTime
Required: Yes
Type: timestamp (string|DateTime or anything parsable by strtotime)

When the invocation was submitted.

AutoToolChoice

Description

The Model automatically decides if a tool should be called or whether to generate text instead. For example, {"auto" : {}}.

Members

ConflictException

Description

Error occurred because of a conflict while performing an operation.

Members
message
Type: string

ContentBlock

Description

A block of content for a message that you pass to, or receive from, a model with the Converse or ConverseStream API operations.

Members
document
Type: DocumentBlock structure

A document to include in the message.

guardContent

Contains the content to assess with the guardrail. If you don't specify guardContent in a call to the Converse API, the guardrail (if passed in the Converse API) assesses the entire message.

For more information, see Use a guardrail with the Converse API in the Amazon Bedrock User Guide.

 </p> 
image
Type: ImageBlock structure

Image to include in the message.

This field is only supported by Anthropic Claude 3 models.

text
Type: string

Text to include in the message.

toolResult
Type: ToolResultBlock structure

The result for a tool request that a model makes.

toolUse
Type: ToolUseBlock structure

Information about a tool use request from a model.

video
Type: VideoBlock structure

Video to include in the message.

ContentBlockDelta

Description

A bock of content in a streaming response.

Members
text
Type: string

The content text.

toolUse
Type: ToolUseBlockDelta structure

Information about a tool that the model is requesting to use.

ContentBlockDeltaEvent

Description

The content block delta event.

Members
contentBlockIndex
Required: Yes
Type: int

The block index for a content block delta event.

delta
Required: Yes
Type: ContentBlockDelta structure

The delta for a content block delta event.

ContentBlockStart

Description

Content block start information.

Members
toolUse
Type: ToolUseBlockStart structure

Information about a tool that the model is requesting to use.

ContentBlockStartEvent

Description

Content block start event.

Members
contentBlockIndex
Required: Yes
Type: int

The index for a content block start event.

start
Required: Yes
Type: ContentBlockStart structure

Start information about a content block start event.

ContentBlockStopEvent

Description

A content block stop event.

Members
contentBlockIndex
Required: Yes
Type: int

The index for a content block.

ConverseMetrics

Description

Metrics for a call to Converse.

Members
latencyMs
Required: Yes
Type: long (int|float)

The latency of the call to Converse, in milliseconds.

ConverseOutput

Description

The output from a call to Converse.

Members
message
Type: Message structure

The message that the model generates.

ConverseStreamMetadataEvent

Description

A conversation stream metadata event.

Members
metrics
Required: Yes
Type: ConverseStreamMetrics structure

The metrics for the conversation stream metadata event.

performanceConfig
Type: PerformanceConfiguration structure

Model performance configuration metadata for the conversation stream event.

trace
Type: ConverseStreamTrace structure

The trace object in the response from ConverseStream that contains information about the guardrail behavior.

usage
Required: Yes
Type: TokenUsage structure

Usage information for the conversation stream event.

ConverseStreamMetrics

Description

Metrics for the stream.

Members
latencyMs
Required: Yes
Type: long (int|float)

The latency for the streaming request, in milliseconds.

ConverseStreamOutput

Description

The messages output stream

Members
contentBlockDelta
Type: ContentBlockDeltaEvent structure

The messages output content block delta.

contentBlockStart
Type: ContentBlockStartEvent structure

Start information for a content block.

contentBlockStop
Type: ContentBlockStopEvent structure

Stop information for a content block.

internalServerException
Type: InternalServerException structure

An internal server error occurred. Retry your request.

messageStart
Type: MessageStartEvent structure

Message start information.

messageStop
Type: MessageStopEvent structure

Message stop information.

metadata
Type: ConverseStreamMetadataEvent structure

Metadata for the converse output stream.

modelStreamErrorException
Type: ModelStreamErrorException structure

A streaming error occurred. Retry your request.

serviceUnavailableException
Type: ServiceUnavailableException structure

The service isn't currently available. For troubleshooting this error, see ServiceUnavailable in the Amazon Bedrock User Guide

throttlingException
Type: ThrottlingException structure

Your request was denied due to exceeding the account quotas for Amazon Bedrock. For troubleshooting this error, see ThrottlingException in the Amazon Bedrock User Guide

validationException
Type: ValidationException structure

The input fails to satisfy the constraints specified by Amazon Bedrock. For troubleshooting this error, see ValidationError in the Amazon Bedrock User Guide

ConverseStreamTrace

Description

The trace object in a response from ConverseStream. Currently, you can only trace guardrails.

Members
guardrail
Type: GuardrailTraceAssessment structure

The guardrail trace object.

promptRouter
Type: PromptRouterTrace structure

The request's prompt router.

ConverseTrace

Description

The trace object in a response from Converse. Currently, you can only trace guardrails.

Members
guardrail
Type: GuardrailTraceAssessment structure

The guardrail trace object.

promptRouter
Type: PromptRouterTrace structure

The request's prompt router.

Document

Members

DocumentBlock

Description

A document to include in a message.

Members
format
Required: Yes
Type: string

The format of a document, or its extension.

name
Required: Yes
Type: string

A name for the document. The name can only contain the following characters:

  • Alphanumeric characters

  • Whitespace characters (no more than one in a row)

  • Hyphens

  • Parentheses

  • Square brackets

This field is vulnerable to prompt injections, because the model might inadvertently interpret it as instructions. Therefore, we recommend that you specify a neutral name.

source
Required: Yes
Type: DocumentSource structure

Contains the content of the document.

DocumentSource

Description

Contains the content of a document.

Members
bytes
Type: blob (string|resource|Psr\Http\Message\StreamInterface)

The raw bytes for the document. If you use an Amazon Web Services SDK, you don't need to encode the bytes in base64.

GuardrailAssessment

Description

A behavior assessment of the guardrail policies used in a call to the Converse API.

Members
contentPolicy

The content policy.

contextualGroundingPolicy

The contextual grounding policy used for the guardrail assessment.

invocationMetrics
Type: GuardrailInvocationMetrics structure

The invocation metrics for the guardrail assessment.

sensitiveInformationPolicy

The sensitive information policy.

topicPolicy

The topic policy.

wordPolicy

The word policy.

GuardrailConfiguration

Description

Configuration information for a guardrail that you use with the Converse operation.

Members
guardrailIdentifier
Required: Yes
Type: string

The identifier for the guardrail.

guardrailVersion
Required: Yes
Type: string

The version of the guardrail.

trace
Type: string

The trace behavior for the guardrail.

GuardrailContentBlock

Description

The content block to be evaluated by the guardrail.

Members
image
Type: GuardrailImageBlock structure

Image within guardrail content block to be evaluated by the guardrail.

text
Type: GuardrailTextBlock structure

Text within content block to be evaluated by the guardrail.

GuardrailContentFilter

Description

The content filter for a guardrail.

Members
action
Required: Yes
Type: string

The guardrail action.

confidence
Required: Yes
Type: string

The guardrail confidence.

filterStrength
Type: string

The filter strength setting for the guardrail content filter.

type
Required: Yes
Type: string

The guardrail type.

GuardrailContentPolicyAssessment

Description

An assessment of a content policy for a guardrail.

Members
filters
Required: Yes
Type: Array of GuardrailContentFilter structures

The content policy filters.

GuardrailContextualGroundingFilter

Description

The details for the guardrails contextual grounding filter.

Members
action
Required: Yes
Type: string

The action performed by the guardrails contextual grounding filter.

score
Required: Yes
Type: double

The score generated by contextual grounding filter.

threshold
Required: Yes
Type: double

The threshold used by contextual grounding filter to determine whether the content is grounded or not.

type
Required: Yes
Type: string

The contextual grounding filter type.

GuardrailContextualGroundingPolicyAssessment

Description

The policy assessment details for the guardrails contextual grounding filter.

Members
filters
Type: Array of GuardrailContextualGroundingFilter structures

The filter details for the guardrails contextual grounding filter.

GuardrailConverseImageBlock

Description

An image block that contains images that you want to assess with a guardrail.

Members
format
Required: Yes
Type: string

The format details for the image type of the guardrail converse image block.

source
Required: Yes
Type: GuardrailConverseImageSource structure

The image source (image bytes) of the guardrail converse image block.

GuardrailConverseImageSource

Description

The image source (image bytes) of the guardrail converse image source.

Members
bytes
Type: blob (string|resource|Psr\Http\Message\StreamInterface)

The raw image bytes for the image.

GuardrailConverseTextBlock

Description

A text block that contains text that you want to assess with a guardrail. For more information, see GuardrailConverseContentBlock.

Members
qualifiers
Type: Array of strings

The qualifier details for the guardrails contextual grounding filter.

text
Required: Yes
Type: string

The text that you want to guard.

GuardrailCoverage

Description

The action of the guardrail coverage details.

Members
images
Type: GuardrailImageCoverage structure

The guardrail coverage for images (the number of images that guardrails guarded).

textCharacters

The text characters of the guardrail coverage details.

GuardrailCustomWord

Description

A custom word configured in a guardrail.

Members
action
Required: Yes
Type: string

The action for the custom word.

match
Required: Yes
Type: string

The match for the custom word.

GuardrailImageBlock

Description

Contain an image which user wants guarded. This block is accepted by the guardrails independent API.

Members
format
Required: Yes
Type: string

The format details for the file type of the image blocked by the guardrail.

source
Required: Yes
Type: GuardrailImageSource structure

The image source (image bytes) details of the image blocked by the guardrail.

GuardrailImageCoverage

Description

The details of the guardrail image coverage.

Members
guarded
Type: int

The count (integer) of images guardrails guarded.

total
Type: int

Represents the total number of images (integer) that were in the request (guarded and unguarded).

GuardrailImageSource

Description

The image source (image bytes) of the guardrail image source. Object used in independent api.

Members
bytes
Type: blob (string|resource|Psr\Http\Message\StreamInterface)

The bytes details of the guardrail image source. Object used in independent api.

GuardrailInvocationMetrics

Description

The invocation metrics for the guardrail.

Members
guardrailCoverage
Type: GuardrailCoverage structure

The coverage details for the guardrail invocation metrics.

guardrailProcessingLatency
Type: long (int|float)

The processing latency details for the guardrail invocation metrics.

usage
Type: GuardrailUsage structure

The usage details for the guardrail invocation metrics.

GuardrailManagedWord

Description

A managed word configured in a guardrail.

Members
action
Required: Yes
Type: string

The action for the managed word.

match
Required: Yes
Type: string

The match for the managed word.

type
Required: Yes
Type: string

The type for the managed word.

GuardrailOutputContent

Description

The output content produced by the guardrail.

Members
text
Type: string

The specific text for the output content produced by the guardrail.

GuardrailPiiEntityFilter

Description

A Personally Identifiable Information (PII) entity configured in a guardrail.

Members
action
Required: Yes
Type: string

The PII entity filter action.

match
Required: Yes
Type: string

The PII entity filter match.

type
Required: Yes
Type: string

The PII entity filter type.

GuardrailRegexFilter

Description

A Regex filter configured in a guardrail.

Members
action
Required: Yes
Type: string

The region filter action.

match
Type: string

The regesx filter match.

name
Type: string

The regex filter name.

regex
Type: string

The regex query.

GuardrailSensitiveInformationPolicyAssessment

Description

The assessment for aPersonally Identifiable Information (PII) policy.

Members
piiEntities
Required: Yes
Type: Array of GuardrailPiiEntityFilter structures

The PII entities in the assessment.

regexes
Required: Yes
Type: Array of GuardrailRegexFilter structures

The regex queries in the assessment.

GuardrailStreamConfiguration

Description

Configuration information for a guardrail that you use with the ConverseStream action.

Members
guardrailIdentifier
Required: Yes
Type: string

The identifier for the guardrail.

guardrailVersion
Required: Yes
Type: string

The version of the guardrail.

streamProcessingMode
Type: string

The processing mode.

The processing mode. For more information, see Configure streaming response behavior in the Amazon Bedrock User Guide.

trace
Type: string

The trace behavior for the guardrail.

GuardrailTextBlock

Description

The text block to be evaluated by the guardrail.

Members
qualifiers
Type: Array of strings

The qualifiers describing the text block.

text
Required: Yes
Type: string

The input text details to be evaluated by the guardrail.

GuardrailTextCharactersCoverage

Description

The guardrail coverage for the text characters.

Members
guarded
Type: int

The text characters that were guarded by the guardrail coverage.

total
Type: int

The total text characters by the guardrail coverage.

GuardrailTopic

Description

Information about a topic guardrail.

Members
action
Required: Yes
Type: string

The action the guardrail should take when it intervenes on a topic.

name
Required: Yes
Type: string

The name for the guardrail.

type
Required: Yes
Type: string

The type behavior that the guardrail should perform when the model detects the topic.

GuardrailTopicPolicyAssessment

Description

A behavior assessment of a topic policy.

Members
topics
Required: Yes
Type: Array of GuardrailTopic structures

The topics in the assessment.

GuardrailTraceAssessment

Description

A Top level guardrail trace object. For more information, see ConverseTrace.

Members
inputAssessment
Type: Associative array of custom strings keys (String) to GuardrailAssessment structures

The input assessment.

modelOutput
Type: Array of strings

The output from the model.

outputAssessments
Type: Associative array of custom strings keys (String) to GuardrailAssessment structuress

the output assessments.

GuardrailUsage

Description

The details on the use of the guardrail.

Members
contentPolicyUnits
Required: Yes
Type: int

The content policy units processed by the guardrail.

contextualGroundingPolicyUnits
Required: Yes
Type: int

The contextual grounding policy units processed by the guardrail.

sensitiveInformationPolicyFreeUnits
Required: Yes
Type: int

The sensitive information policy free units processed by the guardrail.

sensitiveInformationPolicyUnits
Required: Yes
Type: int

The sensitive information policy units processed by the guardrail.

topicPolicyUnits
Required: Yes
Type: int

The topic policy units processed by the guardrail.

wordPolicyUnits
Required: Yes
Type: int

The word policy units processed by the guardrail.

GuardrailWordPolicyAssessment

Description

The word policy assessment.

Members
customWords
Required: Yes
Type: Array of GuardrailCustomWord structures

Custom words in the assessment.

managedWordLists
Required: Yes
Type: Array of GuardrailManagedWord structures

Managed word lists in the assessment.

ImageBlock

Description

Image content for a message.

Members
format
Required: Yes
Type: string

The format of the image.

source
Required: Yes
Type: ImageSource structure

The source for the image.

ImageSource

Description

The source for an image.

Members
bytes
Type: blob (string|resource|Psr\Http\Message\StreamInterface)

The raw image bytes for the image. If you use an AWS SDK, you don't need to encode the image bytes in base64.

InferenceConfiguration

Description

Base inference parameters to pass to a model in a call to Converse or ConverseStream. For more information, see Inference parameters for foundation models.

If you need to pass additional parameters that the model supports, use the additionalModelRequestFields request field in the call to Converse or ConverseStream. For more information, see Model parameters.

Members
maxTokens
Type: int

The maximum number of tokens to allow in the generated response. The default value is the maximum allowed value for the model that you are using. For more information, see Inference parameters for foundation models.

stopSequences
Type: Array of strings

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

temperature
Type: 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.

The default value is the default value for the model that you are using. For more information, see Inference parameters for foundation models.

topP
Type: float

The percentage of most-likely candidates that the model considers for the next token. For example, if you choose a value of 0.8 for topP, the model selects from the top 80% of the probability distribution of tokens that could be next in the sequence.

The default value is the default value for the model that you are using. For more information, see Inference parameters for foundation models.

InternalServerException

Description

An internal server error occurred. For troubleshooting this error, see InternalFailure in the Amazon Bedrock User Guide

Members
message
Type: string

Message

Description

A message input, or returned from, a call to Converse or ConverseStream.

Members
content
Required: Yes
Type: Array of ContentBlock structures

The message content. Note the following restrictions:

  • You can include up to 20 images. Each image's size, height, and width must be no more than 3.75 MB, 8000 px, and 8000 px, respectively.

  • You can include up to five documents. Each document's size must be no more than 4.5 MB.

  • If you include a ContentBlock with a document field in the array, you must also include a ContentBlock with a text field.

  • You can only include images and documents if the role is user.

role
Required: Yes
Type: string

The role that the message plays in the message.

MessageStartEvent

Description

The start of a message.

Members
role
Required: Yes
Type: string

The role for the message.

MessageStopEvent

Description

The stop event for a message.

Members
additionalModelResponseFields
Type: document (null|bool|string|numeric) or an (array|associative array) whose members are all valid documents

The additional model response fields.

stopReason
Required: Yes
Type: string

The reason why the model stopped generating output.

ModelErrorException

Description

The request failed due to an error while processing the model.

Members
message
Type: string
originalStatusCode
Type: int

The original status code.

resourceName
Type: string

The resource name.

ModelInputPayload

Members

ModelNotReadyException

Description

The model specified in the request is not ready to serve inference requests. The AWS SDK will automatically retry the operation up to 5 times. For information about configuring automatic retries, see Retry behavior in the AWS SDKs and Tools reference guide.

Members
message
Type: string

ModelStreamErrorException

Description

An error occurred while streaming the response. Retry your request.

Members
message
Type: string
originalMessage
Type: string

The original message.

originalStatusCode
Type: int

The original status code.

ModelTimeoutException

Description

The request took too long to process. Processing time exceeded the model timeout length.

Members
message
Type: string

PayloadPart

Description

Payload content included in the response.

Members
bytes
Type: blob (string|resource|Psr\Http\Message\StreamInterface)

Base64-encoded bytes of payload data.

PerformanceConfiguration

Description

Performance settings for a model.

Members
latency
Type: string

To use a latency-optimized version of the model, set to optimized.

PromptRouterTrace

Description

A prompt router trace.

Members
invokedModelId
Type: string

The ID of the invoked model.

PromptVariableValues

Description

Contains a map of variables in a prompt from Prompt management to an object containing the values to fill in for them when running model invocation. For more information, see How Prompt management works.

Members
text
Type: string

The text value that the variable maps to.

ResourceNotFoundException

Description

The specified resource ARN was not found. For troubleshooting this error, see ResourceNotFound in the Amazon Bedrock User Guide

Members
message
Type: string

ResponseStream

Description

Definition of content in the response stream.

Members
chunk
Type: PayloadPart structure

Content included in the response.

internalServerException
Type: InternalServerException structure

An internal server error occurred. Retry your request.

modelStreamErrorException
Type: ModelStreamErrorException structure

An error occurred while streaming the response. Retry your request.

modelTimeoutException
Type: ModelTimeoutException structure

The request took too long to process. Processing time exceeded the model timeout length.

serviceUnavailableException
Type: ServiceUnavailableException structure

The service isn't available. Try again later.

throttlingException
Type: ThrottlingException structure

Your request was throttled because of service-wide limitations. Resubmit your request later or in a different region. You can also purchase Provisioned Throughput to increase the rate or number of tokens you can process.

validationException
Type: ValidationException structure

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

S3Location

Description

A storage location in an S3 bucket.

Members
bucketOwner
Type: string

If the bucket belongs to another AWS account, specify that account's ID.

uri
Required: Yes
Type: string

An object URI starting with s3://.

ServiceQuotaExceededException

Description

Your request exceeds the service quota for your account. You can view your quotas at Viewing service quotas. You can resubmit your request later.

Members
message
Type: string

ServiceUnavailableException

Description

The service isn't currently available. For troubleshooting this error, see ServiceUnavailable in the Amazon Bedrock User Guide

Members
message
Type: string

SpecificToolChoice

Description

The model must request a specific tool. For example, {"tool" : {"name" : "Your tool name"}}.

This field is only supported by Anthropic Claude 3 models.

Members
name
Required: Yes
Type: string

The name of the tool that the model must request.

SystemContentBlock

Description

A system content block.

Members
guardContent

A content block to assess with the guardrail. Use with the Converse or ConverseStream API operations.

For more information, see Use a guardrail with the Converse API in the Amazon Bedrock User Guide.

text
Type: string

A system prompt for the model.

Tag

Description

A tag.

Members
key
Required: Yes
Type: string

The tag's key.

value
Required: Yes
Type: string

The tag's value.

ThrottlingException

Description

Your request was denied due to exceeding the account quotas for Amazon Bedrock. For troubleshooting this error, see ThrottlingException in the Amazon Bedrock User Guide

Members
message
Type: string

TokenUsage

Description

The tokens used in a message API inference call.

Members
inputTokens
Required: Yes
Type: int

The number of tokens sent in the request to the model.

outputTokens
Required: Yes
Type: int

The number of tokens that the model generated for the request.

totalTokens
Required: Yes
Type: int

The total of input tokens and tokens generated by the model.

Tool

Description

Information about a tool that you can use with the Converse API. For more information, see Tool use (function calling) in the Amazon Bedrock User Guide.

Members
toolSpec
Type: ToolSpecification structure

The specfication for the tool.

ToolChoice

Description

Determines which tools the model should request in a call to Converse or ConverseStream. ToolChoice is only supported by Anthropic Claude 3 models and by Mistral AI Mistral Large.

Members
any
Type: AnyToolChoice structure

The model must request at least one tool (no text is generated).

auto
Type: AutoToolChoice structure

(Default). The Model automatically decides if a tool should be called or whether to generate text instead.

tool
Type: SpecificToolChoice structure

The Model must request the specified tool. Only supported by Anthropic Claude 3 models.

ToolConfiguration

Description

Configuration information for the tools that you pass to a model. For more information, see Tool use (function calling) in the Amazon Bedrock User Guide.

Members
toolChoice
Type: ToolChoice structure

If supported by model, forces the model to request a tool.

tools
Required: Yes
Type: Array of Tool structures

An array of tools that you want to pass to a model.

ToolInputSchema

Description

The schema for the tool. The top level schema type must be object.

Members
json
Type: document (null|bool|string|numeric) or an (array|associative array) whose members are all valid documents

The JSON schema for the tool. For more information, see JSON Schema Reference.

ToolResultBlock

Description

A tool result block that contains the results for a tool request that the model previously made.

Members
content
Required: Yes
Type: Array of ToolResultContentBlock structures

The content for tool result content block.

status
Type: string

The status for the tool result content block.

This field is only supported Anthropic Claude 3 models.

toolUseId
Required: Yes
Type: string

The ID of the tool request that this is the result for.

ToolResultContentBlock

Description

The tool result content block.

Members
document
Type: DocumentBlock structure

A tool result that is a document.

image
Type: ImageBlock structure

A tool result that is an image.

This field is only supported by Anthropic Claude 3 models.

json
Type: document (null|bool|string|numeric) or an (array|associative array) whose members are all valid documents

A tool result that is JSON format data.

text
Type: string

A tool result that is text.

video
Type: VideoBlock structure

A tool result that is video.

ToolSpecification

Description

The specification for the tool.

Members
description
Type: string

The description for the tool.

inputSchema
Required: Yes
Type: ToolInputSchema structure

The input schema for the tool in JSON format.

name
Required: Yes
Type: string

The name for the tool.

ToolUseBlock

Description

A tool use content block. Contains information about a tool that the model is requesting be run., The model uses the result from the tool to generate a response.

Members
input
Required: Yes
Type: document (null|bool|string|numeric) or an (array|associative array) whose members are all valid documents

The input to pass to the tool.

name
Required: Yes
Type: string

The name of the tool that the model wants to use.

toolUseId
Required: Yes
Type: string

The ID for the tool request.

ToolUseBlockDelta

Description

The delta for a tool use block.

Members
input
Required: Yes
Type: string

The input for a requested tool.

ToolUseBlockStart

Description

The start of a tool use block.

Members
name
Required: Yes
Type: string

The name of the tool that the model is requesting to use.

toolUseId
Required: Yes
Type: string

The ID for the tool request.

ValidationException

Description

The input fails to satisfy the constraints specified by Amazon Bedrock. For troubleshooting this error, see ValidationError in the Amazon Bedrock User Guide

Members
message
Type: string

VideoBlock

Description

A video block.

Members
format
Required: Yes
Type: string

The block's format.

source
Required: Yes
Type: VideoSource structure

The block's source.

VideoSource

Description

A video source. You can upload a smaller video as a base64-encoded string as long as the encoded file is less than 25MB. You can also transfer videos up to 1GB in size from an S3 bucket.

Members
bytes
Type: blob (string|resource|Psr\Http\Message\StreamInterface)

Video content encoded in base64.

s3Location
Type: S3Location structure

The location of a video object in an S3 bucket.