def test_restore_agent(self): # Setup Expected Response expected_response = {} expected_response = empty_pb2.Empty(**expected_response) operation = operations_pb2.Operation( name='operations/test_restore_agent', done=True) operation.response.Pack(expected_response) # Mock the API response channel = ChannelStub(responses=[operation]) patch = mock.patch('google.api_core.grpc_helpers.create_channel') with patch as create_channel: create_channel.return_value = channel client = dialogflow_v2.AgentsClient() # Setup Request parent = client.project_path('[PROJECT]') response = client.restore_agent(parent) result = response.result() assert expected_response == result assert len(channel.requests) == 1 expected_request = agent_pb2.RestoreAgentRequest(parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_search_agents(self): # Setup Expected Response next_page_token = '' agents_element = {} agents = [agents_element] expected_response = { 'next_page_token': next_page_token, 'agents': agents } expected_response = agent_pb2.SearchAgentsResponse(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = dialogflow_v2.AgentsClient(channel=channel) # Setup Request parent = client.project_path('[PROJECT]') paged_list_response = client.search_agents(parent) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.agents[0] == resources[0] assert len(channel.requests) == 1 expected_request = agent_pb2.SearchAgentsRequest(parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request
def updateEventoKeyWordEntities(sender, instance, created, **kwargs): assunto = instance.assunto # instancia o modelo de nlp nlp = pt_core_news_sm.load() doc = nlp(assunto) # Separação de tokens tokens = pre_processing(doc) # Requisição do dialogflow para obter as entities client = dialogflow_v2.EntityTypesClient() parent = client.project_agent_path(os.environ['PROJECT_ID']) list_entity_types_response = list(client.list_entity_types(parent)) # cria uma nova instância com as novas entities processadas list_entity_types_response = list(client.list_entity_types(parent)) entity_type = list_entity_types_response[2] entries = [] entities = list(entity_type.entities) for token in tokens: entities.append({'value': token.lemma_, 'synonyms': [token.text]}) #realiza o submit das entities ao dialogflow response = client.batch_update_entities(entity_type.name, entities) response.done() # treina o modelo do client = dialogflow_v2.AgentsClient() project_parent = client.project_path(os.environ['PROJECT_ID']) client.train_agent(project_parent)
def __init__(self, namespace, project): self.namespace = namespace self.project = project self.agents_client = dialogflow.AgentsClient() self.intents_client = dialogflow.IntentsClient() self.agent = self.load_agent()
def test_export_agent(self): # Setup Expected Response agent_uri = 'agentUri-1700713166' agent_content = b'63' expected_response = { 'agent_uri': agent_uri, 'agent_content': agent_content } expected_response = agent_pb2.ExportAgentResponse(**expected_response) operation = operations_pb2.Operation( name='operations/test_export_agent', done=True) operation.response.Pack(expected_response) # Mock the API response channel = ChannelStub(responses=[operation]) client = dialogflow_v2.AgentsClient(channel=channel) # Setup Request parent = client.project_path('[PROJECT]') response = client.export_agent(parent) result = response.result() assert expected_response == result assert len(channel.requests) == 1 expected_request = agent_pb2.ExportAgentRequest(parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_export_agent(self): # Setup Expected Response agent_uri_2 = "agentUri21997190245" expected_response = {"agent_uri": agent_uri_2} expected_response = agent_pb2.ExportAgentResponse(**expected_response) operation = operations_pb2.Operation( name="operations/test_export_agent", done=True ) operation.response.Pack(expected_response) # Mock the API response channel = ChannelStub(responses=[operation]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = dialogflow_v2.AgentsClient() # Setup Request parent = client.project_path("[PROJECT]") agent_uri = "agentUri-1700713166" response = client.export_agent(parent, agent_uri) result = response.result() assert expected_response == result assert len(channel.requests) == 1 expected_request = agent_pb2.ExportAgentRequest( parent=parent, agent_uri=agent_uri ) actual_request = channel.requests[0][1] assert expected_request == actual_request
def create_intent(project_id, display_name, training_phrases_parts, message_texts): intents_client = dialogflow.IntentsClient() parent = intents_client.project_agent_path(project_id) training_phrases = [] for training_phrases_part in training_phrases_parts: part = dialogflow.types.Intent.TrainingPhrase.Part( text=training_phrases_part) training_phrase = dialogflow.types.Intent.TrainingPhrase(parts=[part]) training_phrases.append(training_phrase) text = dialogflow.types.Intent.Message.Text(text=message_texts) message = dialogflow.types.Intent.Message(text=text) intent = dialogflow.types.Intent(display_name=display_name, training_phrases=training_phrases, messages=[message]) response = intents_client.create_intent(parent, intent, language_code=LANGUAGE_CODE) print('Intent created: {}'.format(response)) client = dialogflow.AgentsClient() parent = client.project_path(project_id) response = client.train_agent(parent)
async def construct( # type: ignore self, _global_config: GlobalConfig, time_zone: str, project: str = "nlutestframework", agent: str = "NLUTestFramework" ) -> None: """ Args: _global_config: Global configuration for the whole test framework. time_zone: The time zone, e.g. Europe/Berlin. See https://www.iana.org/time-zones for the list of possible values. project: The name of the Dialogflow project. Defaults to "nlutestframework". agent: The name of the Dialogflow agent. Defaults to "NLUTestFramework". """ self.__time_zone = time_zone self.__project = project self.__agent = agent # Create the various clients to interact with the Dialogflow API clients_config: Dict[str, Any] = {} self.__agents_client = dialogflow_v2.AgentsClient(**clients_config) self.__intents_client = dialogflow_v2.IntentsClient(**clients_config) self.__sessions_client = dialogflow_v2.SessionsClient(**clients_config) await self.__removeIntents()
def test_search_agents(self): # Setup Expected Response next_page_token = '' agents_element = {} agents = [agents_element] expected_response = { 'next_page_token': next_page_token, 'agents': agents } expected_response = agent_pb2.SearchAgentsResponse(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch('google.api_core.grpc_helpers.create_channel') with patch as create_channel: create_channel.return_value = channel client = dialogflow_v2.AgentsClient() # Setup Request parent = client.project_path('[PROJECT]') paged_list_response = client.search_agents(parent) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.agents[0] == resources[0] assert len(channel.requests) == 1 expected_request = agent_pb2.SearchAgentsRequest(parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_search_agents_exception(self): channel = ChannelStub(responses=[CustomException()]) client = dialogflow_v2.AgentsClient(channel=channel) # Setup request parent = client.project_path('[PROJECT]') paged_list_response = client.search_agents(parent) with pytest.raises(CustomException): list(paged_list_response)
def test_get_validation_result_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = dialogflow_v2.AgentsClient() with pytest.raises(CustomException): client.get_validation_result()
def test_get_agent_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) client = dialogflow_v2.AgentsClient(channel=channel) # Setup request parent = client.project_path('[PROJECT]') with pytest.raises(CustomException): client.get_agent(parent)
def train_agent(project_id): client = dialogflow.AgentsClient() parent = parent = client.project_path(project_id) response = client.train_agent(parent) def callback(operation_future): result = operation_future.result() response.add_done_callback(callback) metadata = response.metadata()
def train_agent(self, callback): client = dialogflow.AgentsClient(credentials=self.credentials) parent = client.project_path(self.project_id) print('Training agent {}...'.format(self.project_id)) begin_training = time.time() response = client.train_agent(parent) response.add_done_callback(callback) return begin_training
def train_agent(self, callback): intents_client = dialogflow.AgentsClient() parent = intents_client.project_path(self.project_id) print 'Training agent {}...'.format(self.project_id) begin_training = time.time() response = intents_client.train_agent(parent) response.add_done_callback(callback) return begin_training
def test_delete_agent_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = dialogflow_v2.AgentsClient() # Setup request parent = client.project_path("[PROJECT]") with pytest.raises(CustomException): client.delete_agent(parent)
def train(): print('--' * 10) print('Foi adicionado ao treinamento') client = dialogflow.AgentsClient() parent = client.project_path('small-talk-c36ba') try: print(list_chamada) response = client.train_agent(parent=parent, metadata=list_chamada.items()) response.add_done_callback(callback) except Exception as error: print(error) return redirect(url_for('main.gerenciamento'))
def test_search_agents_exception(self): channel = ChannelStub(responses=[CustomException()]) patch = mock.patch('google.api_core.grpc_helpers.create_channel') with patch as create_channel: create_channel.return_value = channel client = dialogflow_v2.AgentsClient() # Setup request parent = client.project_path('[PROJECT]') paged_list_response = client.search_agents(parent) with pytest.raises(CustomException): list(paged_list_response)
def save_invents(): """ save and lern intent in dialogflow""" client = dialogflow_v2.AgentsClient() parent = client.project_path(get_project_id()) response = client.train_agent(parent) def callback(operation_future): # Handle result. result = operation_future.result() response.add_done_callback(callback) # Handle metadata. metadata = response.metadata() print(metadata)
def test_delete_agent(self): channel = ChannelStub() patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = dialogflow_v2.AgentsClient() # Setup Request parent = client.project_path("[PROJECT]") client.delete_agent(parent) assert len(channel.requests) == 1 expected_request = agent_pb2.DeleteAgentRequest(parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_restore_agent_exception(self): # Setup Response error = status_pb2.Status() operation = operations_pb2.Operation( name='operations/test_restore_agent_exception', done=True) operation.error.CopyFrom(error) # Mock the API response channel = ChannelStub(responses=[operation]) client = dialogflow_v2.AgentsClient(channel=channel) # Setup Request parent = client.project_path('[PROJECT]') response = client.restore_agent(parent) exception = response.exception() assert exception.errors[0] == error
def test_get_validation_result(self): # Setup Expected Response expected_response = {} expected_response = validation_result_pb2.ValidationResult(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = dialogflow_v2.AgentsClient() response = client.get_validation_result() assert expected_response == response assert len(channel.requests) == 1 expected_request = agent_pb2.GetValidationResultRequest() actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_restore_agent_exception(self): # Setup Response error = status_pb2.Status() operation = operations_pb2.Operation( name='operations/test_restore_agent_exception', done=True) operation.error.CopyFrom(error) # Mock the API response channel = ChannelStub(responses=[operation]) patch = mock.patch('google.api_core.grpc_helpers.create_channel') with patch as create_channel: create_channel.return_value = channel client = dialogflow_v2.AgentsClient() # Setup Request parent = client.project_path('[PROJECT]') response = client.restore_agent(parent) exception = response.exception() assert exception.errors[0] == error
def test_get_agent(self): # Setup Expected Response parent_2 = 'parent21175163357' display_name = 'displayName1615086568' default_language_code = 'defaultLanguageCode856575222' time_zone = 'timeZone36848094' description = 'description-1724546052' avatar_uri = 'avatarUri-402824826' enable_logging = False classification_threshold = 1.11581064E8 expected_response = { 'parent': parent_2, 'display_name': display_name, 'default_language_code': default_language_code, 'time_zone': time_zone, 'description': description, 'avatar_uri': avatar_uri, 'enable_logging': enable_logging, 'classification_threshold': classification_threshold } expected_response = agent_pb2.Agent(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch('google.api_core.grpc_helpers.create_channel') with patch as create_channel: create_channel.return_value = channel client = dialogflow_v2.AgentsClient() # Setup Request parent = client.project_path('[PROJECT]') response = client.get_agent(parent) assert expected_response == response assert len(channel.requests) == 1 expected_request = agent_pb2.GetAgentRequest(parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_export_agent_exception(self): # Setup Response error = status_pb2.Status() operation = operations_pb2.Operation( name="operations/test_export_agent_exception", done=True ) operation.error.CopyFrom(error) # Mock the API response channel = ChannelStub(responses=[operation]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = dialogflow_v2.AgentsClient() # Setup Request parent = client.project_path("[PROJECT]") agent_uri = "agentUri-1700713166" response = client.export_agent(parent, agent_uri) exception = response.exception() assert exception.errors[0] == error
def test_get_agent(self): # Setup Expected Response parent_2 = "parent21175163357" display_name = "displayName1615086568" default_language_code = "defaultLanguageCode856575222" time_zone = "timeZone36848094" description = "description-1724546052" avatar_uri = "avatarUri-402824826" enable_logging = False classification_threshold = 1.11581064e8 expected_response = { "parent": parent_2, "display_name": display_name, "default_language_code": default_language_code, "time_zone": time_zone, "description": description, "avatar_uri": avatar_uri, "enable_logging": enable_logging, "classification_threshold": classification_threshold, } expected_response = agent_pb2.Agent(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = dialogflow_v2.AgentsClient() # Setup Request parent = client.project_path("[PROJECT]") response = client.get_agent(parent) assert expected_response == response assert len(channel.requests) == 1 expected_request = agent_pb2.GetAgentRequest(parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_restore_agent(self): # Setup Expected Response expected_response = {} expected_response = empty_pb2.Empty(**expected_response) operation = operations_pb2.Operation( name='operations/test_restore_agent', done=True) operation.response.Pack(expected_response) # Mock the API response channel = ChannelStub(responses=[operation]) client = dialogflow_v2.AgentsClient(channel=channel) # Setup Request parent = client.project_path('[PROJECT]') response = client.restore_agent(parent) result = response.result() assert expected_response == result assert len(channel.requests) == 1 expected_request = agent_pb2.RestoreAgentRequest(parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request
class Chat(): client = dialogflow_v2.AgentsClient() parent = client.project_path SESSION_ID = Config.DIALOGFLOW_CONFIG_JSON['session_id'] PROJECT_ID = Config.DIALOGFLOW_CONFIG_JSON['project_id'] LANGUAGE_CODE = Config.DIALOGFLOW_CONFIG_JSON['language'] session_client = dialogflow_v2.SessionsClient() session = session_client.session_path(PROJECT_ID, SESSION_ID) def send_message(self, text): text_input = dialogflow_v2.types.TextInput( text=text, language_code=self.LANGUAGE_CODE) query_input = dialogflow_v2.types.QueryInput(text=text_input) try: response = self.session_client.detect_intent( session=self.session, query_input=query_input) except: print('Exception') return 'Fulfillment text: {}'.format( response.query_result.fulfillment_text)
def start_train_agent(project_id): client = dialogflow.AgentsClient() parent = client.project_path(project_id) client.train_agent(parent)
def get_agent(self): client = dialogflow.AgentsClient(credentials=self.credentials) parent = client.project_path(self.project_id) return client.get_agent(parent)