Dialogflow V2 - Custom Contexts - dialogflow-es

How can I create a custom system context to pass values from my API to dialogflow which is not dependent on any event.
I tried to put the same in the output context, but it is giving error Invalid Argument as the context name doesn't exist.
Here is the below pseudo code which I am doing (Java),
1. define the contextSettings object by setting credentials provider.
2. Create ContextsClient object using contextSettings object.
3. Create CreateContextRequest object by setting parent and context object.
4. Get the final Context object using ContextsClient.createContext(contextRequest)
5. Set the above context object in queryParameters to pass in DetectIntent Request.
But this is failing in Step # 4, and giving an error as Invalid Argument as the context name is not present under /projects/session
Please help me resolving this issue.
The reason that I want to create custom context is that I need to set values from API to pass to dialogflow and it is independent of Events or a specific flows.
We were able to create custom context in Dialogflow V1 using AIContext class and set the context object in the AIRequest object.
Thanks,
Ron

I am able to resolve the issue. I was not passing fully formed context path while creating the context object.
Context dialogflowContext = Context.newBuilder().setName(
"projects/[project-id]/agent/sessions/" + sessionId + "/contexts/[context-name]")
.setParameters(paramPair).setLifespanCount(1).build();

Related

Mule 4 Groovy Script

Is there any way to call mule "flow" instance using groovy ? like When I use the groovy script and it will call the another flow, that means ( calls the another flow -- > sets the variable value and get back with the results). = Expected Behaviour.
Requirement :
Like, Mule Flow A is running independently and keep on incrementing variable value.
Mule flow B wants to access the Flow A variable (Incremental value) ( only variable ) using groovy or python Script.
Note: Script should not execute flow A for getting variable value.
Is there method like to get instance of variable in groovy ? like
flow=registry.lookupByName('A-flow').getInstance(VariableName) ?
// Need to get only variable value.
Groovy Script to call a Mule flow:
import org.mule.runtime.api.message.Message;
import org.mule.runtime.core.api.event.CoreEvent;
import org.mule.runtime.core.api.event.EventContextFactory;
flow=registry.lookupByName('A-flow').grep();
msg = Message.builder().value(payload).build();
event =CoreEvent.builder(EventContextFactory.create(flow, org.mule.runtime.dsl.api.component.config.
DefaultComponentLocation.fromSingleComponent("add-location"))).message(msg).build();
result =flow.process(event);
Mule flow B wants to access the Flow A variable with out deploying or
starting the flow A (as it is running independently ) using groovy or
python Script.
Variables live inside a Mule Event, which is really what contains the status of an execution triggered from a flow. However even if you get a list of all active events you may not know which one is the one you are interested. It is also a bad practice trying to use Mule internals inside an application.
Instead you should share the value of the variable you are interested using a standard method for Mule, like an object store, a queue or database. It really depends on what you are trying to do and the design of your application what is the method that will fit best.

How do I set the applicaiton insights operationID to my custom correlationID?

I have a .net6 worker service and I need the Request Telemetry OperationID set to a custom value. This value is my CorrelationID that is read from a message queue, and it's format is a guid with dashes.
TelemetryClient.StartOperation has an overload that takes an operationId, but it only works with a specific format. It will not work with my guid.
I have tried the code below, which appears to work in the debugger. However, the value that shows up in applicaiton insights is not what I set it to.
var client = new TelemetryClient();
client.Context.Operation.Id = internalId;
I have tried creating an ITelemetryInitializer. If I set the operationID in the initialize method will work. The problem here is getting the correlationID to the initializer in the correct dependency injection scope.
It seems as though this is a common scenario. I have seen where others ask the question but I have not found a suitable solution.
Has anyone solved this problem?
The problem is that since .Net 5 the default Id format is set to W3C standard instead of the Hierarchical Id format, see the docs:
Parent-Child relationships between Activities in the distributed trace tree are established using unique IDs. .NET's implementation of distributed tracing supports two ID schemes: the W3C standard TraceContext, which is the default in .NET 5+, and an older .NET convention called 'Hierarchical' that's available for backwards compatibility. Activity.DefaultIdFormat controls which ID scheme is used. In the W3C TraceContext standard, every trace is assigned a globally unique 16-byte trace-id (Activity.TraceId), and every Activity within the trace is assigned a unique 8-byte span-id (Activity.SpanId). Each Activity records the trace-id, its own span-id, and the span-id of its parent (Activity.ParentSpanId). Because distributed traces can track work across process boundaries, parent and child Activities may not be in the same process. The combination of a trace-id and parent span-id can uniquely identify the parent Activity globally, regardless of what process it resides in.
Activity.DefaultIdFormat controls which ID format is used for starting new traces, but by default adding a new Activity to an existing trace uses whatever format the parent Activity is using. Setting Activity.ForceDefaultIdFormat to true overrides this behavior and creates all new Activities with the DefaultIdFormat, even when the parent uses a different ID format.
When you set the Activity.DefaultIdFormat to ActivityIdFormat.Hierarchical you can specify any string as an operation Id as it does not have to conform to the W3C standard.
So the following code works like a charm:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Activity.DefaultIdFormat = ActivityIdFormat.Hierarchical;
int index = 0;
while (!stoppingToken.IsCancellationRequested)
{
++index;
using var operation = _telemetryClient.StartOperation<RequestTelemetry>($"op{index}", $"a-b-c-{index}");
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
but it might break the distributed trace flow for your api controllers if you want to trace the end-to-end flow between multiple seperate applications.
Another way is to just include your own correlation Id as a custom propery:
operation.Telemetry.Properties["MessageCorrelationId"] = "xxx";

No MessageBodyWriter for Single

I'm trying to use resteasy-rxjava2 to provide an XML document using jaxb, within a vertx application (using a non-vertx legacy library we have). But I get:
Could not find MessageBodyWriter for response object of type:
org.jboss.resteasy.rxjava2.propagation.ContextPropagatorOnSingleAssemblyAction$ContextPropagatorSingle of media type:
application/xml;charset=UTF-8
From what I can tell, this comes down to the difference between a MessageBodyWriter and the AsyncResponseProvider that is in the resteasy-rxjava2 dependency for a Single (SingleProvider).
I have the following resteasy service definition
#GET
#Path(FdsnwsPaths.QUERY)
#Produces(MediaType.APPLICATION_XML)
#Stream
// CHECKSTYLE:OFF too many parameters
public Response getQuery(...)
How do I get resteasy to properly serve the data asynchrously, using the SingleProvider or otherwise.
The #Get method must return the Single explicitly or it doesn't work. (Can't use Response or Object). In my case, the Single contains the jaxb xml root element.
#GET
#Path(FdsnwsPaths.QUERY)
#Produces(MediaType.APPLICATION_XML)
#Stream
public Single<FDSNStationXML> getQuery(...)
Then, to make things more complicated, in order to handle specific exception types and map them to specific response status codes, I have to create a custom ExceptionMapper which creates the Response object I used to be able to create directly in the method. (in resteasy-vertx, I found no documentation on how to do this, but in my case, I am creating my own VertxRestEasyDeployment object so I can register the class of the ExceptionMapper(s) like this:
VertxResteasyDeployment deployment = new VertxResteasyDeployment();
deployment.getActualProviderClasses().addAll(providerClasses);
For reference, this is all being done with:
RestEasy 5.0.3.Final (including resteasy-rxjava2)
RxJava 2.2.20
Vertx 3.9.5

Connexion create object instance

I am working on refactoring a flask app which uses connexion package for the RESTful API. Previously the code base was function based and I`m refactoring it with some OOP design principles.
app = connexion.App(__name__)
app.add_api(
os.path.join(global_variables.ROOT_DIR, "openapi.yaml"),
pythonic_params=True,
validate_responses=VALIDATE_RESPONSES,
validator_map={"parameter": request_parameter_validator.RequestParameterValidator},
)
In the openapi.yaml the operationId specifies the full path to the class method which handles the request, but it throws the error:
TypeError: be_autocomplete_handler() missing 1 required positional argument: 'self'
How can I create an instance of that class in this case and pass it in the parameters field? Also, I do not pass any parameters in the constructor for now.
However, is there a preferred workflow in this case? Rather than creating an object instance?

Azure Functions - how to obtain invocation ID from within the function?

I am trying to return the invocation ID of an Azure function, similar to WebJob's sending the WebJob run ID back in the HTTP Location header. This is so the invoker of my function can check the status periodically to know when it completes.
I see that I must add this id into the response object, and I surmise I need to retrieve it from some context object in the function. This is because when I visit the Functions UI at https://functionapp.scm.azurewebsites.net/azurejobs/#/functions/invocations/a-long-guid
I see a variable named _context with the invocation id. However, I can't seem to access a variable named context, _context, etc in my function.
You can bind to the ExecutionContext by adding a parameter of that type to your function's method (e.g. Run(..., ExecutionContext context)).
That type exposes an InvocationId property that will give you the information you're looking for.

Resources