Operações CRUD com entidades no DialogFlow (C #)

Introdução


Mais recentemente, comecei a trabalhar em um novo projeto, que incluía trabalhar com o serviço já conhecido (AI) do Google - DialogFlow. O ponto principal foi que tínhamos um bot (Telegram) que funcionava com a API de vários sites, enquanto o próprio DialogFlow nos ajudou a estruturar a comunicação com uma pessoa, para a qual ele basicamente foi criado. Devo dizer que o artigo é destinado a pessoas que acabaram de se familiarizar com o serviço ou que já têm pouca experiência; portanto, os seguintes termos são possíveis: Intenção, Contexto, Ação, Evento e para o que reunimos para o bem de - Entidades. Espero que o artigo seja útil para aqueles que não entenderam um pouco como exatamente através do código as operações CRUD com Entidades podem ser feitas.

Entidades no DialogFlow


No DialogFlow, existem entidades que consistem em ReferenceValue e Sinônimos. Algo semelhante a um valor-chave, apenas com a diferença de que pode haver muitos sinônimos, e quanto mais houver, melhor, porque "simplifica a vida do bot" e é mais fácil para ele entender de que valor está sendo falado e a marca de seleção A correspondência difusa ajudará o bot também a entender o que está em jogo, mesmo que você perca uma letra ou outro símbolo. Parece algo assim:

Moscou - Moscou, Moscou, Moscou ...

Terminando uma pequena excursão, gostaria de acrescentar que é com a Entidade que há muito barulho. Obviamente, não reduzo o significado das intenções e assim por diante, mas o fato permanece.

EntityTypes


Aqui estava a primeira, embora pequena, armadilha para mim. Afinal, a documentação possui métodos para trabalhar com Entity, e existem métodos para trabalhar com EntityType - qual deles é o quê?

De fato, tudo não é tão complicado, apenas a confusão surge devido ao fato de que no próprio DialogFlow a guia com EntityTypes é chamada Entidades:

imagem

EntityType: imagem

Entitie: imagem

Embora se acredite no próprio DialogFlow que existe Entity e ele tem Entries (ou seja, A essência e entradas nele).

Vamos continuar.

Você pode criar um EntityType manualmente diretamente no DialoFlow, mas mostrarei como isso pode ser feito através do código (afinal, para criar Entidades, precisaremos saber em qual EntityType é).

Primeiro, ative o pacote NuGet Google.Cloud.Dialogflow.V2. No momento da redação deste artigo, a versão 1.1.0 foi instalada:

imagem

primeiro, criamos uma classe e a chamamos de EntityTypeManagement na qual haverá operações básicas:

using Google.Api.Gax;
using Google.Cloud.Dialogflow.V2;

public class EntityTypeManagement
    {
      //Create -   EntityType   Test1 (  ) 
      //projectId - Id    DialogFlow
      //displayName -         
        public async Task Create(string projectId, string displayName, EntityType.Types.Kind kind = 
      EntityType.Types.Kind.Map)
        {
            var client = await EntityTypesClient.CreateAsync();

            var entityType = new EntityType();
            entityType.DisplayName = displayName;
            entityType.Kind = kind;

            var createdEntityType = client.CreateEntityType(
                parent: new ProjectAgentName(projectId),
                entityType: entityType
            );

            Console.WriteLine($"Created EntityType: {createdEntityType.Name}");
        }
       
      //List -   EntityTypes   
      //projectId - Id    DialogFlow
        public async Task<PagedEnumerable<ListEntityTypesResponse,EntityType>> List(string projectId)
        {
            var client = await EntityTypesClient.CreateAsync();
            var response = client.ListEntityTypes(
                parent: new ProjectAgentName(projectId)
            );
            return response;
        }

       //GetEntityTypeId -  EntityType  
       //projectId - Id    DialogFlow
       //targetEventTypeName -  EntityType,    
        public async Task<string> GetEntityTypeId(string projectId,string targetEventTypeName)
        {
            var client = await EntityTypesClient.CreateAsync();
            var response = client.ListEntityTypes(
                parent: new ProjectAgentName(projectId)
            );
            string id = response.Where(x => x.DisplayName == targetEventTypeName).FirstOrDefault().Name;
            string returningId = id.Replace($"projects/{projectId}/agent/entityTypes/", "");
            return returningId;
        }

       //Delete  BatchDelete      EntityType
       //   entityTypeId
        public async Task Delete(string projectId, string entityTypeId)
        {
            var client = await EntityTypesClient.CreateAsync();

            client.DeleteEntityType(new EntityTypeName(projectId, entityTypeId: entityTypeId));

            Console.WriteLine($"Deleted EntityType: {entityTypeId}");

        }

        
        public async Task BatchDelete(string projectId, IEnumerable<string> entityTypeIds)
        {
            var client = await EntityTypesClient.CreateAsync();
            var entityTypeNames = entityTypeIds.Select(
                id => new EntityTypeName(projectId, id).ToString());
            client.BatchDeleteEntityTypes(new ProjectAgentName(projectId),
                entityTypeNames);
        }
    }

Aqui, deve-se dizer imediatamente que não há função de atualização apenas porque o Create já desempenha sua função.

Agora que temos os métodos básicos para trabalhar com EntityTypes, vamos para Entity e crie imediatamente uma classe EntityManagement:

public class EntityManagement
    {
       using Google.Cloud.Dialogflow.V2;        


      //Create -    Entity
      //entityTypeId - Id EntityType      Entity
      //entityValue - ReferenceValue  Entity
      // synonyms -    Entity
        public async Task Create(string projectId,
                                 string entityTypeId,
                                 string entityValue,
                                 string[] synonyms)
        {
            var client = await EntityTypesClient.CreateAsync();
            var entity = new EntityType.Types.Entity() { Value = entityValue};
            entity.Synonyms.AddRange(synonyms);
            
            var operation = await client.BatchCreateEntitiesAsync(
                parent: new EntityTypeName(projectId, entityTypeId),
                entities: new[] { entity }
            ); 
            operation.PollUntilCompleted();
        }

       //CreateMany -   Entities 
       //entityTypeId - Id EntityType      Entity
       //entities -  Entities  
        public async Task CreateMany(string projectId,string entityTypeId, IEnumerable<Entity> entities)
        {
            var client = await EntityTypesClient.CreateAsync();
            List<EntityType.Types.Entity> results = new List<EntityType.Types.Entity>();
            foreach (var item in entities)
            {
                var entity = new EntityType.Types.Entity() { Value = item.value };
                entity.Synonyms.AddRange(item.synonyms);
                results.Add(entity);
            }
           
            var operation = await client.BatchCreateEntitiesAsync(
                parent: new EntityTypeName(projectId, entityTypeId),
                entities: results.ToArray());
            operation.PollUntilCompleted();
        }

      //Delete -    Entity,   "string entityValue"   
     //string[] entityValue      entityValues: entityValue
     //    .
        public async Task Delete(string projectId, string entityTypeId, string entityValue)
        {
            var client = await EntityTypesClient.CreateAsync();

            var operation = await client.BatchDeleteEntitiesAsync(
                parent: new EntityTypeName(projectId, entityTypeId),
                entityValues: new[] { entityValue }
            );

            Console.WriteLine("Waiting for the entity deletion operation to complete.");
            operation.PollUntilCompleted();

            Console.WriteLine($"Deleted Entity: {entityValue}");

        }
        
      //List -   Entities  EntityType 
     public async Task<List<Entity>> List(string projectId, string entityTypeId)
        {
            var client = await EntityTypesClient.CreateAsync();
            var entityType = await client.GetEntityTypeAsync(new EntityTypeName(
                projectId, entityTypeId
            ));
            List<Entity> EntitiesList = new List<Entity>();
            
            foreach (var entity in entityType.Entities)
            {
                List<string> Synonyms = new List<string>();
                foreach (var item in entity.Synonyms)
                {
                    Synonyms.Add(item);
                }
                EntitiesList.Add(new Entity { value = entity.Value, synonyms = Synonyms.ToArray() });
                Synonyms = null;
            }

            return EntitiesList;
        }
    }

Adicione nosso modelo que representará a Entidade:

public class Entity
    {
        public string value { get; set; }
        public string[] synonyms { get; set; }
    }

Feito, todos os recursos básicos de CRUD estão prontos. Novamente, retornando ao Update, ele pode ser implementado separadamente, mas simplesmente não é necessário, pois o Create também funciona como o Update.

Os exemplos são bastante simples e, devo concordar, ainda existe um "código rígido", mas espero que o artigo seja útil para aqueles que, como eu, não conseguiram descobrir como executar corretamente as operações CRUD por meio do código.

static void Main(string[] args)
        {
      EntityTypesManagement entityTypesManagement = new EntityTypesManagement();
      EntityManagement entityManagement = new EntityManagement();
       string ProjectId = "Your Project`s id";
       string EntityName = "Your EntityName";
      var entityId = await entityTypesManagement.GetEntityTypeId(ProjectId, EntityName);
       Entity entity =  new Entity{value = "1", synonyms = new[]{"1","1"}};
      /*await*/ entityManagement.Create(ProjectId,entityId,entity);
 }

Source: https://habr.com/ru/post/undefined/


All Articles