/// <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;
}
}
C# 调用 QnA Maker 实现一对一问答
最新推荐文章于 2024-02-09 12:01:21 发布