首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >翻译器文本API 3.0版本- Microsoft聊天机器人的连接问题

翻译器文本API 3.0版本- Microsoft聊天机器人的连接问题
EN

Stack Overflow用户
提问于 2018-07-01 10:04:16
回答 1查看 449关注 0票数 0

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

我是在C#和Microsoft 的在线代码编辑器上这样做的。

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

当我尝试调试它时,我可以看到它停止在这个特定的部分:

代码语言:javascript
运行
复制
var response = await client.SendAsync(request);

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

我检查了网络超时错误,有很多(20)。他们都说“向bot发送此消息时出错: HTTP状态代码GatewayTimeout”。

我通常可以"build.cmd“,没有任何错误,当我尝试做Debug.WriteLine或Console.WriteLine时,什么都没有打印出来(我甚至尝试了VS和模拟器)。

与上面的链接相比,我所做的唯一不同之处是,我在私有方法之外定义了"host“和"key”:

代码语言:javascript
运行
复制
private static async Task<string> TranslateQuestionToEnglish (...)

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

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

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

另一件我不确定的事情是,如果这个东西有问题的话,当我进入所有资源时,我可以看到我的qnatestbot(网络应用程序机器人)和translator_test(认知服务)是“全局”位置,而我的qnatestbot(应用服务)是“西欧”型的。他们在不同地区的情况会造成问题吗?,我应该把他们都放在西欧(既然我在德国)?

尽管现在我看了translator_test(认知服务)端点,但我可以看到它是translator_test

但是,当我创建一个资源时,它是像这样自动创建的,而没有从我的身边指定它?,如何更改它?

我希望有人能成功地遇到这样的问题,并能帮助我。提前谢谢你

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-02 06:20:19

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

我尝试创建一个示例来实现您的需求:将用户输入翻译成英语,并将翻译文本传递给QnAMaker对话框,该示例在本地和Azure上都工作得很好,您可以参考它。

In MessagesController:

代码语言:javascript
运行
复制
[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;
    }
}

对话框中的

代码语言:javascript
运行
复制
[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"))))
    { }

}

测试结果:

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51122311

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档