public void DifferentAgentsTest()
		{
			var query = "I want pizza";

			{
				var dataService = CreateDataService();

				var request = new AIRequest(query);
				
				var response = dataService.Request(request);
				Assert.IsNotNull(response.Result);
				Assert.AreEqual("pizza", response.Result.Action);
				
			}

			{
				var config = new AIConfiguration(SUBSCRIPTION_KEY, "968235e8e4954cf0bb0dc07736725ecd", SupportedLanguage.English);
				var dataService = new AIDataService(config);
				var request = new AIRequest(query);
				
				var response = dataService.Request(request);
				Assert.IsNotNull(response.Result);
				Assert.IsTrue(string.IsNullOrEmpty(response.Result.Action));
				
			}

		}
Beispiel #2
0
		public AIResponse TextRequest(AIRequest request)
		{
			if (request == null) {
				throw new ArgumentNullException("request");
			}

			return dataService.Request(request);
		}
        public AIResponse Request(AIRequest request)
        {

            request.Language = config.Language.code;
            request.Timezone = TimeZone.CurrentTimeZone.StandardName;
            request.SessionId = sessionId;

            try
            {
                var httpRequest = (HttpWebRequest)WebRequest.Create(config.RequestUrl);
                httpRequest.Method = "POST";
                httpRequest.ContentType = "application/json; charset=utf-8";
                httpRequest.Accept = "application/json";
						
                httpRequest.Headers.Add("Authorization", "Bearer " + config.ClientAccessToken);
                httpRequest.Headers.Add("ocp-apim-subscription-key", config.SubscriptionKey);
						
                var jsonSettings = new JsonSerializerSettings
                { 
                    NullValueHandling = NullValueHandling.Ignore
                };
			
                var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);

                if (config.DebugLog)
                {
                    Debug.WriteLine("Request: " + jsonRequest);
                }

                using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
                {
                    streamWriter.Write(jsonRequest);
                    streamWriter.Close();
                }

                var httpResponse = httpRequest.GetResponse() as HttpWebResponse;
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();

                    if (config.DebugLog)
                    {
                        Debug.WriteLine("Response: " + result);
                    }

                    var aiResponse = JsonConvert.DeserializeObject<AIResponse>(result);

                    CheckForErrors(aiResponse);

                    return aiResponse;
                }

            }
            catch (Exception e)
            {
                throw new AIServiceException(e);
            }
        }
Beispiel #4
0
        public async Task<AIResponse> TextRequestAsync(AIRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            return await dataService.RequestAsync(request);
        }
		public void TextRequestTest()
		{
			var dataService = CreateDataService();

		    var request = new AIRequest("Hello");
			
			var response = dataService.Request(request);
			Assert.IsNotNull(response);
			Assert.AreEqual("greeting", response.Result.Action);
            Assert.AreEqual("Hi! How are you?", response.Result.Fulfillment.Speech);
		}
Beispiel #6
0
        public void TextRequestStart(AIRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            AIResponseList = new List<AIResponse>();
            for (var i = 0; i < m; i++)
            {
                tasks[i] = Task.Factory.StartNew(() => TextRequestExecAsync(request));
            }
        }
        public async Task TestTextRequest()
        {
            var config = new AIConfiguration(SUBSCRIPTION_KEY, ACCESS_TOKEN, SupportedLanguage.English);
            var dataService = new AIDataService(config);

            var request = new AIRequest("Hello");

            var response = await dataService.RequestAsync(request);

            Assert.IsNotNull(response);
            Assert.AreEqual("greeting", response.Result.Action);
            Assert.AreEqual("Hi! How are you?", response.Result.Fulfillment.Speech);
        }
 public override async Task<AIResponse> TextRequestAsync(AIRequest request)
 {
     return await DataService.RequestAsync(request);
 }
        public AIResponse VoiceRequest(Stream voiceStream, RequestExtras requestExtras = null)
        {
            var request = new AIRequest();
            request.Language = config.Language.code;
            request.Timezone = TimeZone.CurrentTimeZone.StandardName;
            request.SessionId = sessionId;

            if (requestExtras != null)
            {
                requestExtras.CopyTo(request);
            }

            try
            {
                var httpRequest = (HttpWebRequest)WebRequest.Create(config.RequestUrl);
                httpRequest.Method = "POST";
                httpRequest.Accept = "application/json";
				
                httpRequest.Headers.Add("Authorization", "Bearer " + config.ClientAccessToken);
                httpRequest.Headers.Add("ocp-apim-subscription-key", config.SubscriptionKey);

                var jsonSettings = new JsonSerializerSettings
                { 
                    NullValueHandling = NullValueHandling.Ignore
                };
				
                var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);

                if (config.DebugLog)
                {
                    Debug.WriteLine("Request: " + jsonRequest);
                }

                var multipartClient = new MultipartHttpClient(httpRequest);
                multipartClient.connect();

                multipartClient.addStringPart("request", jsonRequest);
                multipartClient.addFilePart("voiceData", "voice.wav", voiceStream);

                multipartClient.finish();

                var responseJsonString = multipartClient.getResponse();

                if (config.DebugLog)
                {
                    Debug.WriteLine("Response: " + responseJsonString);
                }

                var aiResponse = JsonConvert.DeserializeObject<AIResponse>(responseJsonString);

                CheckForErrors(aiResponse);

                return aiResponse;

            }
            catch (Exception e)
            {
                throw new AIServiceException(e);
            }
        }
        public async Task<AIResponse> RequestAsync(AIRequest request, CancellationToken cancellationToken)
        {

            request.Language = config.Language.code;
            request.Timezone = TimeZoneInfo.Local.StandardName;
            request.SessionId = sessionId;

            try
            {
                var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);

                if (config.DebugLog)
                {
                    Debug.WriteLine($"Request: {jsonRequest}");
                }

                var content = new HttpStringContent(jsonRequest, UnicodeEncoding.Utf8, "application/json");

                var response = await httpClient.PostAsync(new Uri(config.RequestUrl), content).AsTask(cancellationToken);
                return await ProcessResponse(response);

            }
            catch (AIServiceException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new AIServiceException(e);
            }
        }
        public async Task<AIResponse> VoiceRequestAsync(Stream voiceStream, RequestExtras requestExtras = null)
        {
            var request = new AIRequest
            {
                Language = config.Language.code,
                Timezone = TimeZoneInfo.Local.StandardName,
                SessionId = sessionId
            };

            if (requestExtras != null)
            {
                if (requestExtras.HasContexts)
                {
                    request.Contexts = requestExtras.Contexts;
                }

                if (requestExtras.HasEntities)
                {
                    request.Entities = requestExtras.Entities;
                }
            }

            try
            {
                var content = new HttpMultipartFormDataContent();
                
                var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);

                if (config.DebugLog)
                {
                    Debug.WriteLine($"Request: {jsonRequest}");
                }

                content.Add(new HttpStringContent(jsonRequest, UnicodeEncoding.Utf8, "application/json"), "request");
                content.Add(new HttpStreamContent(voiceStream.AsInputStream()), "voiceData", "voice.wav");
                
                var response = await httpClient.PostAsync(new Uri(config.RequestUrl), content);
                return await ProcessResponse(response);
            }
            catch (Exception e)
            {
                throw new AIServiceException(e);
            }
        }
        public void ResetContextsTest()
        {
            var dataService = CreateDataService();

            dataService.ResetContexts();

            {
                var aiRequest = new AIRequest("what is your name");
                var aiResponse = MakeRequest(dataService, aiRequest);
                Assert.IsTrue(aiResponse.Result.Contexts.Any(c=>c.Name == "name_question"));
                var resetSucceed = dataService.ResetContexts();
                Assert.IsTrue(resetSucceed);
            }

            {
                var aiRequest = new AIRequest("hello");
                var aiResponse = MakeRequest(dataService, aiRequest);
                Assert.IsFalse(aiResponse.Result.Contexts.Any(c=>c.Name == "name_question"));
            }
                
        }
        public void ContextsTest()
        {
            var dataService = CreateDataService();
            var aiRequest = new AIRequest("weather");

            dataService.ResetContexts();

            var aiResponse = MakeRequest(dataService, aiRequest);
            var action = aiResponse.Result.Action;
            Assert.AreEqual("showWeather", action);
            Assert.IsTrue(aiResponse.Result.Contexts.Any(c=>c.Name == "weather"));
                
        }
		public void ParametersTest()
		{
			var dataService = CreateDataService();
			
			var request = new AIRequest("what is your name");
			
			var response = MakeRequest(dataService, request);

			Assert.IsNotNull(response.Result.Parameters);
			Assert.IsTrue(response.Result.Parameters.Count > 0);

			Assert.IsTrue(response.Result.Parameters.ContainsKey("my_name"));
			Assert.IsTrue(response.Result.Parameters.ContainsValue("Sam"));

			Assert.IsNotNull(response.Result.Contexts);
			Assert.IsTrue(response.Result.Contexts.Length > 0);
			var context = response.Result.Contexts[0];

			Assert.IsNotNull(context.Parameters);
			Assert.IsTrue(context.Parameters.ContainsKey("my_name"));
			Assert.IsTrue(context.Parameters.ContainsValue("Sam"));
		}
 private async Task<AIResponse> MakeRequestAsync(AIDataService service, AIRequest request)
 {
     var aiResponse = await service.RequestAsync(request);
     Assert.IsNotNull(aiResponse);
     Assert.IsFalse(aiResponse.IsError);
     Assert.IsFalse(string.IsNullOrEmpty(aiResponse.Id));
     Assert.IsNotNull(aiResponse.Result);
     return aiResponse;
 }
		public void SessionTest()
		{
			var config = new AIConfiguration(SUBSCRIPTION_KEY, ACCESS_TOKEN, SupportedLanguage.English);
			
			var firstService = new AIDataService(config);
			var secondService = new AIDataService(config);

			{
				var weatherRequest = new AIRequest("weather");
				var weatherResponse = MakeRequest(firstService, weatherRequest);
                Assert.IsNotNull(weatherResponse);
			}
			
			{
				var checkSecondRequest = new AIRequest("check weather");
				var checkSecondResponse = MakeRequest(secondService, checkSecondRequest);
                Assert.IsEmpty(checkSecondResponse.Result.Action);
			}
			
			{
				var checkFirstRequest = new AIRequest("check weather");
				var checkFirstResponse = MakeRequest(firstService, checkFirstRequest);
				Assert.IsNotNull(checkFirstResponse.Result.Action);
				Assert.IsTrue(checkFirstResponse.Result.Action.Equals("checked", StringComparison.InvariantCultureIgnoreCase));
			}
		}
        public void EntitiesTest()
        {
            var dataService = CreateDataService();

            var aiRequest = new AIRequest("hi nori");

            var myDwarfs = new Entity("dwarfs");
            myDwarfs.AddEntry(new EntityEntry("Ori", new [] {"ori", "Nori"}));
            myDwarfs.AddEntry(new EntityEntry("bifur", new [] {"Bofur","Bombur"}));

            var extraEntities = new List<Entity> { myDwarfs };

            aiRequest.Entities = extraEntities;

            var aiResponse = MakeRequest(dataService, aiRequest);

            Assert.IsTrue(!string.IsNullOrEmpty(aiResponse.Result.ResolvedQuery));
            Assert.AreEqual("say_hi", aiResponse.Result.Action);
            Assert.AreEqual("hi Bilbo, I am Ori", aiResponse.Result.Fulfillment.Speech);
        }
 public async Task<AIResponse> RequestAsync(AIRequest request)
 {
     return await RequestAsync(request, CancellationToken.None);
 }
        public void WrongEntitiesTest()
        {
            var dataService = CreateDataService();

            var aiRequest = new AIRequest("hi nori");

            var myDwarfs = new Entity("not_dwarfs");
            myDwarfs.AddEntry(new EntityEntry("Ori", new [] {"ori", "Nori"}));
            myDwarfs.AddEntry(new EntityEntry("bifur", new [] {"Bofur","Bombur"}));

            var extraEntities = new List<Entity> { myDwarfs };

            aiRequest.Entities = extraEntities;

            MakeRequest(dataService, aiRequest);
        }
Beispiel #20
0
 /// <summary>
 /// Send simple text request. This method does not use OnResult and OnSuccess callbacks because for simplicity
 /// </summary>
 /// <param name="request"></param>
 /// <returns>Server response</returns>
 /// <exception cref="ArgumentNullException">If text null or empty</exception>
 /// <exception cref="AIServiceException">If any error appears while request</exception>
 public abstract Task<AIResponse> TextRequestAsync(AIRequest request);
        public void ComplexParameterTest()
        {
            var config = new AIConfiguration(SUBSCRIPTION_KEY, 
                "23e7d37f6dd24e4eb7dbbd7491f832cf", // special agent with domains
                SupportedLanguage.English);
            
            var dataService = new AIDataService(config);

            var aiRequest = new AIRequest("Turn off TV at 7pm");
            var response = MakeRequest(dataService, aiRequest);

            Assert.AreEqual("domains", response.Result.Source);
            Assert.AreEqual("smarthome.appliances_off", response.Result.Action);

            var actionCondition = response.Result.GetJsonParameter("action_condition");

            var timeToken = actionCondition.SelectToken("time");
            Assert.IsNotNull(timeToken);
        }
 public bool ResetContexts()
 {
     var cleanRequest = new AIRequest("empty_query_for_resetting_contexts");
     cleanRequest.ResetContexts = true;
     try {
         var response = Request(cleanRequest);
         return !response.IsError;
     } catch (AIServiceException e) {
         Debug.WriteLine("Exception while contexts clean." + e);
         return false;
     }
 }
	    public void InputContextWithParametersTest()
	    {
            var dataService = CreateDataService();

            var aiRequest = new AIRequest("and for tomorrow");
            var aiContext = new AIContext
            {
                Name = "weather",
                Parameters = new Dictionary<string,string>
                {
                    { "location", "London"}
                }
            };

            aiRequest.Contexts =
                new List<AIContext>
                {
                    aiContext
                };

            var response = MakeRequest(dataService, aiRequest);

            Assert.AreEqual("Weather in London for tomorrow", response.Result.Fulfillment.Speech);
	    }
        private async Task ProcessRecognitionResultsAsync(SpeechRecognitionResult results, RequestExtras requestExtras)
        {
            if (!string.IsNullOrWhiteSpace(results.Text))
            {
                var request = new AIRequest();
                request.Query = new[] { results.Text };
                try
                {
                    request.Confidence = new[] { Convert.ToSingle(results.RawConfidence) };
                }
                catch
                {
                }

                try
                {
                    if (requestExtras != null)
                    {
                        requestExtras.CopyTo(request);
                    }

                    var response = await dataService.RequestAsync(request);
                    FireOnResult(response);
                }
                catch (Exception e)
                {
                    FireOnError(new AIServiceException(e));
                }
            }
        }
        public void InputContextLifespanTest()
        {
            var dataService = CreateDataService();
            var aiRequest = new AIRequest("and for tomorrow");
            var aiContext = new AIContext
            {
                Name = "weather",
                Parameters = new Dictionary<string, string>
                {
                    { "location", "London"}
                },
                Lifespan = 3
            };

            aiRequest.Contexts =
                new List<AIContext>
                {
                    aiContext
                };

            var response = MakeRequest(dataService, aiRequest);
            Assert.IsNotNull(response.Result.GetContext("weather"));

            for (int i = 0; i < 2; i++)
            {
                response = MakeRequest(dataService, new AIRequest("next request"));
            }

            Assert.IsNotNull(response.Result.GetContext("weather"));
            response = MakeRequest(dataService, new AIRequest("next request"));
            Assert.IsNull(response.Result.GetContext("weather"));
        }
        private AIRequest CreateAIRequest(SpeechRecognitionResult recognitionResults)
        {
            var texts = new List<string> { recognitionResults.Text };
            var confidences = new List<float> { ConfidenceToFloat(recognitionResults.Confidence) };

            var aiRequest = new AIRequest();

            var alternates = recognitionResults.GetAlternates(5);
            if (alternates != null)
            {
                foreach (var a in alternates)
                {
                    texts.Add(a.Text);
                    confidences.Add(ConfidenceToFloat(a.Confidence));
                }
            }
            aiRequest.Query = texts.ToArray();
            aiRequest.Confidence = confidences.ToArray();
            return aiRequest;
        }
		private AIResponse MakeRequest(AIDataService service, AIRequest request)
		{
			var aiResponse = service.Request(request);
			Assert.IsNotNull(aiResponse);
			Assert.IsFalse(aiResponse.IsError);
			Assert.IsFalse(string.IsNullOrEmpty(aiResponse.Id));
			Assert.IsNotNull(aiResponse.Result);
			return aiResponse;
		}
Beispiel #28
0
 private void TextRequestExecAsync(AIRequest request) {
     var response = dataService.Request(request);
     AIResponseList.Add(response);
 }
        public async Task WrongEntitiesTest()
        {
            var config = new AIConfiguration(SUBSCRIPTION_KEY, ACCESS_TOKEN, SupportedLanguage.English);
            var dataService = new AIDataService(config);

            var aiRequest = new AIRequest("hi nori");

            var myDwarfs = new Entity("not_dwarfs");
            myDwarfs.AddEntry(new EntityEntry("Ori", new[] { "ori", "Nori" }));
            myDwarfs.AddEntry(new EntityEntry("bifur", new[] { "Bofur", "Bombur" }));

            var extraEntities = new List<Entity> { myDwarfs };

            aiRequest.Entities = extraEntities;

            try
            {
                var aiResponse = await MakeRequestAsync(dataService, aiRequest);
                Assert.IsTrue(false, "Request should throws bad_request exception");
            }
            catch (AIServiceException e)
            {
                Assert.IsTrue(true);
            }
        }
        public void CopyTo(AIRequest request)
        {
            if (HasContexts)
            {
                request.Contexts = Contexts;
            }

            if (HasEntities)
            {
                request.Entities = Entities;
            }
        }