gpt4 book ai didi

c# - 如何使用 C# 使用 IBM Watson Dialog 服务?

转载 作者:太空宇宙 更新时间:2023-11-03 23:27:22 25 4
gpt4 key购买 nike

一个客户正在使用 IBM 的 Watson Dialog 服务,但我找不到任何使用 .Net(特别是 c#)来做最基本的事情的例子。

IBM 仅显示使用 Curl、Node 和 Java 的示例...

我的第一个目标是能够向 watson 服务添加一个新的 xml 文件(对话树)。看起来很简单,但我已经苦思冥想了一段时间。

最佳答案

因此,我最终通过拼凑有关相关主题的大约一打谷歌搜索的帮助来完成这项工作。我想我会在这里发布工作版本。

下面是我的代码,它将在 MVC Controller 中使用 C# 将 xml 文件上传到 Watson Dialog 服务。

前端是一种采用友好名称(我将其转换为 .xml 文件名)和文件本身上传(使用 dropzone)的表单。

我确信可以进行优化,但我希望这对某些人有所帮助。好消息是,这可以用作执行几乎任何 Watson Dialog 服务调用(添加、更新、删除)的基础。

    public ContentResult Save(FormCollection form)
{
try
{
var name = form["txtDialogName"];

var filename = name + ".xml";
byte[] bytes = null;

foreach (string s in Request.Files)
{
var file = Request.Files[s];

using (Stream inputStream = file.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}

bytes = memoryStream.ToArray();
}

break;
}

if (bytes == null)
{
var contentResult = new ContentResult
{
ContentType = "application/json",
Content = null
};
return contentResult;
}


var basePath = ConfigurationManager.AppSettings["WatsonPath"];

var username = ConfigurationManager.AppSettings["WatsonUsername"];
var password = ConfigurationManager.AppSettings["WatsonPassword"];
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password)));

var values = new[]
{ new KeyValuePair<string, string>("name", filename) };

using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

foreach (var keyValuePair in values)
{
formData.Add(new StringContent(keyValuePair.Value), string.Format("\"{0}\"", keyValuePair.Key));
}

formData.Add(new ByteArrayContent(bytes),
'"' + "file" + '"',
'"' + filename + '"');

var response = client.PostAsync(basePath + "/v1/dialogs", formData).Result;
var result = response.Content.ReadAsStringAsync().Result;
if (!response.IsSuccessStatusCode)
{
var contentResult = new ContentResult
{
ContentType = "application/json",
Content = response.ReasonPhrase
};
return contentResult;
}

var successResult = new ContentResult
{
ContentType = "application/json",
Content = result
};

return successResult;
}
}
catch (Exception ex)
{
HandleError(ex);
var contentResult = new ContentResult
{
ContentType = "application/json",
Content = "false"
};
return contentResult;
}
}

关于c# - 如何使用 C# 使用 IBM Watson Dialog 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33414277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com