How to get parameter from previous context in Dialogflow - javascript

I am creating a chatbot for an IP firm. Its have an entity named service to have 4 type values. (Patent, Copyright, Trademark, design).
Client: What is a patent?
Bot: (Answer)
Client: how much cost to file it?
How I can know client asking about the patent from the previous context?
I can't use followup-intent in every intent.
Right now I'm using a global variable to get the slot agent.parameters.Service inside fulfillment.
let slot='patent';
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
function service_typeHandler(agent){
var serv ='';
serv = agent.parameters.Service;
if(serv ===''){
serv=slot;
}
else{
slot=serv;
}
switch( serv ){
case 'patent':

First of all, you're correct on two fronts:
Don't use followup Intents. There are few cases where you actually want followup Intents. Most of the time you want to do this with other means.
Use Contexts. These are (part of) the "other means" in most cases.
In this case, it sounds like you'll have two Intents (and likely more, but this illustrates the point):
"ask.what" - which is the user saying things like "What is a patent?"
"ask.price" - which is the user saying things like "How much to file a patent?", but also "How much to file it?"
For the "ask.what" Intent, you would set an "Outgoing Context". This will automatically capture the parameters that are attached to the Intent. If you want to control it more yourself, you can create your own Context in your webhook and set parameters to whatever value you want. I suggest the latter, because it lets you use a parameter name that you don't use elsewhere. Let's assume that you're using a context named "savedInfo" and that you're setting the parameter to "savedService".
In your "ask.price" Intent, you'd do something similar to what you're doing now. Except that if the Service parameter is empty, get the parameters from the "savedInfo" context and, specifically, the savedService parameter.

Related

Is there a way to reply to only the sender, after receiving a BroadcastChannel message?

Suppose I have a bunch of same-origin windows or tabs A, B, C, D, and E, that don't hold references to each other. (e.g. a user opened them independently). Suppose A sends a BroadcastChannel message to the others, and as a result, D needs to send some data back to A, ideally without involving B, C, or E.
Is this possible, using any of the message-passing APIs?
There's an event.source property on the broadcast message event, which looked as if it should maybe contain a WindowProxy or MessagePort object in this context, but (in my tests with Firefox 78 at least) it was simply null. There's also a ports array, but that was empty.
...I'm aware that you could start up a SharedWorker to assign each window a unique ID and act as a waystation for passing messages between them, but (a) that seems very complicated for the functionality desired, and (b) every message sent that way is going to need 2 hops, from window to sharedWorker and back to a window, crossing thread boundaries both times, and (usually) getting serialized & unserialized both times as well - even when the two windows share the same javascript thread! So it's not very efficient.
This seems like such an obvious thing to want to do, I'm finding it hard to believe there isn't something obvious I'm missing... but I don't see it, if so!
Looks like the standards require source to be null for a BroadcastChannel. But it shares the MessageEvent interface with several other APIs that do use source, hence why it exists, but is null.
The postMessage(message) method steps are:
...
5. Remove source from destinations.
Looks like they intentionally kept BroadcastChannel very lightweight. Just a guess, but the functionality you're looking for might have required additional resources that they didn't want to allocate. This guess is based on a general note they have in the spec:
For elaborate cases, e.g. to manage locking of shared state, to manage synchronization of resources between a server and multiple local clients, to share a WebSocket connection with a remote host, and so forth, shared workers are the most appropriate solution.
For simple cases, though, where a shared worker would be an unreasonable overhead, authors can use the simple channel-based broadcast mechanism described in this section.
SharedWorkers are definitely more appropriate for complicated cases, think of the BroadcastChannel really just as a one-to-many simple notification sender.
It isn't able to transfer data — Which of the receivers should become the owner then? — so except in the case of Blobs (which are just small wrappers with no data of their own), passing data through a BroadcastChannel means it has to be fully deserialized by all receivers, not the most performant way of doing.
So I'm not sure what kind of data you need to send, but if it's big data that should normally be transferable, then probably prefer a SharedWorker.
One workaround though if your data is not to be transfered, is to create a new BroadcastChannel that only your two contexts will listen at.
Live demo
In page A:
const common_channel = new BroadcastChannel( "main" );
const uuid = "private-" + Math.random();
common_channel.postMessage( {
type: "gimme the data",
from: "pageB",
respondAt: uuid
} );
const private_channel = new BroadcastChannel( uuid );
private_channel.onmessage = ({data}) => {
handleDataFromPageB(data);
private_channel.close();
};
In page B:
const common_channel = new BroadcastChannel( "main" );
common_channel.onmessage = ({ data }) => {
if( data.from === "pageB" && data.type === "gimme the data" ) {
const private_channel = new BroadcastChannel( data.respondAt );
private_channel.postMessage( the_data );
private_channel.close();
}
};
Regarding why you can't have a ports value on MessageEvent firing on BroadcastChannels it's because MessagePorts must be transfered, but as we already said, BroadcastChannels can't do transfers.
For why there is no source, it's probably because as you expected that should have been a WindowProxy object, but WorkerContexts can also post messages to BroadcastChannels, and they don't implement that interface (e.g their postMessage method wouldn't do the same thing at all than for a WindowContext).

Access multiple gRPC Services over the same Connection (with a single Channel)

Note that this is not a duplicate of a similar question for go, since this uses grpc-node. For some reason, there seems to be differences in the API
I do the standard procedure of creating my APIPackageDefinitions and APIPackagePbjects, and create two separate clients from each one, individually.
let grpc = require('grpc')
let protoLoader = require('#grpc/proto-loader')
async function createGrcpConnection() {
const HOST = 'localhost'
const PORT = '50053'
const PORT2 = '50054'
let physicalProjectAPIPackageDefinition = await protoLoader.load(
'./physical_project_api.proto',protoLoaderOptions
)
let configAPIPackageDefinition = await protoLoader.load(
'./config_api.proto', protoLoaderOptions
)
let physicalProjectAPIPackageObject = grpc.loadPackageDefinition(
physicalProjectAPIPackageDefinition
).package.v1
let configAPIPackageObject = grpc.loadPackageDefinition(
configAPIPackageDefinition
).package.v1
let grpcClient1 = physicalProjectAPIPackageObject.PhysicalProjectAPI(
`${HOST}:${PORT}`,
grpc.credentials.createInsecure()
)
let grpcClient2 = configAPIPackageObject.ConfigAPI(
`${HOST}:${PORT2}`,
grpc.credentials.createInsecure()
)
return { grpcClient1, grpcClient2 }
}
I am looking for a way to create two clients that share the same connection. I think I am close to the solution by creating a new Channel and replacing the last two let statements with
let cc = new grpc.Channel(
`${HOST}:${PORT}`,
grpc.credentials.createInsecure()
)
let grpcClient1 = physicalProjectAPIPackageObject.PhysicalProjectAPI(cc)
let grpcClient2 = configAPIPackageObject.ConfigAPI(cc)
However, I received a TypeError: Channel's first argument (address) must be a string. I'm not sure how to incorporate the newly instantiated Channel to create new clients for each service. I couldn't find any useful methods on the docs. Any help would be appreciated.
P.S. At the moment I am trying to use two services, and create a client for each service, and have those two clients share a connection on the same channel. Is it possible to use two service, and create a single client for both services? Maybe I can use .proto package namespaces to my advantage here? My internet search fu failed me on this question.
There is an API to do this, but it is a bit more awkward than what you were trying. And you don't actually need to use it to get what you want. The grpc library internally pools connections to the same server, as long as those connections were created with identical parameters. So, the Client objects created in your first code block will actually use the same TCP connection.
However, as mentioned, there is a way to do this explicitly. The third argument to the Client constructor is an optional object with various additional options, including channelOverride. That accepts a Channel object like the one you constructed at the beginning of your second code block. You still have to pass valid values for the first two arguments, but they will actually be ignored and the third argument will be used instead. You can see more information about that constructor's arguments in the API documentation.

How to discover and load js files at runtime?

I'm writing a node.js based server that manages a range of devices. The node.js based server tells connected clients about its abilities. The abilities are defined by separate js files that define objects that are using inheritance via util.inherits().
The problem I have is that right now, I have to define a new js for a new ability and then update the main js program to require the new js, change the code to publish that the ability is available, and then utilise the new ability if requested to by the client.
I would like to make the main code more generic whereby it can
detect the new abilities,
automatically include them,
notify the clients, and
utilise the code.
The detection I can do via the various npm modules out there that support tree browsing, I can just nominate a subdirectory for all capabilities and discover what files are there. I presume that I can use require for step 2 (though not 100% certain), however I don't know how to do step 3 and 4 or use the results from step 2 with step 3 and 4.
I would value any feedback on how to solve this problem.
To clarify my problem. Right now my logic is as per the following:
var logicA = requires('./capabilities/a.js');
var logicB = requires('./capabilities/b.js');
var logicC = requires('./capabilities/c.js');
var Comms.CAPABILITY_A = 'a';
var Comms.CAPABILITY_B = 'b';
var Comms.CAPABILITY_C = 'c';
var Comms.MSG_CAPABILITY = 0;
var Comms.MSG_DO_LOGIC = 1;
function onMessageReceived(comms, msgId, body) {
switch (msgId) {
case(MSG_DO_LOGIC):
doLogic(body);
break;
...
}
}
function doLogic(flag) {
switch(flag) {
case(Comms.CAPABILITY_A):
logicA.doLogic();
break;
case(Comms.CAPABILITY_B):
logicB.doLogic();
break;
case(Comms.CAPABILITY_C):
logicC.doLogic();
break;
}
}
At the client side I have hard coded logic that presumes what is available. I can remove this by having the server send an array of the capabilities to the client, and then the client can choose one of the elements of the array and pass it back as the request to execute the logic. This is not my problem.
My problem is understanding how to cause the host program load all the logic dynamically and then evaluate which logic to execute on the dynamically loaded logic.
I should state that when I say dynamic, I mean that the code available is determined at runtime. However the evaluation is only ever performed when the server is first started.
I solved the problem by creating a register.js where all the protocols are kept. Each time I create a new protocol, I add it to the register.
Via the register I can get an array of all registered protocols. I can pass them back to the client, the client can choose a protocol and I can request an instance of the protocol via the register class.
While there is some hardcoding, it's restricted to the register class which is in the same directory as the protocols.
So in the register I have the following functions:
getList()
getText()
validateProtocolId()
getProtocol()
I use getList() to return an array of the protocol id's that are registered. I use getText() to provide a human readable list of supported protocols. I use validateProtocolId() to validate an id returned from the client to confirm that the id represents a registered protocol and then I use getProtocol() to generate an instance of the registered protocol.
In essence the getProtocol() just does a require('./<protocol file>.js') as appropriate.
It's not as elegant as auto discovery, but it allows tighter controls on what is registered without forcing custom file, etc.

AngularJS $resource # prefixed parameter

I am learning AngularJS and reading its API
Angular JS Resource
It says "If the parameter value is prefixed with # then the value of that parameter is extracted from the data object " with code example:
var User = $resource('/user/:userId', {userId:'#id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
I am so slow that after the example I still don't get what the prefixed # means/does. Could someone please give me some examples With and Without the # and elaborate it? Thanks...
Sure.
It means that the value of :userId in your url will be replaced with the id property from the user object when that property is required.
So when is it required? Its required when you are doing something to an existing user, like geting one, updating one. It is not required when you create a user.
In most cases, you will want to have at least one param prefixed with # in your REST url that resource uses (probably the object id). If you dont have one, that means that in order for you to save an instance of an object, you dont need to know anything about where its stored. This implies that its a singleton object. Maybe like a settings object.
Here is your long awaited example:
var User = $resource('/user/:userId/:dogName', {userId:'#id', dogName:#dog});
User.get({userId:123, dog:'Matt'}, function() { .. })
will produce the request: GET /user/123/Matt

How can we identify a unique nsHTTPChannel?

I am doing some development on the firefox both with javascript and C++ for some XPCOM components.
I am trying to monitor the http activity with nsIHttpActivityDistributor.
The problem now is , is there any flag or id that belong to nsIHttpChannel that I can use to identify a unique nsHttpChannel object?
I want to save some nsIHttpChannel referred objects in C++ and then process later in Javascript or C++. The thing is that currently I cannot find a elegent way to identify a channel object that can used both in js and C++, which is used to log it clearly into a log file.
Any idea?
You can easily add your own data to HTTP channels, they always implement nsIPropertyBag2 and nsIWritablePropertyBag2 interfaces. Something along these lines (untested code, merely to illustrate the principle):
static PRInt64 maxChannelID = -1;
...
nsCOMPtr<nsIWritablePropertyBag2> bag = do_QueryInterface(channel);
if (!bag)
...
nsAutoString prop(NS_LITERAL_STRING("myChannelID"));
PRInt64 channelID;
rv = bag->GetPropertyAsInt64(prop, &channelID);
if (NS_FAILED(rv))
{
// First time that we see that channel, assign it an ID
channelID = ++maxChannelID;
rv = bag->SetPropertyAsInt64(prop, channelID)
if (NS_FAILED(rv))
...
}
printf("Channel ID: %i\n", channelID);
You might want to check what happens on HTTP redirect however. I think that channel properties are copied over to the new channel in that case, not sure whether this is desirable for you.

Categories