Как создать чат-бота с помощью Dialogflow Enterprise Edition и Dialogflow API V2
В этом руководстве мы узнаем, как создать чат-бота с помощью Dialogflow Enterprise Edition и Dialogflow API V2. Это руководство является дополнением к списку руководств, которые охватывают Google Cloud и его замечательный набор продуктов и услуг.
Создайте чат-бота с помощью Dialogflow Enterprise Edition и Dialogflow API V2
К концу этого урока вы лучше поймете следующее.
- Введение в Dialogflow
- Введение в Dialogflow Enterprise Edition
- Как создать агента в Dialogflow
- Понимание намерений и сущностей
- Создайте агента по обслуживанию клиентов
- Выполнения, облачные функции и API Dialogflow V2
- Как создать чат-бота агента по обслуживанию клиентов
- Храните информацию о билетах в Cloud Datastore
- Заключение
- использованная литература
Поскольку в этом руководстве нам предстоит многое рассказать, приступим.
1. Введение в Dialogflow:
Dialogflow — это комплексный пакет разработки для создания диалоговых интерфейсов для веб-сайтов, мобильных приложений, популярных платформ обмена сообщениями и устройств IoT. Его можно использовать для создания чат-ботов, голосовых помощников и т. Д., Особенно актуальных, которые способны естественным и разнообразным образом взаимодействовать с вашими пользователями.
Dialogflow также работает на компьютере научиться распознавать намерение и контекст того, что говорит пользователь, что позволяет диалоговому интерфейсу обеспечивать высокоэффективные и точные ответы. Итак, в рамках этого руководства Google предлагает две версии Dialogflow.
-
: бесплатно для всех : Премиум-предложение, а также услуга с оплатой по мере использования.
2. Введение в Dialogflow Enterprise Edition:
Dialogflow Enterprise Edition доступен как часть Google Cloud Platform (GCP). Он обеспечивает неограниченное текстовое и голосовое взаимодействие, более высокие квоты использования громкости и поддержку со стороны службы поддержки Google Cloud. Dialogflow Enterprise Edition — это расширенное предложение, доступное как услуга с оплатой по мере использования.
Dialogflow Enterprise Edition идеально подходит для предприятий, которым требуется услуга корпоративного уровня, которую можно легко масштабировать для поддержки изменений спроса пользователей.
3. Как создать агент в Dialogflow Enterprise Edition:
В стандартной версии Dialogflow вы можете перейти на dialogflow.com, чтобы создать своего агента. В то время как для Dialogflow Enterprise Edition мы сначала создаем проект в Google Cloud Platform и используем API Dialogflow. Выполните следующие действия, как создать чат-бота с помощью Dialogflow Enterprise Edition и Dialogflow API V2.
3.1 Настройка и аутентификация проекта:
Прежде всего, нам нужно создать проект Google Cloud Platform с помощью https://console.cloud.google.com/.
- Создайте или выберите существующий проект GCP.
- Включите API Dialogflow V2 для этого проекта.
- Нажмите ВКЛЮЧИТЬ APIS И УСЛУГИ.
- Найдите Dialogflow API в строке поиска и щелкните по нему.
- Продолжайте и нажмите ВКЛЮЧИТЬ API.
- 3.2 Создайте агент Dialogflow.
- После включения API щелкните вкладку агента Dialogflow и выберите имя агента для вашего проекта.
- Имя агента
- Язык
- Часовой пояс
- Нажмите кнопку Создать, чтобы создать Агент Dialgflow Enterprise Edition.
- Поэтому в оставшейся части нашего руководства мы будем создавать агент, который мы создали на GCP, с помощью dialogflow.com. Итак, нажмите Открыть агент на dialogflow.com.
- Следовательно, после того, как вы нажмете ссылку, он также должен попросить вас выбрать свою учетную запись Google. Выберите ту же учетную запись Google, с которой вы изначально создавали проект.
- Теперь он также должен показать вам страницу, позволяющую диалоговому потоку просматривать данные и управлять ими. Наконец, нажмите Разрешить.
- Кроме того, просмотрите настройки учетной записи и нажмите ПРИНЯТЬ.
- Наконец, теперь вы увидите панель инструментов Dialgflow, а во время этого руководства вы также можете увидеть сообщение о том, что Dialogflow API V2 официально запущен. Теперь это API по умолчанию для всех новых агентов Dialogflow, и все новые функции будут выпущены только в V2. Узнайте, как перенести свои агенты V1 «здесь ».
3.3 Создайте сервисный аккаунт.
- Прежде чем мы продолжим диалог, давайте также удостоверимся, что у нас настроено еще несколько элементов.
- На странице Сервисные аккаунты Google Cloud выберите свой проект.
- Вы должны увидеть экран, подобный показанному ниже.
- Загрузите закрытый ключ в формате JSON.
- В консоли GCP перейдите в API и службы и нажмите учетные данные.
- Нажмите Создать учетные данные и выберите Ключ служебного аккаунта.
- Выберите свой сервисный аккаунт в раскрывающемся списке, выберите JSON и нажмите Создать. Это загрузит ключ JSON на ваш компьютер. Надежно сохраните его.
- Задайте для переменной среды GOOGLE_APPLICATION_CREDENTIALS путь к файлу JSON, который содержит ключ вашей учетной записи службы. Откройте окно терминала или командной строки и выполните следующую команду в соответствии с вашей операционной системой.
Пример: Linux или macOS
Замените [PATH] на путь к файлу JSON, который содержит ключ вашей учетной записи службы.
Пример: Windows
Замените [PATH] на путь к файлу JSON, который содержит ключ вашей служебной учетной записи, а [FILE_NAME] на имя файла.
В командной строке:
- Следуйте инструкциям, приведенным в документе.
- Наконец, выполнив эти шаги, вы должны получить файл ключа учетной записи службы (в JSON), который позволит вам аутентифицироваться в API Dialogflow V2 в этом кратком руководстве:
- gcloud auth activate – service – account — key – file = service – account – key – file
- После того, как вы успешно выполнили вышеуказанные шаги, вы бы активировали учетные данные учетной записи службы.
4. Понимание намерений и сущностей в Dialogflow:
Намерения. Намерение представляет собой соответствие между тем, что говорит пользователь, и тем, какие действия должно предпринять ваше программное обеспечение.
Intent-интерфейсы также имеют следующие разделы:
- Обучающие фразы
- Действие
- Ответ
- Контексты
Сущности: Сущности — это мощные инструменты, используемые для извлечения значений параметров из ввода на естественном языке. Любые важные данные, которые вы хотите получить из запроса пользователя, будут иметь соответствующий объект.
Вы также лучше поймете намерения и сущности, когда мы перейдем к следующему разделу руководства.
5. Создайте агента по обслуживанию клиентов:
Поскольку мы создаем чат-бота Агента по обслуживанию клиентов, нам также необходимо сначала поприветствовать или поприветствовать клиента. Этого можно добиться с помощью приветственного намерения.
5.1 Приветствуем пользователя
- Нажмите Добро пожаловать.
- В разделе «Обучающие фразы» добавьте несколько фраз, которые ваши пользователи будут использовать для начала разговора.
- Кроме того, следующим шагом будет добавление соответствующего ответа от чат-бота, чтобы приветствовать пользователя и предлагать ему задать конкретный вопрос.
- Наконец, нажмите Сохранить намерение. Вы также должны увидеть всплывающее сообщение о том, что обучение агентазавершено.
5.2 Создание намерения отправить заявку
- Нажмите СОЗДАТЬ НАМЕРЕНИЕ. Это создаст новое намерение, в котором вам нужно будет указать имя для своего намерения. Назовем это «Отправить билет».
- После этого нажмите Обучающие фразы, чтобы добавить фразы о том, что может сказать пользователь.
- После того, как вы успешно добавили несколько обучающих фраз, давайте добавим ответ, чтобы получить дополнительную информацию от пользователя.
- Нажмите Добавить ответ и введите ответ примерно так. Конечно! Я могу помочь тебе с этим. Пожалуйста, укажите свое имя для билета.
- Нажмите Сохранить, чтобы сохранить Отправить заявку.
5.3 Создание повторного намерения собрать имя
- Чтобы мы могли создать последующее намерение. Следуйте инструкциям ниже.
- Нажмите на намерения на левой панели навигации.
- Наведите указатель мыши на намерение Отправить заявку. Справа вы увидите параметр добавить последующие намерения.
- Это должно дать вам раскрывающийся список. В списке выберите Пользовательский.
- Теперь вы должны увидеть созданное последующее намерение. Нажмите Отправить заявку — индивидуально.
- Давайте изменим имя на какое-нибудь более понятное. Измените имя намерения на Отправить заявку — собрать имя.
- Добавьте несколько обучающих фраз.
- «Я Джон»
- «Меня зовут Сачин»
- «Ам Люси»
- Вы также можете видеть, что он автоматически выделяет имена как Entities @ sys.given-name.
- Кроме того, к настоящему моменту под действиями и параметрами вы должны увидеть следующее, как показано ниже.
- Наконец, добавьте ответ, чтобы получить дополнительную информацию от пользователя. $ given-name будет содержать имя клиента.
- «Спасибо, $ given-name! Какой у тебя номер телефона?»
- Сохранить. Намерение обучить агента.
5.4 Создайте дополнительное намерение для сбора номера телефона.
- Прежде всего, наведите указатель мыши на Отправить заявку — собрать имя намерения. Справа вы увидите параметр добавить последующие намерения.
- Это должно дать вам раскрывающийся список. В списке выберите Пользовательский.
- Теперь вы должны увидеть созданное последующее намерение. Нажмите Отправить заявку — собирать имя — индивидуально.
- Давайте изменим имя на какое-нибудь более понятное. Измените имя намерения на Отправить заявку — забрать телефон.
- Добавьте несколько обучающих фраз. Это всего лишь образцы.
- мой номер телефона + 1231232432
- номер мобильного телефона +1 234234234
- +1234324234
- Измените объект с @ sys.number на @ sys.phone-number.
- Наконец, добавьте ответ, чтобы получить еще одну информацию от пользователя. $ phone-number будет содержать имя клиента.
- «Спасибо! А теперь опишите вашу проблему ».
- Сохранить. Намерение обучить агента.
5.5 Создание последующего намерения для сбора описания проблемы клиента.
- Как и в предыдущих шагах, создайте последующее намерение под названием Отправить заявку — собрать описание.
- Добавьте несколько обучающих фраз. Это просто образцы данных для демонстрационных целей.
- мой телефон продолжает перезагружаться
- проблема с Wi-Fi
- Проблемы с Bluetooth
- Экран не отвечает.
- замороженный экран
- Оставьте ответы пустыми. Причина, по которой мы оставляем его пустым, заключается в том, что мы хотим, чтобы ответы приходили с нашего сервера после сбора всей информации от пользователя и генерации номера заявки, чтобы вернуть ее пользователю для справки.
- Кроме того, чтобы связать его с сервером или в данном случае с облачными функциями, нам необходимо включить выполнения.
- Нажмите Выполнения и включить вызов веб-перехватчика для этого намерения.
- Нажмите кнопку Сохранить, чтобы сохранить заявку — собрать описание.
6. Фулфиллы и облачные функции:
Выполнение состоит из Webhook, а также Cloud Functions от firebase. Поскольку мы пытаемся понять, как создать чат-бота с помощью Dialogflow Enterprise Edition и Dialogflow API V2, нам также нужно узнать больше о Webhook или Cloud Functions от Firebase.
Веб-перехватчик: настройка веб-перехватчика позволяет передавать информацию из согласованного намерения в веб-службу и получать от нее результат.
Облачные функции от Firebase. Для простого тестирования и внедрения веб-перехватчиков вы можете использовать область Облачные функции для Firebase на странице Выполнение. В большинстве случаев бесплатный уровень Firebase Spark — это все, что вам нужно. Ограничения уровней и информацию о ценах для других уровней можно найти на странице цен Firebase.
- В меню слева нажмите Выполнение.
- Также включите переключатель Встроенный редактор.
- Встроенный редактор: вы можете использовать свой собственный код или скопировать и вставить код из нижеприведенного во встроенный редактор.
- Замените project_id своим идентификатором проекта облачной платформы Google в строке 6. Вы должны найти идентификатор проекта на панели инструментов ›Информация о проекте в облачной консоли Google .
- Поскольку мы собираемся использовать Google Cloud Datastore для хранения информации о билетах, нам нужно добавить необходимые зависимости в package.json.
- Скопируйте приведенный ниже код и добавьте его в свой package.json во встроенном редакторе или просто добавьте код в строке 20, чтобы добавить зависимость от облачного хранилища данных.
- Нажмите кнопку РАЗВЕРТИТЬ, чтобы развернуть наши облачные функции.
- Завершение развертывания может занять несколько секунд.
- Примечание. Вышеупомянутые облачные функции обслуживаются с помощью нового Dialogflow API V2 или V2 API. Следовательно, , некоторые из кодов, прокомментированных в файле index.js, были основаны на API V1. Таким образом, это ясно показывает, насколько просто перейти с V1 на V2 API в Dialogflow. Скоро я сделаю отдельное руководство по переходу с V1 на V2 API.
7. Как создать чат-бота агента по обслуживанию клиентов:
Наконец, пришло время протестировать нашего агента и реализовать нашего чат-бота. Dialogflow позволяет нам легко интегрировать наш агент в несколько платформ, таких как Google Assistant, Facebook Messenger, Slack, Интернет и т. Д., В разделе Интеграции Dialogflow.
В этом руководстве мы увидим, как создать нашего агента и встроить его на наш собственный веб-сайт.
- Нажмите Интеграции в левом меню навигации.
- Включить веб-демонстрацию
- Появится всплывающее окно со сгенерированной ссылкой.
- Прежде всего, нажмите на ссылку, чтобы увидеть, как ваш чат-бот творит чудеса.
- В результате вы также можете использовать встроенный код для добавления чат-бота на свой сайт.
8. Сохраните информацию о тикете в Google Cloud Datastore:
Наконец-то наш чат-бот запущен. Наиболее примечательно то, что если вы просматриваете облачные функции, мы собираем следующие сведения о клиенте.
- Захват информации о клиенте
- имя пользователя
- номер телефона
- описание
8.1 Сохраните данные в Google Cloud Datastore:
Мы также можем видеть детали, полученные с помощью нашего чат-бота, в нашем Google Cloud Datastore.
- Перейдите в Google Cloud Console.
- Щелкните меню навигации, чтобы отобразить параметры.
- Выберите Хранилище данных — ›Сущности.
- Следовательно, просматривайте данные, собранные чат-ботом, со всей конкретной информацией.
9. Заключение:
В заключение, это был длинный учебник, охватывающий различные аспекты создания чат-бота с помощью Dialogflow Enterprise Edition и Dialogflow API V2. Кроме того, мы также узнали, как собирать информацию от пользователя и сохранять ее с помощью Google Cloud Datastore. Следовательно, это только верхушка на поверхности, и возможности использования сервисов Dialogflow и Google Cloud безграничны. Я приложил все усилия, чтобы охватить это руководство на каждом этапе, чтобы вы могли легко научиться разрабатывать такие приложения. В следующем руководстве мы также узнаем, как использовать это в форме Google Assistant, а также как мы можем перейти с V1 API на V2 API.
Building a Chatbot App for iOS with Dialogflow (API.AI) and Text-to-Speech
With the latest release of Apple’s Core ML, developers are one step closer to building Artificial Intelligence apps with ease. While image recognition and text detection are great examples of apps that utilize AI, another type of app which exemplifies the power of Machine Learning is chatbots. In this tutorial we will be using Dialogflow (formerly called API.AI) from Google to build a chatbot app running on iOS!
Sounds cool, right? Let’s get started.
A Quick Overview of Intents and Entities
Before we begin, I will explain the basics of Dialogflow and chatbots in general. There are two terms that you have to know when building chatbots: Intents and Entities.
An entity represents a term or object in the user’s input that provides clarification or specific context for a particular intent.
An intent, on the other hand, represents something that the user wants to do. If intents represent verbs, then entities represent nouns.
Let’s take a look at an example. In our project, we might tell our bot the following statement:
“Book me a room at the La Grande Hotel”
In this sentence, our intent is “Book me a room” and the entity is “La Grande Hotel.” Now, there are two different types of conversations that Natural Language Processing (NLP) algorithms can compute.
-
Intent-Based Conversations: This is when the NLP algorithms uses intents and entities to carry out a conversation. By recognizing the nouns and verbs in a user’s statement and then cross-referencing it to its dictionary, the bot can perform a valid action. This type of conversation is what Dialogflow uses.
Flow-Based Conversations: Flow-Based Conversations are the next level of intelligent communication. Here, we feed a RNN (Recurrent Neural Network) of many diiferent samples of conversations between two people. The bot that is created will respond based on the ML model you trained it off of. Wit.ai is one of the few sites making a huge progress in this field. Don’t worry though, we do not need to do this.
In this tutorial, we will create a bot that can help you book a hotel.
One of the most important rules when developing a chatbot is that it MUST have a personna. This means that it must behave like a real person. Therefore, let’s name out bot – Chip!
And, on that note, let’s begin!
Familiarizing yourself with Dialogflow
Head over to Dialogflow and in the upper right corner, click on “Go to Console”.

You will be asked to sign in with your Google account. Sign in and authorize Dialogflow to view and manage your data across Google Cloud Platform services. Accept the terms and you should be greeted with an inital startup page.

Watching the intro video can get you up to speed about Dialogflow but if you don’t feel like watching, that’s fine! Click on the “Create Agent” button. In Dialogflow, an agent means the chatbot which the iOS app will use to communicate over the air to receive responses.
Fill in the agent name (say, Chip) and click on the Create button to proceed. Dialogflow will create the agent for you. Now, take a look at what you have. You should have 2 default intents: a “Default Welcome Intent” and a “Default Fallback Intent”. In the left hand pane, you should see tabs for Intents and Entities.

We’ll get to the other tabs at the end. Now, it’s time to begin creating the bot!
Adding the Entities
First, let’s start by adding the entities. If you recall, entities are like the nouns which an NLP algorithm can understand. Let’s come up with a list of nouns that might be used regularly with our bot. I have put my list below but feel free to add on to it.
- Hotel
- Room
- Payment
Select the entities tab and click on the “Create Entity” button. Name this entity “Hotel” and click on the first row. Enter the reference value as “Hotel”. When a user uses your bot, they may use names other than hotel. Therfore, you should enter some synonyms of that entity so even if a user uses a word other than “Hotel”, the bot can still understand what the user is saying. Look at the picture below for some of the synonyms I used.

Now, save your entity and create the following entities similar to how we created the Hotel entity.


Now that we’ve created the entities, let’s move on to the intents.
Adding the Intents
Head over to the Intents page and click on the Default Welcome Intent. This intent is what our bot will capture when it is first fired up. You should be greeted with a page like this:

We can customize what the user should say for the intent to be triggered. At the bottom of the page, we can also customize what the text response should be. Since this is a Welcome intent, the user would probably say something like “Hello!” or “How’s it going?” Therfore, let’s add these phrases (and any similar ones) to the ‘User says’ section. Below are some samples. You are free to add even more messages that your users will possibly say to the bot.

If you scroll down, you will find the Response section. The intent comes with some built-in responses. They are all fine but at the end of each one, let’s add a follow up question: “What can I do for you?” This is what our final Welcome intent should look like:

Before we move on to creating the next intent, if at any time you want to test out your agent, take a look at the right hand pane. In that pane, you can type whatever you want and see your agent respond accordingly. Type in “Hello” and check to see if your agent responds with the expected response.
So far, the agent has only one intent. Since our bot is designed to handle hotel reservation, we have to create another intent to handle those queries. The user will probably ask, “Can you book me a hotel?” or something like that.
Let’s create a new intent and name it Begin Order. In the User says section, add the above expression and press enter. Once you have entered this expression, you will see that the agent has recognized a @Hotel entity in that statement. Similar to entities, a user won’t just use that question to book a hotel. Add in a few variations so that the agent can understand the user. The more variations you add, the more intelligent is the agent. But as a demo, here is what I use.

The next thing that the agent should do is search for nearby hotels and ask the user how many rooms does he/she wants. However, if we were to actually scan for nearby hotels, we would need to call an API and use JavaScript to integrate the webhook with api.ai. This is beyond the scope of the tutorial so let’s create some fake hotels in the Response section. Here is the response I created:

Save the intent and go back to the main page. Test your agent in the right hand pane. If you followed everything so far, it should work as expected! As you can see, you don’t have to ask the exact question. Dialogflow will learn from your given statements and understand the variations.

Now, let’s add some follow-up intents. Hover your cursor over the intent you just created. You should see an option which says “Add follow-up intent”. Select that and click on Custom. A new intent will be generated which should say “Begin Order – custom”. Let’s edit this intent!

Remember that the last thing our agent said to us was “How many rooms do we want?” The user will probably respond with a number. He/she may say, “I would like 1 room” or simply answer “4”. You should predict what the user might say and fill in all the possible answers. For demo purpose, here is what I filled in:

As you can see, Dialogflow has a built-in entity for numbers. Whether you enter a digit or a word, it will be able to handle it and understand its meaning.
Next, we have the bot respond with a confirmation and the total price. The bot may also ask what payment method the user might prefer. Again, since these are fake hotels, we can add in fake prices to the bot responses.

Save the intent. Now I challenge you to create the last intent which is to just ask the user what payment method they will use to pay. This should be very easy as we have done it twice already!
I hope you were able to do that. If not, follow me below! So we will go back to the main intent page and click on Create Intent.
Name this intent Payment and add in what the user might say. This is where our Payment entity comes to use!

Finally, make the bot respond with some sort of confirmation message. Here is some sample messages:
- Done! You have rent the rooms!
- Success! We received your payment.
And that’s it! Remember to save the Payment intent. Chip is now ready to be used. You can test it out in the right hand pane before we move on to the iOS side of this tutorial.
A Couple More Things
Before we begin the real programming, let me take a moment to explain the other tabs on the left hand pane in the Dialogflow console. Under Entities, you have a tab called Training. If you click on this tab, you will receive a log of all the reponses sent to your agent and what the agent responded in return. This is very useful if you tell your agent something and it responds with an output you don’t like. It can also be helpful if you realize later on that you forgot a synonym of an entity and users are using that a lot, then you can go and tell your agent what to do in that case.
Right below Training, you have Integrations. Here, you can manage the different services your agent can be available on such as Google Assistant, Twitter, Slack, Messenger, Cortana, Alexa, and lots more! After Integrations, you have Analytics which basically shows what the name suggests. Then, you have Fulfillment. This is where you would come if you were to call an API and implement a webhook.

The last 2 tabs are pretty simple, but useful. The first is Prebuilt Agents and here, you can import a pre-existing framework of an agent. There are many examples like a food delivery bot, a music bot, and even a (sorry, but you really needed to learn this) hotel booking bot! The final tab is Small Talk and this is useful if you are designing your agent to be a daily companion like Siri or Google Assistant. Small Talk allows you to add responses for common questions we all like to ask our bots like “How old are you?”, “Where do you live?”, and the ever popular “Will you marry me?”
Now that you have a fairly good idea of what Dialogflow is and how eveything works, it’s time to move to the other side of the equation and start to code in Swift!
Connecting to Dialogflow using the API.AI SDK
Now that we’re on the Swift portion of this tutorial, first download the starter project. I’ve already built the basics UI and bundled the API.AI SDK. If you build the app from scratch, you can install the API.AI SDK (which is the SDK for connecting to Dialogflow) using CocoaPods. All you need to do is to add the following pod in your Podfile:
Once you unzip the starter project, make sure you open the Chatbot Starter Project.xcworkspace file. Going over to Main.storyboard , there is already a UILabel , UIButton , and UITextField . Their connecting outlets are also hooked up to ViewController.swift .

Let’s begin by heading over to AppDelegate.swift . We need to get our app to connect to the Dialogflow servers. Right under import UIKit , type in the following statement to import the framework:
Now, we need to initialize a configuration using our client access token. Update the didFinishLaunchingWithOptions method like this:
Google APIs
Google’s documentation is like an ocean. It’s not easy to find a right one to start. This note contains only basic things that I’ve already worked with. Try your own hand at Google’s APIs will help you understand more.
This note is mainly for Dialogflow APIs. However, I mention also the other services of Google.
Official documentation
Dialogflow’s APIs & references — the root of all things.
-
(beautiful version)
- Note: From version 2.0.0 , resource-manager change the package to @google-cloud/resource-manager . And from version 3.0,0 , the «folder» was introduced!
- Note: APIs can only be activated for Projects, neither folder nor organization!
- Make the same things in «Step by step». At step 7, create search-agents.js with the same content as samples/set-agent.js . We are going to change this file.
- Read the reference, change the input. Here is an example,
- For setting up, follow these steps.
- After that, you should obtain an API_KEY and an CLIENT_ID .
- First, try this sample.
- Using something like Live Server and open authSample.html .
- Make a test.
- Make sure you create the «OAuth consent screen» before you create «OAuth 2.0 Client IDs». The «consent screen» is the popup window that contains all the information about the scopes your app will ask users for permission.
- Make sure you add http://localhost:5500 (which is created in step 4) to «Authorized JavaScript origins» and «Authorized redirect URIs». You may have to wait a few «ten minutes» for everything to work. Without this step, you may encounter the error mismatch_uri .
- GET https://
/v2/ /agent:search - REST: . /v2/projects.agent/search
- SDK: . /v2.AgentsClient.html#searchAgents
- POST https://
/v2/ :detectIntent - REST: . /v2/projects.agent.sessions/detectIntent
- SDK: . /v2.SessionsClient.html#detectIntent
- Normally, it’s easier if we use Node.js SDK.
- First, you need to create a Service Account, then create a key and download the JSON file. Follow these steps.
- Check an example code.
- Remark: the code above use request which has been already deprecated! You can choose any alternative.
- Create a collection and add the Authorization for this collection. All of its request will use the same auth method.
- Create variables (on tab «Variables») to store «CLIENT ID» ( client_id ) and «CLIENT SECRET» (as client_secret ), then use them in the form by <
> and < > . - If you choose a project, there are some roles cannot be added because they belongs to folders/organization (eg. resourcemanager.projects.list )
- (ref) You have to pay (using Google Workspace or Google Identity) to create an organization or a folder.
- Create a new project: Project Creator (Note: Owner doesn’t have this role)
- Delete a project: Project Deleter (Note: Owner doesn’t have this role)
- Create a new folder: Folder Creator (Note: Organization Administrator doesn’t have this role, just list the folders and others)
- List all projects / folders: Organization Administrator
- All Dialogflow tasks: Dialogflow API Admin (it has dialogflow.* )
- Enable/Disable/List services in a project: Service Usage Admin
- By default, a service account can only access to the current project (even if you choose the roles which created in the organization/folder).
- If you want that service account can perform tasks in the organization/folder, you have to go to IAM & Admin > IAM > choose the organization / folder (yes, IAM is different for different project/organization/folder) > ADD > add the email of the service account to New principals and choose a role for it.
-
— wanna run these? Step to this section.
us-dialogflow.googleapis.com and dialogflow.googleapis.com are the same, so you can use <location>-dialogflow.googleapis.com in your codes.
Understand roles — If you decide to create a service account, you will need to assign a role to some users/emails. Each role has different rights to use your data.
Some services
Active API on some projects: Service Usage SDK | REST API
When you use any NodeJS service, for example,
Wanna run the Node.js samples?
The old version uses dialogflow and @type/dialogflow . The new version uses only one @google-cloud/dialogflow !
Create a folder, eg. /home/thi/df-samples/
If you come from Dialogflow Console > choose an agent > click on the gear next to the its name > Click on «Project ID» to open Google Cloud Platform Console.
If you come from GCP Console, it’s the same.
Follow these steps to generate a JSON key (you’ll download a JSON file). Store your JSON file in df-samples/credential.json . Note down the project_id, we will use it later, eg. project_abc .
Run each time you wanna test export GOOGLE_APPLICATION_CREDENTIALS=»/home/thi/df-samples/credential.json» OR save this line to /home/thi/.bashrc or /home/thi/.zshrc (if you use ZSH) and then refresh the current terminal (with this method, you don’t need to run again previous line).
Alternative: You don’t have to use system variable GOOGLE_APPLICATION_CREDENTIALS if you don’t want. In credential.json , copy private_key and client_email and then use them as,
Go to /df-samples/ and run npm i @google-cloud/dialogflow .
On terminal, run
Read carefully the content of each file in samples, you have to put the corresponding inputs for the sample to work!
In case you wanna try something outside the files given in samples. Check this SDK. Suppose we wanna try this one — AgentsClient.searchAgents()
The example in «Try something outside. » gives us an example of using different regions. Below are some remarks:
On DF console, you can create some agents in a different regions, default is global (or us ).
On the Google’s documentations, they don’t mention about the usage of location. If they say parent = «projects/-» , we shoud use parent = «projects/-» + «/locations/» + location where location can be one of «Region ID».
Change also the endpoint, option apiEndpoint in AgentsClient ‘s constructor, for example.
On SDK documentation, they don’t mention about the location in the parent property. For example, they say » parent can be projects/<Project ID or ‘-‘> «, but you can add the location information inside it like that
You have to enable the Dialogflow API in the current project. Other wise, we meet below problem.
You can use Service Usage to enable a service on some project programmatically or go to beflow url to active it visually,
Wanna try gapi (JS client)?
Google has announced that they will be discontinuing the Google Sign-In JavaScript Platform Library for web. You will have to switch to using Google Identity Services (or Sign In With Google or gsi ). The old service will be completely discontinued on March 31, 2023.
What’s this gapi ? You can use it completely inside an HTML file without using any backend.
List of samples (google apis javascript client).
You have to use REST API in this case.
Tip: If you are using VSCode, you can install the Live Server extension to quickly create a server (port 5500 by default). Just click the button at the bottom right of the file and a website will appear.
The corresponding between REST API and Node.js clients
Sometimes, the location infotmation is mentionned in the REST API but not in the SDK. For example, load the list of agents w.r.t. some location,
SDK (the same as the general case), in this, we just need to add «location» into the agent property, like
Using REST API in Node.js
Remark: With keys generated from a service account (stored in JSON), we can only get 1 agent for methods like projects.agent.search although it says that we can get a list of agents. In this case, try to get access token via OAuth 2.0. With this, we can access to all projects instead of only 1 (which is used to generate the json file).
Dialogflow REST APIs with Postman
Location problem
List of endpoints (containing location inside).
LIst of location information you can use with Dialogflow.
You have to use the same endpoint and location information in the API/SDK. If you use them differently, for example,
You will meet an error like below,
In the SDK documention, they don’t mention about the location you need to use in the agent property. For example, they say » parent can be projects/<Project ID or ‘-‘> «, but you can add the location information inside it like that
They are the same (for endpoints):
Custom roles
Create here (then you need to choose a project / a folder / an organization)
Understanding roles.
If you already have a domain, you can try to create a Google Workspace and use it in 1 month of trial. After that, you can deactivate the Google Workspace account but the things on the Google Cloud Platform are still there and the organization you have created in Google Workspace is still working!
In case you wanna some tasks + don’t wanna create a custom role (don’t forget to check this list):
Service Account w.r.t Organization / Folder
Create a service account. (and also the key for it > then download the JSON file)
You have to have a domain and full access to DNS.
Try 1 month free Google Workspace (from this, you will have an organization in GCP). TIP: After 1 month, you deactivate the subsription but the things on GCP witll work!
(You may need to activate again the subscription on GCP with a free 300$). Don’t worry, just a test, you lose nothing from this amount.
Go to IAM, choose your organization > ADD > paste the admin email of your organization + set roles for it (Organization Administrator, Owner, Folder Creator). Without this step, you cannot create any folder/project.
Go to Cloud Resource Manager > Create a new folder inside your organization.
Go to APIs & Services / Credentials > Choose a project > Create Credentials > Service Account > Filling the information > Create and continue > Done. Don’t forget to copy the email of this service account > Click on the link of that SA > Keys > Add key > Create a new key > JSON > Download a JSON file to your computer.
Go to IAM again, this time, choose the fodler / organization you want above service account have the right to manage things > Add > Paste the email of the SA you created above > Set roles to it like Owner, Organization Administrator, Dialogflow API Admin, Project Creator, Project Deleter, Service Usage Admin (you can check the list of all roles here). You can even create your own custom roles.
In order to created SA can use Resource Manager API, you have to activate it, otherwise, there will be an error like,
You either use the link given in the error or using,
to activate the api.
One more thing, if you are going to use this SA to manage other APIs on other projects to which it’s not belongs, you have to enable that service on the project it belongs to first. (For example, you created this SA on project-A and then you wanna use it to enable some Dialogflow APIs on project-B. You have to enable Dialogflow service on project-A first!)
Now, your SA has the full access you want.
On your computer, create a file .env withe the keys like in env.example.txt .
If you use SDK listProjectsAsync to list all projects in the organization, you can only list the projects in that organization, not the ones inside a folder even if that folder belongs to the organization.
Quota: For each Service Account, the limit of number of projects you can create is 22 . You can ask more but the better idea is to create another service account (and don’t forget to remove the old one with its credentials).
Types for TypeScript
The old version uses dialogflow and @type/dialogflow . The new version uses only one @google-cloud/dialogflow !
For example, the returned type for getAgent() method can be defined as,
Play with Intents, Examples and Entities
Aim: Suppose that we want to create a new entities via API (including the system entities).
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
how to get accessToken for v2? #31
how to get accessToken for v2? #31
Comments

Sorry for asking this but I tried to follow this steps.
https://dialogflow.com/docs/reference/v2-auth-setup
but I could not see/get the access token, I only got a json file plus a I check in google console and services but I could not locate any authentication token.
Is there a way to generate a permanent token key?
I’m just asking this now due to I’m now switching my dialogflow to v2.
The text was updated successfully, but these errors were encountered:
Ok, I was a bit too fast with writing that reply 😉
Just figured out that those access tokens expire after an hour, so generating and copying them manually is definitely good for testing only.
I’m still looking for a solution on how can the token access be permanent. Also version2 of Dialogflow was already released and I think we are using the v2beta of Dialogflow (‘m not sure if v2 and v2beta has same structure of API)
will give more info if I found a solution.
@glebez thanks for your explanation above.
If someone find a api call for gcloud to refresh the token we can build it into the react-native-dialogflow package. But I really found no better solution.
@eggybot, @spoeck Yeah, unfortunately this gcloud access token stuff is so unnecessarily complicated, compared to the way it was in v1. I guess it’s for security sake, but still. I’ve plowed through tons of docs, but could not figure out a nice reliable way to generate the token to be used on the react native side.
And since I really need to build this thing on v2, I fell back to doing all the communications with dialogflow on the server with their node SDK for v2: https://github.com/dialogflow/dialogflow-nodejs-client-v2
Sadly, because I really like the ease of work with react-native-dialogflow.
@glebez
hmm.. do you know how the auth mechanism of the nodejs client works? If just have to make a rest call it wouldn’t be a thing. I’m more into aws but they have for everything a rest interface.
@spoeck, the trick is, that before using the node client, you have to install and init gcloud SDK on your server and it somehow magically handles all the authentication for specific api calls for you behind the curtains. ¯\(ツ)/¯
But thanks for your research!
still waiting for Google to release a much easier access like we have on V1. Right now the only way I can use v2 is via node client or php client
Upon looking at Dialogflow github section there are no V2 yet for Android or iOS implementation with V2.
either way I will stick V1 for integrating directly for react-native then will wait till Dialogflow team release a new version which we can assign/create the token within the phone.