Creating Intents

Here is an example of creating an intent in a Dialogflow agent.

Set up your GCP project and authentication

Create an agent

Import the example intents and entities

Create intent

Protocol

Intents determine which user requests are understood and what action to take. In this example, we will create an intent to expand what the room reservation agent can respond to. The new intent will associate user questions about which rooms are available with the action listRooms.

  1. To create the intent, use the following curl command to access the intents endpoint. Replace project-id with your Google Cloud project ID. The command uses the gcloud command-line interface from the Google Cloud SDK to get an authorization token for the command. For instructions on setting up authorization, see Quickstart.

    curl -X POST -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) -H "Content-Type: application/json; charset=utf-8" --data "{
      '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:'
              ]
            }
          }
        ],
    }" "https://dialogflow.googleapis.com/v2/projects/project-id/agent/intents"
      

    You should see a response similar to the following:

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

    If you detect intent with text of "what rooms are available at 9am?", then you should see a response similar to the following. Notice that the user intent is mapped to the listRooms action.

    {
      "responseId": "5b35eb91-084f-4072-ac08-3ed47ed6e6ae",
      "queryResult": {
        "queryText": "what rooms are available at 9am?",
        "action": "listRooms",
        "parameters": {},
        "allRequiredParamsPresent": true,
        "fulfillmentText": "Here are the available rooms:",
        "fulfillmentMessages": [
          {
            "text": {
              "text": [
                "Here are the available rooms:"
              ]
            }
          }
        ],
        "intent": {
          "name": "projects/project-id/agent/intents/5b290a94-55d6-4074-96f4-9c4c4879c2bb",
          "displayName": "ListRooms"
        },
        "intentDetectionConfidence": 0.63,
        "diagnosticInfo": {},
        "languageCode": "en-us"
      }
    }
      

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 ProjectAgentName(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 Exception {
  // Instantiates a client
  try (IntentsClient intentsClient = IntentsClient.create()) {
    // Set the project agent name using the projectID (my-project-id)
    ProjectAgentName parent = ProjectAgentName.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

// Imports the Dialogflow library
const dialogflow = require('dialogflow');

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

// 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 responses = await intentsClient.createIntent(createIntentRequest);
console.log(`Intent ${responses[0].name} created`);

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->projectAgentName($projectId);

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

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

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

    // prepare intent
    $intent = new Intent();
    $intent->setDisplayName($displayName);
    $intent->setTrainingPhrases($trainingPhrases);
    $intent->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.new
parent = intents_client.class.project_agent_path project_id

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

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

Was this page helpful? Let us know how we did:

Send feedback about...

Dialogflow Enterprise Edition Documentation