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-name with the name of your Google Cloud project. 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-name/agent/intents"
      

    You should see a response similar to the following:

    {
      "name": "projects/project-name/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-name/agent/intents/5b290a94-55d6-4074-96f4-9c4c4879c2bb",
          "displayName": "ListRooms"
        },
        "intentDetectionConfidence": 0.63,
        "diagnosticInfo": {},
        "languageCode": "en-us"
      }
    }
      

C#

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

        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

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

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

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

/**
 * 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.
 */
public static void 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);
  }
}

Node.js

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

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

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

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

// Setup intents for ordering a pizza.

// First of all, let's create an intent that triggers pizza order flow.

// Output contexts for ordering pizza. They are used for matching follow-up
// intents. For pizza ordering intents, a "pizza" output context is used for
// hinting the conversation is about pizza ordering, not beer or something
// else. For the first intent, it returns responses asking users to provide
// size information, with a "size" output context for matching the intent
// asking for the size of the pizza.

// Note that session ID is unknown here, using asterisk.
const pizzaOutputContexts = [
  {
    name: contextsClient.contextPath(
      projectId,
      '*' /* sessionId */,
      'pizza_order'
    ),
    lifespanCount: 5,
  },
];

// The result of the matched intent.
const pizzaResult = {
  action: 'pizza',
  parameters: [
    {
      displayName: 'size',
      value: '$size',
      entityTypeDisplayName: '@size',
      mandatory: true,
      prompts: [
        'What size pizza would you like to order?',
        'Would you like a large, medium, or small pizza?',
      ],
    },
    {
      displayName: 'topping',
      value: '$topping',
      entityTypeDisplayName: '@topping',
      mandatory: true,
      prompts: ['What toppings would you like?'],
      isList: true,
    },
    {
      displayName: 'address',
      value: '$address',
      // The API provides a built-in entity type @sys.address for addresses.
      entityTypeDisplayName: '@sys.location',
      mandatory: true,
      prompts: ['What is the delivery address?'],
    },
  ],
  messages: [
    {
      text: {
        text: [
          'No problem. Getting a $size pizza with $topping and delivering ' +
            'to $address.',
        ],
      },
    },
    {
      text: {
        text: [
          'Reply "check" to place your order. Reply "cancel" to cancel ' +
            'your order. You can change your delivery address as well.',
        ],
      },
    },
    {
      quickReplies: {
        title:
          'No problem. Getting a $size pizza with $topping and ' +
          'delivering to $address.',
        quickReplies: ['Place order', 'Cancel'],
      },
      platform: 'PLATFORM_FACEBOOK',
    },
  ],
  outputContexts: pizzaOutputContexts,
};

// The phrases for training the linguistic model.
const pizzaPhrases = [
  {type: 'TYPE_EXAMPLE', parts: [{text: 'Order pizza'}]},
  {type: 'TYPE_EXAMPLE', parts: [{text: 'Pizza'}]},
  {
    type: 'TYPE_EXAMPLE',
    parts: [
      {text: 'Get me a '},
      {text: 'large', entityType: '@size', alias: 'size'},
      {text: ' '},
      {text: 'mushrooms', entityType: '@topping', alias: 'topping'},
      {text: ' for '},
      {
        text: '1 1st st, New York, NY',
        entityType: '@sys.location',
        alias: 'address',
      },
    ],
  },
  {
    type: 'TYPE_EXAMPLE',
    parts: [
      {text: "I'd like to order a "},
      {text: 'large', entityType: '@size', alias: 'size'},
      {text: ' pizza with '},
      {text: 'mushrooms', entityType: '@topping', alias: 'topping'},
    ],
  },
  {
    type: 'TYPE_TEMPLATE',
    parts: [{text: "I'd like a @size:size pizza"}],
  },
];

// The intent to be created.
const pizzaIntent = {
  displayName: 'Pizza',
  events: ['order_pizza'],
  // Webhook is disabled because we are not ready to call the webhook yet.
  webhookState: 'WEBHOOK_STATE_DISABLED',
  trainingPhrases: pizzaPhrases,
  mlEnabled: true,
  priority: 500000,
  result: pizzaResult,
};

const pizzaRequest = {
  parent: agentPath,
  intent: pizzaIntent,
};

// Create the pizza intent
intentsClient
  .createIntent(pizzaRequest)
  .then(responses => {
    console.log('Created Pizza intent:');
    logIntent(responses[0]);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

// Create an intent to change the delivery address. This intent sets input
// contexts to make sure it's triggered in the conversation with the pizza
// intent created above.

// The input contexts are the output contexts of the pizza intent.
const changeDeliveryAddressInputContexts = [
  contextsClient.contextPath(projectId, '*' /* sessionId */, 'pizza_order'),
];

// Renew the pizza_order intent. Without doing so the lifespan count of the
// pizza_order intent will decrease and eventually disappear if the user
// changes the delivery address a couple times.
const changeDeliveryAddressOutputContexts = [
  {
    name: contextsClient.contextPath(
      projectId,
      '*' /* sessionId */,
      'pizza_order'
    ),
    lifespanCount: 5,
  },
];

// This intent requires the $address parameter to be provided. The other
// parameters are collected from the pizza_order context.
const changeDeliveryAddressParameters = [
  {
    displayName: 'address',
    entityTypeDisplayName: '@sys.location',
    mandatory: true,
    prompts: ['What is new address?'],
  },
  {
    displayName: 'size',
    value: '#pizza_order.size',
    entityTypeDisplayName: '@size',
  },
  {
    displayName: 'topping',
    value: '#pizza_order.topping',
    entityTypeDisplayName: '@topping',
    isList: true,
  },
];

const changeDeliveryAddressResult = {
  action: 'change-delivery-address',
  parameters: changeDeliveryAddressParameters,
  messages: [
    {
      text: {
        text: ['OK, the delivery address is changed to $address'],
      },
    },
    {text: {text: ['You ordered a $size pizza with $topping.']}},
    {
      text: {
        text: [
          'Reply "check" to place your order. Reply "cancel" to cancel ' +
            'your order. You can change your delivery address as well.',
        ],
      },
    },
  ],
  outputContexts: changeDeliveryAddressOutputContexts,
};

// The triggering phrases. One is an annotated example, the other is a
// template.
const changeDeliveryAddressPhrases = [
  {
    type: 'TYPE_EXAMPLE',
    parts: [
      {text: 'Change address to '},
      {
        text: '1 1st st, new york, ny',
        entityType: '@sys.location',
        alias: 'address',
      },
    ],
  },
  {
    type: 'TYPE_EXAMPLE',
    parts: [
      {
        text: '1 1st st, new york, ny',
        entityType: '@sys.location',
        alias: 'address',
      },
    ],
  },
];

const changeDeliveryAddressIntent = {
  displayName: 'ChangeDeliveryAddress',
  webhookState: 'WEBHOOK_STATE_DISABLED',
  trainingPhrases: changeDeliveryAddressPhrases,
  inputContexts: changeDeliveryAddressInputContexts,
  mlEnabled: true,
  priority: 500000,
  result: changeDeliveryAddressResult,
};

const changeDeliveryAddressRequest = {
  parent: agentPath,
  intent: changeDeliveryAddressIntent,
};

// Create the size intent
intentsClient
  .createIntent(changeDeliveryAddressRequest)
  .then(responses => {
    console.log('Created ChangeDeliveryAddress intent: ');
    logIntent(responses[0]);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

// Finally, create two intents, one to place the order, and the other one to
// cancel it.

const placeOrderInputContexts = [
  contextsClient.contextPath(projectId, '*' /* sessionId */, 'pizza_order'),
];

// Collect all parameters from the "pizza_output".
const placeOrderParameters = [
  {
    displayName: 'size',
    value: '#pizza_order.size',
    entityTypeDisplayName: '@size',
  },
  {
    displayName: 'topping',
    value: '#pizza_order.topping',
    entityTypeDisplayName: '@topping',
    isList: true,
  },
  {
    displayName: 'address',
    value: '#pizza_order.address',
    entityTypeDisplayName: '@sys.location',
  },
];

const placeOrderResult = {
  action: 'pizza_confirm',
  parameters: placeOrderParameters,
  messages: [
    {
      text: {
        text: [
          'Sure! Getting a $size pizza with $topping and shipping to $address.',
        ],
      },
    },
  ],
  // Conclude the conversation by setting no output contexts and setting
  // resetContexts to true. This clears all existing contexts.
  outputContexts: [],
  resetContexts: true,
};

const placeOrderPhrases = [
  {type: 'TYPE_EXAMPLE', parts: [{text: 'check'}]},
  {type: 'TYPE_EXAMPLE', parts: [{text: 'confirm'}]},
  {type: 'TYPE_EXAMPLE', parts: [{text: 'yes'}]},
  {type: 'TYPE_EXAMPLE', parts: [{text: 'place order'}]},
];

const placeOrderIntent = {
  displayName: 'PlaceOrder',
  webhookState: 'WEBHOOK_STATE_ENABLED',
  trainingPhrases: placeOrderPhrases,
  inputContexts: placeOrderInputContexts,
  mlEnabled: true,
  priority: 500000,
  result: placeOrderResult,
};

const placeOrderRequest = {
  parent: agentPath,
  intent: placeOrderIntent,
};

intentsClient
  .createIntent(placeOrderRequest)
  .then(responses => {
    console.log('Created PlaceOrder intent: ');
    logIntent(responses[0]);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

const cancelOrderInputContexts = [
  contextsClient.contextPath(projectId, '*' /* sessionId */, 'pizza_order'),
];

const cancelOrderResult = {
  action: 'cancel-order',
  parameters: [],
  messages: [{text: {text: ['Your order is canceled.']}}],
  outputContexts: [],
  resetContexts: true,
};

const cancelOrderPhrases = [
  {type: 'TYPE_EXAMPLE', parts: [{text: 'cancel'}]},
  {type: 'TYPE_EXAMPLE', parts: [{text: 'no'}]},
  {type: 'TYPE_EXAMPLE', parts: [{text: 'cancel order'}]},
  {type: 'TYPE_EXAMPLE', parts: [{text: "I don't want it any more"}]},
];

const cancelOrderIntent = {
  displayName: 'CancelOrder',
  webhookState: 'WEBHOOK_STATE_DISABLED',
  trainingPhrases: cancelOrderPhrases,
  inputContexts: cancelOrderInputContexts,
  mlEnabled: true,
  priority: 500000,
  result: cancelOrderResult,
};

const cancelOrderRequest = {
  parent: agentPath,
  intent: cancelOrderIntent,
};

intentsClient
  .createIntent(cancelOrderRequest)
  .then(responses => {
    console.log('Created Cancel Order intent: ');
    logIntent(responses[0]);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

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

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

def create_intent(project_id, display_name, training_phrases_parts,
                  message_texts):
    """Create an intent of the given intent type."""
    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

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

# 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