All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.aws.sdk.kotlin.services.lexruntimev2.DefaultLexRuntimeV2Client.kt Maven / Gradle / Ivy

// Code generated by smithy-kotlin-codegen. DO NOT EDIT!

package aws.sdk.kotlin.services.lexruntimev2

import aws.sdk.kotlin.runtime.http.ApiMetadata
import aws.sdk.kotlin.runtime.http.AwsUserAgentMetadata
import aws.sdk.kotlin.runtime.http.interceptors.AwsSpanInterceptor
import aws.sdk.kotlin.runtime.http.interceptors.BusinessMetricsInterceptor
import aws.sdk.kotlin.runtime.http.middleware.AwsRetryHeaderMiddleware
import aws.sdk.kotlin.runtime.http.middleware.RecursionDetection
import aws.sdk.kotlin.runtime.http.middleware.UserAgent
import aws.sdk.kotlin.services.lexruntimev2.auth.LexRuntimeV2AuthSchemeProviderAdapter
import aws.sdk.kotlin.services.lexruntimev2.auth.LexRuntimeV2IdentityProviderConfigAdapter
import aws.sdk.kotlin.services.lexruntimev2.endpoints.internal.EndpointResolverAdapter
import aws.sdk.kotlin.services.lexruntimev2.model.*
import aws.sdk.kotlin.services.lexruntimev2.serde.*
import aws.smithy.kotlin.runtime.auth.AuthSchemeId
import aws.smithy.kotlin.runtime.auth.awssigning.AwsSignedBodyHeader
import aws.smithy.kotlin.runtime.auth.awssigning.AwsSigningAttributes
import aws.smithy.kotlin.runtime.auth.awssigning.DefaultAwsSigner
import aws.smithy.kotlin.runtime.awsprotocol.AwsAttributes
import aws.smithy.kotlin.runtime.client.SdkClientOption
import aws.smithy.kotlin.runtime.collections.attributesOf
import aws.smithy.kotlin.runtime.collections.putIfAbsent
import aws.smithy.kotlin.runtime.collections.putIfAbsentNotNull
import aws.smithy.kotlin.runtime.http.SdkHttpClient
import aws.smithy.kotlin.runtime.http.auth.AuthScheme
import aws.smithy.kotlin.runtime.http.auth.SigV4AuthScheme
import aws.smithy.kotlin.runtime.http.operation.OperationAuthConfig
import aws.smithy.kotlin.runtime.http.operation.OperationMetrics
import aws.smithy.kotlin.runtime.http.operation.SdkHttpOperation
import aws.smithy.kotlin.runtime.http.operation.context
import aws.smithy.kotlin.runtime.http.operation.execute
import aws.smithy.kotlin.runtime.http.operation.roundTrip
import aws.smithy.kotlin.runtime.http.operation.telemetry
import aws.smithy.kotlin.runtime.io.SdkManagedGroup
import aws.smithy.kotlin.runtime.io.addIfManaged
import aws.smithy.kotlin.runtime.operation.ExecutionContext

internal class DefaultLexRuntimeV2Client(override val config: LexRuntimeV2Client.Config) : LexRuntimeV2Client {
    private val managedResources = SdkManagedGroup()
    private val client = SdkHttpClient(config.httpClient)
    private val identityProviderConfig = LexRuntimeV2IdentityProviderConfigAdapter(config)
    private val configuredAuthSchemes = with(config.authSchemes.associateBy(AuthScheme::schemeId).toMutableMap()){
        getOrPut(AuthSchemeId.AwsSigV4){
            SigV4AuthScheme(DefaultAwsSigner, "lex")
        }
        toMap()
    }
    private val authSchemeAdapter = LexRuntimeV2AuthSchemeProviderAdapter(config)
    private val telemetryScope = "aws.sdk.kotlin.services.lexruntimev2"
    private val opMetrics = OperationMetrics(telemetryScope, config.telemetryProvider)

    init {
        managedResources.addIfManaged(config.httpClient)
        managedResources.addIfManaged(config.credentialsProvider)
    }

    private val awsUserAgentMetadata = AwsUserAgentMetadata.fromEnvironment(ApiMetadata(ServiceId, SdkVersion), config.applicationId)

    /**
     * Removes session information for a specified bot, alias, and user ID.
     *
     * You can use this operation to restart a conversation with a bot. When you remove a session, the entire history of the session is removed so that you can start again.
     *
     * You don't need to delete a session. Sessions have a time limit and will expire. Set the session time limit when you create the bot. The default is 5 minutes, but you can specify anything between 1 minute and 24 hours.
     *
     * If you specify a bot or alias ID that doesn't exist, you receive a `BadRequestException.`
     *
     * If the locale doesn't exist in the bot, or if the locale hasn't been enables for the alias, you receive a `BadRequestException`.
     */
    override suspend fun deleteSession(input: DeleteSessionRequest): DeleteSessionResponse {
        val op = SdkHttpOperation.build {
            serializeWith = DeleteSessionOperationSerializer()
            deserializeWith = DeleteSessionOperationDeserializer()
            operationName = "DeleteSession"
            serviceName = ServiceId
            telemetry {
                provider = config.telemetryProvider
                scope = telemetryScope
                metrics = opMetrics
                attributes = attributesOf {
                    "rpc.system" to "aws-api"
                }
            }
            execution.auth = OperationAuthConfig(authSchemeAdapter, configuredAuthSchemes, identityProviderConfig)
            execution.endpointResolver = EndpointResolverAdapter(config)
            execution.retryStrategy = config.retryStrategy
            execution.retryPolicy = config.retryPolicy
        }
        mergeServiceDefaults(op.context)
        op.install(AwsRetryHeaderMiddleware())
        op.interceptors.add(AwsSpanInterceptor)
        op.interceptors.add(BusinessMetricsInterceptor())
        op.install(UserAgent(awsUserAgentMetadata))
        op.install(RecursionDetection())
        op.interceptors.addAll(config.interceptors)
        return op.roundTrip(client, input)
    }

    /**
     * Returns session information for a specified bot, alias, and user.
     *
     * For example, you can use this operation to retrieve session information for a user that has left a long-running session in use.
     *
     * If the bot, alias, or session identifier doesn't exist, Amazon Lex V2 returns a `BadRequestException`. If the locale doesn't exist or is not enabled for the alias, you receive a `BadRequestException`.
     */
    override suspend fun getSession(input: GetSessionRequest): GetSessionResponse {
        val op = SdkHttpOperation.build {
            serializeWith = GetSessionOperationSerializer()
            deserializeWith = GetSessionOperationDeserializer()
            operationName = "GetSession"
            serviceName = ServiceId
            telemetry {
                provider = config.telemetryProvider
                scope = telemetryScope
                metrics = opMetrics
                attributes = attributesOf {
                    "rpc.system" to "aws-api"
                }
            }
            execution.auth = OperationAuthConfig(authSchemeAdapter, configuredAuthSchemes, identityProviderConfig)
            execution.endpointResolver = EndpointResolverAdapter(config)
            execution.retryStrategy = config.retryStrategy
            execution.retryPolicy = config.retryPolicy
        }
        mergeServiceDefaults(op.context)
        op.install(AwsRetryHeaderMiddleware())
        op.interceptors.add(AwsSpanInterceptor)
        op.interceptors.add(BusinessMetricsInterceptor())
        op.install(UserAgent(awsUserAgentMetadata))
        op.install(RecursionDetection())
        op.interceptors.addAll(config.interceptors)
        return op.roundTrip(client, input)
    }

    /**
     * Creates a new session or modifies an existing session with an Amazon Lex V2 bot. Use this operation to enable your application to set the state of the bot.
     */
    override suspend fun  putSession(input: PutSessionRequest, block: suspend (PutSessionResponse) -> T): T {
        val op = SdkHttpOperation.build {
            serializeWith = PutSessionOperationSerializer()
            deserializeWith = PutSessionOperationDeserializer()
            operationName = "PutSession"
            serviceName = ServiceId
            telemetry {
                provider = config.telemetryProvider
                scope = telemetryScope
                metrics = opMetrics
                attributes = attributesOf {
                    "rpc.system" to "aws-api"
                }
            }
            execution.auth = OperationAuthConfig(authSchemeAdapter, configuredAuthSchemes, identityProviderConfig)
            execution.endpointResolver = EndpointResolverAdapter(config)
            execution.retryStrategy = config.retryStrategy
            execution.retryPolicy = config.retryPolicy
        }
        mergeServiceDefaults(op.context)
        op.install(AwsRetryHeaderMiddleware())
        op.interceptors.add(AwsSpanInterceptor)
        op.interceptors.add(BusinessMetricsInterceptor())
        op.install(UserAgent(awsUserAgentMetadata))
        op.install(RecursionDetection())
        op.interceptors.addAll(config.interceptors)
        return op.execute(client, input, block)
    }

    /**
     * Sends user input to Amazon Lex V2. Client applications use this API to send requests to Amazon Lex V2 at runtime. Amazon Lex V2 then interprets the user input using the machine learning model that it build for the bot.
     *
     * In response, Amazon Lex V2 returns the next message to convey to the user and an optional response card to display.
     *
     * If the optional post-fulfillment response is specified, the messages are returned as follows. For more information, see [PostFulfillmentStatusSpecification](https://docs.aws.amazon.com/lexv2/latest/dg/API_PostFulfillmentStatusSpecification.html).
     * + **Success message** - Returned if the Lambda function completes successfully and the intent state is fulfilled or ready fulfillment if the message is present.
     * + **Failed message** - The failed message is returned if the Lambda function throws an exception or if the Lambda function returns a failed intent state without a message.
     * + **Timeout message** - If you don't configure a timeout message and a timeout, and the Lambda function doesn't return within 30 seconds, the timeout message is returned. If you configure a timeout, the timeout message is returned when the period times out.
     *
     * For more information, see [Completion message](https://docs.aws.amazon.com/lexv2/latest/dg/streaming-progress.html#progress-complete.html).
     */
    override suspend fun recognizeText(input: RecognizeTextRequest): RecognizeTextResponse {
        val op = SdkHttpOperation.build {
            serializeWith = RecognizeTextOperationSerializer()
            deserializeWith = RecognizeTextOperationDeserializer()
            operationName = "RecognizeText"
            serviceName = ServiceId
            telemetry {
                provider = config.telemetryProvider
                scope = telemetryScope
                metrics = opMetrics
                attributes = attributesOf {
                    "rpc.system" to "aws-api"
                }
            }
            execution.auth = OperationAuthConfig(authSchemeAdapter, configuredAuthSchemes, identityProviderConfig)
            execution.endpointResolver = EndpointResolverAdapter(config)
            execution.retryStrategy = config.retryStrategy
            execution.retryPolicy = config.retryPolicy
        }
        mergeServiceDefaults(op.context)
        op.install(AwsRetryHeaderMiddleware())
        op.interceptors.add(AwsSpanInterceptor)
        op.interceptors.add(BusinessMetricsInterceptor())
        op.install(UserAgent(awsUserAgentMetadata))
        op.install(RecursionDetection())
        op.interceptors.addAll(config.interceptors)
        return op.roundTrip(client, input)
    }

    /**
     * Sends user input to Amazon Lex V2. You can send text or speech. Clients use this API to send text and audio requests to Amazon Lex V2 at runtime. Amazon Lex V2 interprets the user input using the machine learning model built for the bot.
     *
     * The following request fields must be compressed with gzip and then base64 encoded before you send them to Amazon Lex V2.
     * + requestAttributes
     * + sessionState
     *
     * The following response fields are compressed using gzip and then base64 encoded by Amazon Lex V2. Before you can use these fields, you must decode and decompress them.
     * + inputTranscript
     * + interpretations
     * + messages
     * + requestAttributes
     * + sessionState
     *
     * The example contains a Java application that compresses and encodes a Java object to send to Amazon Lex V2, and a second that decodes and decompresses a response from Amazon Lex V2.
     *
     * If the optional post-fulfillment response is specified, the messages are returned as follows. For more information, see [PostFulfillmentStatusSpecification](https://docs.aws.amazon.com/lexv2/latest/dg/API_PostFulfillmentStatusSpecification.html).
     * + **Success message** - Returned if the Lambda function completes successfully and the intent state is fulfilled or ready fulfillment if the message is present.
     * + **Failed message** - The failed message is returned if the Lambda function throws an exception or if the Lambda function returns a failed intent state without a message.
     * + **Timeout message** - If you don't configure a timeout message and a timeout, and the Lambda function doesn't return within 30 seconds, the timeout message is returned. If you configure a timeout, the timeout message is returned when the period times out.
     *
     * For more information, see [Completion message](https://docs.aws.amazon.com/lexv2/latest/dg/streaming-progress.html#progress-complete.html).
     */
    override suspend fun  recognizeUtterance(input: RecognizeUtteranceRequest, block: suspend (RecognizeUtteranceResponse) -> T): T {
        val op = SdkHttpOperation.build {
            serializeWith = RecognizeUtteranceOperationSerializer()
            deserializeWith = RecognizeUtteranceOperationDeserializer()
            operationName = "RecognizeUtterance"
            serviceName = ServiceId
            telemetry {
                provider = config.telemetryProvider
                scope = telemetryScope
                metrics = opMetrics
                attributes = attributesOf {
                    "rpc.system" to "aws-api"
                }
            }
            execution.auth = OperationAuthConfig(authSchemeAdapter, configuredAuthSchemes, identityProviderConfig)
            execution.endpointResolver = EndpointResolverAdapter(config)
            execution.retryStrategy = config.retryStrategy
            execution.retryPolicy = config.retryPolicy
        }
        mergeServiceDefaults(op.context)
        op.context.set(AwsSigningAttributes.SignedBodyHeader, AwsSignedBodyHeader.X_AMZ_CONTENT_SHA256)
        op.install(AwsRetryHeaderMiddleware())
        op.interceptors.add(AwsSpanInterceptor)
        op.interceptors.add(BusinessMetricsInterceptor())
        op.install(UserAgent(awsUserAgentMetadata))
        op.install(RecursionDetection())
        op.interceptors.addAll(config.interceptors)
        return op.execute(client, input, block)
    }

    /**
     * Starts an HTTP/2 bidirectional event stream that enables you to send audio, text, or DTMF input in real time. After your application starts a conversation, users send input to Amazon Lex V2 as a stream of events. Amazon Lex V2 processes the incoming events and responds with streaming text or audio events.
     *
     * Audio input must be in the following format: `audio/lpcm sample-rate=8000 sample-size-bits=16 channel-count=1; is-big-endian=false`.
     *
     * If the optional post-fulfillment response is specified, the messages are returned as follows. For more information, see [PostFulfillmentStatusSpecification](https://docs.aws.amazon.com/lexv2/latest/dg/API_PostFulfillmentStatusSpecification.html).
     * + **Success message** - Returned if the Lambda function completes successfully and the intent state is fulfilled or ready fulfillment if the message is present.
     * + **Failed message** - The failed message is returned if the Lambda function throws an exception or if the Lambda function returns a failed intent state without a message.
     * + **Timeout message** - If you don't configure a timeout message and a timeout, and the Lambda function doesn't return within 30 seconds, the timeout message is returned. If you configure a timeout, the timeout message is returned when the period times out.
     *
     * For more information, see [Completion message](https://docs.aws.amazon.com/lexv2/latest/dg/streaming-progress.html#progress-complete.html).
     *
     * If the optional update message is configured, it is played at the specified frequency while the Lambda function is running and the update message state is active. If the fulfillment update message is not active, the Lambda function runs with a 30 second timeout.
     *
     * For more information, see [Update message ](https://docs.aws.amazon.com/lexv2/latest/dg/streaming-progress.html#progress-update.html)
     *
     * The `StartConversation` operation is supported only in the following SDKs:
     * + [AWS SDK for C++](https://docs.aws.amazon.com/goto/SdkForCpp/runtime.lex.v2-2020-08-07/StartConversation)
     * + [AWS SDK for Java V2](https://docs.aws.amazon.com/goto/SdkForJavaV2/runtime.lex.v2-2020-08-07/StartConversation)
     * + [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/runtime.lex.v2-2020-08-07/StartConversation)
     */
    override suspend fun  startConversation(input: StartConversationRequest, block: suspend (StartConversationResponse) -> T): T {
        val op = SdkHttpOperation.build {
            serializeWith = StartConversationOperationSerializer()
            deserializeWith = StartConversationOperationDeserializer()
            operationName = "StartConversation"
            serviceName = ServiceId
            telemetry {
                provider = config.telemetryProvider
                scope = telemetryScope
                metrics = opMetrics
                attributes = attributesOf {
                    "rpc.system" to "aws-api"
                }
            }
            execution.auth = OperationAuthConfig(authSchemeAdapter, configuredAuthSchemes, identityProviderConfig)
            execution.endpointResolver = EndpointResolverAdapter(config)
            execution.retryStrategy = config.retryStrategy
            execution.retryPolicy = config.retryPolicy
        }
        mergeServiceDefaults(op.context)
        op.context.set(AwsSigningAttributes.SignedBodyHeader, AwsSignedBodyHeader.X_AMZ_CONTENT_SHA256)
        op.install(AwsRetryHeaderMiddleware())
        op.interceptors.add(AwsSpanInterceptor)
        op.interceptors.add(BusinessMetricsInterceptor())
        op.install(UserAgent(awsUserAgentMetadata))
        op.install(RecursionDetection())
        op.interceptors.addAll(config.interceptors)
        return op.execute(client, input, block)
    }

    override fun close() {
        managedResources.unshareAll()
    }

    /**
     * merge the defaults configured for the service into the execution context before firing off a request
     */
    private fun mergeServiceDefaults(ctx: ExecutionContext) {
        ctx.putIfAbsent(SdkClientOption.ClientName, config.clientName)
        ctx.putIfAbsent(SdkClientOption.LogMode, config.logMode)
        ctx.putIfAbsentNotNull(AwsAttributes.Region, config.region)
        ctx.putIfAbsentNotNull(AwsSigningAttributes.SigningRegion, config.region)
        ctx.putIfAbsent(AwsSigningAttributes.SigningService, "lex")
        ctx.putIfAbsent(AwsSigningAttributes.CredentialsProvider, config.credentialsProvider)
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy