import { awsExpectUnion as __expectUnion, loadRestJsonErrorCode, parseJsonBody as parseBody, parseJsonErrorBody as parseErrorBody, } from "@aws-sdk/core";
import { requestBuilder as rb } from "@smithy/core";
import { _json, collectBody, decorateServiceException as __decorateServiceException, expectBoolean as __expectBoolean, expectInt32 as __expectInt32, expectNonNull as __expectNonNull, expectObject as __expectObject, expectString as __expectString, isSerializableHeaderValue, limitedParseDouble as __limitedParseDouble, map, parseRfc3339DateTimeWithOffset as __parseRfc3339DateTimeWithOffset, serializeDateTime as __serializeDateTime, serializeFloat as __serializeFloat, take, withBaseException, } from "@smithy/smithy-client";
import { v4 as generateIdempotencyToken } from "@smithy/uuid";
import { BedrockRuntimeServiceException as __BaseException } from "../models/BedrockRuntimeServiceException";
import { AccessDeniedException, ConflictException, ContentBlock, CountTokensInput, DocumentSource, GuardrailContentBlock, GuardrailConverseContentBlock, GuardrailConverseImageSource, GuardrailImageSource, ImageSource, InternalServerException, InvokeModelWithBidirectionalStreamInput, ModelErrorException, ModelNotReadyException, ModelStreamErrorException, ModelTimeoutException, ReasoningContentBlock, ResourceNotFoundException, ServiceQuotaExceededException, ServiceUnavailableException, SystemContentBlock, ThrottlingException, Tool, ToolInputSchema, ToolResultContentBlock, ValidationException, VideoSource, } from "../models/models_0";
export const se_ApplyGuardrailCommand = async (input, context) => {
    const b = rb(input, context);
    const headers = {
        "content-type": "application/json",
    };
    b.bp("/guardrail/{guardrailIdentifier}/version/{guardrailVersion}/apply");
    b.p("guardrailIdentifier", () => input.guardrailIdentifier, "{guardrailIdentifier}", false);
    b.p("guardrailVersion", () => input.guardrailVersion, "{guardrailVersion}", false);
    let body;
    body = JSON.stringify(take(input, {
        content: (_) => se_GuardrailContentBlockList(_, context),
        outputScope: [],
        source: [],
    }));
    b.m("POST").h(headers).b(body);
    return b.build();
};
export const se_ConverseCommand = async (input, context) => {
    const b = rb(input, context);
    const headers = {
        "content-type": "application/json",
    };
    b.bp("/model/{modelId}/converse");
    b.p("modelId", () => input.modelId, "{modelId}", false);
    let body;
    body = JSON.stringify(take(input, {
        additionalModelRequestFields: (_) => se_Document(_, context),
        additionalModelResponseFieldPaths: (_) => _json(_),
        guardrailConfig: (_) => _json(_),
        inferenceConfig: (_) => se_InferenceConfiguration(_, context),
        messages: (_) => se_Messages(_, context),
        performanceConfig: (_) => _json(_),
        promptVariables: (_) => _json(_),
        requestMetadata: (_) => _json(_),
        system: (_) => se_SystemContentBlocks(_, context),
        toolConfig: (_) => se_ToolConfiguration(_, context),
    }));
    b.m("POST").h(headers).b(body);
    return b.build();
};
export const se_ConverseStreamCommand = async (input, context) => {
    const b = rb(input, context);
    const headers = {
        "content-type": "application/json",
    };
    b.bp("/model/{modelId}/converse-stream");
    b.p("modelId", () => input.modelId, "{modelId}", false);
    let body;
    body = JSON.stringify(take(input, {
        additionalModelRequestFields: (_) => se_Document(_, context),
        additionalModelResponseFieldPaths: (_) => _json(_),
        guardrailConfig: (_) => _json(_),
        inferenceConfig: (_) => se_InferenceConfiguration(_, context),
        messages: (_) => se_Messages(_, context),
        performanceConfig: (_) => _json(_),
        promptVariables: (_) => _json(_),
        requestMetadata: (_) => _json(_),
        system: (_) => se_SystemContentBlocks(_, context),
        toolConfig: (_) => se_ToolConfiguration(_, context),
    }));
    b.m("POST").h(headers).b(body);
    return b.build();
};
export const se_CountTokensCommand = async (input, context) => {
    const b = rb(input, context);
    const headers = {
        "content-type": "application/json",
    };
    b.bp("/model/{modelId}/count-tokens");
    b.p("modelId", () => input.modelId, "{modelId}", false);
    let body;
    body = JSON.stringify(take(input, {
        input: (_) => se_CountTokensInput(_, context),
    }));
    b.m("POST").h(headers).b(body);
    return b.build();
};
export const se_GetAsyncInvokeCommand = async (input, context) => {
    const b = rb(input, context);
    const headers = {};
    b.bp("/async-invoke/{invocationArn}");
    b.p("invocationArn", () => input.invocationArn, "{invocationArn}", false);
    let body;
    b.m("GET").h(headers).b(body);
    return b.build();
};
export const se_InvokeModelCommand = async (input, context) => {
    const b = rb(input, context);
    const headers = map({}, isSerializableHeaderValue, {
        [_ct]: input[_cT] || "application/octet-stream",
        [_a]: input[_a],
        [_xabt]: input[_t],
        [_xabg]: input[_gI],
        [_xabg_]: input[_gV],
        [_xabpl]: input[_pCL],
    });
    b.bp("/model/{modelId}/invoke");
    b.p("modelId", () => input.modelId, "{modelId}", false);
    let body;
    if (input.body !== undefined) {
        body = input.body;
    }
    b.m("POST").h(headers).b(body);
    return b.build();
};
export const se_InvokeModelWithBidirectionalStreamCommand = async (input, context) => {
    const b = rb(input, context);
    const headers = {
        "content-type": "application/json",
    };
    b.bp("/model/{modelId}/invoke-with-bidirectional-stream");
    b.p("modelId", () => input.modelId, "{modelId}", false);
    let body;
    if (input.body !== undefined) {
        body = se_InvokeModelWithBidirectionalStreamInput(input.body, context);
    }
    b.m("POST").h(headers).b(body);
    return b.build();
};
export const se_InvokeModelWithResponseStreamCommand = async (input, context) => {
    const b = rb(input, context);
    const headers = map({}, isSerializableHeaderValue, {
        [_ct]: input[_cT] || "application/octet-stream",
        [_xaba]: input[_a],
        [_xabt]: input[_t],
        [_xabg]: input[_gI],
        [_xabg_]: input[_gV],
        [_xabpl]: input[_pCL],
    });
    b.bp("/model/{modelId}/invoke-with-response-stream");
    b.p("modelId", () => input.modelId, "{modelId}", false);
    let body;
    if (input.body !== undefined) {
        body = input.body;
    }
    b.m("POST").h(headers).b(body);
    return b.build();
};
export const se_ListAsyncInvokesCommand = async (input, context) => {
    const b = rb(input, context);
    const headers = {};
    b.bp("/async-invoke");
    const query = map({
        [_sTA]: [() => input.submitTimeAfter !== void 0, () => __serializeDateTime(input[_sTA]).toString()],
        [_sTB]: [() => input.submitTimeBefore !== void 0, () => __serializeDateTime(input[_sTB]).toString()],
        [_sE]: [, input[_sE]],
        [_mR]: [() => input.maxResults !== void 0, () => input[_mR].toString()],
        [_nT]: [, input[_nT]],
        [_sB]: [, input[_sB]],
        [_sO]: [, input[_sO]],
    });
    let body;
    b.m("GET").h(headers).q(query).b(body);
    return b.build();
};
export const se_StartAsyncInvokeCommand = async (input, context) => {
    const b = rb(input, context);
    const headers = {
        "content-type": "application/json",
    };
    b.bp("/async-invoke");
    let body;
    body = JSON.stringify(take(input, {
        clientRequestToken: [true, (_) => _ ?? generateIdempotencyToken()],
        modelId: [],
        modelInput: (_) => se_ModelInputPayload(_, context),
        outputDataConfig: (_) => _json(_),
        tags: (_) => _json(_),
    }));
    b.m("POST").h(headers).b(body);
    return b.build();
};
export const de_ApplyGuardrailCommand = async (output, context) => {
    if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
    }
    const contents = map({
        $metadata: deserializeMetadata(output),
    });
    const data = __expectNonNull(__expectObject(await parseBody(output.body, context)), "body");
    const doc = take(data, {
        action: __expectString,
        actionReason: __expectString,
        assessments: (_) => de_GuardrailAssessmentList(_, context),
        guardrailCoverage: _json,
        outputs: _json,
        usage: _json,
    });
    Object.assign(contents, doc);
    return contents;
};
export const de_ConverseCommand = async (output, context) => {
    if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
    }
    const contents = map({
        $metadata: deserializeMetadata(output),
    });
    const data = __expectNonNull(__expectObject(await parseBody(output.body, context)), "body");
    const doc = take(data, {
        additionalModelResponseFields: (_) => de_Document(_, context),
        metrics: _json,
        output: (_) => de_ConverseOutput(__expectUnion(_), context),
        performanceConfig: _json,
        stopReason: __expectString,
        trace: (_) => de_ConverseTrace(_, context),
        usage: _json,
    });
    Object.assign(contents, doc);
    return contents;
};
export const de_ConverseStreamCommand = async (output, context) => {
    if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
    }
    const contents = map({
        $metadata: deserializeMetadata(output),
    });
    const data = output.body;
    contents.stream = de_ConverseStreamOutput(data, context);
    return contents;
};
export const de_CountTokensCommand = async (output, context) => {
    if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
    }
    const contents = map({
        $metadata: deserializeMetadata(output),
    });
    const data = __expectNonNull(__expectObject(await parseBody(output.body, context)), "body");
    const doc = take(data, {
        inputTokens: __expectInt32,
    });
    Object.assign(contents, doc);
    return contents;
};
export const de_GetAsyncInvokeCommand = async (output, context) => {
    if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
    }
    const contents = map({
        $metadata: deserializeMetadata(output),
    });
    const data = __expectNonNull(__expectObject(await parseBody(output.body, context)), "body");
    const doc = take(data, {
        clientRequestToken: __expectString,
        endTime: (_) => __expectNonNull(__parseRfc3339DateTimeWithOffset(_)),
        failureMessage: __expectString,
        invocationArn: __expectString,
        lastModifiedTime: (_) => __expectNonNull(__parseRfc3339DateTimeWithOffset(_)),
        modelArn: __expectString,
        outputDataConfig: (_) => _json(__expectUnion(_)),
        status: __expectString,
        submitTime: (_) => __expectNonNull(__parseRfc3339DateTimeWithOffset(_)),
    });
    Object.assign(contents, doc);
    return contents;
};
export const de_InvokeModelCommand = async (output, context) => {
    if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
    }
    const contents = map({
        $metadata: deserializeMetadata(output),
        [_cT]: [, output.headers[_ct]],
        [_pCL]: [, output.headers[_xabpl]],
    });
    const data = await collectBody(output.body, context);
    contents.body = data;
    return contents;
};
export const de_InvokeModelWithBidirectionalStreamCommand = async (output, context) => {
    if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
    }
    const contents = map({
        $metadata: deserializeMetadata(output),
    });
    const data = output.body;
    contents.body = de_InvokeModelWithBidirectionalStreamOutput(data, context);
    return contents;
};
export const de_InvokeModelWithResponseStreamCommand = async (output, context) => {
    if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
    }
    const contents = map({
        $metadata: deserializeMetadata(output),
        [_cT]: [, output.headers[_xabct]],
        [_pCL]: [, output.headers[_xabpl]],
    });
    const data = output.body;
    contents.body = de_ResponseStream(data, context);
    return contents;
};
export const de_ListAsyncInvokesCommand = async (output, context) => {
    if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
    }
    const contents = map({
        $metadata: deserializeMetadata(output),
    });
    const data = __expectNonNull(__expectObject(await parseBody(output.body, context)), "body");
    const doc = take(data, {
        asyncInvokeSummaries: (_) => de_AsyncInvokeSummaries(_, context),
        nextToken: __expectString,
    });
    Object.assign(contents, doc);
    return contents;
};
export const de_StartAsyncInvokeCommand = async (output, context) => {
    if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
    }
    const contents = map({
        $metadata: deserializeMetadata(output),
    });
    const data = __expectNonNull(__expectObject(await parseBody(output.body, context)), "body");
    const doc = take(data, {
        invocationArn: __expectString,
    });
    Object.assign(contents, doc);
    return contents;
};
const de_CommandError = async (output, context) => {
    const parsedOutput = {
        ...output,
        body: await parseErrorBody(output.body, context),
    };
    const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);
    switch (errorCode) {
        case "AccessDeniedException":
        case "com.amazonaws.bedrockruntime#AccessDeniedException":
            throw await de_AccessDeniedExceptionRes(parsedOutput, context);
        case "InternalServerException":
        case "com.amazonaws.bedrockruntime#InternalServerException":
            throw await de_InternalServerExceptionRes(parsedOutput, context);
        case "ResourceNotFoundException":
        case "com.amazonaws.bedrockruntime#ResourceNotFoundException":
            throw await de_ResourceNotFoundExceptionRes(parsedOutput, context);
        case "ServiceQuotaExceededException":
        case "com.amazonaws.bedrockruntime#ServiceQuotaExceededException":
            throw await de_ServiceQuotaExceededExceptionRes(parsedOutput, context);
        case "ServiceUnavailableException":
        case "com.amazonaws.bedrockruntime#ServiceUnavailableException":
            throw await de_ServiceUnavailableExceptionRes(parsedOutput, context);
        case "ThrottlingException":
        case "com.amazonaws.bedrockruntime#ThrottlingException":
            throw await de_ThrottlingExceptionRes(parsedOutput, context);
        case "ValidationException":
        case "com.amazonaws.bedrockruntime#ValidationException":
            throw await de_ValidationExceptionRes(parsedOutput, context);
        case "ModelErrorException":
        case "com.amazonaws.bedrockruntime#ModelErrorException":
            throw await de_ModelErrorExceptionRes(parsedOutput, context);
        case "ModelNotReadyException":
        case "com.amazonaws.bedrockruntime#ModelNotReadyException":
            throw await de_ModelNotReadyExceptionRes(parsedOutput, context);
        case "ModelTimeoutException":
        case "com.amazonaws.bedrockruntime#ModelTimeoutException":
            throw await de_ModelTimeoutExceptionRes(parsedOutput, context);
        case "ModelStreamErrorException":
        case "com.amazonaws.bedrockruntime#ModelStreamErrorException":
            throw await de_ModelStreamErrorExceptionRes(parsedOutput, context);
        case "ConflictException":
        case "com.amazonaws.bedrockruntime#ConflictException":
            throw await de_ConflictExceptionRes(parsedOutput, context);
        default:
            const parsedBody = parsedOutput.body;
            return throwDefaultError({
                output,
                parsedBody,
                errorCode,
            });
    }
};
const throwDefaultError = withBaseException(__BaseException);
const de_AccessDeniedExceptionRes = async (parsedOutput, context) => {
    const contents = map({});
    const data = parsedOutput.body;
    const doc = take(data, {
        message: __expectString,
    });
    Object.assign(contents, doc);
    const exception = new AccessDeniedException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents,
    });
    return __decorateServiceException(exception, parsedOutput.body);
};
const de_ConflictExceptionRes = async (parsedOutput, context) => {
    const contents = map({});
    const data = parsedOutput.body;
    const doc = take(data, {
        message: __expectString,
    });
    Object.assign(contents, doc);
    const exception = new ConflictException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents,
    });
    return __decorateServiceException(exception, parsedOutput.body);
};
const de_InternalServerExceptionRes = async (parsedOutput, context) => {
    const contents = map({});
    const data = parsedOutput.body;
    const doc = take(data, {
        message: __expectString,
    });
    Object.assign(contents, doc);
    const exception = new InternalServerException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents,
    });
    return __decorateServiceException(exception, parsedOutput.body);
};
const de_ModelErrorExceptionRes = async (parsedOutput, context) => {
    const contents = map({});
    const data = parsedOutput.body;
    const doc = take(data, {
        message: __expectString,
        originalStatusCode: __expectInt32,
        resourceName: __expectString,
    });
    Object.assign(contents, doc);
    const exception = new ModelErrorException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents,
    });
    return __decorateServiceException(exception, parsedOutput.body);
};
const de_ModelNotReadyExceptionRes = async (parsedOutput, context) => {
    const contents = map({});
    const data = parsedOutput.body;
    const doc = take(data, {
        message: __expectString,
    });
    Object.assign(contents, doc);
    const exception = new ModelNotReadyException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents,
    });
    return __decorateServiceException(exception, parsedOutput.body);
};
const de_ModelStreamErrorExceptionRes = async (parsedOutput, context) => {
    const contents = map({});
    const data = parsedOutput.body;
    const doc = take(data, {
        message: __expectString,
        originalMessage: __expectString,
        originalStatusCode: __expectInt32,
    });
    Object.assign(contents, doc);
    const exception = new ModelStreamErrorException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents,
    });
    return __decorateServiceException(exception, parsedOutput.body);
};
const de_ModelTimeoutExceptionRes = async (parsedOutput, context) => {
    const contents = map({});
    const data = parsedOutput.body;
    const doc = take(data, {
        message: __expectString,
    });
    Object.assign(contents, doc);
    const exception = new ModelTimeoutException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents,
    });
    return __decorateServiceException(exception, parsedOutput.body);
};
const de_ResourceNotFoundExceptionRes = async (parsedOutput, context) => {
    const contents = map({});
    const data = parsedOutput.body;
    const doc = take(data, {
        message: __expectString,
    });
    Object.assign(contents, doc);
    const exception = new ResourceNotFoundException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents,
    });
    return __decorateServiceException(exception, parsedOutput.body);
};
const de_ServiceQuotaExceededExceptionRes = async (parsedOutput, context) => {
    const contents = map({});
    const data = parsedOutput.body;
    const doc = take(data, {
        message: __expectString,
    });
    Object.assign(contents, doc);
    const exception = new ServiceQuotaExceededException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents,
    });
    return __decorateServiceException(exception, parsedOutput.body);
};
const de_ServiceUnavailableExceptionRes = async (parsedOutput, context) => {
    const contents = map({});
    const data = parsedOutput.body;
    const doc = take(data, {
        message: __expectString,
    });
    Object.assign(contents, doc);
    const exception = new ServiceUnavailableException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents,
    });
    return __decorateServiceException(exception, parsedOutput.body);
};
const de_ThrottlingExceptionRes = async (parsedOutput, context) => {
    const contents = map({});
    const data = parsedOutput.body;
    const doc = take(data, {
        message: __expectString,
    });
    Object.assign(contents, doc);
    const exception = new ThrottlingException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents,
    });
    return __decorateServiceException(exception, parsedOutput.body);
};
const de_ValidationExceptionRes = async (parsedOutput, context) => {
    const contents = map({});
    const data = parsedOutput.body;
    const doc = take(data, {
        message: __expectString,
    });
    Object.assign(contents, doc);
    const exception = new ValidationException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents,
    });
    return __decorateServiceException(exception, parsedOutput.body);
};
const se_InvokeModelWithBidirectionalStreamInput = (input, context) => {
    const eventMarshallingVisitor = (event) => InvokeModelWithBidirectionalStreamInput.visit(event, {
        chunk: (value) => se_BidirectionalInputPayloadPart_event(value, context),
        _: (value) => value,
    });
    return context.eventStreamMarshaller.serialize(input, eventMarshallingVisitor);
};
const se_BidirectionalInputPayloadPart_event = (input, context) => {
    const headers = {
        ":event-type": { type: "string", value: "chunk" },
        ":message-type": { type: "string", value: "event" },
        ":content-type": { type: "string", value: "application/json" },
    };
    let body = new Uint8Array();
    body = se_BidirectionalInputPayloadPart(input, context);
    body = context.utf8Decoder(JSON.stringify(body));
    return { headers, body };
};
const de_ConverseStreamOutput = (output, context) => {
    return context.eventStreamMarshaller.deserialize(output, async (event) => {
        if (event["messageStart"] != null) {
            return {
                messageStart: await de_MessageStartEvent_event(event["messageStart"], context),
            };
        }
        if (event["contentBlockStart"] != null) {
            return {
                contentBlockStart: await de_ContentBlockStartEvent_event(event["contentBlockStart"], context),
            };
        }
        if (event["contentBlockDelta"] != null) {
            return {
                contentBlockDelta: await de_ContentBlockDeltaEvent_event(event["contentBlockDelta"], context),
            };
        }
        if (event["contentBlockStop"] != null) {
            return {
                contentBlockStop: await de_ContentBlockStopEvent_event(event["contentBlockStop"], context),
            };
        }
        if (event["messageStop"] != null) {
            return {
                messageStop: await de_MessageStopEvent_event(event["messageStop"], context),
            };
        }
        if (event["metadata"] != null) {
            return {
                metadata: await de_ConverseStreamMetadataEvent_event(event["metadata"], context),
            };
        }
        if (event["internalServerException"] != null) {
            return {
                internalServerException: await de_InternalServerException_event(event["internalServerException"], context),
            };
        }
        if (event["modelStreamErrorException"] != null) {
            return {
                modelStreamErrorException: await de_ModelStreamErrorException_event(event["modelStreamErrorException"], context),
            };
        }
        if (event["validationException"] != null) {
            return {
                validationException: await de_ValidationException_event(event["validationException"], context),
            };
        }
        if (event["throttlingException"] != null) {
            return {
                throttlingException: await de_ThrottlingException_event(event["throttlingException"], context),
            };
        }
        if (event["serviceUnavailableException"] != null) {
            return {
                serviceUnavailableException: await de_ServiceUnavailableException_event(event["serviceUnavailableException"], context),
            };
        }
        return { $unknown: event };
    });
};
const de_InvokeModelWithBidirectionalStreamOutput = (output, context) => {
    return context.eventStreamMarshaller.deserialize(output, async (event) => {
        if (event["chunk"] != null) {
            return {
                chunk: await de_BidirectionalOutputPayloadPart_event(event["chunk"], context),
            };
        }
        if (event["internalServerException"] != null) {
            return {
                internalServerException: await de_InternalServerException_event(event["internalServerException"], context),
            };
        }
        if (event["modelStreamErrorException"] != null) {
            return {
                modelStreamErrorException: await de_ModelStreamErrorException_event(event["modelStreamErrorException"], context),
            };
        }
        if (event["validationException"] != null) {
            return {
                validationException: await de_ValidationException_event(event["validationException"], context),
            };
        }
        if (event["throttlingException"] != null) {
            return {
                throttlingException: await de_ThrottlingException_event(event["throttlingException"], context),
            };
        }
        if (event["modelTimeoutException"] != null) {
            return {
                modelTimeoutException: await de_ModelTimeoutException_event(event["modelTimeoutException"], context),
            };
        }
        if (event["serviceUnavailableException"] != null) {
            return {
                serviceUnavailableException: await de_ServiceUnavailableException_event(event["serviceUnavailableException"], context),
            };
        }
        return { $unknown: event };
    });
};
const de_ResponseStream = (output, context) => {
    return context.eventStreamMarshaller.deserialize(output, async (event) => {
        if (event["chunk"] != null) {
            return {
                chunk: await de_PayloadPart_event(event["chunk"], context),
            };
        }
        if (event["internalServerException"] != null) {
            return {
                internalServerException: await de_InternalServerException_event(event["internalServerException"], context),
            };
        }
        if (event["modelStreamErrorException"] != null) {
            return {
                modelStreamErrorException: await de_ModelStreamErrorException_event(event["modelStreamErrorException"], context),
            };
        }
        if (event["validationException"] != null) {
            return {
                validationException: await de_ValidationException_event(event["validationException"], context),
            };
        }
        if (event["throttlingException"] != null) {
            return {
                throttlingException: await de_ThrottlingException_event(event["throttlingException"], context),
            };
        }
        if (event["modelTimeoutException"] != null) {
            return {
                modelTimeoutException: await de_ModelTimeoutException_event(event["modelTimeoutException"], context),
            };
        }
        if (event["serviceUnavailableException"] != null) {
            return {
                serviceUnavailableException: await de_ServiceUnavailableException_event(event["serviceUnavailableException"], context),
            };
        }
        return { $unknown: event };
    });
};
const de_BidirectionalOutputPayloadPart_event = async (output, context) => {
    const contents = {};
    const data = await parseBody(output.body, context);
    Object.assign(contents, de_BidirectionalOutputPayloadPart(data, context));
    return contents;
};
const de_ContentBlockDeltaEvent_event = async (output, context) => {
    const contents = {};
    const data = await parseBody(output.body, context);
    Object.assign(contents, de_ContentBlockDeltaEvent(data, context));
    return contents;
};
const de_ContentBlockStartEvent_event = async (output, context) => {
    const contents = {};
    const data = await parseBody(output.body, context);
    Object.assign(contents, _json(data));
    return contents;
};
const de_ContentBlockStopEvent_event = async (output, context) => {
    const contents = {};
    const data = await parseBody(output.body, context);
    Object.assign(contents, _json(data));
    return contents;
};
const de_ConverseStreamMetadataEvent_event = async (output, context) => {
    const contents = {};
    const data = await parseBody(output.body, context);
    Object.assign(contents, de_ConverseStreamMetadataEvent(data, context));
    return contents;
};
const de_InternalServerException_event = async (output, context) => {
    const parsedOutput = {
        ...output,
        body: await parseBody(output.body, context),
    };
    return de_InternalServerExceptionRes(parsedOutput, context);
};
const de_MessageStartEvent_event = async (output, context) => {
    const contents = {};
    const data = await parseBody(output.body, context);
    Object.assign(contents, _json(data));
    return contents;
};
const de_MessageStopEvent_event = async (output, context) => {
    const contents = {};
    const data = await parseBody(output.body, context);
    Object.assign(contents, de_MessageStopEvent(data, context));
    return contents;
};
const de_ModelStreamErrorException_event = async (output, context) => {
    const parsedOutput = {
        ...output,
        body: await parseBody(output.body, context),
    };
    return de_ModelStreamErrorExceptionRes(parsedOutput, context);
};
const de_ModelTimeoutException_event = async (output, context) => {
    const parsedOutput = {
        ...output,
        body: await parseBody(output.body, context),
    };
    return de_ModelTimeoutExceptionRes(parsedOutput, context);
};
const de_PayloadPart_event = async (output, context) => {
    const contents = {};
    const data = await parseBody(output.body, context);
    Object.assign(contents, de_PayloadPart(data, context));
    return contents;
};
const de_ServiceUnavailableException_event = async (output, context) => {
    const parsedOutput = {
        ...output,
        body: await parseBody(output.body, context),
    };
    return de_ServiceUnavailableExceptionRes(parsedOutput, context);
};
const de_ThrottlingException_event = async (output, context) => {
    const parsedOutput = {
        ...output,
        body: await parseBody(output.body, context),
    };
    return de_ThrottlingExceptionRes(parsedOutput, context);
};
const de_ValidationException_event = async (output, context) => {
    const parsedOutput = {
        ...output,
        body: await parseBody(output.body, context),
    };
    return de_ValidationExceptionRes(parsedOutput, context);
};
const se_BidirectionalInputPayloadPart = (input, context) => {
    return take(input, {
        bytes: context.base64Encoder,
    });
};
const se_ContentBlock = (input, context) => {
    return ContentBlock.visit(input, {
        cachePoint: (value) => ({ cachePoint: _json(value) }),
        citationsContent: (value) => ({ citationsContent: _json(value) }),
        document: (value) => ({ document: se_DocumentBlock(value, context) }),
        guardContent: (value) => ({ guardContent: se_GuardrailConverseContentBlock(value, context) }),
        image: (value) => ({ image: se_ImageBlock(value, context) }),
        reasoningContent: (value) => ({ reasoningContent: se_ReasoningContentBlock(value, context) }),
        text: (value) => ({ text: value }),
        toolResult: (value) => ({ toolResult: se_ToolResultBlock(value, context) }),
        toolUse: (value) => ({ toolUse: se_ToolUseBlock(value, context) }),
        video: (value) => ({ video: se_VideoBlock(value, context) }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_ContentBlocks = (input, context) => {
    return input
        .filter((e) => e != null)
        .map((entry) => {
        return se_ContentBlock(entry, context);
    });
};
const se_ConverseTokensRequest = (input, context) => {
    return take(input, {
        messages: (_) => se_Messages(_, context),
        system: (_) => se_SystemContentBlocks(_, context),
    });
};
const se_CountTokensInput = (input, context) => {
    return CountTokensInput.visit(input, {
        converse: (value) => ({ converse: se_ConverseTokensRequest(value, context) }),
        invokeModel: (value) => ({ invokeModel: se_InvokeModelTokensRequest(value, context) }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_DocumentBlock = (input, context) => {
    return take(input, {
        citations: _json,
        context: [],
        format: [],
        name: [],
        source: (_) => se_DocumentSource(_, context),
    });
};
const se_DocumentSource = (input, context) => {
    return DocumentSource.visit(input, {
        bytes: (value) => ({ bytes: context.base64Encoder(value) }),
        content: (value) => ({ content: _json(value) }),
        s3Location: (value) => ({ s3Location: _json(value) }),
        text: (value) => ({ text: value }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_GuardrailContentBlock = (input, context) => {
    return GuardrailContentBlock.visit(input, {
        image: (value) => ({ image: se_GuardrailImageBlock(value, context) }),
        text: (value) => ({ text: _json(value) }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_GuardrailContentBlockList = (input, context) => {
    return input
        .filter((e) => e != null)
        .map((entry) => {
        return se_GuardrailContentBlock(entry, context);
    });
};
const se_GuardrailConverseContentBlock = (input, context) => {
    return GuardrailConverseContentBlock.visit(input, {
        image: (value) => ({ image: se_GuardrailConverseImageBlock(value, context) }),
        text: (value) => ({ text: _json(value) }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_GuardrailConverseImageBlock = (input, context) => {
    return take(input, {
        format: [],
        source: (_) => se_GuardrailConverseImageSource(_, context),
    });
};
const se_GuardrailConverseImageSource = (input, context) => {
    return GuardrailConverseImageSource.visit(input, {
        bytes: (value) => ({ bytes: context.base64Encoder(value) }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_GuardrailImageBlock = (input, context) => {
    return take(input, {
        format: [],
        source: (_) => se_GuardrailImageSource(_, context),
    });
};
const se_GuardrailImageSource = (input, context) => {
    return GuardrailImageSource.visit(input, {
        bytes: (value) => ({ bytes: context.base64Encoder(value) }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_ImageBlock = (input, context) => {
    return take(input, {
        format: [],
        source: (_) => se_ImageSource(_, context),
    });
};
const se_ImageSource = (input, context) => {
    return ImageSource.visit(input, {
        bytes: (value) => ({ bytes: context.base64Encoder(value) }),
        s3Location: (value) => ({ s3Location: _json(value) }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_InferenceConfiguration = (input, context) => {
    return take(input, {
        maxTokens: [],
        stopSequences: _json,
        temperature: __serializeFloat,
        topP: __serializeFloat,
    });
};
const se_InvokeModelTokensRequest = (input, context) => {
    return take(input, {
        body: context.base64Encoder,
    });
};
const se_Message = (input, context) => {
    return take(input, {
        content: (_) => se_ContentBlocks(_, context),
        role: [],
    });
};
const se_Messages = (input, context) => {
    return input
        .filter((e) => e != null)
        .map((entry) => {
        return se_Message(entry, context);
    });
};
const se_ModelInputPayload = (input, context) => {
    return input;
};
const se_ReasoningContentBlock = (input, context) => {
    return ReasoningContentBlock.visit(input, {
        reasoningText: (value) => ({ reasoningText: _json(value) }),
        redactedContent: (value) => ({ redactedContent: context.base64Encoder(value) }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_SystemContentBlock = (input, context) => {
    return SystemContentBlock.visit(input, {
        cachePoint: (value) => ({ cachePoint: _json(value) }),
        guardContent: (value) => ({ guardContent: se_GuardrailConverseContentBlock(value, context) }),
        text: (value) => ({ text: value }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_SystemContentBlocks = (input, context) => {
    return input
        .filter((e) => e != null)
        .map((entry) => {
        return se_SystemContentBlock(entry, context);
    });
};
const se_Tool = (input, context) => {
    return Tool.visit(input, {
        cachePoint: (value) => ({ cachePoint: _json(value) }),
        toolSpec: (value) => ({ toolSpec: se_ToolSpecification(value, context) }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_ToolConfiguration = (input, context) => {
    return take(input, {
        toolChoice: _json,
        tools: (_) => se_Tools(_, context),
    });
};
const se_ToolInputSchema = (input, context) => {
    return ToolInputSchema.visit(input, {
        json: (value) => ({ json: se_Document(value, context) }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_ToolResultBlock = (input, context) => {
    return take(input, {
        content: (_) => se_ToolResultContentBlocks(_, context),
        status: [],
        toolUseId: [],
    });
};
const se_ToolResultContentBlock = (input, context) => {
    return ToolResultContentBlock.visit(input, {
        document: (value) => ({ document: se_DocumentBlock(value, context) }),
        image: (value) => ({ image: se_ImageBlock(value, context) }),
        json: (value) => ({ json: se_Document(value, context) }),
        text: (value) => ({ text: value }),
        video: (value) => ({ video: se_VideoBlock(value, context) }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_ToolResultContentBlocks = (input, context) => {
    return input
        .filter((e) => e != null)
        .map((entry) => {
        return se_ToolResultContentBlock(entry, context);
    });
};
const se_Tools = (input, context) => {
    return input
        .filter((e) => e != null)
        .map((entry) => {
        return se_Tool(entry, context);
    });
};
const se_ToolSpecification = (input, context) => {
    return take(input, {
        description: [],
        inputSchema: (_) => se_ToolInputSchema(_, context),
        name: [],
    });
};
const se_ToolUseBlock = (input, context) => {
    return take(input, {
        input: (_) => se_Document(_, context),
        name: [],
        toolUseId: [],
    });
};
const se_VideoBlock = (input, context) => {
    return take(input, {
        format: [],
        source: (_) => se_VideoSource(_, context),
    });
};
const se_VideoSource = (input, context) => {
    return VideoSource.visit(input, {
        bytes: (value) => ({ bytes: context.base64Encoder(value) }),
        s3Location: (value) => ({ s3Location: _json(value) }),
        _: (name, value) => ({ [name]: value }),
    });
};
const se_Document = (input, context) => {
    return input;
};
const de_AsyncInvokeSummaries = (output, context) => {
    const retVal = (output || [])
        .filter((e) => e != null)
        .map((entry) => {
        return de_AsyncInvokeSummary(entry, context);
    });
    return retVal;
};
const de_AsyncInvokeSummary = (output, context) => {
    return take(output, {
        clientRequestToken: __expectString,
        endTime: (_) => __expectNonNull(__parseRfc3339DateTimeWithOffset(_)),
        failureMessage: __expectString,
        invocationArn: __expectString,
        lastModifiedTime: (_) => __expectNonNull(__parseRfc3339DateTimeWithOffset(_)),
        modelArn: __expectString,
        outputDataConfig: (_) => _json(__expectUnion(_)),
        status: __expectString,
        submitTime: (_) => __expectNonNull(__parseRfc3339DateTimeWithOffset(_)),
    });
};
const de_BidirectionalOutputPayloadPart = (output, context) => {
    return take(output, {
        bytes: context.base64Decoder,
    });
};
const de_ContentBlock = (output, context) => {
    if (output.cachePoint != null) {
        return {
            cachePoint: _json(output.cachePoint),
        };
    }
    if (output.citationsContent != null) {
        return {
            citationsContent: _json(output.citationsContent),
        };
    }
    if (output.document != null) {
        return {
            document: de_DocumentBlock(output.document, context),
        };
    }
    if (output.guardContent != null) {
        return {
            guardContent: de_GuardrailConverseContentBlock(__expectUnion(output.guardContent), context),
        };
    }
    if (output.image != null) {
        return {
            image: de_ImageBlock(output.image, context),
        };
    }
    if (output.reasoningContent != null) {
        return {
            reasoningContent: de_ReasoningContentBlock(__expectUnion(output.reasoningContent), context),
        };
    }
    if (__expectString(output.text) !== undefined) {
        return { text: __expectString(output.text) };
    }
    if (output.toolResult != null) {
        return {
            toolResult: de_ToolResultBlock(output.toolResult, context),
        };
    }
    if (output.toolUse != null) {
        return {
            toolUse: de_ToolUseBlock(output.toolUse, context),
        };
    }
    if (output.video != null) {
        return {
            video: de_VideoBlock(output.video, context),
        };
    }
    return { $unknown: Object.entries(output)[0] };
};
const de_ContentBlockDelta = (output, context) => {
    if (output.citation != null) {
        return {
            citation: _json(output.citation),
        };
    }
    if (output.reasoningContent != null) {
        return {
            reasoningContent: de_ReasoningContentBlockDelta(__expectUnion(output.reasoningContent), context),
        };
    }
    if (__expectString(output.text) !== undefined) {
        return { text: __expectString(output.text) };
    }
    if (output.toolUse != null) {
        return {
            toolUse: _json(output.toolUse),
        };
    }
    return { $unknown: Object.entries(output)[0] };
};
const de_ContentBlockDeltaEvent = (output, context) => {
    return take(output, {
        contentBlockIndex: __expectInt32,
        delta: (_) => de_ContentBlockDelta(__expectUnion(_), context),
    });
};
const de_ContentBlocks = (output, context) => {
    const retVal = (output || [])
        .filter((e) => e != null)
        .map((entry) => {
        return de_ContentBlock(__expectUnion(entry), context);
    });
    return retVal;
};
const de_ConverseOutput = (output, context) => {
    if (output.message != null) {
        return {
            message: de_Message(output.message, context),
        };
    }
    return { $unknown: Object.entries(output)[0] };
};
const de_ConverseStreamMetadataEvent = (output, context) => {
    return take(output, {
        metrics: _json,
        performanceConfig: _json,
        trace: (_) => de_ConverseStreamTrace(_, context),
        usage: _json,
    });
};
const de_ConverseStreamTrace = (output, context) => {
    return take(output, {
        guardrail: (_) => de_GuardrailTraceAssessment(_, context),
        promptRouter: _json,
    });
};
const de_ConverseTrace = (output, context) => {
    return take(output, {
        guardrail: (_) => de_GuardrailTraceAssessment(_, context),
        promptRouter: _json,
    });
};
const de_DocumentBlock = (output, context) => {
    return take(output, {
        citations: _json,
        context: __expectString,
        format: __expectString,
        name: __expectString,
        source: (_) => de_DocumentSource(__expectUnion(_), context),
    });
};
const de_DocumentSource = (output, context) => {
    if (output.bytes != null) {
        return {
            bytes: context.base64Decoder(output.bytes),
        };
    }
    if (output.content != null) {
        return {
            content: _json(output.content),
        };
    }
    if (output.s3Location != null) {
        return {
            s3Location: _json(output.s3Location),
        };
    }
    if (__expectString(output.text) !== undefined) {
        return { text: __expectString(output.text) };
    }
    return { $unknown: Object.entries(output)[0] };
};
const de_GuardrailAssessment = (output, context) => {
    return take(output, {
        automatedReasoningPolicy: (_) => de_GuardrailAutomatedReasoningPolicyAssessment(_, context),
        contentPolicy: _json,
        contextualGroundingPolicy: (_) => de_GuardrailContextualGroundingPolicyAssessment(_, context),
        invocationMetrics: _json,
        sensitiveInformationPolicy: _json,
        topicPolicy: _json,
        wordPolicy: _json,
    });
};
const de_GuardrailAssessmentList = (output, context) => {
    const retVal = (output || [])
        .filter((e) => e != null)
        .map((entry) => {
        return de_GuardrailAssessment(entry, context);
    });
    return retVal;
};
const de_GuardrailAssessmentListMap = (output, context) => {
    return Object.entries(output).reduce((acc, [key, value]) => {
        if (value === null) {
            return acc;
        }
        acc[key] = de_GuardrailAssessmentList(value, context);
        return acc;
    }, {});
};
const de_GuardrailAssessmentMap = (output, context) => {
    return Object.entries(output).reduce((acc, [key, value]) => {
        if (value === null) {
            return acc;
        }
        acc[key] = de_GuardrailAssessment(value, context);
        return acc;
    }, {});
};
const de_GuardrailAutomatedReasoningFinding = (output, context) => {
    if (output.impossible != null) {
        return {
            impossible: de_GuardrailAutomatedReasoningImpossibleFinding(output.impossible, context),
        };
    }
    if (output.invalid != null) {
        return {
            invalid: de_GuardrailAutomatedReasoningInvalidFinding(output.invalid, context),
        };
    }
    if (output.noTranslations != null) {
        return {
            noTranslations: _json(output.noTranslations),
        };
    }
    if (output.satisfiable != null) {
        return {
            satisfiable: de_GuardrailAutomatedReasoningSatisfiableFinding(output.satisfiable, context),
        };
    }
    if (output.tooComplex != null) {
        return {
            tooComplex: _json(output.tooComplex),
        };
    }
    if (output.translationAmbiguous != null) {
        return {
            translationAmbiguous: de_GuardrailAutomatedReasoningTranslationAmbiguousFinding(output.translationAmbiguous, context),
        };
    }
    if (output.valid != null) {
        return {
            valid: de_GuardrailAutomatedReasoningValidFinding(output.valid, context),
        };
    }
    return { $unknown: Object.entries(output)[0] };
};
const de_GuardrailAutomatedReasoningFindingList = (output, context) => {
    const retVal = (output || [])
        .filter((e) => e != null)
        .map((entry) => {
        return de_GuardrailAutomatedReasoningFinding(__expectUnion(entry), context);
    });
    return retVal;
};
const de_GuardrailAutomatedReasoningImpossibleFinding = (output, context) => {
    return take(output, {
        contradictingRules: _json,
        logicWarning: _json,
        translation: (_) => de_GuardrailAutomatedReasoningTranslation(_, context),
    });
};
const de_GuardrailAutomatedReasoningInvalidFinding = (output, context) => {
    return take(output, {
        contradictingRules: _json,
        logicWarning: _json,
        translation: (_) => de_GuardrailAutomatedReasoningTranslation(_, context),
    });
};
const de_GuardrailAutomatedReasoningPolicyAssessment = (output, context) => {
    return take(output, {
        findings: (_) => de_GuardrailAutomatedReasoningFindingList(_, context),
    });
};
const de_GuardrailAutomatedReasoningSatisfiableFinding = (output, context) => {
    return take(output, {
        claimsFalseScenario: _json,
        claimsTrueScenario: _json,
        logicWarning: _json,
        translation: (_) => de_GuardrailAutomatedReasoningTranslation(_, context),
    });
};
const de_GuardrailAutomatedReasoningTranslation = (output, context) => {
    return take(output, {
        claims: _json,
        confidence: __limitedParseDouble,
        premises: _json,
        untranslatedClaims: _json,
        untranslatedPremises: _json,
    });
};
const de_GuardrailAutomatedReasoningTranslationAmbiguousFinding = (output, context) => {
    return take(output, {
        differenceScenarios: _json,
        options: (_) => de_GuardrailAutomatedReasoningTranslationOptionList(_, context),
    });
};
const de_GuardrailAutomatedReasoningTranslationList = (output, context) => {
    const retVal = (output || [])
        .filter((e) => e != null)
        .map((entry) => {
        return de_GuardrailAutomatedReasoningTranslation(entry, context);
    });
    return retVal;
};
const de_GuardrailAutomatedReasoningTranslationOption = (output, context) => {
    return take(output, {
        translations: (_) => de_GuardrailAutomatedReasoningTranslationList(_, context),
    });
};
const de_GuardrailAutomatedReasoningTranslationOptionList = (output, context) => {
    const retVal = (output || [])
        .filter((e) => e != null)
        .map((entry) => {
        return de_GuardrailAutomatedReasoningTranslationOption(entry, context);
    });
    return retVal;
};
const de_GuardrailAutomatedReasoningValidFinding = (output, context) => {
    return take(output, {
        claimsTrueScenario: _json,
        logicWarning: _json,
        supportingRules: _json,
        translation: (_) => de_GuardrailAutomatedReasoningTranslation(_, context),
    });
};
const de_GuardrailContextualGroundingFilter = (output, context) => {
    return take(output, {
        action: __expectString,
        detected: __expectBoolean,
        score: __limitedParseDouble,
        threshold: __limitedParseDouble,
        type: __expectString,
    });
};
const de_GuardrailContextualGroundingFilters = (output, context) => {
    const retVal = (output || [])
        .filter((e) => e != null)
        .map((entry) => {
        return de_GuardrailContextualGroundingFilter(entry, context);
    });
    return retVal;
};
const de_GuardrailContextualGroundingPolicyAssessment = (output, context) => {
    return take(output, {
        filters: (_) => de_GuardrailContextualGroundingFilters(_, context),
    });
};
const de_GuardrailConverseContentBlock = (output, context) => {
    if (output.image != null) {
        return {
            image: de_GuardrailConverseImageBlock(output.image, context),
        };
    }
    if (output.text != null) {
        return {
            text: _json(output.text),
        };
    }
    return { $unknown: Object.entries(output)[0] };
};
const de_GuardrailConverseImageBlock = (output, context) => {
    return take(output, {
        format: __expectString,
        source: (_) => de_GuardrailConverseImageSource(__expectUnion(_), context),
    });
};
const de_GuardrailConverseImageSource = (output, context) => {
    if (output.bytes != null) {
        return {
            bytes: context.base64Decoder(output.bytes),
        };
    }
    return { $unknown: Object.entries(output)[0] };
};
const de_GuardrailTraceAssessment = (output, context) => {
    return take(output, {
        actionReason: __expectString,
        inputAssessment: (_) => de_GuardrailAssessmentMap(_, context),
        modelOutput: _json,
        outputAssessments: (_) => de_GuardrailAssessmentListMap(_, context),
    });
};
const de_ImageBlock = (output, context) => {
    return take(output, {
        format: __expectString,
        source: (_) => de_ImageSource(__expectUnion(_), context),
    });
};
const de_ImageSource = (output, context) => {
    if (output.bytes != null) {
        return {
            bytes: context.base64Decoder(output.bytes),
        };
    }
    if (output.s3Location != null) {
        return {
            s3Location: _json(output.s3Location),
        };
    }
    return { $unknown: Object.entries(output)[0] };
};
const de_Message = (output, context) => {
    return take(output, {
        content: (_) => de_ContentBlocks(_, context),
        role: __expectString,
    });
};
const de_MessageStopEvent = (output, context) => {
    return take(output, {
        additionalModelResponseFields: (_) => de_Document(_, context),
        stopReason: __expectString,
    });
};
const de_PayloadPart = (output, context) => {
    return take(output, {
        bytes: context.base64Decoder,
    });
};
const de_ReasoningContentBlock = (output, context) => {
    if (output.reasoningText != null) {
        return {
            reasoningText: _json(output.reasoningText),
        };
    }
    if (output.redactedContent != null) {
        return {
            redactedContent: context.base64Decoder(output.redactedContent),
        };
    }
    return { $unknown: Object.entries(output)[0] };
};
const de_ReasoningContentBlockDelta = (output, context) => {
    if (output.redactedContent != null) {
        return {
            redactedContent: context.base64Decoder(output.redactedContent),
        };
    }
    if (__expectString(output.signature) !== undefined) {
        return { signature: __expectString(output.signature) };
    }
    if (__expectString(output.text) !== undefined) {
        return { text: __expectString(output.text) };
    }
    return { $unknown: Object.entries(output)[0] };
};
const de_ToolResultBlock = (output, context) => {
    return take(output, {
        content: (_) => de_ToolResultContentBlocks(_, context),
        status: __expectString,
        toolUseId: __expectString,
    });
};
const de_ToolResultContentBlock = (output, context) => {
    if (output.document != null) {
        return {
            document: de_DocumentBlock(output.document, context),
        };
    }
    if (output.image != null) {
        return {
            image: de_ImageBlock(output.image, context),
        };
    }
    if (output.json != null) {
        return {
            json: de_Document(output.json, context),
        };
    }
    if (__expectString(output.text) !== undefined) {
        return { text: __expectString(output.text) };
    }
    if (output.video != null) {
        return {
            video: de_VideoBlock(output.video, context),
        };
    }
    return { $unknown: Object.entries(output)[0] };
};
const de_ToolResultContentBlocks = (output, context) => {
    const retVal = (output || [])
        .filter((e) => e != null)
        .map((entry) => {
        return de_ToolResultContentBlock(__expectUnion(entry), context);
    });
    return retVal;
};
const de_ToolUseBlock = (output, context) => {
    return take(output, {
        input: (_) => de_Document(_, context),
        name: __expectString,
        toolUseId: __expectString,
    });
};
const de_VideoBlock = (output, context) => {
    return take(output, {
        format: __expectString,
        source: (_) => de_VideoSource(__expectUnion(_), context),
    });
};
const de_VideoSource = (output, context) => {
    if (output.bytes != null) {
        return {
            bytes: context.base64Decoder(output.bytes),
        };
    }
    if (output.s3Location != null) {
        return {
            s3Location: _json(output.s3Location),
        };
    }
    return { $unknown: Object.entries(output)[0] };
};
const de_Document = (output, context) => {
    return output;
};
const deserializeMetadata = (output) => ({
    httpStatusCode: output.statusCode,
    requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
    extendedRequestId: output.headers["x-amz-id-2"],
    cfId: output.headers["x-amz-cf-id"],
});
const collectBodyString = (streamBody, context) => collectBody(streamBody, context).then((body) => context.utf8Encoder(body));
const _a = "accept";
const _cT = "contentType";
const _ct = "content-type";
const _gI = "guardrailIdentifier";
const _gV = "guardrailVersion";
const _mR = "maxResults";
const _nT = "nextToken";
const _pCL = "performanceConfigLatency";
const _sB = "sortBy";
const _sE = "statusEquals";
const _sO = "sortOrder";
const _sTA = "submitTimeAfter";
const _sTB = "submitTimeBefore";
const _t = "trace";
const _xaba = "x-amzn-bedrock-accept";
const _xabct = "x-amzn-bedrock-content-type";
const _xabg = "x-amzn-bedrock-guardrailidentifier";
const _xabg_ = "x-amzn-bedrock-guardrailversion";
const _xabpl = "x-amzn-bedrock-performanceconfig-latency";
const _xabt = "x-amzn-bedrock-trace";
