C# 调用 QnA Maker 实现一对一问答

5 篇文章 0 订阅
4 篇文章 0 订阅
 /// <summary>
    /// QnA Maker提供的服务
    /// </summary>
    public class QnAMakerService 
    {
        public KnowledgeBaseConfig KnowledgeBaseCfg { get; set; }
        
        public QnAMakerService(KnowledgeBaseConfig knowledgeBaseCfg)
        {
            this.KnowledgeBaseCfg = knowledgeBaseCfg;
        }

        /// <summary>
        /// 生成答案
        /// </summary>
        /// <param name="question"></param>
        /// <returns></returns>
        public async Task<QnAResult> GenerateAnswer(string question)
        {
            QnAResult ret = null;

            QnAQuestion qnAQuestion = new QnAQuestion(question);

            HttpClient client = new HttpClient();

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", KnowledgeBaseCfg.SubscriptionKey);

            //拼接Url
            var uri = string.Format(KnowledgeBaseCfg.Host, KnowledgeBaseCfg.KnowledgeBaseId);

            HttpResponseMessage response;

            string json = JsonConvert.SerializeObject(qnAQuestion);

            try
            {
                // Request body
                byte[] byteData = Encoding.UTF8.GetBytes(json);

                using (var content = new ByteArrayContent(byteData))
                {
                    //指定Json格式
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    response = await client.PostAsync(uri, content).ConfigureAwait(false);
                    string result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    LogHelper.Warn("QnAMaker返回的消息:"+result, LogSources.BotEngine);
                    //html转义
                    //result = result.Replace("<", "<").Replace(">", ">").Replace(""","\"").Replace("'","'").Replace("&", "&");

                    ret = JsonConvert.DeserializeObject<QnAResult>(result);

                    foreach (var item in ret.answers)
                    {
                        item.answer = item.answer.Replace("<", "<").Replace(">", ">").Replace(""", "\"").Replace("'", "'").Replace("&", "&");
                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return ret;
        }

        /// <summary>
        /// 删除知识库
        /// </summary>
        /// <param name="question"></param>
        public async void Deleted(string question) {
           
                QnAQuestion qnAQuestion = new QnAQuestion(question);

                HttpClient client = new HttpClient();

                // Request headers
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", KnowledgeBaseCfg.SubscriptionKey);
                

                string json = JsonConvert.SerializeObject(qnAQuestion);
                // Request body
                byte[] byteData = Encoding.UTF8.GetBytes(json);
               using (var content = new ByteArrayContent(byteData))
                    {
                    //拼接Url
                    var uri = string.Format(KnowledgeBaseCfg.Host, KnowledgeBaseCfg.KnowledgeBaseId, "?" + content);
                    //指定Json格式
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    //执行删除
                    await client.DeleteAsync(uri);
                   
                }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="question"></param>
        public async Task<HttpResponseMessage> Add(QnaPairsCreate model)
        {

            HttpClient client = new HttpClient();

                // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", KnowledgeBaseCfg.SubscriptionKey);
            
            
            using (StringContent sc = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(model)))
                {
                    //拼接Url  updateAlterations
                    var uri = string.Format("https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/create");
                    //指定Json格式
                    sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    //执行添加
                    return  await client.PostAsync(uri, sc);

                }


            
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="question"></param>
        public void Update(string question)
        {
            QnAQuestion qnAQuestion = new QnAQuestion(question);

            HttpClient client = new HttpClient();

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", KnowledgeBaseCfg.SubscriptionKey);


            string json = JsonConvert.SerializeObject(qnAQuestion);
            // Request body
            byte[] byteData = Encoding.UTF8.GetBytes(json);
            using (var content = new ByteArrayContent(byteData))
            {
                //拼接Url  updateAlterations
                var uri = string.Format("https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/{0}/updateAlterations", KnowledgeBaseCfg.KnowledgeBaseId);
                //指定Json格式
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                //执行添加
                client.DefaultRequestHeaders.Add(uri, content.ToString());

            }



        }

        /// <summary>
        /// 添加  删除 
        /// </summary>
        /// <param name="question"></param>
        public async Task<HttpResponseMessage> Update(QnaQuestionItem model)
        {
            //拼接Url  updateAlterations
            var uri = string.Format("https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/{0}"
                , KnowledgeBaseCfg.KnowledgeBaseId);
            HttpWebRequest client = HttpWebRequest.Create(uri) as HttpWebRequest;
            HttpStatusCode code;
            
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(model);
            byte[] byteData = Encoding.UTF8.GetBytes(json);
            HttpResponseMessage responsePublish;
            HttpClient clientPublish = new HttpClient();
            using (var content = new ByteArrayContent(byteData))
            {
                
                //指定Json格式
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                client.Method = "PATCH";
                // Request headers
                client.Headers.Add("Ocp-Apim-Subscription-Key", KnowledgeBaseCfg.SubscriptionKey);
                client.ContentType = "application/json";
                client.ContentLength = byteData.Length;
                client.KeepAlive = true;

                //执行添加
                if (!string.IsNullOrEmpty(json))
                {
                    Stream reqStream = client.GetRequestStream();
                    reqStream.Write(byteData, 0, byteData.Length);
                }

                string strReturn = "";
                try
                {
                    HttpWebResponse response = (HttpWebResponse)client.GetResponse();
                    var respStream = response.GetResponseStream();
                    strReturn = new StreamReader(respStream).ReadToEnd();
                    clientPublish.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", KnowledgeBaseCfg.SubscriptionKey);
                    responsePublish = await clientPublish.PutAsync(uri, content);
                    code = response.StatusCode;
                }
                catch (Exception e)
                {
                    strReturn = e.Message;
                    code = HttpStatusCode.BadRequest;
                }

                return new HttpResponseMessage (){StatusCode= code };
            }



        }

        //下载知识库
        public async Task<string> GetResult()
        {
            QnAResult ret = null;
            

            HttpClient client = new HttpClient();

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", KnowledgeBaseCfg.SubscriptionKey);
            var queryString = HttpUtility.ParseQueryString(string.Empty);
            
            //拼接Url
            var uri = string.Format(@"https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/{0}"
, KnowledgeBaseCfg.KnowledgeBaseId);

            HttpResponseMessage response;

            string result = "";
            try
            {
                response = await client.GetAsync(uri);
                StreamContent content = response.Content as StreamContent;
                string str = await content.ReadAsStringAsync();
                result = str.Replace("\"", "");
              
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return result;
        }

        
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值