static async Task RecognizeUserInput() { while (true) { // Read the text to recognize Console.WriteLine("Enter the text to recognize:"); string input = Console.ReadLine().Trim(); if (input.ToLower() == "exit") { // Close application if user types "exit" break; } else { if (input.Length > 0) { // Create client with SuscriptionKey and AzureRegion var client = new LUISRuntimeClient(new Uri(EndPoint), new ApiKeyServiceClientCredentials(SubscriptionKey)); // Predict var result = await client.Prediction.ResolveAsync(ApplicationId, input); // Print result var json = JsonConvert.SerializeObject(result, Formatting.Indented); Console.WriteLine(json); Console.WriteLine(); } } } }
static async Task <LuisResult> GetPrediction() { // Use Language Understanding or Cognitive Services key // to create authentication credentials var endpointPredictionkey = "<REPLACE-WITH-YOUR-KEY>"; var credentials = new ApiKeyServiceClientCredentials(endpointPredictionkey); // Create Luis client and set endpoint // region of endpoint must match key's region var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { }); luisClient.Endpoint = "https://<REPLACE-WITH-YOUR-KEY-REGION>.api.cognitive.microsoft.com"; // Set query values // public Language Understanding Home Automation app var appId = "df67dcdb-c37d-46af-88e1-8b97951ca1c2"; // query specific to home automation app var query = "turn on the bedroom light"; // common settings for remaining parameters Double?timezoneOffset = null; var verbose = true; var staging = false; var spellCheck = false; String bingSpellCheckKey = null; var log = false; // Create prediction client var prediction = new Prediction(luisClient); // get prediction return(await prediction.ResolveAsync(appId, query, timezoneOffset, verbose, staging, spellCheck, bingSpellCheckKey, log, CancellationToken.None)); }
public static async Task TestLuisApiKeyAsync(string key, string apiEndpoint) { bool isUri = !string.IsNullOrEmpty(apiEndpoint) ? Uri.IsWellFormedUriString(apiEndpoint, UriKind.Absolute) : false; if (!isUri) { throw new ArgumentException("Invalid URI"); } else { var luisClient = new LUISRuntimeClient(new ApiKeyServiceClientCredentials(key)); luisClient.Endpoint = apiEndpoint; try { // pass an invalid app ID just to see what kind of exception we get LuisResult result = await luisClient.Prediction.ResolveAsync("LuisAppID", "Hello"); } catch (Exception ex) { // 'BadRequest' exception is expected for the attempted call when the key is valid if (ex.Message != "Operation returned an invalid status code 'BadRequest'") { throw ex; } } // LUIS App to be tested separately } }
/// <summary> /// The main program entry point. /// </summary> /// <param name="args">The command-line arguments.</param> private static void Main(string[] args) { // create the LUIS client object var client = new LUISRuntimeClient(new ApiKeyServiceClientCredentials(LUIS_KEY)) { Endpoint = LUIS_API }; // start the query loop Console.WriteLine("Hi Mark, how can I help you?"); Console.WriteLine("(you can type 'exit' at any time to leave this conversation)"); while (true) { // get the user query Console.Write(">> "); var query = Console.ReadLine(); // abort if the user typed 'exit' if (query.ToLower() == "exit") { return; } // ****************** // ADD YOUR CODE HERE // ****************** } }
static async Task <LuisResult> GetPrediction() { var endpointPredictionkey = "5cfeca8bb6734baf81b8c65f71635515"; var credentials = new ApiKeyServiceClientCredentials(endpointPredictionkey); var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { }); luisClient.Endpoint = "https://westus.api.cognitive.microsoft.com"; // public Language Understanding Home Automation app var appId = "344b9f85-5975-4edc-9e66-56cdc7013b9a"; // query specific to home automation app var query = "probando"; // common settings for remaining parameters Double?timezoneOffset = 0; var verbose = true; var staging = true; var spellCheck = false; String bingSpellCheckKey = null; var log = true; // Create prediction client var prediction = new Prediction(luisClient); // get prediction return(await prediction.ResolveAsync(appId, query, timezoneOffset, verbose, staging, spellCheck, bingSpellCheckKey, log, CancellationToken.None)); }
public async Task <UserQuery> DetectIntent(string message, string sessionId) { var credentials = new ApiKeyServiceClientCredentials(PredictionSubscriptionKey); var runtimeClient = new LUISRuntimeClient(credentials) { Endpoint = PredictionEndpoint }; var request = new PredictionRequest { Query = message }; var response = await runtimeClient.Prediction.GetSlotPredictionAsync(Guid.Parse(AppId), SlotName, request); var prediction = response.Prediction; var isFallback = prediction.Intents.Values.Max(i => i.Score) < 0.6 || prediction.TopIntent == "None"; return(new UserQuery { IntentName = prediction.TopIntent, IsFallback = isFallback, Parameters = prediction.Entities.ToDictionary( entity => entity.Key, entity => entity.Value is Newtonsoft.Json.Linq.JArray arr ? string.Join(',', arr.Select(s => s.ToString())) : entity.Value), AllRequiredParamsPresent = true, FulfillmentText = isFallback ? FallbackMessage : null, Timestamp = DateTime.UtcNow.Ticks });
private async Task <LuisResult> GetPrediction(String message) { var endpointPredictionkey = _config.GetSection("LuisConfig:endpointPredictionkey").Value; var credentials = new ApiKeyServiceClientCredentials(endpointPredictionkey); var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { }); luisClient.Endpoint = _config.GetSection("LuisConfig:Endpoint").Value; // public Language Understanding Home Automation app var appId = _config.GetSection("LuisConfig:appId").Value; // query specific to home automation app var query = message; // common settings for remaining parameters Double?timezoneOffset = _config.GetSection("LuisConfig").GetValue <int>("timezoneOffset"); var verbose = _config.GetSection("LuisConfig").GetValue <bool>("verbose"); var staging = _config.GetSection("LuisConfig").GetValue <bool>("staging"); var spellCheck = _config.GetSection("LuisConfig").GetValue <bool>("spellCheck"); var bingSpellCheckKey = _config.GetSection("LuisConfig:bingSpellCheckKey").Value; var log = _config.GetSection("LuisConfig").GetValue <bool>("log"); // Create prediction client var prediction = new Prediction(luisClient); // get prediction return(await prediction.ResolveAsync(appId, query, timezoneOffset, verbose, staging, spellCheck, bingSpellCheckKey, log, CancellationToken.None)); }
public static IServiceCollection AddLUIS(this IServiceCollection services, IConfiguration configuration) { services.Configure <LuisSettings>(configuration.GetSection("Luis")); var settings = services.BuildServiceProvider().GetRequiredService <IOptions <LuisSettings> >()?.Value ?? throw new ArgumentNullException(nameof(LuisSettings)); services.AddScoped <ILUISAuthoringClient>(_ => { var credentials = new ApiKeyServiceClientCredentials(settings.AuthoringKey); var client = new LUISAuthoringClient(credentials); client.Endpoint = settings.AuthoringEndpoint; return(client); }) .AddScoped <ILUISRuntimeClient>(_ => { var credentials = new ApiKeyServiceClientCredentials(settings.SubscriptionKey); var client = new LUISRuntimeClient(credentials); client.Endpoint = settings.RuntimeEndpoint; return(client); }); return(services); }
private async Task <LuisResult> LuisRequest(string query) { var endpointPredictionkey = "YOUR_KEY"; var credentials = new ApiKeyServiceClientCredentials(endpointPredictionkey); var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { }); luisClient.Endpoint = "https://westus.api.cognitive.microsoft.com/"; // public Language Understanding Home Automation app var appId = "YOUR_APP_ID"; // query specific to home automation app // common settings for remaining parameters Double?timezoneOffset = null; var verbose = true; var staging = false; var spellCheck = false; String bingSpellCheckKey = null; var log = false; // Create prediction client var prediction = new Prediction(luisClient); // get prediction return(await prediction.ResolveAsync(appId, query, timezoneOffset, verbose, staging, spellCheck, bingSpellCheckKey, log, CancellationToken.None)); }
private static async Task <ChatbotModel.IntentInfo> RecognizeUserInput(string phrase) { string input = phrase.Trim(); if (input.Length > 0) { // Create client with SuscriptionKey and AzureRegion var client = new LUISRuntimeClient(new ApiKeyServiceClientCredentials(SubscriptionKey)); client.Endpoint = EndPoint; // Predict try { var result = await client.Prediction.ResolveAsync(ApplicationId, input); return(GetIntentInfoFromLUISResponse(result)); } catch (Exception ex) { Debug.WriteLine("---------------------------" + ex.Message); returnResponse = ex + "\nSomething went wrong. Please Make sure your app is published and try again.\n"; } } return(null); }
static void Main(string[] args) { LUISRuntimeClient luisClient = new LUISRuntimeClient( new ApiKeyServiceClientCredentials(ConfigurationManager.AppSettings["LUIS.SubscriptionKey"])) { Endpoint = "https://westus.api.cognitive.microsoft.com/" }; while (true) { Console.Write("Input: "); LuisResult luisResult = luisClient.Prediction.ResolveAsync(ConfigurationManager.AppSettings["LUIS.ApplicationId"], Console.ReadLine()).Result; if (luisResult.TopScoringIntent != null) { Console.WriteLine($"TopScoringIntent: {luisResult.TopScoringIntent.Intent} - Score: {luisResult.TopScoringIntent.Score}"); } if (luisResult.Intents != null) { foreach (IntentModel luisIntent in luisResult.Intents) { Console.WriteLine($"TopScoringIntent: {luisIntent.Intent} - Score: {luisIntent.Score}"); } } } }
private void Form1_Load(object sender, EventArgs e) { try { SpeechFactory speechFactory = SpeechFactory.FromSubscription(speechKey, speechRegion); // 设置识别中文 recognizer = speechFactory.CreateSpeechRecognizer("zh-CN"); // 挂载识别中的事件 // 收到中间结果 recognizer.IntermediateResultReceived += Recognizer_IntermediateResultReceived; // 收到最终结果 recognizer.FinalResultReceived += Recognizer_FinalResultReceived; // 发生错误 recognizer.RecognitionErrorRaised += Recognizer_RecognitionErrorRaised; // 启动语音识别器,开始持续监听音频输入 recognizer.StartContinuousRecognitionAsync(); // 设置意图预测器 LUISRuntimeClient client = new LUISRuntimeClient(new ApiKeyServiceClientCredentials(luisKey)); client.Endpoint = luisEndpoint; intentPrediction = new Prediction(client); } catch (Exception ex) { Log(ex.Message); } }
private static async Task <PredictionResponse> GetIntentAndEntities(string messageText) { var credentials = new ApiKeyServiceClientCredentials(_luisPredictionKey); var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { }) { Endpoint = _luisBaseUrl }; var requestOptions = new PredictionRequestOptions { DatetimeReference = DateTime.Parse("2019-01-01"), PreferExternalEntities = true }; var predictionRequest = new PredictionRequest { Query = messageText, Options = requestOptions }; // get prediction return(await luisClient.Prediction.GetSlotPredictionAsync( Guid.Parse(_luisAppId), slotName : "production", predictionRequest, verbose : true, showAllIntents : true, log : true)); }
private PredictionResponse GetPrediction(string utterance) { var language = GuessLanguage(utterance); var appId = GetAppId(language); var credentials = new ApiKeyServiceClientCredentials(Config.PredictionKey); using (var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { }) { Endpoint = Config.Endpoint }) { var requestOptions = new PredictionRequestOptions { DatetimeReference = DateTime.Now, //DateTime.Parse("2019-01-01"), PreferExternalEntities = true }; var predictionRequest = new PredictionRequest { Query = utterance, Options = requestOptions }; // get prediction return(luisClient.Prediction.GetSlotPredictionAsync( Guid.Parse(appId), slotName: "staging", predictionRequest, verbose: true, showAllIntents: true, log: true).Result); } }
public async static Task Main(string[] args) { var cli = new LUISRuntimeClient(new ApiKeyServiceClientCredentials(apiKey)) { BaseUri = new Uri("https://westus.api.cognitive.microsoft.com/luis/v2.0") }; while (true) { var utterance = Console.ReadLine(); var prediction = await cli.Prediction.ResolveWithHttpMessagesAsync(modelId, utterance); if (prediction.Body.TopScoringIntent.Intent == "check-room-availability") { var bookingRequest = prediction.Body.ParseLuisBookingRequest(); Console.WriteLine($"check-room-availability: {bookingRequest}"); } else if (prediction.Body.TopScoringIntent.Intent == "discover-rooms") { Console.WriteLine($"discover-rooms"); } else { Console.WriteLine($"unknown"); } } }
private void Form1_Load(object sender, EventArgs e) { try { SpeechConfig config = SpeechConfig.FromSubscription(speechKey, speechRegion); config.SpeechRecognitionLanguage = "zh-cn"; recognizer = new SpeechRecognizer(config); // 挂载识别中的事件 // 收到中间结果 recognizer.Recognizing += Recognizer_Recognizing; // 收到最终结果 recognizer.Recognized += Recognizer_Recognized; // 发生错误 recognizer.Canceled += Recognizer_Canceled; // 启动语音识别器,开始持续监听音频输入 recognizer.StartContinuousRecognitionAsync(); // 设置意图预测器 LUISRuntimeClient client = new LUISRuntimeClient(new ApiKeyServiceClientCredentials(luisKey)); client.Endpoint = luisEndpoint; intentPrediction = new Prediction(client); } catch (Exception ex) { Log(ex.Message); } }
public static void Main(string[] args) { var key = "13ba3bfb329b48d98645c4519d8b39b8"; var luisClient = new LUISRuntimeClient (new ApiKeyServiceClientCredentials(key), new System.Net.Http.DelegatingHandler[] { }); luisClient.Endpoint = "https://westus.api.cognitive.microsoft.com"; string appId = "7998ce4d-827c-44b7-a0f7-2632d06252a4"; while (true) { Console.WriteLine("Enter some text..."); var input = Console.ReadLine(); var prediction = new Prediction(luisClient); var result = prediction.ResolveAsync(appId, input).Result; switch (result.TopScoringIntent.Intent) { case "GetJobInfo": Console.WriteLine($"Matches the GetJobInfo intent with a score of {result.TopScoringIntent.Score}"); break; case "ApplyForJob": Console.WriteLine($"Matches the ApplyForJob intent with a score of {result.TopScoringIntent.Score}"); break; default: Console.WriteLine($"Matches the None intent with a score of {result.TopScoringIntent.Score}"); break; } } }
static async Task Main(string[] args) { const string PREDICTION_KEY = "PONER AQUI LA CLAVE DEL RECURSO DE PREDICCION DE LUIS"; const string ENDPOINT = "PONER AQUI LA URL DEL ENDPOINT DE PREDICCION DE LUIS"; Guid APPID = new Guid("PONER AQUI EL IDENTIFICADOR DE LA APLICACION DE LUIS"); string slot = "Staging"; //Staging o Production LUISRuntimeClient client = new LUISRuntimeClient(new ApiKeyServiceClientCredentials(PREDICTION_KEY)) { Endpoint = ENDPOINT }; while (true) { //Realizamos la petición a la API Console.Write("Introduce la orden: "); string pregunta = Console.ReadLine(); PredictionRequest peticion = new PredictionRequest { Query = pregunta }; PredictionResponse prediccion = await client.Prediction.GetSlotPredictionAsync(APPID, slot, peticion); //Procesamos el resultado Console.WriteLine($"Acción: {prediccion.Prediction.TopIntent}"); foreach (var entidad in prediccion.Prediction.Entities) { Console.WriteLine($"{entidad.Key}: {JsonConvert.DeserializeObject<List<string>>(entidad.Value.ToString())[0]}"); } Console.WriteLine(); } }
private ILUISRuntimeClient GetClient(DelegatingHandler handler, string subscriptionKey = subscriptionKey) { var client = new LUISRuntimeClient(new ApiKeyServiceClientCredentials(subscriptionKey), handlers: handler); client.Endpoint = "https://westus.api.cognitive.microsoft.com"; return(client); }
protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken) { var appId = "a4fe9ae0-be39-4837-b2d9-ed3ca0b33af2"; var key = "127183aa64af4de893cc822599f2a4ec"; var predictionResourceName = "luisgroup"; var predictionEndpoint = $"https://{predictionResourceName}.cognitiveservices.azure.com/"; var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(key); var runtimeClient = new LUISRuntimeClient(credentials) { Endpoint = predictionEndpoint }; var gAppId = new Guid(appId); var request = new PredictionRequest { Query = "add tomatoes to rakata1" }; var predi = await runtimeClient.Prediction.GetSlotPredictionAsync(gAppId, "Production", request); var topIntent = predi.Prediction.TopIntent; switch (topIntent) { /* * aqui estara todas las opciones que ahorita se ocupan de luis */ } }
public LuisNLP(IConfiguration config) { this.config = config; this.credentials = new ApiKeyServiceClientCredentials(config["Luis.AuthoringKey"]); this.luisClient = new LUISRuntimeClient(credentials); this.luisClient.Endpoint = config["Luis.Endpoint"]; this.prediction = new Prediction(luisClient); }
public async Task <LuisResult> ExtractEntitiesFromLUIS(string textToAnalyze) { var method = "ExtractEntitiesFromLUIS"; try { _logger.LogInformation(string.Format("{0} - {1}", method, "IN")); _logger.LogInformation(string.Format("{0} - {1}", method, "Getting credentials.")); var subscriptionKey = Environment.GetEnvironmentVariable("LUISAPISubscriptionKey"); if (subscriptionKey == null) { throw new System.ArgumentNullException("subscriptionKey"); } var credentials = new ApiKeyServiceClientCredentials(Environment.GetEnvironmentVariable("LUISAPISubscriptionKey")); _logger.LogInformation(string.Format("{0} - {1}", method, "Creating client.")); var client = new LUISRuntimeClient(credentials); _logger.LogInformation(string.Format("{0} - {1}", method, "Setting Endpoint")); client.Endpoint = "https://westeurope.api.cognitive.microsoft.com/"; _logger.LogInformation(string.Format("{0} - {1}", method, "Getting app ID.")); var appID = Environment.GetEnvironmentVariable("LUISAPPID"); if (appID == null) { throw new System.ArgumentNullException("appID"); } _logger.LogInformation(string.Format("{0} - {1}", method, "Getting Bing Subscription Key.")); var bingSubcriptionKey = Environment.GetEnvironmentVariable("BingAPISubscriptionKey"); if (bingSubcriptionKey == null) { throw new System.ArgumentNullException("bingSubcriptionKey"); } _logger.LogInformation(string.Format("{0} - {1}", method, "Predicting.")); return(await _predictionHelperService.ResolveAsync(client.Prediction, appID, textToAnalyze, null, null, false, true, bingSubcriptionKey)); } catch (ArgumentNullException arg) { _logger.LogError(string.Format("{0} - {1}", method, "Received a null argument.")); _logger.LogError(string.Format("{0} - {1}", method, "Argument:")); _logger.LogError(string.Format("{0} - {1}", method, arg.ParamName)); return(null); } catch (Exception ex) { _logger.LogError(string.Format("{0} - {1}", method, "Generic Exception.")); _logger.LogError(string.Format("{0} - {1}", method, "Message:")); _logger.LogError(string.Format("{0} - {1}", method, ex.Message)); return(null); } }
private static async Task DetectIntent(LUISRuntimeClient client, string query) { var prediction = await client.Prediction.ResolveAsync(ApplicationID, query); Console.WriteLine($"Top Intent: {prediction.TopScoringIntent.Intent}"); Console.WriteLine(); Console.WriteLine($"Entities"); prediction.Entities.ToList().ForEach(e => Console.WriteLine($" {e.Entity}")); }
// </snippet_main> // <snippet_create_client> static LUISRuntimeClient CreateClient() { var credentials = new ApiKeyServiceClientCredentials(predictionKey); var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { }) { Endpoint = predictionEndpoint }; return(luisClient); }
public LuisPredictionService(string endpoint, string key, string appId) { _appId = Guid.Parse(appId); var credentials = new ApiKeyServiceClientCredentials(key); _client = new LUISRuntimeClient(credentials) { Endpoint = endpoint }; }
private static void InitLuis() { if (Cliente == null) { var credentials = new ApiKeyServiceClientCredentials(API_KEY); Cliente = new LUISRuntimeClient(credentials) { Endpoint = ENDPOINT }; } }
public PizzaOrderRecognizer(IConfiguration configuration) { var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId"]) && !string.IsNullOrEmpty(configuration["LuisAPIKey"]) && !string.IsNullOrEmpty(configuration["LuisAPIHostName"]); if (luisIsConfigured) { appId = new Guid(configuration["LuisAppId"]); _recognizer = new LUISRuntimeClient(new ApiKeyServiceClientCredentials(configuration["LuisAPIKey"])); _recognizer.Endpoint = "https://" + configuration["LuisAPIHostName"]; } }
private MainDialog(IConfiguration configuration) : base(Id) { LuisModelId = configuration.GetValue <string>("LuisModelId"); LuisModelKey = configuration.GetValue <string>("LuisModelKey"); LuisEndpoint = configuration.GetValue <string>("LuisEndpoint"); Dialogs.Add(DialogId, new WaterfallStep[] { async(dc, args, next) => { var dialogInput = args["Value"] as string; if (string.IsNullOrEmpty(dialogInput)) { // 8. introduce bot if its the first time a user has visited await dc.Context.SendActivity($"How can I help?"); await dc.End(); } else { // 9. otherwise, run NLP in LUIS to start the "Identify" stage var cli = new LUISRuntimeClient(new ApiKeyServiceClientCredentials(LuisModelKey)) { BaseUri = new Uri(LuisEndpoint) }; var prediction = await cli.Prediction.ResolveWithHttpMessagesAsync(LuisModelId, dialogInput); if (prediction.Body.TopScoringIntent.Intent == "check-room-availability") { var bookingRequest = prediction.Body.ParseLuisBookingRequest(); var checkRoomAvailabilityDialogArgs = new Dictionary <string, object> { { "bookingRequest", bookingRequest } }; // 10. if the top scoring intent is check-room-availability, then transition into the CheckRoomAvailability dialog await dc.Begin(CheckRoomAvailabilityDialog.Id, checkRoomAvailabilityDialogArgs); } else { await dc.Context.SendActivity($"Sorry, I don't know what you mean"); await dc.End(); } } }, async(dc, args, next) => { await dc.Prompt("textPrompt", $"Please let me know if I can help with anything else"); await dc.End(); } } ); Dialogs.Add(CheckRoomAvailabilityDialog.Id, CheckRoomAvailabilityDialog.Instance); Dialogs.Add("textPrompt", new TextPrompt()); }
public AzureLUIS(string endpointUrl, string authKey, string appId, CancellationToken ct) : base(ct) { EndpointUrl = endpointUrl ?? throw new ArgumentNullException("endpointUrl"); AuthKey = authKey ?? throw new ArgumentNullException("authKey"); AppId = appId ?? throw new ArgumentNullException("appId"); var credentials = new ApiKeyServiceClientCredentials(authKey); Client = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { }); Client.Endpoint = EndpointUrl; AppId = appId; Initialized = true; }
public async Task <PredictionResponse> Process(string text) { var client = new LUISRuntimeClient(new ApiKeyServiceClientCredentials(Config.LuisSubscriptionKey)) { Endpoint = Config.LuisEndPoint }; return(await client.Prediction.GetSlotPredictionAsync( new Guid(Config.LuisAppId), "Production", //"Staging", new PredictionRequest(text))); }