Operaciones CRUD con entidades en DialogFlow (C #)

Introducción


Más recientemente, comencé a trabajar en un nuevo proyecto, que incluía trabajar con el ya conocido servicio (AI) de Google: DialogFlow. La conclusión fue que teníamos un bot (Telegram) que funcionaba con la API de varios sitios, mientras que DialogFlow nos ayudó a estructurar la comunicación con una persona, para lo cual básicamente fue creado. Debo decir que el artículo está destinado a personas que acaban de comenzar a conocer el servicio o que ya tienen poca experiencia, por lo que los siguientes términos son posibles: Intención, Contexto, Acción, Evento y por lo que reunimos por el bien de las Entidades. Espero que el artículo sea útil para aquellos que no entendieron un poco cómo exactamente a través del código se pueden realizar operaciones CRUD con entidades.

Entidades en DialogFlow


En DialogFlow, las entidades son algunas entidades que consisten en ReferenceValue y Sinónimos. Algo similar a un valor clave, solo con la diferencia de que puede haber muchos sinónimos, y cuantos más haya, mejor, porque "simplifica la vida del bot" y le es más fácil entender de qué valor se habla, y la marca de verificación La coincidencia aproximada ayudará al bot a comprender también lo que está en juego, incluso si pierde una letra u otro símbolo. Se parece a esto:

Moscú - Moscú, Moscú, Moscú ...

Terminando una corta excursión, me gustaría agregar que es con Entity que hay mucho alboroto. Por supuesto, no reduzco el significado de las intenciones, etc., pero el hecho permanece.

EntityTypes


Aquí estaba la primera trampa, aunque pequeña, para mí. Después de todo, la documentación tiene métodos para trabajar con Entity, y hay métodos para trabajar con EntityType, ¿cuál de ellos es qué?

De hecho, no todo es tan complicado, solo surge la confusión debido al hecho de que en DialogFlow la pestaña con EntityTypes se llama Entities:

imagen

EntityType: imagen

Entitie: imagen

Aunque se cree en DialogFlow que existe Entity y tiene Entradas (es decir, La esencia y las entradas en ella).

Vamonos.

Puede crear un EntityType manualmente directamente en DialoFlow, pero le mostraré cómo se puede hacer esto a través del código (después de todo, para crear Entidades necesitaremos saber en qué EntityType se encuentra).

Primero, habilite el paquete NuGet Google.Cloud.Dialogflow.V2. Al momento de escribir, se instaló la versión 1.1.0:

imagen

Primero creamos una clase y la llamamos EntityTypeManagement en la que habrá operaciones 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);
        }
    }

Aquí debe decirse de inmediato que no hay una función de Actualización solo porque Crear ya realiza su función.

Ahora que tenemos los métodos básicos para trabajar con EntityTypes, pasemos a Entity e inmediatamente creemos una clase 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;
        }
    }

Agregue nuestro modelo que representará a la entidad:

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

Hecho, todas las características básicas de CRUD están listas. Nuevamente, volviendo a Actualizar, se puede implementar por separado, pero simplemente no es necesario, ya que Crear también funciona como Actualizar.

Los ejemplos son bastante simples y, debo estar de acuerdo, todavía hay un "código duro", pero espero que el artículo sea útil para aquellos que, como yo, no pudieron descubrir cómo realizar correctamente las operaciones CRUD a través del 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