Search code examples
phpdialogflow-es

Dialogflow V2 API - How to pass context and/or payload [PHP]


I am trying to send context and payload to the Dialogflow V2 API. I am able to successfully send a queryString and get a response from my agent. However, I need to pass context and payload parameters with this query and I cannot seem to find ANY help on this for PHP. Please see my code below. I am able to create the context object and the payload object (atleast I think its created), but how do I pass it to the API?

Any help would be appreciated as I am very new to dialogflow and have been struggling with this for a few days now.

function detect_intent_texts($projectId, $text, $sessionId, $context, $parameters, $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);

    $contextStruct = new Struct();
    $contextStruct->setFields($context['parameters']);
    $paramStruct = new Struct();
    $paramStruct->setFields($parameters['parameters']);

    $contextInput = new Context();
    $contextInput->setLifespanCount($context['lifespan']);
    $contextInput->setName($context['name']);
    $contextInput->setParameters($contextStruct);

    $queryParams = new QueryParameters();
    $queryParams->setPayload($paramStruct);

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

    // get response and relevant info
    $response = $sessionsClient->detectIntent($session, $queryInput); // Here I don't know how to send the context and payload
    $responseId = $response->getResponseId();
    $queryResult = $response->getQueryResult();
    $queryText = $queryResult->getQueryText();
    $intent = $queryResult->getIntent();
    $displayName = $intent->getDisplayName();
    $confidence = $queryResult->getIntentDetectionConfidence();
    $fulfilmentText = $queryResult->getFulfillmentText();

    $returnResponse = array(
        'responseId' => $responseId,
        'fulfillmentText' => $fulfilmentText
    );

    $sessionsClient->close();

    return $returnResponse;
}

Solution

  • Just as it happens, the moment I post my question, I get a result.

    Thanks to this post How to set query parameters dialogflow php sdk.

    I added the following to my code and it worked.

    Added

    $optionalsParams = ['queryParams' => $queryParams];
    

    Changed

    $response = $sessionsClient->detectIntent($session, $queryInput, $optionalsParams);