Virtual assistants have become an important part of our lives, simplifying tasks and enhancing productivity. Creating your own virtual assistant can seem like a complicated task, but with the right tools and framework, it’s entirely achievable. In this guide, we’ll walk through the process of developing a virtual assistant using NextGenSwitch, Wit.ai, and Laravel.
In this tutorial, we’ll guide you through building a chatbot designed to assist in managing loans. To give you a visual overview, here’s the flow diagram illustrating the steps involved in the loan management chatbot
In our scenario, the virtual assistant initiates the conversation with a greeting message and then engages in a dialogue with the customer to address their inquiries about pending dues. Here’s the conversation flow:
Please check the recorded audio below
To begin building our virtual assistant with Laravel, let’s create a new Laravel project. Laravel provides a convenient command-line tool, Composer, to create new projects effortlessly.
Depending on your operating system, open your terminal or command prompt. Ensure you have Composer installed globally on your system. If not, you can download and install Composer from getcomposer.org.
Use Composer to create a new Laravel project. Run the following command:
composer create-project --prefer-dist laravel/laravel virtual-assistant
This command will create a new Laravel project named “virtual-assistant” in a directory named “virtual-assistant” within your current location. It fetches the latest version of Laravel from Packagist and installs it along with its dependencies.
Once the project is created, navigate to the project directory using the following command:
cd virtual-assistant
You can verify that the installation was successful by running the development server. Execute the following command:
php artisan serve
This command starts a development server at http://localhost:8000
, allowing you to access the default Laravel welcome page in your web browser.
Congratulations! You’ve successfully created a new Laravel project. Now, we can proceed with integrating NextGenSwitch and building our virtual assistant.
NextGenSwitch is a powerful tool that facilitates communication between your Laravel application and various services, including voice-based interactions. In this step, we’ll integrate NextGenSwitch into our Laravel project.
Use Composer to install the NextGenSwitch PHP package. Run the following command in your terminal:
composer require nextgenswitch/nextgenswitch-php @dev
Before delving into the code implementation, it’s essential to understand the key functionalities of NextGenSwitch and Wit.ai.
NextGenSwitch:
say
for delivering voice messages and gather
for capturing customer responses.Wit.ai:
In this scenario, you’ve defined two intents: “get_date” and “yes_no”, along with some entities. Let’s understand how these intents and entities are structured and their role in the conversation flow.
Here is the sample code of the virtual voice assistant.
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use NextGenSwitch\VoiceResponse;
Route::post('/', function(){
$response = getVoices();
return $response;
})->name('home');
Route::post('/hello', function(){
return getVoices('hello');
})->name('hello');
Route::post('/yes_no', function(Request $request){
if($request->input('speech_result') != ''){
$response = getWitIntent($request->input('speech_result'));
if(isset($response["entity"]) && $response["entity"]['name'] == "no"){
return getVoices('yes_no_no');
}else{
return getVoices('yes_no_yes');
}
}else{
$voice_response->say("can not understand sir ");
return route('hello');
}
})->name('yes_no');
Route::post('/get_date', function(Request $request){
if($request->input('speech_result') != ''){
return getVoices('get_date');
}else{
return getVoices('get_avaialable_yes');
}
})->name('get_date');
Route::post('/get_avaialable', function(Request $request){
if($request->input('speech_result') != ''){
$response = getWitIntent($request->input('speech_result'));
if(isset($response["entity"]) && $response["entity"]['name'] == "yes"){
return getVoices('get_avaialable_yes');
}else{
return getVoices('get_avaialable_no');
}
}else{
return getVoices('yes_no_yes');
}
})->name('get_avaialable');
function getVoices($action = ''){
$voice_response = new VoiceResponse();
if(empty($action)){
$gather = $voice_response->gather(['input'=>'speech','transcript'=>false,'action'=>route('hello')]);
$gather->say("Hello Sir !!");
}elseif($action == 'hello'){
$voice_response->say("Good morning Sir ! I am Ria talking from City Central Bank.");
$voice_response->say("Am I Talking with");
$gather = $voice_response->gather(['input'=>'speech','action'=>route('yes_no')]);
$gather->say("Mr. Khairul Alam");
}elseif($action == 'get_avaialable_yes'){
$voice_response->say("Ok, Sir thanks for your confirmation .");
}elseif($action == 'get_avaialable_no'){
$voice_response->say("Can you please tell me when the money will be available in your account ?");
$gather = $voice_response->gather(['input'=>'speech','action'=>route('get_date')]);
$gather->say("Today , tomorrow or some other days ?");
}elseif($action == 'yes_no_yes'){
$voice_response->say("Sir, You have an E M I due amount fourty five thousand .");
$gather = $voice_response->gather(['input'=>'speech','action'=>route('get_avaialable')]);
$gather->say("Can you please confirm the money is available in your account ?");
}elseif($action == 'yes_no_no'){
$voice_response->say("Ok Sir, I will Call some other time . Thank you.");
}elseif($action == 'get_date')
$voice_response->say("Thanks for your confirmation Sir. Have a good day ! ");
return $voice_response->xml();
}
function getWitIntent($text){
define('BARIER_KEY','ONUSS24K2F3JPI4SAQVQYNI5CCKNUXV6');
$url = 'https://api.wit.ai/message';
$params = [
'v' =>'20240311',
'q' => $text,
];
$queryString = http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . $queryString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Authorization: Bearer ' . BARIER_KEY,
'Content-Type: application/json',
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$data = array();
if (curl_errno($ch))
return false;
curl_close($ch);
$response = json_decode($response, true);
/*
if( count($response['intents']) == 0){
return false;
}
*/
if( count($response['intents']) > 0){
$data['intent'] = $response['intents'][0]['name'];
}
if(count($response['entities']) > 0){
$expected_entities = $response['entities'][array_key_first($response['entities'])];
$entity = $expected_entities[array_key_first($expected_entities)];
$data['entity'] = [
'name' => $entity['name'],
'value' => $entity['value']
];
}
return $data;
}
Routes: There are several routes to handle different interactions with the virtual assistant. They only accept POST requests.
/
:getVoices()
function and returns the response./hello
:getVoices('hello')
function and returns the response./yes_no
:getWitIntent()
function to analyze the customer’s response and determine the intent.getVoices()
function./get_date
:getVoices('get_date')
function and returns the response./get_available
:getWitIntent()
function to analyze the customer’s response and determine the intent.getVoices()
function based on the intent.Function getWitIntent($text)
:
Function getVoices($action = '')
:
The getVoices($action = '')
function generates voice responses based on the provided action parameter, which represents different scenarios in the virtual assistant’s interaction flow.
VoiceResponse
class, incorporating spoken messages and gathering actions for user input.$voice_response->say("Good morning Sir ! I am Ria talking from City Central Bank.");
$voice_response->say("Am I Talking with");
$gather = $voice_response->gather(['input'=>'speech','action'=>route('yes_no')]);
$gather->say("Mr. Khairul Alam");
this code segment initiates a conversation by providing the user with a greeting, asking a question, and enabling the assistant to listen for the user’s response. Once the user finishes speaking, their response is sent to the ‘yes_no’ route for further processing.
Use Ngrok or any other method to host your Laravel project live.
To Live your local Laravel project via Ngrok:
ngrok http http://localhost:8000
Testing
Now it’s time to proceed with testing. We have several testing methods available, one of which involves testing through an API. To set up the API for testing, follow these steps:
After setting up the API, we’ll define a route “/send-call” and write the following code to initiate a call:
Route::get('send-call', function(){
$client = new CurlClient();
$response = $client->request('post', 'http://your-pbx-url/api/v1/call', [], [
'to' => '01518307641',
'from' => '5002',
'response' => https://6734-103-86-196-156.ngrok-free.app
], [
'X-Authorization' => 'RWopQ05OeelxJ6K526gPr.....',
'X-Authorization-Secret' => 'wZHEJvcrCiFbWP.....'
]);
if($response->ok()){
echo "<pre>";
print_r($response->getContent());
echo "</pre>";
} else {
echo $response;
}
});
The request is authenticated using the provided API key and secret. If the call request is successful, it prints the response content; otherwise, it echoes the response.
Another testing method involves utilizing custom functions. Let’s walk through the process step by step.
Following these steps will allow you to effectively test your Laravel project’s integration with NextGenSwitch by interacting with the virtual voice assistant.
To access a demo of NextGenSwitch, please visit our website NextGenSwitch.