public MainDialog(IConfiguration configuration, IStatePropertyAccessor <AuthenticatedUser> AuthenticatedUserAccessor, IBotServices botServices, Intents intents) : base(nameof(MainDialog), configuration["ConnectionName"]) { Configuration = configuration; _AuthenticatedUserAccessor = AuthenticatedUserAccessor; _botServices = botServices; Intents = intents; AddDialog(new OAuthPrompt( nameof(OAuthPrompt), new OAuthPromptSettings { ConnectionName = ConnectionName, Text = "Before we start, I would need from you to verify your account.", Title = "Verify Account", Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5) })); //AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt))); AddAllPossibleDialogs(); AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[] { PromptStepAsync, LoginStepAsync, StartProcessingIntents, EndProcessingIntents })); // The initial child Dialog to run. InitialDialogId = nameof(WaterfallDialog); }
public Package(string name, NLUEngine engine, Controller controller, CancellationToken ct, params Package[] subPackages) : base(ct) { Name = name; NLUEngine = engine; Controller = controller; Intents.Add("info", Info); Intents.Add("help", Help); Intents.Add("menu", Menu); Intents.Add("enable", Enable); Intents.Add("disable", Disable); Intents.Add("back", Back); Intents.Add("page", Page); Intents.Add("list", List); if (subPackages != null && subPackages.Length > 0) { SubPackages = subPackages.ToList(); } foreach (var vn in VariableNames) { Variables.Add(Prefixed(vn), null); } foreach (var i in ItemNames) { Items.Add(Prefixed(i), null); } foreach (var m in MenuNames) { Menus.Add(Prefixed(m), null); } }
private static async void HandleEvent(Event e) { var msgEvent = e as MessageEvent; if (uiHandlers != 0 || msgEvent == null || !settings.NotifyPrivate) { return; } var intent = Intents.Create <MainActivity>(); if (notificationCount == 0) { intent.PutExtra(NotificationsSenderKey, msgEvent.Message.Sender.Name); } var builder = new NotificationCompat.Builder(Application.Context).SetAutoCancel(true) .SetContentTitle(notificationCount > 0 ? Strings.Events_Message_TitleMany : string.Format(Strings.Events_Message_TitleOne, msgEvent.Message.Sender.Name)) .SetContentText(notificationCount > 0 ? Strings.Events_Message_TextMany : msgEvent.Message.Text) .SetSmallIcon(Resource.Drawable.icon) .SetContentIntent(PendingIntent.GetActivity(Application.Context, notificationId, intent, PendingIntentFlags.UpdateCurrent)) .SetLargeIcon(await Mvx.GetSingleton <IMvxImageCache <Bitmap> >().RequestImage(Helpers.GetAvatar(msgEvent.Message.Sender.Name))); if (settings.Vibrate) { builder.SetVibrate(new long[] { 500, 500 }); } Android.App.NotificationManager.FromContext(Application.Context).Notify(notificationId, builder.Build()); ++notificationCount; }
public virtual bool ParseIntent(CUIContext context, DateTime time, string input) { var intent = NLUEngine.GetIntent(input); if (Controller.DebugEnabled) { DebugIntent(intent); } if (!intent.IsNone && intent.Top.Label == "menu" && intent.Top.Score > 0.7) { Menu(intent); } if (intent.Top.Score < 0.8) { return(false); } else { if (Intents.ContainsKey(intent.Top.Label)) { DispatchIntent(intent, Intents[intent.Top.Label]); } else { SayErrorLine("This package recognizes intent {0} but does not have handler for it.", intent.Top.Label); DebugIntent(intent); } return(true); } }
public CUIPackage(string name, NLUEngine engine, CUIController controller, CancellationToken ct, params CUIPackage[] subPackages) : base(ct) { Name = name; NLUEngine = engine; Controller = controller; Intents.Add("help", Help); Intents.Add("menu", Menu); if (subPackages != null && subPackages.Length > 0) { SubPackages = subPackages.ToList(); } foreach (var vn in VariableNames) { Variables.Add(Prefixed(vn), null); } foreach (var i in ItemNames) { Items.Add(Prefixed(i), null); ItemsPageSize.Add(Prefixed(i), 10); ItemsCurrentPage.Add(Prefixed(i), 1); ItemsSelection.Add(Prefixed(i), -1); ItemsDescriptionHandlers.Add(Prefixed(i), null); } foreach (var m in MenuNames) { MenuHandlers.Add(Prefixed(m), null); MenuIndexes.Add(Prefixed(m), 0); } }
public void AddIntent(Intents intent) { intent.RegistDate = DateTime.Now; intent.ModifyDate = DateTime.Now; db.Intents.Add(intent); db.SaveChanges(); }
public async Task <ActionResult> Create(UtteranceManageVM vm) { Intents intent = intentService.GetIntentInfo(Convert.ToInt32(vm.Utterance.IntentIDX)); string authoringKey = ConfigurationManager.AppSettings["AuthoringKey"].ToString(); string appID = ConfigurationManager.AppSettings["LuisAppID"].ToString(); string appVersion = ConfigurationManager.AppSettings["AppVersion"].ToString(); string appHost = ConfigurationManager.AppSettings["LuisHost"].ToString(); vm.Utterance.IsUseYN = true; vm.Utterance.RegistUserID = "eddy"; //HttpContext.User.Identity.Name; vm.Utterance.RegistDate = DateTime.Now; vm.Utterance.ModifyUserID = "eddy"; //HttpContext.User.Identity.Name; vm.Utterance.ModifyDate = DateTime.Now; //LUIS 해당 인텐트에 발화메시지 등록처리 Example example = new Example(); example.IntentName = intent.IntentName; example.Text = vm.Utterance.Utterance; Utterance utterance = await LuisCreateUtterance(appID, appVersion, authoringKey, example); //발화메시지 DB저장 vm.Utterance.ExampleID = utterance.ExampleId; intentService.AddUtterance(vm.Utterance); return(RedirectToAction("List", "Utterance")); }
public OpenShift(CUIController controller, CancellationToken ct) : base("OpenShift", new SnipsNLUEngine(Path.Combine("Engines", "openshift")), controller, ct) { Intents.Add("list", List); Intents.Add("page", Page); MenuHandlers["OPENSHIFT_OBJECTS"] = GetOpenShiftMenuSelection; MenuIndexes["OPENSHIFT_OBJECTS"] = 5; ItemsDescriptionHandlers["OPENSHIFT_PODS"] = DescribePods; ItemsDescriptionHandlers["OPENSHIFT_PROJECTS"] = DescribeProjects; ItemsDescriptionHandlers["OPENSHIFT_BUILDS"] = DescribeBuilds; ApiUrl = Config("CUI_VISH_OPENSHIFT_URL"); ApiToken = Config("CUI_VISH_OPENSHIFT_TOKEN"); if (!string.IsNullOrEmpty(ApiToken) && !string.IsNullOrEmpty(ApiUrl)) { var handler = new HttpClientHandler { }; Client = new OpenShiftAPIwithKubernetes(new Uri(ApiUrl), new TokenCredentials(ApiToken), handler); Initialized = true; } else if (string.IsNullOrEmpty(ApiUrl)) { SayErrorLine("I could not determine your OpenShift API URL. Please ensure the value exists in your config.json configuration file or as the environment variable {0}.", "CUI_VISH_OPENSHIFT_URL"); } else if (string.IsNullOrEmpty(ApiToken)) { SayErrorLine("I could not determine your OpenShift service API token. Please ensure the value exists in your config.json configuration file or as the environment variable {0}.", "CUI_VISH_OPENSHIFT_TOKENs"); } }
public MedTracker(CUIController controller, CancellationToken ct) : base("Vish", new SnipsNLUEngine(Path.Combine("Engines", "vish")), controller, ct) { Intents.Add("launch", Launch); MenuIndexes["VISH_PACKAGES"] = 3; MenuHandlers["VISH_PACKAGES"] = GetPackagesMenuItem; Initialized = NLUEngine.Initialized; }
// Start is called before the first frame update public IntentDetector(TextAsset jsonFile) { intentsFromJson = JsonUtility.FromJson <Intents>(jsonFile.text); foreach (Intent intent in intentsFromJson.intents) { Debug.Log(intent.intentName); } }
public void Dispose() { Apps.Dispose(); Entities.Dispose(); Examples.Dispose(); Intents.Dispose(); Publishing.Dispose(); Versions.Dispose(); Training.Dispose(); }
public DialogBot(IBotServices botServices, ConversationState conversationState, UserState userState, IConfiguration configuration) { ConversationState = conversationState; UserState = userState; //Dialog = dialog; //Logger = logger; _botServices = botServices; Configuration = configuration; _AuthenticatedUserAccessor = UserState.CreateProperty <AuthenticatedUser>(nameof(AuthenticatedUser)); Intents = Configuration.Get <Intents>(); this.Dialog = new MainDialog(configuration, _AuthenticatedUserAccessor, _botServices, Intents); }
internal void AddIntent(MatchIntentAndEntities intent, DialogVariablesSimulator dialogVariables) { if (!Intents.ContainsKey(intent.Name)) { Intents.Add(intent.Name, intent); dialogVariables.AddMatchIntentAndEntities(intent); } else { var otherIntent = Intents[intent.Name]; LogMessage(intent.LineNumber, MessageType.DuplicateKey, "Two intent matching nodes found for intent \"" + intent.Name + "\" : line " + intent.LineNumber + " and line " + otherIntent.LineNumber); } }
public (string, double) GetTopIntent() { var intent = Intents.OrderByDescending(kp => kp.Value)?.FirstOrDefault(i => i.Value >= 0.30); if (intent.HasValue) { return(intent.Value.Key, intent.Value.Value); } else { return(null, 0d); } }
public void Refresh() { mSuppressCollectionChangedEvents = true; Elements.Match <ArrowElementVm, ArrowElementSave>(mModel.Elements); Intents.Match <ArrowIntentVm, ArrowIntentSave>(mModel.Intents); RebuildTopLevelItems(); foreach (var intent in TopLevelItems) { intent.Refresh(); } mSuppressCollectionChangedEvents = false; }
public void IntentsRemoveInvalid() { int numRemoved = 0; for (int i = Intents.Count - 1; i >= 0; i--) { if (!Intents[i].Valid) { Intents.RemoveAt(i); numRemoved++; } } Debug.Log($"Removed {numRemoved} invalidated intents"); }
private void ProcessMessage(Match match, string mensagem, Intents intent) { if (match.DateOpportunity) { //Update the azure table register // Create a retrieve operation that takes a customer entity. TableOperation retrieveOperation = TableOperation.Retrieve <Matches>(this.TinderSession.CurrentUser.Id, match.Id); // Execute the retrieve operation. TableResult retrievedResult = matchesTable.Execute(retrieveOperation); // Print the phone number of the result. if (retrievedResult.Result != null) { var retrievedMatch = (Matches)retrievedResult.Result; retrievedMatch.DateOpportunity = true; TableOperation updateOperation = TableOperation.Replace(retrievedMatch); // Execute the operation. matchesTable.Execute(updateOperation); } //TODO: Call the user, send some sort of notification } //Send the message to the user var tinderMessageTask = this.TinderSession.SendMessage(match.Id, mensagem); tinderMessageTask.ConfigureAwait(true); //Register the message on matchesHistory table var matchHistory = new MatchesHistory(); matchHistory.PartitionKey = this.TinderSession.CurrentUser.Id; matchHistory.RowKey = match.Id; matchHistory.Timestamp = DateTimeOffset.Now; matchHistory.Message = mensagem; matchHistory.Intent = intent.Intent; matchHistory.Score = intent.Score; TableOperation insertOperation = TableOperation.Insert(matchHistory); var insertTask = matchesHistoryTable.ExecuteAsync(insertOperation); insertTask.ConfigureAwait(false); }
private IEnumerable <IContextContainer> GetNestedContainers() { var contextContainers = Intents.OfType <IContextContainer>().ToList(); var i = 0; while (i < contextContainers.Count) { var current = contextContainers[i]; var unknownContainers = current.GetContexts() .SelectMany(c => c.Intents.OfType <IContextContainer>()) .Except(contextContainers); contextContainers.AddRange(unknownContainers); i++; } return(contextContainers); }
public void UpdateIntent(Intents intents) { Intents data = GetIntentInfo(intents.IntentIDX); data.BizTypeCode = intents.BizTypeCode; data.LuisAppID = intents.LuisAppID; data.IntentID = intents.IntentID; data.IntentName = intents.IntentName; data.Reply1 = intents.Reply1; data.ReplyLink = intents.ReplyLink; data.SystemName = intents.SystemName; data.IsUseYN = intents.IsUseYN; data.ModifyUserID = intents.ModifyUserID; data.ModifyDate = intents.ModifyDate; db.Entry(data).State = EntityState.Modified; db.SaveChanges(); }
public async Task ReloadData(bool reCreate = false) { var intents = Intents.LoadIntents(); var responses = Responses.LoadResponses(); if (reCreate) { foreach (var intent in intents) { _intentsRepository.Remove(intent.Id); } foreach (var response in responses) { _responsesRepository.Remove(response.Id); } } _intentsRepository.Add(intents.ToList()); _responsesRepository.Add(responses.ToList()); }
/// <summary>Determines whether the specified object is equal to the current object.</summary> /// <param name="obj">The object to compare with the current object.</param> /// <returns>true if the specified object is equal to the current object; otherwise, false.</returns> public override bool Equals(object?obj) { if (ReferenceEquals(null, obj)) { return(false); } if (ReferenceEquals(this, obj)) { return(true); } if (obj.GetType() != GetType()) { return(false); } var other = (SchemaGeneratorContext)obj; return(Type == other.Type && Intents.ContentsEqual(other.Intents)); }
/// <summary> /// Soft-resets session state related to the game world /// </summary> public void Clear() { Intents.Clear(); GameData.Clear(); clearDecorated(); LoadSave = null; PreviousScene = null; NextScene = null; SkipLoadingScreen = false; void clearDecorated() { var decoratedMembers = GetType().GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Where(m => m.GetCustomAttributes(typeof(ClearAttribute), false).Length > 0) .ToList(); foreach (var member in decoratedMembers) { object value = null; var defaultValueAttribute = member.GetCustomAttribute <DefaultValueAttribute>(); if (defaultValueAttribute != null) { value = defaultValueAttribute.Value; } if (member.MemberType == MemberTypes.Property) { PropertyInfo property = member as PropertyInfo; property.SetValue(this, value); //apparently setting value to none will actually work } else if (member.MemberType == MemberTypes.Field) { FieldInfo field = member as FieldInfo; field.SetValue(this, value); } } } }
private BotState IntentStringToIssue(Intents intent) { switch (intent) { case Intents.Theft: return(BotState.Issue_Theft); case Intents.Assault: return(BotState.Issue_Assault); case Intents.CarCrash: return(BotState.Issue_CarCrash); case Intents.CriminalDamage: return(BotState.Issue_CriminalDamage); case Intents.Harassment: return(BotState.Issue_Harassment); case Intents.Information: return(BotState.Issue_Information); case Intents.None: return(BotState.Issue_None); default: return(BotState.AskIssue); } }
internal void Optimize() { var thisHash = GetHashCode(); var allContexts = GetChildContexts(); var defsByHashCode = allContexts.Where(g => g.Value.Count > 1 && (g.Value.Context.Intents.Count != 1 || !(g.Value.Context.Intents[0] is TypeIntent))) .ToDictionary(g => g.Key, g => g.Value.Context); var currentNames = new List <string>(); var defs = new Dictionary <string, SchemaGeneratorContext>(); var contextContainers = GetNestedContainers().ToList(); foreach (var def in defsByHashCode) { var name = def.Value.GetDefName(currentNames); var refIntent = new RefIntent(new Uri(def.Key == thisHash ? "#" : $"#/$defs/{name}", UriKind.Relative)); var refContext = new SchemaGeneratorContext(def.Value.Type, null !, Configuration); refContext.Intents.Add(refIntent); foreach (var intent in contextContainers) { intent.Replace(def.Key, refContext); } if (def.Key == thisHash) { continue; } defs[name] = def.Value; } if (defs.Any()) { var defsIntent = new DefsIntent(defs); Intents.Add(defsIntent); } }
/// <summary> /// Every conversation turn for our LUIS Bot will call this method. /// There are no dialogs used, the sample only uses "single turn" processing, /// meaning a single request and response, with no stateful conversation. /// </summary> /// <param name="turnContext">A <see cref="ITurnContext"/> containing all the data needed /// for processing this conversation turn. </param> /// <param name="cancellationToken">(Optional) A <see cref="CancellationToken"/> that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns> public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { if (turnContext.Activity.Type == ActivityTypes.Message) { // Check LUIS model var recognizerResult = await _services.LuisServices[LuisKey].RecognizeAsync(turnContext, cancellationToken); var topIntent = recognizerResult?.GetTopScoringIntent(); if (topIntent != null && topIntent.HasValue && topIntent.Value.intent != "None") { Intents intent = (Intents)Enum.Parse(typeof(Intents), topIntent.Value.intent); switch (intent) { case Intents.ShowMenu: await turnContext.SendActivityAsync($"Here is our menu: \n Coffee: {CoffeesMethods.DisplayCoffees()}\n Tea: {TeaMethods.DisplayTeas()}", cancellationToken : cancellationToken); break; case Intents.ChooseRank: // Here we generate the event ID for this Rank. var response = await ChooseRankAsync(turnContext, _rlFeaturesManager.GenerateEventId(), cancellationToken); _rlFeaturesManager.CurrentPreference = response.Ranking; await turnContext.SendActivityAsync($"How about {response.RewardActionId}?", cancellationToken : cancellationToken); break; case Intents.RewardLike: if (!string.IsNullOrEmpty(_rlFeaturesManager.CurrentEventId)) { await RewardAsync(turnContext, _rlFeaturesManager.CurrentEventId, 1, cancellationToken); await turnContext.SendActivityAsync($"That's great! I'll keep learning your preferences over time.", cancellationToken : cancellationToken); await SendByebyeMessageAsync(turnContext, cancellationToken); } else { await turnContext.SendActivityAsync($"Not sure what you like. Did you ask for a suggestion?", cancellationToken : cancellationToken); } break; case Intents.RewardDislike: if (!string.IsNullOrEmpty(_rlFeaturesManager.CurrentEventId)) { await RewardAsync(turnContext, _rlFeaturesManager.CurrentEventId, 0, cancellationToken); await turnContext.SendActivityAsync($"Oh well, maybe I'll guess better next time.", cancellationToken : cancellationToken); await SendByebyeMessageAsync(turnContext, cancellationToken); } else { await turnContext.SendActivityAsync($"Not sure what you dislike. Did you ask for a suggestion?", cancellationToken : cancellationToken); } break; case Intents.Reset: _rlFeaturesManager.GenerateRLFeatures(); await SendResetMessageAsync(turnContext, cancellationToken); break; default: break; } } else { var msg = @"No LUIS intents were found. This sample is about identifying intents: 'ShowMenu' 'ChooseRank' 'RewardLike' 'RewardDislike'. Try typing 'Show me the menu','What do you suggest','I like it','I don't like it'."; await turnContext.SendActivityAsync(msg); } } else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate) { _rlFeaturesManager.GenerateRLFeatures(); // Send a welcome message to the user and tell them what actions they may perform to use this bot await SendWelcomeMessageAsync(turnContext, cancellationToken); } else { await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected", cancellationToken : cancellationToken); } }
public string GetValidIntent() { var intent = Intents.AsEnumerable().FirstOrDefault(i => i.Score > 0.08); return(intent != null ? intent.IntentName : string.Empty); }
public LogMessageEvent(string message, Intents intent, Targets target) { this.strMessage = message; this.intent = intent; this.target = target; }
public override string ToString() => Intents.ToString();
private (Intent intent, double score) ProcessUserInput() { var intentScore = new Microsoft.Bot.Builder.IntentScore { Score = 0.9909704, Properties = new Dictionary <string, object>() }; switch (UserInput.ToLower()) { case "set temperature to 21 degrees": Entities.SETTING = new string[] { "temperature" }; Entities.AMOUNT = new string[] { "21" }; Entities.UNIT = new string[] { "degrees" }; break; case "increase temperature by 2": Entities.VALUE = new string[] { "increase" }; Entities.SETTING = new string[] { "temperature" }; Entities.TYPE = new string[] { "by" }; Entities.AMOUNT = new string[] { "2" }; break; case "increase temperature to 24": Entities.VALUE = new string[] { "increase" }; Entities.SETTING = new string[] { "temperature" }; Entities.AMOUNT = new string[] { "24" }; break; case "change the temperature": Entities.SETTING = new string[] { "temperature" }; break; case "turn lane assist off": Entities.SETTING = new string[] { "lane assist" }; Entities.VALUE = new string[] { "off" }; break; case "warm up the back of the car": Entities.SETTING = new string[] { "back" }; Entities.VALUE = new string[] { "warm up" }; break; case "defog my windshield": Entities.VALUE = new string[] { "defog" }; break; case "put the air on my feet": Entities.SETTING = new string[] { "air" }; Entities.VALUE = new string[] { "feet" }; break; case "turn off the ac": Entities.SETTING = new string[] { "ac" }; Entities.VALUE = new string[] { "off" }; break; case "increase forward automatic braking to 50%": Entities.SETTING = new string[] { "forward automatic braking" }; Entities.VALUE = new string[] { "increase" }; Entities.AMOUNT = new string[] { "50" }; Entities.UNIT = new string[] { "%" }; break; case "i'm feeling cold": Entities.VALUE = new string[] { "cold" }; Intents.Add(Intent.VEHICLE_SETTINGS_DECLARATIVE, intentScore); break; case "it's feeling cold in the back": Entities.SETTING = new string[] { "back" }; Entities.VALUE = new string[] { "cold" }; Intents.Add(Intent.VEHICLE_SETTINGS_DECLARATIVE, intentScore); break; case "adjust equalizer": Entities.SETTING = new string[] { "equalizer" }; break; case "change pedestrian detection": Entities.SETTING = new string[] { "pedestrian detection" }; break; default: return(Intent.None, 0.0); } // Default is setting change apart from declarative used occasionally above if (Intents.Count == 0) { Intents.Add(Intent.VEHICLE_SETTINGS_CHANGE, intentScore); } return(TopIntent()); }
public QueryResult ToQueryResult() { return(new QueryResult { Entities = Entities.Select(qr => qr.ToEntity()).ToList(), Intents = Intents.Select(i => i.ToIntent()).ToList() }); }