private async Task <IntentItem> CreateIntentItem(IntentItem item) { string appId = Environment.GetEnvironmentVariable("LuisAppId"); string subscriptionKey = Environment.GetEnvironmentVariable("LuisSubscriptionKey"); bool preview = true; var client = new LuisClient(appId, subscriptionKey, preview); LuisResult res = await client.Predict(item.Utterance); var processingResult = new ProcessingResult(); List <string> entitiesNames = new List <string>(); var entities = res.GetAllEntities(); foreach (Entity entity in entities) { processingResult.Entities.Add(entity.Name, entity.Value); } processingResult.Confidence = res.TopScoringIntent.Score; processingResult.Intent = res.TopScoringIntent.Name; processingResult.IsFromCache = false; item.Intent = processingResult.Intent; item.JsonEntities = JsonConvert.SerializeObject(processingResult.Entities); return(item); }
/// <summary> /// Static constructor to initialize our LUIS client. /// LuisClient is using HttpClient and that is meant to be used as a single instance, /// so let's keep this static. /// </summary> static LuisHelper() { var appId = ConfigurationManager.AppSettings["LuisClientAppId"]; var appKey = ConfigurationManager.AppSettings["LuisClientAppKey"]; _luisClient = new LuisClient(appId, appKey); }
//private static TextProcessor instance = null; public TextProcessor(string luisAppId, string luisSubscriptionKey, string mobileAppUri) //:base() { this.mobileAppUri = mobileAppUri; this.luisAppId = luisAppId; this.luisSubscriptionKey = luisSubscriptionKey; MobileService = new MobileServiceClient(mobileAppUri); intentTable = MobileService.GetSyncTable <IntentItem>(); telemetryTable = MobileService.GetSyncTable <TelemetryItem>(); try { var t = Task.Run(async() => { await InitLocalStoreAsync(); }); t.Wait(); } // Case of offline start // TODO imporve error handling catch (Exception ex) { Debug.WriteLine(ex); } bool preview = true; _client = new LuisClient(luisAppId, luisSubscriptionKey, preview); }
private async Task <LuisResult> Predict(string appId, string subscriptionKey, string textToPredict) { bool _preview = true; LuisClient client = new LuisClient(appId, subscriptionKey, _preview); return(await client.Predict(textToPredict).ConfigureAwait(false)); }
public async Task Predict() { LuisClient client = new LuisClient(_appId, _subscriptionKey, _preview); LuisResult res = await client.Predict(_textToPredict); processRes(res); }
static void Main(string[] args) { LuisClient luisClient = new LuisClient("", ""); while (true) { // Ler o texto a ser reconhecido Console.Write("Escreva algo: "); string input = Console.ReadLine().Trim(); if (input.ToLower() == "exit") { break; } else { if (input.Length > 0) { // Faz a requisição e deserializa LuisResult result = luisClient.Predict(input).Result; // Tomada de decisão HandleUserIntent(result); } } } }
public static bool HitLuis(string lineMessage, out string message) { message = string.Empty; //return false; //建立LuisClient var lc = new LuisClient(LuisAppId, LuisAppKey, true, Luisdomain); //Call Luis API 查詢 var ret = lc.Predict(lineMessage).Result; if (ret.Intents.Count() <= 0) { return(false); } else if (ret.TopScoringIntent.Name == "None") { return(false); } else { message = $"OK,我知道你想 '{ret.TopScoringIntent.Name}'"; if (ret.Entities.Count > 0) { message += $"對象 {ret.Entities.FirstOrDefault().Value.FirstOrDefault().Value}"; } return(true); } }
async Task <MatchedMessage> PredictWithLUIS(List <Tweet> messages, string username, string input) { bool _preview = true; LuisClient client = new LuisClient(_luisAppId, _luisSubscriptionKey, _preview); LuisResult res = await client.Predict(input); return(ProcessLUISMessage(messages, username, res)); }
/// <summary> /// Constructs a new utterance prediction object, initializing a LUIS Client to predict utterances. /// </summary> public UtterancePrediction() { var resources = ResourceLoader.GetForCurrentView("/RobbieSenses/Resources"); var luisAppId = resources.GetString("LUISAppID"); var luisAppKey = resources.GetString("LUISAppKey"); luisClient = new LuisClient(luisAppId, luisAppKey); }
/// <summary> /// Makes sure that the client has been created. /// </summary> private void EnsureClient() { this.AssertEnabled(); if (client == null) { client = new LuisClient(AppId, AppKey, Verbose, Domain); } }
/// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { if (activity.Type == ActivityTypes.Message) { ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); LuisMessage luisMessage = await LuisClient.ParseMessage(activity.Text); string replyMessage = string.Empty; if (luisMessage.intents.Count() > 0) { switch (luisMessage.intents[0].intent) { case "GetFlightInfo": FlightInformation flightInfo = await FlightAwareClient.GetFlightData( ConfigurationManager.AppSettings["FlightAwareUserName"], ConfigurationManager.AppSettings["FlightAwareApiKey"], luisMessage.entities[0].entity); replyMessage = FlightAwareClient.GetFlightStatus(flightInfo); break; case "GetDepartureStatus": replyMessage = luisMessage.intents[0].intent; break; case "GetArrivalStatus": replyMessage = luisMessage.intents[0].intent; break; case "RepeatPrevious": replyMessage = luisMessage.intents[0].intent; break; default: replyMessage = "I didn't catch that."; break; } } else { replyMessage = "I didn't catch that."; } // return our reply to the user Activity reply = activity.CreateReply(replyMessage); await connector.Conversations.ReplyToActivityAsync(reply); } else { HandleSystemMessage(activity); } var response = Request.CreateResponse(HttpStatusCode.OK); return(response); }
public static void TestLuis() { LuisClient client = new LuisClient(); string query = "周末天气好吗"; LUInfo result = client.Query(query); Console.WriteLine(result.ToString()); }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result) { var activity = await result as Activity; LuisClient luis = new LuisClient("", ""); LuisResult luisResult = await luis.Predict(activity.Text); await HandleLuisIntentAsync(context, luisResult); }
private async Task GetLuisEntities(string LuisInput) { var entity = new Microsoft.Cognitive.LUIS.Entity(); Debug.Log(entity.GetHashCode()); var client = new LuisClient(AppId, AppKey, Verbose, Domain); var luisResults = await client.Predict(LuisInput); ProcessResults(luisResults); }
/// <summary> /// Makes sure that the client has been created. /// </summary> private void EnsureClient() { if (client == null) { if (!this.enabled) { throw new InvalidOperationException($"Attempting to connect to LUIS but {nameof(LuisManager)} is not enabled."); } client = new LuisClient(AppId, AppKey, Verbose, Domain); } }
private string GetLuisAnswer(string text, out double score) { string LUIS_APP_ID = ConfigurationManager.AppSettings["LuisApplicationId"]; string LUIS_KEY = ConfigurationManager.AppSettings["LuisSubscriptionKey"]; LuisClient luisClient = new LuisClient(LUIS_APP_ID, LUIS_KEY); var resultLuis = luisClient.Predict(text).Result; var luisOriginalIntent = resultLuis.TopScoringIntent.Name; score = resultLuis.TopScoringIntent.Score; return(luisOriginalIntent.Replace('-', ' ')); }
public async Task Reply() { string _appId = txtAppId.Text; string _subscriptionKey = ((MainWindow)Application.Current.MainWindow).SubscriptionKey; bool _preview = true; string _textToPredict = txtPredict.Text; LuisClient client = new LuisClient(_appId, _subscriptionKey, _preview); LuisResult res = await client.Reply(prevResult, _textToPredict); processRes(res); ((MainWindow)Application.Current.MainWindow).Log("Replied successfully."); }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result) { var activity = await result as Activity; var client = new LuisClient(modelId, subscriptionKey, domain); using (var router = IntentRouter.Setup <IntentHandlers>(client)) { var handled = await router.Route(activity.Text, this); } context.Wait(MessageReceivedAsync); }
static void Main(string[] args) { var dm = new DBManager(); dm.CreateDB(); dm.ShowRecords(); var id = ConfigurationManager.AppSettings["id"].ToString(); var subscriptionKey = ConfigurationManager.AppSettings["subscription-key"].ToString(); var client = new LuisClient(id, subscriptionKey); for (;;) { WriteLine("Please Enter Some Query"); var query = ReadLine(); if (string.IsNullOrEmpty(query)) { continue; } var response = client.Query(query); if (response == null) { WriteLine("Not able to understand the query you entered"); continue; } var maxScoreIntent = response.Intents.ToList().Max(x => x.score); var maxScoreEntity = response.Entities.ToList().Max(x => x.score); var intent = response.Intents.ToList().First(x => x.score == maxScoreIntent); var entity = response.Entities.ToList().First(x => x.score == maxScoreEntity); var str = entity.entity; WriteLine(str); MapToQuery(intent.intent, entity.entity); WriteLine(dbQuery); dm.Execute(dbQuery); //Get the Query to be executed //CSharpScript.EvaluateAsync<string>() //WriteLine("Query: " + response.Query); //response.Intents.ToList().ForEach(x => WriteLine(x.intent + Environment.NewLine + x.score)); //response.Entities.ToList().ForEach(x => WriteLine(x.entity + Environment.NewLine + x.score)); } }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result) { var msg = (await result as Activity).Text; var cmdMatch = new Regex("cmd:\\/\\/(?<commandName>.*)\\/(?<commandParam>.*)").Match(msg); if (cmdMatch.Success) { // explicit command var commandName = cmdMatch.Groups["commandName"].Value; var commandParam = cmdMatch.Groups["commandParam"].Value; if (commandName == "register") { var dialog = ServiceLocator.EventRegistration; dialog.EventId = commandParam; context.Call(dialog, ResumeAfterRegisterDialogCompleted); } else { await context.SayAsync($"unknown command {msg}"); } } else { // delegate to luis LuisResult luisResult = null; await context.Activity.DoWithTyping(async() => { var luisId = ConfigurationManager.AppSettings["luisId"]; var luisKey = ConfigurationManager.AppSettings["luisKey"]; if (string.IsNullOrEmpty(luisId)) { throw new Exception(@"populate appsetting <add key=""luisId"" value=""""/>"); } if (string.IsNullOrEmpty(luisKey)) { throw new Exception(@"populate appsetting <add key=""luisKey"" value=""""/>"); } var luisClient = new LuisClient(luisId, luisKey); luisResult = await luisClient.Predict(msg); }); if (luisResult.TopScoringIntent.Name == "discover") { var month = luisResult.Entities.FirstOrDefault(x => x.Key == "builtin.datetimeV2.daterange").Value?.FirstOrDefault(); context.Call(new DiscoverDialog(month?.Value), ResumeAfterDiscoverDialogCompleted); } } }
private static async void GetLuisUsingLuis() { var luisClient = new LuisClient(LuisAppId, SubscriptionKey, true); var res = await luisClient.Predict(QueryString); var outputMsg = $@"Intent [{res.Intents.FirstOrDefault().Name}, {res.Intents.FirstOrDefault().Score}] {Environment.NewLine}"; foreach (var resEntity in res.Entities) { outputMsg += $@"Entity: [{resEntity.Value.FirstOrDefault().Name}, {resEntity.Value.FirstOrDefault().Score} ] {Environment.NewLine}"; } Console.Write(outputMsg); }
public async Task AzureLuisClientExamples() { var options = new AzureCloudOptions(null, "A", "B", "C"); var handler = new MockHttpMessageHandler() .Set("[{ \"id\": 533303694, \"text\": \"good day\", \"intentLabel\": \"Hello\" }]", "application/json"); var client = new LuisClient(() => handler, options); var result = await client.GetExamplesAsync(); Assert.AreEqual(533303694, result[0].Id); Assert.AreEqual("good day", result[0].Text); Assert.AreEqual("Hello", result[0].IntentLabel); }
/// <summary> /// Recognizes the text. /// </summary> /// <param name="luisClient">The luis client.</param> /// <param name="text">The text.</param> /// <returns></returns> private LanguageUnderstandingResult RecognizeText(string text) { var luisClient = new LuisClient(appId, appKey); var result = luisClient.Predict(text).Result; var intent = result.TopScoringIntent; Dictionary <string, string> entities = new Dictionary <string, string>(); foreach (var entity in result.Entities) { entities.Add(entity.Key, entity.Value.First().Value); } return(new LanguageUnderstandingResult(intent.Name, entities)); }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result) { try { if (await result is Activity activity) { var client = new LuisClient(WebConfigurationManager.AppSettings["LuisAppId"], WebConfigurationManager.AppSettings["LuisSubscriptionKey"]); if (string.IsNullOrEmpty(activity.Text)) { await SayAnswerAsync(context, MessagesService.GetLaunchMessage()); return; } var prediction = await client.Predict(activity.Text); var predictedIntent = prediction.TopScoringIntent.Name; switch (predictedIntent) { case HelloIntent: await SayAnswerAsync(context, MessagesService.GetLaunchMessage()); break; case HelpIntent: await SayAnswerAsync(context, MessagesService.GetHelpMessage()); break; case QuoteIntent: await HandleQuoteIntentAsync(context); break; default: await SayAnswerAsync(context, MessagesService.GetHelpMessage()); break; } } } catch (Exception ex) { await context.PostAsync($"{MessagesService.GetErrorMessage()} {Environment.NewLine} {ex.Message}"); context.Wait(MessageReceivedAsync); } }
public async Task AzureLuisConnector_Deconstruct() { var options = new AzureCloudOptions(null, "A", "B", "C"); var handler = new MockHttpMessageHandler() .Set("{ \"query\": \"Test\", \"topScoringIntent\": { \"intent\": \"A\", \"score\": 0.75, }, \"intents\": [ { \"intent\": \"A\", \"score\": 0.75 }, { \"intent\": \"None\", \"score\": 0.0168218873 }], \"entities\": [{ \"entity\": \"bob\", \"type\": \"Name\", \"startIndex\": 0, \"endIndex\": 8, \"score\": 0.573899543 }] }", "application/json"); var client = new LuisClient(() => handler, options); var connector = new AzureLuisConnector(client); var info = await connector.DeconstructAsync("TT"); Assert.AreEqual("Test", info.TextSentanceChunk); Assert.AreEqual(0.75, info.ConfidenceRating); Assert.AreEqual("bob", info.Entities["Name"].FirstOrDefault()); }
public LuisRecognizerMiddleware(string appId, string appKey) : base() { if (string.IsNullOrWhiteSpace(appId)) { throw new ArgumentNullException(nameof(appId)); } if (string.IsNullOrWhiteSpace(appKey)) { throw new ArgumentNullException(nameof(appKey)); } _luisClient = new LuisClient(appId, appKey); SetupOnRecognize(); }
public PizzaBotPage() { this.InitializeComponent(); _luisClient = new LuisClient("2fa72221-4611-4795-90b8-ec3f0396fc53", "5fdfc85a71e34146850e0ff08849520d"); _speechRecognizer = new SpeechRecognizer(); _speechRecognizer.Timeouts.EndSilenceTimeout = new TimeSpan(24, 0, 0); _speechRecognizer.Timeouts.InitialSilenceTimeout = new TimeSpan(24, 0, 0); _speechRecognizer.HypothesisGenerated += _speechRecognizer_HypothesisGenerated; _speechRecognizer.StateChanged += _speechRecognizer_StateChanged; StartListeningAsync(); }
private async Task LuisMessageReceivedAsync(IDialogContext context, IAwaitable <object> result) { var activity = result as Activity; var luisClient = new LuisClient(ConfigurationManager.AppSettings["LuisAppId"], ConfigurationManager.AppSettings["LuisSubKey"], domain: "westus"); var luisResult = await luisClient.Predict(activity.Text); switch (luisResult.Intents[0].Name) { case "Help": // ヘルプメニュー表示 await context.PostAsync($"【ヘルプ】(score: " + luisResult.Intents[0].Score + ") \n\n" + "何かお困りですか? 検索したい内容を文章 またはキーワードで入れてください。\n\n" + // DB を直接 AzureSearch で検索する場合 "複数の単語を空白で区切って入力すると、キーワード検索になります。" ); context.Wait(MessageReceivedAsync); break; case "SearchQA": // FAQ検索 await context.PostAsync($"【FAQ検索】(score: " + luisResult.Intents[0].Score + ")"); // AzureSearch で検索 //await context.Forward(new SearchFaqDbDialog(), SearchFaqDBResumeAfter, activity); // QnAMaker で検索 await context.Forward(new SearchQnADialog(), SearchQnAResumeAfter, activity); break; case "ListFAQ": //FAQリスト表示 await context.PostAsync($"【FAQリスト表示 - 未実装】(score: " + luisResult.Intents[0].Score + ")"); //未実装 context.Wait(MessageReceivedAsync); break; default: // case "Greeting", "None" // 初期メッセージ表示 await context.PostAsync($"【初期メニュー】(score: " + luisResult.Intents[0].Score + ") \n\n" + "こんにちは。FAQ Bot です。\n\n" + "何かお困りですか? 検索したい内容を文章 またはキーワードで入れてください。"); context.Wait(MessageReceivedAsync); break; } }
private async void ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionResultGeneratedEventArgs args) { string speechResult = args.Result.Text; Debug.WriteLine($"Heared: {speechResult}"); Debug.WriteLine($"Text: {speechResult}"); if (speechResult.ToLower().StartsWith("hey")) { LuisClient client = new LuisClient(_appId, _luiskey); LuisResult result = await client.Predict(speechResult); HandleLuisResult(result); Debug.WriteLine($"LUIS Result: {result.Intents.First().Name} {string.Join(",", result.Entities.Select(a => $"{a.Key}:{a.Value.First().Value}"))}"); } }
static void Main(string[] args) { //var query = new EnglishQuery(); //query.Predict("what is the weather in tokyo").Wait(); //var result = query.Result; var objWeather = new WeatherApp(); var luisClient = new LuisClient("f3a00b57-72d0-4817-ad66-f1e2cb739d62", "0412598c6e17402280a6d10d02b0321d", true); IntentRouter router = IntentRouter.Setup <WeatherApp>(luisClient); Task <bool> taskResult = router.Route("weather in delhi", objWeather); taskResult.Wait(); Console.WriteLine("Task Completed"); Console.ReadLine(); }