Translator Text API版本3.0的连接问题-Microsoft Azure QnA聊天机器人

时间:2018-07-01 10:04:16

标签: c# azure botframework chatbot

我想将我的Azure QnA聊天机器人与翻译层认知系统连接起来。我将此页面用作参考:https://docs.microsoft.com/en-us/azure/cognitive-services/translator/quickstart-csharp-translate

我正在 C#和Microsoft Azure的在线代码编辑器中进行此操作。

不幸的是,我无法连接到翻译层(至少看起来像这样)。

当我尝试调试它时,我看到它停止在此特定部分:

var response = await client.SendAsync(request);

var responseBody = await response.Content.ReadAsStringAsync();

我检查了网络超时错误,并且有很多(20)。他们所有人都说“发送此消息到您的机器人时出错:HTTP状态代码GatewayTimeout”。

我可以正常地“ build.cmd”,没有任何错误,并且当我尝试执行Debug.WriteLine或Console.WriteLine时,什么也没打印出来(我什至在VS和Emulator中也尝试过)

与上面的链接相比,我要做的唯一不同的是,我在私有方法之外定义了“主机”和“密钥”:

private static async Task<string> TranslateQuestionToEnglish (...)

所以,我想把任何单词都想翻译成英文。 当我取出这两行代码并测试具有静态值的方法时,它显然可以工作(全部与QnA和其他所有功能一起使用)。

稍后,我在“任务MessageReceivedAsync”中调用此方法。

我创建了翻译认知服务,并且从那里获得的唯一东西是“ Keys”中的第一个键,并在此方法中使用了它。 这是我创建认知服务唯一需要的吗?

我不确定的另一件事是,如果那是一个问题,那就是当我使用所有资源时,可以看到我的qnatestbot(网络应用程序bot)和translator_test(认知服务)的类型为“全球”位置,而我的qnatestbot(应用程序服务)类型为“西欧”位置。他们在不同地区的事物会造成问题吗? 我应该把它们都放在西欧吗(因为我在德国)?

尽管,现在我看了translator_test(认知服务)端点,我可以看到它是... api.congitivemicrosft.com /.../ v1.0

>

但是,当我创建资源时,它是自动创建的,而无需从我旁边指定它? 如何更改它?

我希望有人成功遇到这样的问题并能为我提供帮助。预先谢谢你

1 个答案:

答案 0 :(得分:0)

  

我想将我的Azure QnA聊天机器人与翻译层认知系统连接起来。我将此页面用作参考:https://docs.microsoft.com/en-us/azure/cognitive-services/translator/quickstart-csharp-translate

我尝试创建一个示例来满足您的要求:将用户输入翻译成英语并将翻译文本传递到QnAMaker对话框,该示例在本地和Azure上都可以正常工作,您可以参考它。

在MessagesController中:

[BotAuthentication]
public class MessagesController : ApiController
{

    static string uri = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=en";
    static string key = "{the_key}";

    /// <summary>
    /// POST: api/Messages
    /// receive a message from a user and send replies
    /// </summary>
    /// <param name="activity"></param>
    [ResponseType(typeof(void))]
    public virtual async Task<HttpResponseMessage> Post([FromBody] Activity activity)
    {
        // check if activity is of type message
        if (activity.GetActivityType() == ActivityTypes.Message)
        {
            if (activity.Text != null)
            {
                var textinEN = await TranslateQuestionToEnglish(activity.Text);
                activity.Text = textinEN;
            }

            await Conversation.SendAsync(activity, () => new RootDialog());
        }
        else
        {
            HandleSystemMessage(activity);
        }
        return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
    }

    private static async Task<string> TranslateQuestionToEnglish(string text)
    {
        System.Object[] body = new System.Object[] { new { Text = text } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(uri);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);

            var response = await client.SendAsync(request);
            var responseBody = await response.Content.ReadAsStringAsync();

            dynamic jsonResponse = JsonConvert.DeserializeObject(responseBody);
            var textinen = jsonResponse[0]["translations"][0]["text"].Value;

            return textinen;
        }
    }

    private Activity HandleSystemMessage(Activity message)
    {
        if (message.Type == ActivityTypes.DeleteUserData)
        {
            // Implement user deletion here
            // If we handle user deletion, return a real message
        }
        else if (message.Type == ActivityTypes.ConversationUpdate)
        {
            // Handle conversation state changes, like members being added and removed
            // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
            // Not available in all channels
        }
        else if (message.Type == ActivityTypes.ContactRelationUpdate)
        {
            // Handle add/remove from contact lists
            // Activity.From + Activity.Action represent what happened
        }
        else if (message.Type == ActivityTypes.Typing)
        {
            // Handle knowing tha the user is typing
        }
        else if (message.Type == ActivityTypes.Ping)
        {
        }

        return null;
    }
}

在对话框中:

[Serializable]
public class RootDialog : IDialog<object>
{
    public async Task StartAsync(IDialogContext context)
    {
        /* Wait until the first message is received from the conversation and call MessageReceviedAsync 
        *  to process that message. */
        context.Wait(this.MessageReceivedAsync);
    }

    private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
    {
        /* When MessageReceivedAsync is called, it's passed an IAwaitable<IMessageActivity>. To get the message,
            *  await the result. */
        var message = await result;

        var qnaAuthKey = GetSetting("QnAAuthKey"); 
        var qnaKBId = Utils.GetAppSetting("QnAKnowledgebaseId");
        var endpointHostName = Utils.GetAppSetting("QnAEndpointHostName");

        // QnA Subscription Key and KnowledgeBase Id null verification
        if (!string.IsNullOrEmpty(qnaAuthKey) && !string.IsNullOrEmpty(qnaKBId))
        {
            // Forward to the appropriate Dialog based on whether the endpoint hostname is present
            if (string.IsNullOrEmpty(endpointHostName))
                await context.Forward(new BasicQnAMakerPreviewDialog(), AfterAnswerAsync, message, CancellationToken.None);
            else
                await context.Forward(new BasicQnAMakerDialog(), AfterAnswerAsync, message, CancellationToken.None);
        }
        else
        {
            await context.PostAsync("Please set QnAKnowledgebaseId, QnAAuthKey and QnAEndpointHostName (if applicable) in App Settings. Learn how to get them at https://aka.ms/qnaabssetup.");
        }

    }

    private async Task AfterAnswerAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
    {
        // wait for the next user message
        context.Wait(MessageReceivedAsync);
    }

    public static string GetSetting(string key)
    {
        var value = Utils.GetAppSetting(key);
        if (String.IsNullOrEmpty(value) && key == "QnAAuthKey")
        {
            value = Utils.GetAppSetting("QnASubscriptionKey"); // QnASubscriptionKey for backward compatibility with QnAMaker (Preview)
        }
        return value;
    }
}

// Dialog for QnAMaker Preview service
[Serializable]
public class BasicQnAMakerPreviewDialog : QnAMakerDialog
{
    // Go to https://qnamaker.ai and feed data, train & publish your QnA Knowledgebase.
    // Parameters to QnAMakerService are:
    // Required: subscriptionKey, knowledgebaseId, 
    // Optional: defaultMessage, scoreThreshold[Range 0.0 – 1.0]
    public BasicQnAMakerPreviewDialog() : base(new QnAMakerService(new QnAMakerAttribute(RootDialog.GetSetting("QnAAuthKey"), Utils.GetAppSetting("QnAKnowledgebaseId"), "No good match in FAQ.", 0.5)))
    { }
}

// Dialog for QnAMaker GA service
[Serializable]
public class BasicQnAMakerDialog : QnAMakerDialog
{
    // Go to https://qnamaker.ai and feed data, train & publish your QnA Knowledgebase.
    // Parameters to QnAMakerService are:
    // Required: qnaAuthKey, knowledgebaseId, endpointHostName
    // Optional: defaultMessage, scoreThreshold[Range 0.0 – 1.0]
    public BasicQnAMakerDialog() : base(new QnAMakerService(new QnAMakerAttribute(RootDialog.GetSetting("QnAAuthKey"), Utils.GetAppSetting("QnAKnowledgebaseId"), "No good match in FAQ.", 0.5, 1, Utils.GetAppSetting("QnAEndpointHostName"))))
    { }

}

测试结果: enter image description here

注意: :如果在本地运行bot应用程序,我们可以使用ConfigurationManager.AppSettings["QnAKnowledgebaseId"];从web.config访问QnAKnowledgebaseId等设置。有关更多信息,请参阅this SO thread