Site icon BotFlo

PHP Client Library for Dialogflow v2 API: Getting started

If you have the choice to go for Python or NodeJS instead of PHP, I recommend using the other two options (between the two, I prefer Python). You will probably find it quite hard to find a lot of discussion online about using PHP with Dialogflow.  

This is a very basic tutorial for getting started with the PHP Client Library for Dialogflow API v2. I don’t cover any advanced stuff, but it should help you get started.

1 Create a new folder for your project

In my case, I am just calling it quickstart.

2 Download the client secret JSON file for your v2 Dialogflow agent into the quickstart folder

2.1 Make sure v2 API is enabled

2.2 Click on the service account email address

You will be taken to the Google Cloud Console.

2.3 Click on the Create Service Account link at the top of the console menu

2.4 Provide a suitable name for the service account

2.5 Select Project -> Owner in the Role dropdown box

2.6 Make sure you check the Furnish a new private key box. Keep the key type as JSON

2.7 Click on the create link

2.8 You will be prompted to save the client secret JSON file. Save the file as client-secret.json to the quickstart folder you just created

New User Interface

Update: After creating this tutorial, I realized that you can do everything here using the Dialogflow API Admin role. The UI has changed a bit now, but essentially you will create a new service account, and choose the role Dialogflow -> API Admin and you will be able to proceed with the rest of the steps in the tutorial. If you are interested in understanding what these roles are, you might want to check out my REST API v2 course.

2.1 Click on Create Service Account

2.2 Select Dialogflow API Admin as the role for the service account

Click on + Create Key button, and select JSON and click on the CREATE button from the slide out. Save the JSON file to the folder.

3 Install composer

If you have Homebrew on Mac, you can simply use

brew install composer

Otherwise you can look online for instructions on how to install composer.

4 Use composer to install Dialogflow client libraries

Before you can use this command, you need to make sure composer was correctly installed. You can use the command

composer require google/cloud-dialogflow

as specified here.

5 PHP Code

5.1 Create an example.php file in the quickstart directory. Your folder structure should look like this at this point. The vendor directory is created when you used composer to install the Dialogflow client libraries.

5.2 Add the required namespaces in example.php

namespace Google\Cloud\Samples\Dialogflow;
use Google\Cloud\Dialogflow\V2\SessionsClient;
use Google\Cloud\Dialogflow\V2\TextInput;
use Google\Cloud\Dialogflow\V2\QueryInput;

5.2 Use Composer’s autoload to add the classes from the vendor directory

require __DIR__.'/vendor/autoload.php';

5.3 Add the following function to example.php

function detect_intent_texts($projectId, $text, $sessionId, $languageCode = 'en-US')
{
    // new session
    $test = array('credentials' => 'client-secret.json');
    $sessionsClient = new SessionsClient($test);
    $session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
    printf('Session path: %s' . PHP_EOL, $session);

    // create text input
    $textInput = new TextInput();
    $textInput->setText($text);
    $textInput->setLanguageCode($languageCode);

    // create query input
    $queryInput = new QueryInput();
    $queryInput->setText($textInput);

    // get response and relevant info
    $response = $sessionsClient->detectIntent($session, $queryInput);
    $queryResult = $response->getQueryResult();
    $queryText = $queryResult->getQueryText();
    $intent = $queryResult->getIntent();
    $displayName = $intent->getDisplayName();
    $confidence = $queryResult->getIntentDetectionConfidence();
    $fulfilmentText = $queryResult->getFulfillmentText();

    // output relevant info
    print(str_repeat("=", 20) . PHP_EOL);
    printf('Query text: %s' . PHP_EOL, $queryText);
    printf('Detected intent: %s (confidence: %f)' . PHP_EOL, $displayName,
        $confidence);
    print(PHP_EOL);
    printf('Fulfilment text: %s' . PHP_EOL, $fulfilmentText);

    $sessionsClient->close();
}

5.4 Call the function with the following parameters

detect_intent_texts('your-project-id','hi','123456');

Replace your-project-id with your Dialogflow project ID. The third parameter, sessionID, can be any string for this purpose. However, if you are going to be using the client library to manage an entire conversation, your sessionID must be the same across an entire conversation session.

6 Run the code

Now in your Terminal type

php example.php

and you should see the following output. (Make sure you have an actual WelcomeIntent in your Dialogflow agent which has “hi” as one of its training phrases).

Questions/comments?

Leave your feedback in the comments section below.

Exit mobile version