Gérer des intents avec l'API

Les intents déterminent les requêtes d'utilisateurs comprises ainsi que les actions à entreprendre. Dans la plupart des cas, vous gérerez les intents à l'aide de la console Dialogflow ES. Dans les scénarios avancés, il se peut que vous préfériez utiliser l'API. Cette page explique comment créer, répertorier et supprimer des intents à l'aide de l'API.

Avant de commencer

Avant de lire ce guide, procédez comme suit :

  1. Consultez la section Principes de base de Dialogflow.
  2. Effectuez la procédure de configuration.

Créer un agent

Si vous n'avez pas encore créé d'agent, créez-en un maintenant:

  1. Accédez à la console Dialogflow ES.
  2. Si nécessaire, connectez-vous à la console Dialogflow. Consultez la section Présentation de la console Dialogflow pour plus d'informations.
  3. Cliquez sur Créer un agent dans le menu de la barre latérale de gauche. (Si vous avez déjà d'autres agents, cliquez sur le nom de l'un d'eux, faites défiler vers le bas, puis cliquez sur Créer un agent.)
  4. Saisissez le nom de l'agent, la langue par défaut et le fuseau horaire par défaut.
  5. Si vous avez déjà créé un projet, saisissez son nom. Si vous souhaitez autoriser la console Dialogflow à créer le projet, sélectionnez Créer un projet Google.
  6. Cliquez sur le bouton Create (Créer).

Importer le fichier d'exemple dans l'agent

Dans la mesure où les étapes de ce guide sont fondées sur certaines hypothèses concernant votre agent, vous devez import un agent préparé pour ce guide. Lors de l'importation, ces étapes utilisent l'option de restauration qui écrase l'ensemble des paramètres, des intents et des entités de l'agent.

Pour importer le fichier, procédez comme suit :

  1. Téléchargez le fichier room-booking-agent.zip.
  2. Accédez à la console Dialogflow ES.
  3. Sélectionnez votre agent.
  4. Cliquez sur le bouton des paramètres à côté du nom de l'agent.
  5. Sélectionnez l'onglet Export and Import (Exporter et importer).
  6. Sélectionnez Restaurer depuis un fichier ZIP et suivez les instructions pour restaurer le fichier ZIP que vous avez téléchargé.

Utiliser IntentView pour renvoyer toutes les données d'un intent

Lorsque vous créez, répertoriez ou obtenez un intent, les données de l'intent sont renvoyées à l'appelant. Par défaut, les données renvoyées sont abrégées. Les exemples ci-dessous utilisent ce comportement par défaut.

Pour récupérer toutes les données d'un intent, vous devez définir le paramètre IntentView sur INTENT_VIEW_FULL. Pour plus d'informations, consultez les méthodes pour le type Intents.

Créer un intent

Les exemples suivants montrent comment créer un intent. Pour en savoir plus, consultez la documentation de référence sur les intents.

REST

Pour créer un intent pour votre agent, appelez la méthode create sur la ressource intent.

Avant d'utiliser les données de requête, effectuez les remplacements suivants:

  • PROJECT_ID : ID de votre projet Google Cloud

Méthode HTTP et URL :

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/agent/intents

Corps JSON de la requête :

{
  "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:"
        ]
      }
    }
  ]
}

Pour envoyer votre requête, développez l'une des options suivantes :

Vous devriez recevoir une réponse JSON de ce type :

Le segment de chemin d'accès après intents contient l'ID du nouvel intent.

Go

Pour vous authentifier auprès de Dialogflow, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour vous authentifier auprès de Dialogflow, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


/**
 * 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

Pour vous authentifier auprès de Dialogflow, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


/**
 * 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.projectAgentPath(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();

Python

Pour vous authentifier auprès de Dialogflow, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

def create_intent(project_id, display_name, training_phrases_parts, message_texts):
    """Create an intent of the given intent type."""
    from google.cloud import dialogflow

    intents_client = dialogflow.IntentsClient()

    parent = dialogflow.AgentsClient.agent_path(project_id)
    training_phrases = []
    for training_phrases_part in training_phrases_parts:
        part = dialogflow.Intent.TrainingPhrase.Part(text=training_phrases_part)
        # Here we create a new training phrase for each provided part.
        training_phrase = dialogflow.Intent.TrainingPhrase(parts=[part])
        training_phrases.append(training_phrase)

    text = dialogflow.Intent.Message.Text(text=message_texts)
    message = dialogflow.Intent.Message(text=text)

    intent = dialogflow.Intent(
        display_name=display_name, training_phrases=training_phrases, messages=[message]
    )

    response = intents_client.create_intent(
        request={"parent": parent, "intent": intent}
    )

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

Langages supplémentaires

C# : Veuillez suivre les Instructions de configuration de C# sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Dialogflow pour .NET.

PHP : Veuillez suivre les Instructions de configuration pour PHP sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Dialogflow pour PHP.

Ruby : Veuillez suivre les Instructions de configuration pour Ruby sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Dialogflow pour Ruby.

Répertorier les intents

Les exemples suivants montrent comment répertorier des intents. Pour en savoir plus, consultez la documentation de référence sur les intents.

REST

Pour répertorier les intents de votre agent, appelez la méthode list sur la ressource intents.

Avant d'utiliser les données de requête, effectuez les remplacements suivants:

  • PROJECT_ID : ID de votre projet Google Cloud

Méthode HTTP et URL :

GET https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/agent/intents

Pour envoyer votre requête, développez l'une des options suivantes :

Vous devriez recevoir une réponse JSON de ce type :

{
  "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:"
            ]
          }
        }
      ]
    },
    ...
  ]
}

Les segments de chemin d'accès après intents contiennent les ID de vos intents.

Go

Pour vous authentifier auprès de Dialogflow, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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

Pour vous authentifier auprès de Dialogflow, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


/**
 * 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

Pour vous authentifier auprès de Dialogflow, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


/**
 * 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.projectAgentPath(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();

Python

Pour vous authentifier auprès de Dialogflow, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

def list_intents(project_id):
    from google.cloud import dialogflow

    intents_client = dialogflow.IntentsClient()

    parent = dialogflow.AgentsClient.agent_path(project_id)

    intents = intents_client.list_intents(request={"parent": 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))

Langages supplémentaires

C# : Veuillez suivre les Instructions de configuration de C# sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Dialogflow pour .NET.

PHP : Veuillez suivre les Instructions de configuration pour PHP sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Dialogflow pour PHP.

Ruby : Veuillez suivre les Instructions de configuration pour Ruby sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Dialogflow pour Ruby.

Supprimer des intents

Les exemples suivants montrent comment supprimer un intent. Pour en savoir plus, consultez la documentation de référence sur les intents.

REST

Pour supprimer un intent de votre agent, appelez la méthode delete sur la ressource intents.

Avant d'utiliser les données de requête, effectuez les remplacements suivants:

  • PROJECT_ID : ID de votre projet Google Cloud
  • INTENT_ID : ID de votre intent

Méthode HTTP et URL :

DELETE https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/agent/intents/INTENT_ID

Pour envoyer votre requête, développez l'une des options suivantes :

Vous devriez recevoir un code d'état indiquant le succès de l'opération (2xx), ainsi qu'une réponse vide.

Go

Pour vous authentifier auprès de Dialogflow, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour vous authentifier auprès de Dialogflow, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


/**
 * 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

Pour vous authentifier auprès de Dialogflow, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

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

const intentPath = intentsClient.projectAgentIntentPath(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;

Python

Pour vous authentifier auprès de Dialogflow, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

def delete_intent(project_id, intent_id):
    """Delete intent with the given intent type and intent value."""
    from google.cloud import dialogflow

    intents_client = dialogflow.IntentsClient()

    intent_path = intents_client.intent_path(project_id, intent_id)

    intents_client.delete_intent(request={"name": intent_path})

Langages supplémentaires

C# : Veuillez suivre les Instructions de configuration de C# sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Dialogflow pour .NET.

PHP : Veuillez suivre les Instructions de configuration pour PHP sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Dialogflow pour PHP.

Ruby : Veuillez suivre les Instructions de configuration pour Ruby sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Dialogflow pour Ruby.