def __init__(
        self, configuration: DefaultConfig, telemetry_client: BotTelemetryClient = None
    ):
        self._recognizer = None

        luis_is_configured = (
            configuration.LUIS_APP_ID
            and configuration.LUIS_API_KEY
            and configuration.LUIS_API_HOST_NAME
        )
        if luis_is_configured:
            # Set the recognizer options depending on which endpoint version you want to use e.g v2 or v3.
            # More details can be found in https://docs.microsoft.com/azure/cognitive-services/luis/luis-migration-api-v3
            luis_application = LuisApplication(
                configuration.LUIS_APP_ID,
                configuration.LUIS_API_KEY,
                "https://" + configuration.LUIS_API_HOST_NAME,
            )

            options = LuisPredictionOptions()
            options.telemetry_client = telemetry_client or NullTelemetryClient()

            self._recognizer = LuisRecognizer(
                luis_application, prediction_options=options
            )
예제 #2
0
    async def execute_luis_query(
        configuration,
        turn_context: TurnContext,
        telemetry_client: BotTelemetryClient = None,
    ) -> BookingDetails:
        """Invoke LUIS service to perform prediction/evaluation of utterance."""
        booking_details = BookingDetails()

        # pylint:disable=broad-except
        try:
            luis_application = LuisApplication(
                configuration.get("LUIS_APP_ID"),
                configuration.get("LUIS_API_KEY"),
                configuration.get("LUIS_API_HOST_NAME"),
            )
            options = LuisPredictionOptions()
            options.telemetry_client = (
                telemetry_client
                if telemetry_client is not None
                else NullTelemetryClient()
            )
            recognizer = LuisRecognizer(luis_application, prediction_options=options)
            recognizer_result = await recognizer.recognize(turn_context)
            print(f"Recognize Result: {recognizer_result}")

            if recognizer_result.intents:
                intent = sorted(
                    recognizer_result.intents,
                    key=recognizer_result.intents.get,
                    reverse=True,
                )[:1][0]
                if intent == "Book_flight":
                    # We need to get the result from the LUIS JSON which at every level returns an array.
                    to_entities = recognizer_result.entities.get("$instance", {}).get(
                        "To", []
                    )
                    if to_entities:
                        booking_details.destination = to_entities[0]["text"]
                    from_entities = recognizer_result.entities.get("$instance", {}).get(
                        "From", []
                    )
                    if from_entities:
                        booking_details.origin = from_entities[0]["text"]

                    # This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part.
                    # TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year.
                    date_entities = recognizer_result.entities.get("$instance", {}).get(
                        "datetime", []
                    )
                    if date_entities:
                        booking_details.travel_date = (
                            None
                        )  # Set when we get a timex format
        except Exception as exception:
            print(exception)

        return booking_details
    def __init__(
        self, 
        config: DefaultConfig, 
        conversation_state: ConversationState, 
        user_state: UserState, 
        dialog: Dialog
        ):
        luis_application = LuisApplication(
            config.LUIS_APP_ID, 
            config.LUIS_API_KEY, 
            "https://" + config.LUIS_API_HOST_NAME
            )
        luis_options = LuisPredictionOptions(include_all_intents=True, include_instance_data=True)
        self.recognizer = LuisRecognizer(luis_application, luis_options, True)

        self.subscription_key = config.LUIS_API_KEY
        self.version_id = config.LUIS_APP_VERSION_ID
        # 可空白或直接填寫一個現有的luis app,不過需要注意其version_id是否與config.py裡的一樣
        self.luis_appid = ''              
        
        # 激活dialog_data.py裡的資訊
        self.user_profile_accessor = user_state.create_property("DialogData")

        if conversation_state is None:
            raise TypeError("[DialogBot]: Missing parameter. conversation_state is required but None was given")
        if user_state is None:
            raise TypeError("[DialogBot]: Missing parameter. user_state is required but None was given")
        if dialog is None:
            raise Exception("[DialogBot]: Missing parameter. dialog is required")
        self.conversation_state = conversation_state
        self.user_state = user_state
        self.dialog = dialog
예제 #4
0
 def __init__(self):
     #connect to LUIS library app
     luis_app = LuisApplication(CONFIG.LUIS_APP_ID, CONFIG.LUIS_API_KEY,
                                CONFIG.LUIS_API_HOST_NAME)
     luis_option = LuisPredictionOptions(include_all_intents=True,
                                         include_instance_data=True)
     self.LuisReg = LuisRecognizer(luis_app, luis_option, True)
예제 #5
0
    async def test_telemetry_no_pii_logged_async(self):
        # Arrange
        utterance: str = "please book from May 5 to June 6"
        response_json: Dict[str, object] = self._empty_luis_response
        telemetry_client = mock.create_autospec(BotTelemetryClient)
        options = LuisPredictionOptions(telemetry_client=telemetry_client,
                                        log_personal_information=False)

        # Act
        await LuisRecognizerTest._get_recognizer_result(
            utterance,
            response_json,
            bot_adapter=NullAdapter(),
            options=options,
            telemetry_properties=None,
        )

        # Assert
        self.assertEqual(1, telemetry_client.track_event.call_count)
        args = telemetry_client.track_event.call_args[0]
        self.assertEqual("LuisResult", args[0])
        self.assertEqual(7, len(args[1]))
        self.assertTrue("applicationId" in args[1])
        self.assertTrue("intent" in args[1])
        self.assertTrue("intentScore" in args[1])
        self.assertTrue("intent2" in args[1])
        self.assertTrue("intentScore2" in args[1])
        self.assertTrue("fromId" in args[1])
        self.assertTrue("entities" in args[1])
        self.assertFalse("question" in args[1])
예제 #6
0
    async def test_telemetry_override_on_derive_async(self):
        # Arrange
        utterance: str = "please book from May 5 to June 6"
        response_json: Dict[str, object] = self._empty_luis_response
        telemetry_client = mock.create_autospec(BotTelemetryClient)
        options = LuisPredictionOptions(
            telemetry_client=telemetry_client, log_personal_information=False
        )
        telemetry_properties: Dict[str, str] = {"test": "testvalue", "foo": "foovalue"}

        # Act
        await LuisRecognizerTest._get_recognizer_result(
            utterance,
            response_json,
            bot_adapter=NullAdapter(),
            options=options,
            telemetry_properties=telemetry_properties,
            recognizer_class=TelemetryOverrideRecognizer,
        )

        # Assert
        self.assertEqual(2, telemetry_client.track_event.call_count)
        call0_args = telemetry_client.track_event.call_args_list[0][0]
        self.assertEqual("LuisResult", call0_args[0])
        self.assertTrue("MyImportantProperty" in call0_args[1])
        self.assertTrue(call0_args[1]["MyImportantProperty"] == "myImportantValue")
        self.assertTrue("test" in call0_args[1])
        self.assertTrue(call0_args[1]["test"] == "testvalue")
        self.assertTrue("foo" in call0_args[1])
        self.assertTrue(call0_args[1]["foo"] == "foovalue")
        call1_args = telemetry_client.track_event.call_args_list[1][0]
        self.assertEqual("MySecondEvent", call1_args[0])
        self.assertTrue("MyImportantProperty2" in call1_args[1])
        self.assertTrue(call1_args[1]["MyImportantProperty2"] == "myImportantValue2")
예제 #7
0
 def __init__(self):
     luis_app = LuisApplication(
         "9e445b81-7a4f-40e6-bfbf-81a1ea50a1e9",
         "dc11dc5d4a854a448842b39c217f064d",
         "https://westus.api.cognitive.microsoft.com/")
     luis_option = LuisPredictionOptions(include_all_intents=True,
                                         include_instance_data=True)
     self.LuisReg = LuisRecognizer(luis_app, luis_option, True)
 def __init__(self):
     self.config_reader = ConfigReader()
     self.configuration = self.config_reader.read_config()
     self.luis_app_id=self.configuration['LUIS_APP_ID']
     self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
     self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
     self.luis_app = LuisApplication(self.luis_app_id,self.luis_endpoint_key,self.luis_endpoint)
     self.luis_options = LuisPredictionOptions(include_all_intents=True,include_instance_data=True)
     self.luis_recognizer = LuisRecognizer(application=self.luis_app,prediction_options=self.luis_options,include_api_results=True)
예제 #9
0
    def __init__(self,constate:ConversationState,userstate:UserState):
        luis_app = LuisApplication("APP ID","primary starter key","https://westus.api.cognitive.microsoft.com/")
        luis_option = LuisPredictionOptions(include_all_intents=True,include_instance_data=True)
        self.LuisReg = LuisRecognizer(luis_app,luis_option,True)
        self.constate = constate
        self.userstate = userstate

        self.conprop = self.constate.create_property("constate")
        self.userprop = self.userstate.create_property("userstate")
    def test_luis_recognizer_timeout(self):
        endpoint = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q="
        expected_timeout = 300
        options_with_timeout = LuisPredictionOptions(timeout=expected_timeout * 1000)

        recognizer_with_timeout = LuisRecognizer(endpoint, options_with_timeout)

        self.assertEqual(
            expected_timeout, recognizer_with_timeout._runtime.config.connection.timeout
        )
예제 #11
0
    def __init__(self):

        config = DefaultConfig()

        luis_application = LuisApplication(
            config.LUIS_APP_ID,
            config.LUIS_API_KEY,
            config.LUIS_API_HOST_NAME,
        )
        luis_options = LuisPredictionOptions(include_all_intents=True,
                                             include_instance_data=True)
        super().__init__(luis_application, luis_options, True)
예제 #12
0
 def __init__(self):
     self.config = Config()
     self.luis_app = LuisApplication(
         self.config.luis_app_id,
         self.config.luis_endpoint_key,
         self.config.luis_endpoint,
     )
     self.luis_option = LuisPredictionOptions(
         include_all_intents=True,
         include_instance_data=True,
     )
     self.Luis_recognizer = LuisRecognizer(
         application=self.luis_app,
         prediction_options=self.luis_option,
         include_api_results=True)
예제 #13
0
    def __init__(self, config: DefaultConfig):

        luis_application = LuisApplication(
            config.LUIS_APP_ID,
            config.LUIS_API_KEY,
            "https://" + config.LUIS_API_HOST_NAME,
        )
        luis_options = LuisPredictionOptions(
            include_all_intents=True, include_instance_data=True
        )
        self.recognizer = LuisRecognizer(luis_application, luis_options, True)

        self.fetch_dataset()

        self._AzMap = AzureMaps(subscription_key=config.AZURE_MAPS_KEY)
예제 #14
0
    def __init__(self, conversation_state: ConversationState,
                 user_state: UserState):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id = self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id,
                                        self.luis_endpoint_key,
                                        self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True,
                                                  include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(
            application=self.luis_app,
            prediction_options=self.luis_options,
            include_api_results=True)
        self.qna_knowledge_base_id = self.configuration["QNA_KNOWLEDGEBASE_ID"]
        self.qna_endpoint_key = self.configuration["QNA_ENDPOINT_KEY"]
        self.qna_host = self.configuration["QNA_ENDPOINT_HOST"]
        self.qna_maker = QnAMaker(
            QnAMakerEndpoint(knowledge_base_id=self.qna_knowledge_base_id,
                             endpoint_key=self.qna_endpoint_key,
                             host=self.qna_host))
        self.log = Log()
        self.IntentIdentified = False
        self.intent = 'none'
        self.stat = 'init'
        self.city = ""
        self.score = ""

        if conversation_state is None:
            raise TypeError(
                "[StateManagementBot]: Missing parameter. conversation_state is required but None was given"
            )
        if user_state is None:
            raise TypeError(
                "[StateManagementBot]: Missing parameter. user_state is required but None was given"
            )

        self.conversation_state = conversation_state
        self.user_state = user_state

        self.conversation_data_accessor = self.conversation_state.create_property(
            "ConversationData")
        self.user_profile_accessor = self.user_state.create_property(
            "UserProfile")
예제 #15
0
    def __init__(self, config: DefaultConfig):
        self.qna_maker = QnAMaker(
            QnAMakerEndpoint(
                knowledge_base_id=config.QNA_KNOWLEDGEBASE_ID,
                endpoint_key=config.QNA_ENDPOINT_KEY,
                host=config.QNA_ENDPOINT_HOST,
            ))

        # If the includeApiResults parameter is set to true, as shown below, the full response
        # from the LUIS api will be made available in the properties  of the RecognizerResult
        luis_application = LuisApplication(
            config.LUIS_APP_ID,
            config.LUIS_API_KEY,
            "https://" + config.LUIS_API_HOST_NAME,
        )
        luis_options = LuisPredictionOptions(include_all_intents=True,
                                             include_instance_data=True)
        self.recognizer = LuisRecognizer(luis_application, luis_options, True)
예제 #16
0
    def __init__(self, config: Config):
        self.qna_maker = QnAMaker(
            QnAMakerEndpoint(
                knowledge_base_id=config.QNA_KNOWLEDGEBASE_ID,
                endpoint_key=config.QNA_ENDPOINT_KEY,
                host=config.QNA_ENDPOINT_HOST,
            ), QnAMakerOptions(score_threshold=0.9))

        luis_application = LuisApplication(
            config.LUIS_APP_ID,
            config.LUIS_API_KEY,
            "https://" + config.LUIS_API_HOST_NAME,
        )
        luis_options = LuisPredictionOptions(include_all_intents=True,
                                             include_instance_data=True)
        self.recognizer = LuisRecognizer(luis_application, luis_options, True)
        self.db_func = DB_function()
        self.favor = my_favorite()
        self.history = history()
예제 #17
0
    async def _test_json(self, response_file: str) -> None:
        # Arrange
        expected_json = LuisRecognizerTest._get_json_for_file(response_file)
        response_json = expected_json["luisResult"]
        utterance = expected_json.get("text")
        if utterance is None:
            utterance = expected_json.get("Text")

        options = LuisPredictionOptions(include_all_intents=True)

        # Act
        _, result = await LuisRecognizerTest._get_recognizer_result(
            utterance, response_json, options=options, include_api_results=True
        )

        # Assert
        actual_result_json = LuisUtil.recognizer_result_as_dict(result)
        trimmed_expected = LuisRecognizerTest._remove_none_property(expected_json)
        trimmed_actual = LuisRecognizerTest._remove_none_property(actual_result_json)
        self.assertEqual(trimmed_expected, trimmed_actual)
    def test_pass_luis_prediction_options_to_recognizer(self):
        # Arrange
        my_app = LuisApplication(
            LuisRecognizerTest._luisAppId,
            LuisRecognizerTest._subscriptionKey,
            endpoint=None,
        )

        luis_prediction_options = LuisPredictionOptions(
            log_personal_information=True, include_all_intents=True, include_instance_data=True
        )

        # Assert
        recognizer = LuisRecognizer(my_app)
        merged_options = recognizer._merge_options(luis_prediction_options)
        self.assertTrue(merged_options.log_personal_information)
        self.assertTrue(merged_options.include_all_intents)
        self.assertTrue(merged_options.include_instance_data)
        self.assertFalse(recognizer._options.log_personal_information)
        self.assertFalse(recognizer._options.include_all_intents)
        self.assertFalse(recognizer._options.include_instance_data)
예제 #19
0
 def __init__(self):
     #Application id, endpoint key and endpoint url of LUIS from luis.ai
     luis_app = LuisApplication("7f01b098-aa58-4b4d-883d-9437b4c76c90","3ebb4461514e49cab8142d2df7e18561","https://westus.api.cognitive.microsoft.com/")
     luis_option = LuisPredictionOptions(include_all_intents=True, include_instance_data=True)
     self.LuisReg = LuisRecognizer(luis_app,luis_option,True)
예제 #20
0
    def __init__(self):

        luis_app = LuisApplication("85e56c2f-7ed4-4da1-b6ec-775b5090f3a8","346756f90f054396ab25f97c61dc13a4","https://westus.api.cognitive.microsoft.com/")
        luis_option = LuisPredictionOptions(include_all_intents=True, include_instance_data=True)
        self.LuisReg = LuisRecognizer(luis_app, luis_option, True)
        self.greet = ['Hey', 'Hello', 'Hi', 'Hello, how may I help you?', 'Welcome to ChatBot', 'Good Day']