Administra intents con la API

Los intents determinan qué solicitudes de usuario se entenderán y qué acciones se realizarán. Por lo general, usarás la consola de Dialogflow para administrar los intents. En situaciones avanzadas, es posible que desees usar la API para administrar intents. En esta página, se describe cómo crear, enumerar y borrar intents con la API.

Antes de comenzar

Debes hacer lo siguiente antes de leer esta guía:

  1. Lee los conceptos básicos de Dialogflow.
  2. Realiza los pasos de configuración.

Crea un agente

Si aún no creaste un agente, sigue estos pasos para crearlo:

  1. Ve a la consola de Dialogflow.
  2. Si se te solicita, accede a la consola de Dialogflow. Consulta Descripción general de la consola de Dialogflow para obtener más información.
  3. Haz clic en Create agent, en el menú de la barra lateral izquierda. (Si ya tienes otros agentes, haz clic en el nombre del agente, desplázate hacia la parte inferior y haz clic en Create new agent).
  4. Ingresa el nombre del agente, y el idioma y la zona horaria predeterminados.
  5. Si ya creaste un proyecto, ingrésalo. Si quieres que la consola de Dialogflow cree el proyecto, selecciona Create a new Google project.
  6. Haz clic en el botón Create.

Importa el archivo de ejemplo al agente

En los pasos que se brindan en esta guía, se hacen suposiciones sobre tu agente, por lo que debes importar un agente preparado para esta guía. Cuando realizas la importación, en estos pasos se usa la opción restablecer, que reemplaza todas las opciones de configuración, intents y entidades del agente.

Para importar el archivo, sigue estos pasos:

  1. Descarga el archivo room-booking-agent.zip.
  2. Ve a la consola de Dialogflow.
  3. Selecciona el agente.
  4. Haz clic en el botón de configuración  que se encuentra junto al nombre del agente.
  5. Selecciona la pestaña Export and Import.
  6. Selecciona Restore From Zip y sigue las instrucciones para restablecer el archivo ZIP que descargaste.

Usa IntentView para mostrar todos los datos de intents

Cuando creas, obtienes o enumeras un intent, los datos del intent se le muestran al emisor. De forma predeterminada, se abrevian los datos que se muestran. En los siguientes ejemplos, se usa este valor predeterminado.

Para recuperar todos los datos del intent, debes configurar el parámetro IntentView como INTENT_VIEW_FULL. Para obtener más información, consulta los métodos del tipo de los Intents.

Crea un intent

En los siguientes ejemplos, se muestra cómo crear un intent. Para obtener más información, consulta la referencia de intents.

LÍNEA DE CMD Y REST

Si quieres crear un intent para tu agente, llama al método create en el recurso intent.

Antes de usar cualquiera de los datos de solicitud siguientes, realiza los siguientes reemplazos:

  • project-id: Es el ID del proyecto de GCP.

Método HTTP y URL:

POST https://dialogflow.googleapis.com/v2/projects/project-id/agent/intents

Cuerpo JSON de la solicitud:

{
  "displayName": "ListRooms",
  "priority": 500000,
  "webhookState": "WEBHOOK_STATE_UNSPECIFIED",
  "trainingPhrases": [
    {
      "type": "EXAMPLE",
      "parts": [
        {
          "text": "What rooms are available at 10am today?"
        }
      ]
    }
  ],
  "action": "listRooms",
  "messages": [
    {
      "text": {
        "text": [
          "Here are the available rooms:"
        ]
      }
    }
  ]
}

Para enviar tu solicitud, expande una de estas opciones:

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "name": "projects/project-id/agent/intents/5b290a94-55d6-4074-96f4-9c4c4879c2bb",
  "displayName": "ListRooms",
  "priority": 500000,
  "action": "listRooms",
  "messages": [
    {
      "text": {
        "text": [
          "Here are the available rooms:"
        ]
      }
    }
  ]
}

El segmento de ruta después de intents contiene el nuevo ID de tu intent.

C#

        public static int Create(string projectId,
                                 string displayName,
                                 string messageText,
                                 string[] trainingPhrasesParts)
        {
            var client = IntentsClient.Create();

            var text = new Intent.Types.Message.Types.Text();
            text.Text_.Add(messageText);

            var message = new Intent.Types.Message()
            {
                Text = text
            };

            var phraseParts = new List<Intent.Types.TrainingPhrase.Types.Part>();
            foreach (var part in trainingPhrasesParts)
            {
                phraseParts.Add(new Intent.Types.TrainingPhrase.Types.Part()
                {
                    Text = part
                });
            }

            var trainingPhrase = new Intent.Types.TrainingPhrase();
            trainingPhrase.Parts.AddRange(phraseParts);

            var intent = new Intent();
            intent.DisplayName = displayName;
            intent.Messages.Add(message);
            intent.TrainingPhrases.Add(trainingPhrase);

            var newIntent = client.CreateIntent(
                parent: new AgentName(projectId),
                intent: intent
            );

            Console.WriteLine($"Created Intent: {newIntent.Name}");

            return 0;
        }

Go

func CreateIntent(projectID, displayName string, trainingPhraseParts, messageTexts []string) error {
	ctx := context.Background()

	intentsClient, clientErr := dialogflow.NewIntentsClient(ctx)
	if clientErr != nil {
		return clientErr
	}
	defer intentsClient.Close()

	if projectID == "" || displayName == "" {
		return errors.New(fmt.Sprintf("Received empty project (%s) or intent (%s)", projectID, displayName))
	}

	parent := fmt.Sprintf("projects/%s/agent", projectID)

	var targetTrainingPhrases []*dialogflowpb.Intent_TrainingPhrase
	var targetTrainingPhraseParts []*dialogflowpb.Intent_TrainingPhrase_Part
	for _, partString := range trainingPhraseParts {
		part := dialogflowpb.Intent_TrainingPhrase_Part{Text: partString}
		targetTrainingPhraseParts = []*dialogflowpb.Intent_TrainingPhrase_Part{&part}
		targetTrainingPhrase := dialogflowpb.Intent_TrainingPhrase{Type: dialogflowpb.Intent_TrainingPhrase_EXAMPLE, Parts: targetTrainingPhraseParts}
		targetTrainingPhrases = append(targetTrainingPhrases, &targetTrainingPhrase)
	}

	intentMessageTexts := dialogflowpb.Intent_Message_Text{Text: messageTexts}
	wrappedIntentMessageTexts := dialogflowpb.Intent_Message_Text_{Text: &intentMessageTexts}
	intentMessage := dialogflowpb.Intent_Message{Message: &wrappedIntentMessageTexts}

	target := dialogflowpb.Intent{DisplayName: displayName, WebhookState: dialogflowpb.Intent_WEBHOOK_STATE_UNSPECIFIED, TrainingPhrases: targetTrainingPhrases, Messages: []*dialogflowpb.Intent_Message{&intentMessage}}

	request := dialogflowpb.CreateIntentRequest{Parent: parent, Intent: &target}

	_, requestErr := intentsClient.CreateIntent(ctx, &request)
	if requestErr != nil {
		return requestErr
	}

	return nil
}

Java


/**
 * Create an intent of the given intent type
 *
 * @param displayName The display name of the intent.
 * @param projectId Project/Agent Id.
 * @param trainingPhrasesParts Training phrases.
 * @param messageTexts Message texts for the agent's response when the intent is detected.
 * @return The created Intent.
 */
public static Intent createIntent(
    String displayName,
    String projectId,
    List<String> trainingPhrasesParts,
    List<String> messageTexts)
    throws ApiException, IOException {
  // Instantiates a client
  try (IntentsClient intentsClient = IntentsClient.create()) {
    // Set the project agent name using the projectID (my-project-id)
    AgentName parent = AgentName.of(projectId);

    // Build the trainingPhrases from the trainingPhrasesParts
    List<TrainingPhrase> trainingPhrases = new ArrayList<>();
    for (String trainingPhrase : trainingPhrasesParts) {
      trainingPhrases.add(
          TrainingPhrase.newBuilder()
              .addParts(Part.newBuilder().setText(trainingPhrase).build())
              .build());
    }

    // Build the message texts for the agent's response
    Message message =
        Message.newBuilder().setText(Text.newBuilder().addAllText(messageTexts).build()).build();

    // Build the intent
    Intent intent =
        Intent.newBuilder()
            .setDisplayName(displayName)
            .addMessages(message)
            .addAllTrainingPhrases(trainingPhrases)
            .build();

    // Performs the create intent request
    Intent response = intentsClient.createIntent(parent, intent);
    System.out.format("Intent created: %s\n", response);

    return response;
  }
}

Node.js


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'The Project ID to use, e.g. 'YOUR_GCP_ID';
// const displayName = 'The display name of the intent, e.g. 'MAKE_RESERVATION';
// const trainingPhrasesParts = 'Training phrases, e.g. 'How many people are staying?';
// const messageTexts = 'Message texts for the agent's response when the intent is detected, e.g. 'Your reservation has been confirmed';

// Imports the Dialogflow library
const dialogflow = require('@google-cloud/dialogflow');

// Instantiates the Intent Client
const intentsClient = new dialogflow.IntentsClient();

async function createIntent() {
  // Construct request

  // The path to identify the agent that owns the created intent.
  const agentPath = intentsClient.agentPath(projectId);

  const trainingPhrases = [];

  trainingPhrasesParts.forEach(trainingPhrasesPart => {
    const part = {
      text: trainingPhrasesPart,
    };

    // Here we create a new training phrase for each provided part.
    const trainingPhrase = {
      type: 'EXAMPLE',
      parts: [part],
    };

    trainingPhrases.push(trainingPhrase);
  });

  const messageText = {
    text: messageTexts,
  };

  const message = {
    text: messageText,
  };

  const intent = {
    displayName: displayName,
    trainingPhrases: trainingPhrases,
    messages: [message],
  };

  const createIntentRequest = {
    parent: agentPath,
    intent: intent,
  };

  // Create the intent
  const [response] = await intentsClient.createIntent(createIntentRequest);
  console.log(`Intent ${response.name} created`);
}

createIntent();

PHP

namespace Google\Cloud\Samples\Dialogflow;

use Google\Cloud\Dialogflow\V2\IntentsClient;
use Google\Cloud\Dialogflow\V2\Intent\TrainingPhrase\Part;
use Google\Cloud\Dialogflow\V2\Intent\TrainingPhrase;
use Google\Cloud\Dialogflow\V2\Intent\Message\Text;
use Google\Cloud\Dialogflow\V2\Intent\Message;
use Google\Cloud\Dialogflow\V2\Intent;

/**
* Create an intent of the given intent type.
*/
function intent_create($projectId, $displayName, $trainingPhraseParts = [],
    $messageTexts = [])
{
    $intentsClient = new IntentsClient();

    // prepare parent
    $parent = $intentsClient->agentName($projectId);

    // prepare training phrases for intent
    $trainingPhrases = [];
    foreach ($trainingPhraseParts as $trainingPhrasePart) {
        $part = (new Part())
            ->setText($trainingPhrasePart);

        // create new training phrase for each provided part
        $trainingPhrase = (new TrainingPhrase())
            ->setParts([$part]);
        $trainingPhrases[] = $trainingPhrase;
    }

    // prepare messages for intent
    $text = (new Text())
        ->setText($messageTexts);
    $message = (new Message())
        ->setText($text);

    // prepare intent
    $intent = (new Intent())
        ->setDisplayName($displayName)
        ->setTrainingPhrases($trainingPhrases)
        ->setMessages([$message]);

    // create intent
    $response = $intentsClient->createIntent($parent, $intent);
    printf('Intent created: %s' . PHP_EOL, $response->getName());

    $intentsClient->close();
}

Python

def create_intent(project_id, display_name, training_phrases_parts,
                  message_texts):
    """Create an intent of the given intent type."""
    import dialogflow_v2 as dialogflow
    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)
        # Here we create a new training phrase for each provided 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)

    print('Intent created: {}'.format(response))

Ruby

# project_id = "Your Google Cloud project ID"
# display_name = "New Display Name"
# message_text = "some message text"
# training_phrases_parts = ["part1", "part2"]

require "google/cloud/dialogflow"

intents_client = Google::Cloud::Dialogflow.intents
parent = intents_client.agent_path project: project_id

intent = {
  display_name:     display_name,
  messages:         [{ text: { text: [message_text] } }],
  training_phrases: training_phrases_parts.map do |part|
    { parts: [{ text: part }] }
  end
}
response = intents_client.create_intent parent: parent, intent: intent

puts "Intent created"
puts "Display name: #{response.display_name}"
puts "Messages:     #{response.messages}"

Mostrar lista de intents

En las siguientes muestras, se indica cómo generar listas de intents. Para obtener más información, consulta la referencia de intents.

LÍNEA DE CMD Y REST

A fin de generar una lista de intents para tu agente, llama al método list en el recurso intents.

Antes de usar cualquiera de los datos de solicitud siguientes, realiza los siguientes reemplazos:

  • project-id: Es el ID del proyecto de GCP.

Método HTTP y URL:

GET https://dialogflow.googleapis.com/v2/projects/project-id/agent/intents

Para enviar tu solicitud, expande una de estas opciones:

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "intents": [
    {
      "name": "projects/project-id/agent/intents/5b290a94-55d6-4074-96f4-9c4c4879c2bb",
      "displayName": "ListRooms",
      "priority": 500000,
      "action": "listRooms",
      "messages": [
        {
          "text": {
            "text": [
              "Here are the available rooms:"
            ]
          }
        }
      ]
    },
    ...
  ]
}

Los segmentos de ruta después de intents contienen los ID de tu intent.

C#

        public static int List(string projectId)
        {
            var client = IntentsClient.Create();

            var intents = client.ListIntents(new AgentName(projectId));

            foreach (var intent in intents)
            {
                Console.WriteLine($"Intent name: {intent.Name}");
                Console.WriteLine($"Intent display name: {intent.DisplayName}");
                Console.WriteLine($"Action: {intent.Action}");
                Console.WriteLine($"Root follow-up intent: {intent.RootFollowupIntentName}");
                Console.WriteLine($"Parent follow-up intent: {intent.ParentFollowupIntentName}");

                Console.WriteLine($"Input contexts:");
                foreach (var inputContextName in intent.InputContextNames)
                {
                    Console.WriteLine($"Input context name: {inputContextName}");
                }

                Console.WriteLine($"Output contexts:");
                foreach (var outputContex in intent.OutputContexts)
                {
                    Console.WriteLine($"Output context name: {outputContex.Name}");
                }
                Console.WriteLine("Messages:");
                foreach (var message in intent.Messages)
                {
                    if (message.Text != null)
                    {
                        foreach (var text in message.Text.Text_)
                        {
                            Console.WriteLine($"Message text: {text}");
                        }
                    }
                }
                Console.WriteLine($"Training Phrases ({intent.TrainingPhrases.Count})");
                foreach (var trainingPhrase in intent.TrainingPhrases)
                {
                    Console.WriteLine($"Phrase name: {trainingPhrase.Name}");
                    Console.WriteLine($"Phrase type: {trainingPhrase.Type}");
                    foreach (var phrasePart in trainingPhrase.Parts)
                    {
                        Console.WriteLine($"Phrase part: {phrasePart.Text}");
                    }
                }
                Console.WriteLine();
            }

            return 0;
        }

Go


func ListIntents(projectID string) ([]*dialogflowpb.Intent, error) {
	ctx := context.Background()

	intentsClient, clientErr := dialogflow.NewIntentsClient(ctx)
	if clientErr != nil {
		return nil, clientErr
	}
	defer intentsClient.Close()

	if projectID == "" {
		return nil, errors.New(fmt.Sprintf("Received empty project (%s)", projectID))
	}

	parent := fmt.Sprintf("projects/%s/agent", projectID)

	request := dialogflowpb.ListIntentsRequest{Parent: parent}

	intentIterator := intentsClient.ListIntents(ctx, &request)
	var intents []*dialogflowpb.Intent

	for intent, status := intentIterator.Next(); status != iterator.Done; {
		intents = append(intents, intent)
		intent, status = intentIterator.Next()
	}

	return intents, nil
}

Java


/**
 * List intents
 *
 * @param projectId Project/Agent Id.
 * @return Intents found.
 */
public static List<Intent> listIntents(String projectId) throws ApiException, IOException {
  List<Intent> intents = Lists.newArrayList();
  // Instantiates a client
  try (IntentsClient intentsClient = IntentsClient.create()) {
    // Set the project agent name using the projectID (my-project-id)
    AgentName parent = AgentName.of(projectId);

    // Performs the list intents request
    for (Intent intent : intentsClient.listIntents(parent).iterateAll()) {
      System.out.println("====================");
      System.out.format("Intent name: '%s'\n", intent.getName());
      System.out.format("Intent display name: '%s'\n", intent.getDisplayName());
      System.out.format("Action: '%s'\n", intent.getAction());
      System.out.format("Root followup intent: '%s'\n", intent.getRootFollowupIntentName());
      System.out.format("Parent followup intent: '%s'\n", intent.getParentFollowupIntentName());

      System.out.format("Input contexts:\n");
      for (String inputContextName : intent.getInputContextNamesList()) {
        System.out.format("\tName: %s\n", inputContextName);
      }
      System.out.format("Output contexts:\n");
      for (Context outputContext : intent.getOutputContextsList()) {
        System.out.format("\tName: %s\n", outputContext.getName());
      }

      intents.add(intent);
    }
  }
  return intents;
}

Node.js


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'The Project ID to use, e.g. 'YOUR_GCP_ID';

// Imports the Dialogflow library
const dialogflow = require('@google-cloud/dialogflow');

// Instantiates clients
const intentsClient = new dialogflow.IntentsClient();

async function listIntents() {
  // Construct request

  // The path to identify the agent that owns the intents.
  const projectAgentPath = intentsClient.agentPath(projectId);

  console.log(projectAgentPath);

  const request = {
    parent: projectAgentPath,
  };

  // Send the request for listing intents.
  const [response] = await intentsClient.listIntents(request);
  response.forEach(intent => {
    console.log('====================');
    console.log(`Intent name: ${intent.name}`);
    console.log(`Intent display name: ${intent.displayName}`);
    console.log(`Action: ${intent.action}`);
    console.log(`Root folowup intent: ${intent.rootFollowupIntentName}`);
    console.log(`Parent followup intent: ${intent.parentFollowupIntentName}`);

    console.log('Input contexts:');
    intent.inputContextNames.forEach(inputContextName => {
      console.log(`\tName: ${inputContextName}`);
    });

    console.log('Output contexts:');
    intent.outputContexts.forEach(outputContext => {
      console.log(`\tName: ${outputContext.name}`);
    });
  });
}

listIntents();

PHP

namespace Google\Cloud\Samples\Dialogflow;

use Google\Cloud\Dialogflow\V2\IntentsClient;

function intent_list($projectId)
{
    // get intents
    $intentsClient = new IntentsClient();
    $parent = $intentsClient->agentName($projectId);
    $intents = $intentsClient->listIntents($parent);

    foreach ($intents->iterateAllElements() as $intent) {
        // print relevant info
        print(str_repeat("=", 20) . PHP_EOL);
        printf('Intent name: %s' . PHP_EOL, $intent->getName());
        printf('Intent display name: %s' . PHP_EOL, $intent->getDisplayName());
        printf('Action: %s' . PHP_EOL, $intent->getAction());
        printf('Root followup intent: %s' . PHP_EOL,
            $intent->getRootFollowupIntentName());
        printf('Parent followup intent: %s' . PHP_EOL,
            $intent->getParentFollowupIntentName());
        print(PHP_EOL);

        print('Input contexts: ' . PHP_EOL);
        foreach ($intent->getInputContextNames() as $inputContextName) {
            printf("\t Name: %s" . PHP_EOL, $inputContextName);
        }

        print('Output contexts: ' . PHP_EOL);
        foreach ($intent->getOutputContexts() as $outputContext) {
            printf("\t Name: %s" . PHP_EOL, $outputContext->getName());
        }
    }
    $intentsClient->close();
}

Python

def list_intents(project_id):
    import dialogflow_v2 as dialogflow
    intents_client = dialogflow.IntentsClient()

    parent = intents_client.project_agent_path(project_id)

    intents = intents_client.list_intents(parent)

    for intent in intents:
        print('=' * 20)
        print('Intent name: {}'.format(intent.name))
        print('Intent display_name: {}'.format(intent.display_name))
        print('Action: {}\n'.format(intent.action))
        print('Root followup intent: {}'.format(
            intent.root_followup_intent_name))
        print('Parent followup intent: {}\n'.format(
            intent.parent_followup_intent_name))

        print('Input contexts:')
        for input_context_name in intent.input_context_names:
            print('\tName: {}'.format(input_context_name))

        print('Output contexts:')
        for output_context in intent.output_contexts:
            print('\tName: {}'.format(output_context.name))

Ruby

# project_id = "Your Google Cloud project ID"

require "google/cloud/dialogflow"

intents_client = Google::Cloud::Dialogflow.intents
parent = intents_client.class.agent_path project: project_id

intents = intents_client.list_intents parent: parent

intents.each do |intent|
  puts "Intent name:            #{intent.name}"
  puts "Intent display name:    #{intent.display_name}"
  puts "Action:                 #{intent.action}"
  puts "Root followup intent:   #{intent.root_followup_intent_name}"
  puts "Parent followup intent: #{intent.parent_followup_intent_name}"

  puts "Input contexts:"
  intent.input_context_names.each do |input_context_name|
    puts "\tName: #{input_context_name}"
  end

  puts "Output contexts:"
  intent.output_contexts.each do |output_context|
    puts "\tName: #{output_context.name}"
  end
end

Borra intents

En las siguientes muestras, se indica cómo borrar un intent. Para obtener más información, consulta la referencia de intents.

LÍNEA DE CMD Y REST

A fin de borrar un intent para tu agente, llama al método delete en el recurso intents.

Antes de usar cualquiera de los datos de solicitud siguientes, realiza los siguientes reemplazos:

  • project-id: Es el ID de tu proyecto de GCP.
  • intent-id: Es el ID de tu intent

Método HTTP y URL:

DELETE https://dialogflow.googleapis.com/v2/projects/project-id/agent/intents/intent-id

Para enviar tu solicitud, expande una de estas opciones:

Deberías recibir un código de estado exitoso (2xx) y una respuesta vacía.

C#

        public static int Delete(string projectId, string intentId)
        {
            var client = IntentsClient.Create();
            client.DeleteIntent(new IntentName(projectId, intentId));

            Console.WriteLine($"Deleted Intent: {intentId}");

            return 0;
        }

Go

func DeleteIntent(projectID, intentID string) error {
	ctx := context.Background()

	intentsClient, clientErr := dialogflow.NewIntentsClient(ctx)
	if clientErr != nil {
		return clientErr
	}
	defer intentsClient.Close()

	if projectID == "" || intentID == "" {
		return errors.New(fmt.Sprintf("Received empty project (%s) or intent (%s)", projectID, intentID))
	}

	targetPath := fmt.Sprintf("projects/%s/agent/intents/%s", projectID, intentID)

	request := dialogflowpb.DeleteIntentRequest{Name: targetPath}

	requestErr := intentsClient.DeleteIntent(ctx, &request)
	if requestErr != nil {
		return requestErr
	}

	return nil
}

Java


/**
 * Delete intent with the given intent type and intent value
 *
 * @param intentId The id of the intent.
 * @param projectId Project/Agent Id.
 */
public static void deleteIntent(String intentId, String projectId)
    throws ApiException, IOException {
  // Instantiates a client
  try (IntentsClient intentsClient = IntentsClient.create()) {
    IntentName name = IntentName.of(projectId, intentId);
    // Performs the delete intent request
    intentsClient.deleteIntent(name);
  }
}

Node.js

// Imports the Dialogflow library
const dialogflow = require('@google-cloud/dialogflow');

// Instantiates clients
const intentsClient = new dialogflow.IntentsClient();

const intentPath = intentsClient.intentPath(projectId, intentId);

const request = {name: intentPath};

// Send the request for deleting the intent.
const result = await intentsClient.deleteIntent(request);
console.log(`Intent ${intentPath} deleted`);
return result;

PHP

namespace Google\Cloud\Samples\Dialogflow;

use Google\Cloud\Dialogflow\V2\IntentsClient;

/**
* Delete intent with the given intent type and intent value.
*/
function intent_delete($projectId, $intentId)
{
    $intentsClient = new IntentsClient();
    $intentName = $intentsClient->intentName($projectId, $intentId);

    $intentsClient->deleteIntent($intentName);
    printf('Intent deleted: %s' . PHP_EOL, $intentName);

    $intentsClient->close();
}

Python

def delete_intent(project_id, intent_id):
    """Delete intent with the given intent type and intent value."""
    import dialogflow_v2 as dialogflow
    intents_client = dialogflow.IntentsClient()

    intent_path = intents_client.intent_path(project_id, intent_id)

    intents_client.delete_intent(intent_path)

Ruby

# project_id = "Your Google Cloud project ID"
# intent_id = "Existing Intent ID"

require "google/cloud/dialogflow"

intents_client = Google::Cloud::Dialogflow.intents
intent_path = intents_client.intent_path project: project_id,
                                         intent:  intent_id

intents_client.delete_intent name: intent_path

puts "Deleted Intent: #{intent_id}"