How to set output contexts while creating a intent in dialogflow PHP? - dialogflow-es

I am trying to set output context to a particular intent via v2 create intent API.
Please check my code.
use Google\Cloud\Dialogflow\V2\SessionsClient;
use Google\Cloud\Dialogflow\V2\TextInput;
use Google\Cloud\Dialogflow\V2\QueryInput;
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;
use Google\Cloud\Dialogflow\V2\Context;
use Google\Cloud\Dialogflow\V2\ContextsClient;
private function intent_create(){
putenv('GOOGLE_APPLICATION_CREDENTIALS='.getcwd() . '/strive_stage.json');
$intentsClient = new IntentsClient();
/** Create Intent **/
$disaplayName = "Where is Goa";
$utterances = ["Goa", "Where is Goa"];
// prepare training phrases for intent
$trainingPhrases = [];
foreach ($utterances 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;
}
$messageTexts = 'Goa is in India.';
// prepare messages for intent
$text = new Intent_Message_Text();
$text->setText([$messageTexts]);
$message = new Intent_Message();
$message->setText($text);
$createIntentObject = $intentsClient->projectAgentName(env("DIALOG_FLOW_PROJECT_ID"));
// prepare intent
$intent = new Intent();
$intent->setDisplayName($disaplayName);
$intent->setTrainingPhrases($trainingPhrases);
$intent->setMessages([$message]);
$contexts = ['test'];
foreach($contexts as $con){
$contextObj = new Context();
$contextObj->setName($con);
$contextData[] = $contextObj;
$intent->setOutputContexts($contextData);
}
// $intent->getOutputContexts('test');
//dd($intent);
$response = $intentsClient->createIntent($createIntentObject, $intent);
printf('Intent created: %s' . PHP_EOL, $response->getName());
}
I am getting error message
{
"message": "com.google.apps.framework.request.BadRequestException: Resource name does not match format 'projects/{project_id}/agent/sessions/{session_id}/contexts/{context_id}' or 'projects/{project_id}/locations/{location_id}/agent/sessions/{session_id}/contexts/{context_id}'.",
"code": 3,
"status": "INVALID_ARGUMENT",
"details": []
}
I believe the issue is with the format of storing the output context. Please help me on this.

I had the same issue. The answer is to not put in the bare name, but to have a string of a certain format made
see http://googleapis.github.io/google-cloud-php/#/docs/google-cloud/v0.131.0/dialogflow/v2/intent?method=setOutputContexts
// $projectId your project id
// $sessionId can be anything, I use $sessionId = uniqid();
$uri = "projects/$projectId/agent/sessions/$sessionId/contexts/$con";
$contextObj->setName($uri);

I can see that there are any response about this topic.
I leave here my solution for the next generations
To create a output context you need to create the correct format, for this objetive you can use Context class Google\Cloud\Dialogflow\V2\Context
private function parseoOutputContexts($contexts, $project_id, $lifespan = 5)
{
$newContexts = array();
foreach ($contexts as $context) {
$newContexts[] = new Context(
[
'name' => 'projects/' . $project_id . '/agent/sessions/-/contexts/' . $context,
'lifespan_count' => $lifespan
]
);
}
return $newContexts;
}
And you can use this function to finnaly add the output context to the object Intent.
$dialogflow_intent = new Intent();
$output_contexts = ['output_context_1'. 'output_context_2'];
$output_contexts = $this->parseOutputContexts($output_contexts, '[YOUR_PROJECT_ID]');
$dialogflow_intent->setOutputContexts($output_contexts);

Related

adding multiple destinations to new relic workflows using terraform

I am trying to create a newrelic workflow using terraform modules. I am fine with creating a workflow with signle destination. But, I am trying to create a workflow with more than one destination.
slack channel ids
variable "channel_ids" {
type = set(string)
default = ["XXXXXXXXXX","YYYYYYYYY"]
}
creating notification channels using slack channel ids
resource "newrelic_notification_channel" "notification_channel" {
for_each = var.channel_ids
name = "test" # will modify if required
type = "SLACK" # will parameterize this
destination_id = "aaaaaaaaa-bbbbb-cccc-ddddd-eeeeeeeeee"
product = "IINT"
property {
key = "channelId"
value = each.value
}
}
Now I want to create something like below (two destinations)
resource "newrelic_workflow" "newrelic_workflow" {
name = "my-workflow"
muting_rules_handling = "NOTIFY_ALL_ISSUES"
issues_filter {
name = "Filter-name"
type = "FILTER"
predicate {
attribute = "accumulations.policyName"
operator = "EXACTLY_MATCHES"
values = [ "policy_name" ]
}
}
destination {
channel_id = newrelic_notification_channel.notification_channel.id
}
destination {
channel_id = newrelic_notification_channel.notification_channel.id
}
}
I tried using for_each and for loop but no luck. Any idea on how to get my desired output?
Is it possible to loop through and create multiple destinations within the same resource, like attaching multiple destination to a single workflow?
I was able to achieve this by using a dynamic block, which produces a dynamic number of destination blocks based on the number of elements of newrelic_notification_channel.notification_channel.
resource "newrelic_workflow" "newrelic_workflow" {
name = "my-workflow"
muting_rules_handling = "NOTIFY_ALL_ISSUES"
issues_filter {
name = "Filter-name"
type = "FILTER"
predicate {
attribute = "accumulations.policyName"
operator = "EXACTLY_MATCHES"
values = [ "policy_name" ]
}
}
dynamic "destination" {
for_each = newrelic_notification_channel.notification_channel
content {
channel_id = destination.value.id
}
}
}

setting context with list of objects as prameters in dialogflow

I have a list of values each having another KEY value corresponding to it, when i present this list to user, user has to select a value and agent has to call an external api with selected value's KEY. how can i achieve this in dialogflow?
I tried to send the entire key value pair in the context and access it in the next intent but for some reason when i set a list(array) to context parameters dialogflow simply ignoring the fulfillment response.
What is happening here and is there any good way to achieve this? I am trying to develop a food ordering chatbot where the category of items in menu is presented and list items in that menu will fetched when user selects a category, this menu is not static thats why i am using api calls to get the dynamic menu.
function newOrder(agent)
{
var categories = []
var cat_parameters = {}
var catarray = []
const conv = agent.conv();
//conv.ask('sure, select a category to order');
agent.add('select a category to order');
return getAllCategories().then((result)=>{
for(let i=0; i< result.restuarantMenuList.length; i++)
{
try{
var name = result.restuarantMenuList[i].Name;
var catid = result.restuarantMenuList[i].Id;
categories.push(name)
//categories.name = catid
cat_parameters['id'] = catid;
cat_parameters['name'] = name
catarray.push(cat_parameters)
}catch(ex)
{
agent.add('trouble getting the list please try again later')
}
}
agent.context.set({
name: 'categorynames',
lifespan: 5,
parameters: catarray, // if i omit this line, the reponse is the fultillment response with categories names, if i keep this line the reponse is fetching from default static console one.
})
return agent.add('\n'+categories.toString())
})
function selectedCategory(agent)
{
//agent.add('category items should be fetched and displayed here');
var cat = agent.parameters.category
const categories = agent.context.get('categorynames')
const cat_ob = categories.parameters.cat_parameters
// use the key in the catarray with the parameter cat to call the external API
agent.add('you have selected '+ cat );
}
}
The primary issue is that the context parameters must be an object, it cannot be an array.
So when you save it, you can do something like
parameters: {
"cat_parameters": catarray
}
and when you deal with it when you get the reply, you can get the array back with
let catarray = categories.parameters.cat_parameters;
(There are some other syntax and scoping issues with your code, but this seems like it is the data availability issue you're having.)

Creating dynamic customer group using suite script

I am trying to create dynamic customer group using suite script in Net suite, I am trying below code but always getting
system INVALID_KEY_OR_REF
Invalid savedsearch reference key 21.
I have checked it is valid save search, Please help I am doing something wrong.
function createDynamicGroup(savedSearchId, groupName) {
var saveSearchObj = nlapiLoadSearch('customer', savedSearchId);
var initValues = new Array();
initValues.grouptype = 'Customer';
initValues.dynamic = 'T';
var goupRecObj = nlapiCreateRecord('entitygroup', initValues);
goupRecObj.setFieldValue('groupname', groupName);
goupRecObj.setFieldValue('savedsearch',saveSearchObj.getId());
nlapiSubmitRecord(goupRecObj);
}
You need group type = 'CustJob' as well as using a public search id:
function createDynamicGroup(savedSearchId, groupName) {
var saveSearchObj = nlapiLoadSearch('customer', savedSearchId);
var initValues = {
grouptype: 'CustJob', // <-- use this
dynamic: 'T'
};
var goupRecObj = nlapiCreateRecord('entitygroup', initValues);
goupRecObj.setFieldValue('groupname', groupName);
goupRecObj.setFieldValue('savedsearch', savedSearchId);
return nlapiSubmitRecord(goupRecObj);
}

Reconstructing an ODataQueryOptions object and GetInlineCount returning null

In an odata webapi call which returns a PageResult I extract the requestUri from the method parameter, manipulate the filter terms and then construct a new ODataQueryOptions object using the new uri.
(The PageResult methodology is based on this post:
http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options )
Here is the raw inbound uri which includes %24inlinecount=allpages
http://localhost:59459/api/apiOrders/?%24filter=OrderStatusName+eq+'Started'&filterLogic=AND&%24skip=0&%24top=10&%24inlinecount=allpages&_=1376341370337
Everything works fine in terms of the data returned except Request.GetInLineCount returns null.
This 'kills' paging on the client side as the client ui elements don't know the total number of records.
There must be something wrong with how I'm constructing the new ODataQueryOptions object.
Please see my code below. Any help would be appreciated.
I suspect this post may contain some clues https://stackoverflow.com/a/16361875/1433194 but I'm stumped.
public PageResult<OrderVm> Get(ODataQueryOptions<OrderVm> options)
{
var incomingUri = options.Request.RequestUri.AbsoluteUri;
//manipulate the uri here to suit the entity model
//(related to a transformation needed for enumerable type OrderStatusId )
//e.g. the query string may include %24filter=OrderStatusName+eq+'Started'
//I manipulate this to %24filter=OrderStatusId+eq+'Started'
ODataQueryOptions<OrderVm> options2;
var newUri = incomingUri; //pretend it was manipulated as above
//Reconstruct the ODataQueryOptions with the modified Uri
var request = new HttpRequestMessage(HttpMethod.Get, newUri);
//construct a new options object using the new request object
options2 = new ODataQueryOptions<OrderVm>(options.Context, request);
//Extract a queryable from the repository. contents is an IQueryable<Order>
var contents = _unitOfWork.OrderRepository.Get(null, o => o.OrderByDescending(c => c.OrderId), "");
//project it onto the view model to be used in a grid for display purposes
//the following projections etc work fine and do not interfere with GetInlineCount if
//I avoid the step of constructing and using a new options object
var ds = contents.Select(o => new OrderVm
{
OrderId = o.OrderId,
OrderCode = o.OrderCode,
CustomerId = o.CustomerId,
AmountCharged = o.AmountCharged,
CustomerName = o.Customer.FirstName + " " + o.Customer.LastName,
Donation = o.Donation,
OrderDate = o.OrderDate,
OrderStatusId = o.StatusId,
OrderStatusName = ""
});
//note the use of 'options2' here replacing the original 'options'
var settings = new ODataQuerySettings()
{
PageSize = options2.Top != null ? options2.Top.Value : 5
};
//apply the odata transformation
//note the use of 'options2' here replacing the original 'options'
IQueryable results = options2.ApplyTo(ds, settings);
//Update the field containing the string representation of the enum
foreach (OrderVm row in results)
{
row.OrderStatusName = row.OrderStatusId.ToString();
}
//get the total number of records in the result set
//THIS RETURNS NULL WHEN USING the 'options2' object - THIS IS MY PROBLEM
var count = Request.GetInlineCount();
//create the PageResult object
var pr = new PageResult<OrderVm>(
results as IEnumerable<OrderVm>,
Request.GetNextPageLink(),
count
);
return pr;
}
EDIT
So the corrected code should read
//create the PageResult object
var pr = new PageResult<OrderVm>(
results as IEnumerable<OrderVm>,
request.GetNextPageLink(),
request.GetInlineCount();
);
return pr;
EDIT
Avoided the need for a string transformation of the enum in the controller method by applying a Json transformation to the OrderStatusId property (an enum) of the OrderVm class
[JsonConverter(typeof(StringEnumConverter))]
public OrderStatus OrderStatusId { get; set; }
This does away with the foreach loop.
InlineCount would be present only when the client asks for it through the $inlinecount query option.
In your modify uri logic add the query option $inlinecount=allpages if it is not already present.
Also, there is a minor bug in your code. The new ODataQueryOptions you are creating uses a new request where as in the GetInlineCount call, you are using the old Request. They are not the same.
It should be,
var count = request.GetInlineCount(); // use the new request that your created, as that is what you applied the query to.

Assigning dynamic value to the receive activity properties

I am writing a custom activity using imperative code. In my compsoition, I have Receive activity as a one of the composed activity. In that activity, I want to set ServiceContractName and OperationName property dynamically, meaning, when developer who is consuming my custom activity have to set. So I declared one property and one InArgument for this purpose. I assign this property and Argument value to the local (sequence varriable). When I try to assign these varriables to Receive activity properties, I am getting compile time error. How to assign a Varriable to string and XName properties of Receive activity.
return new Sequence
{
Variables = { operationName, serviceContractName},
Activities =
{
new Assign<string>
{
To = new OutArgument<string>(serviceContractName),
Value = new InArgument<string>(ctx => ServiceContractName.Get(ctx))
},
new Assign<string>
{
To = new OutArgument<string>(operationName),
Value = new InArgument<string>(ctx => OperationName)
},
new Receive
{
ServiceContractName = serviceContractName,
OperationName = operationName,
CanCreateInstance = true,
Content = new ReceiveMessageContent
{
Message = new OutArgument<Request>(request)
}
}
},
}
};
You can't do that. The ServiceContractName and the OperationName are not InArguments but normal properties and they have to be set at design time, not at run time.

Resources