Merge pull request #10 from Microsoft/develop

Develop
This commit is contained in:
Hesham ElBaz 2016-10-23 16:42:51 +02:00 коммит произвёл GitHub
Родитель 9e81c7ac83 4ae6ff21d1
Коммит 363b22f147
15 изменённых файлов: 696 добавлений и 33 удалений

Просмотреть файл

@ -54,9 +54,9 @@ namespace Microsoft.Cognitive.LUIS
/// <exception cref="System.Net.Http.HttpRequestException">Thrown if a non-success result is returned from the server.</exception>
public async static Task<JToken> RestGet(this HttpClient client, string url)
{
var response = await client.GetAsync(url);
var response = await client.GetAsync(url).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return JToken.Parse(body);
}
}

Просмотреть файл

@ -36,7 +36,6 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
@ -49,7 +48,7 @@ namespace Microsoft.Cognitive.LUIS
/// <param name="entities">Dictionary containing <see cref="Entity"/> objects identified by the LUIS service.</param>
/// <param name="context">Opaque content provided by the application to its intent handlers.</param>
/// <returns>True if the intent was handled.</returns>
public delegate Task<bool> IntentHandlerFunc(LuisResult result, object context);
public delegate void IntentHandlerFunc(LuisResult result, object context);
/// <summary>
/// Routes results returns from the LUIS service to registed intent handlers.
@ -253,8 +252,8 @@ namespace Microsoft.Cognitive.LUIS
{
if (_client == null) throw new InvalidOperationException("No API endpoint has been specified for this IntentRouter");
var result = await _client.Predict(text);
return await Route(result, context);
LuisResult result = result = await _client.Predict(text);
return Route(result, context);
}
/// <summary>
@ -263,7 +262,7 @@ namespace Microsoft.Cognitive.LUIS
/// <param name="result">Result from LUIS service to route.</param>
/// <param name="context">Opaque context object to pass through to activated intent handler</param>
/// <returns>True if an intent was routed and handled.</returns>
public async Task<bool> Route(LuisResult result, object context)
public bool Route(LuisResult result, object context)
{
if (result.Intents == null)
return false;
@ -273,8 +272,8 @@ namespace Microsoft.Cognitive.LUIS
HandlerDetails handler;
if (_handlers.TryGetValue(intent.Name, out handler) && (handler.Threshold < intent.Score))
{
var handled = await handler.Exec(result, context);
if (handled) return true;
handler.Exec(result, context);
return true;
}
}

Просмотреть файл

@ -127,16 +127,21 @@ namespace Microsoft.Cognitive.LUIS
/// Encodes text to be suitable for http requests
/// </summary>
/// <param name="text"></param>
/// <param name="forceSetParameterName">The name of a parameter to reset in the current dialog</param>
/// <returns></returns>
private string EncodeRequest(string text)
private string EncodeRequest(string text, string forceSetParameterName = null)
{
string applicationUrl;
if (Preview)
applicationUrl = CreateApplicationPreviewUri(_appId);
else
applicationUrl = CreateApplicationUri(_appId);
return applicationUrl + WebUtility.UrlEncode(text);
applicationUrl += WebUtility.UrlEncode(text);
if (!String.IsNullOrWhiteSpace(forceSetParameterName))
{
applicationUrl += $"&forceset={forceSetParameterName}";
}
return applicationUrl;
}
/// <summary>
@ -144,18 +149,18 @@ namespace Microsoft.Cognitive.LUIS
/// </summary>
/// <param name="luisResult">The luis result obtained from the previous step (Predict/Reply)</param>
/// <param name="text">The text to Reply with</param>
/// <param name="forceSetParameterName">The name of a parameter to reset in the current dialog</param>
/// <returns></returns>
public async Task<LuisResult> Reply(LuisResult luisResult, string text)
public async Task<LuisResult> Reply(LuisResult luisResult, string text, string forceSetParameterName = null)
{
if (String.IsNullOrWhiteSpace(text))
return new LuisResult();
if (String.IsNullOrWhiteSpace(text)) throw new ArgumentException(nameof(text));
if (luisResult == null) throw new ArgumentNullException("Luis result can't be null");
if (luisResult.DialogResponse == null) throw new ArgumentNullException("Dialog can't be null in order to Reply");
if (luisResult.DialogResponse.ContextId == null) throw new ArgumentNullException("Context id cannot be null");
var uri = EncodeRequest(text) + $"&contextid={luisResult.DialogResponse.ContextId}";
var result = await _http.RestGet(uri);
var uri = EncodeRequest(text, forceSetParameterName) + $"&contextid={luisResult.DialogResponse.ContextId}";
var result = await _http.RestGet(uri).ConfigureAwait(false);
return new LuisResult(this, result);
}
@ -166,11 +171,10 @@ namespace Microsoft.Cognitive.LUIS
/// <returns></returns>
public async Task<LuisResult> Predict(string text)
{
if (String.IsNullOrWhiteSpace(text))
return new LuisResult();
if (String.IsNullOrWhiteSpace(text)) throw new ArgumentException(nameof(text));
var uri = EncodeRequest(text);
var result = await _http.RestGet(uri);
var result = await _http.RestGet(uri).ConfigureAwait(false);
return new LuisResult(this, result);
}

Просмотреть файл

@ -1,9 +1,9 @@
LUIS
LUIS
==============
LUIS is a service for language understanding that provides intent classification and entity extraction.
In order to use the SDK you first need to create and publish an app on www.luis.ai where you will get your appID and appKey.
In order to use the SDK you first need to create and publish an app on www.luis.ai where you will get your Application Id and Subscription Key.
The solution contains the SDK itself and a sample application that allow you to enter you appId and appKey, and to perform the two actions "predict" and "reply".
The solution contains the SDK and a sample application that allows you to enter your appId and appKey, and to perform the two actions "predict" and "reply".
Cloning The Repo
--------------
@ -18,11 +18,19 @@ The SDK can be used in 2 different ways (both are shown in the sample).
Sample Application
--------------
The sample application allows you to perform the Predict and Reply operations and to view the following parts of the parsed response:
- Query
- Top Intent
- Dialog prompt/status
- Entities
The sample application allows you to try three different modes.
- Mode 1: Perform the Predict and Reply actions using LuisClient directly operations and to view the following parts of the parsed response: Query, Top Intent, Dialog prompt/status, Entities
- Mode 2: Perform the Predict action function using the IntentRouter class and an IntentHandlers class that contains normal functions
- Mode 3: Perform the Predict action function using the IntentRouter class and an IntentHandlers class that contain static functions
Intent Router and Handlers mode
--------------
In order to use modes 2 and 3 of the sample application you have to import this [LUIS application JSON file](</Sample/LUIS Sample Application JSON/SDK Test.json>) using your LUIS account, train and publish it, and use its Application Id in those two modes.
You can try the following utterances:
- "Book me a flight" get routed to "Book a flight" intent handler
- "Book me a cab" gets routed to "Book a cab" intent handler
- "Order food" gets routed to "None" intent handler
- "Book me a train" doesn't get routed to any intent handler due to low confidence score
License
=======
@ -33,5 +41,5 @@ All Microsoft Cognitive Services SDKs and samples are licensed with the MIT Lice
Developer Code of Conduct
=======
Developers using Cognitive Services, including this client library & sample, are required to follow the “[Developer Code of Conduct for Microsoft Cognitive Services](http://go.microsoft.com/fwlink/?LinkId=698895)”.
Developers using Cognitive Services, including this client library & sample, are required to follow the “[Developer Code of Conduct for Microsoft Cognitive Services](http://go.microsoft.com/fwlink/?LinkId=698895)”.

Просмотреть файл

@ -0,0 +1,40 @@
{
"luis_schema_version": "1.3.0",
"name": "SDK Test",
"desc": "",
"culture": "en-us",
"intents": [
{
"name": "Book a cab"
},
{
"name": "Book a flight"
},
{
"name": "None"
}
],
"entities": [],
"composites": [],
"bing_entities": [],
"actions": [],
"model_features": [],
"regex_features": [],
"utterances": [
{
"text": "book me a flight",
"intent": "Book a flight",
"entities": []
},
{
"text": "book me a cab",
"intent": "Book a cab",
"entities": []
},
{
"text": "order food",
"intent": "None",
"entities": []
}
]
}

Просмотреть файл

@ -0,0 +1,35 @@
using System;
using System.Windows;
using Microsoft.Cognitive.LUIS;
namespace Sample
{
class IntentHandlers
{
// 0.65 is the confidence score required by this intent in order to be activated
// Only picks out a single entity value
[IntentHandler(0.65, Name = "Book a flight")]
public void BookAFlight(LuisResult result, object context)
{
UsingIntentRouter usingIntentRouter = (UsingIntentRouter)context;
usingIntentRouter.queryTextBlock.Text = result.OriginalQuery;
usingIntentRouter.topIntentTextBlock.Text = "Book a flight";
}
[IntentHandler(0.65, Name = "Book a cab")]
public void BookACab(LuisResult result, object context)
{
UsingIntentRouter usingIntentRouter = (UsingIntentRouter)context;
usingIntentRouter.queryTextBlock.Text = result.OriginalQuery;
usingIntentRouter.topIntentTextBlock.Text = "Book a cab";
}
[IntentHandler(0.7, Name = "None")]
public static void None(LuisResult result, object context)
{
UsingIntentRouter usingIntentRouter = (UsingIntentRouter)context;
usingIntentRouter.queryTextBlock.Text = result.OriginalQuery;
usingIntentRouter.topIntentTextBlock.Text = "None";
}
}
}

Просмотреть файл

@ -71,18 +71,34 @@
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="IntentHandlers.cs" />
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Page Include="MakePredictionPage.xaml">
<Page Include="UsingIntentRouter.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="UsingStaticIntentRouter.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="UsingLUISClientDirectly.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
<ItemGroup>
<Compile Include="MakePredictionPage.xaml.cs">
<DependentUpon>MakePredictionPage.xaml</DependentUpon>
<Compile Include="StaticIntentHandlers.cs" />
<Compile Include="UsingIntentRouter.xaml.cs">
<DependentUpon>UsingIntentRouter.xaml</DependentUpon>
</Compile>
<Compile Include="UsingStaticIntentRouter.xaml.cs">
<DependentUpon>UsingStaticIntentRouter.xaml</DependentUpon>
</Compile>
<Compile Include="UsingLUISClientDirectly.xaml.cs">
<DependentUpon>UsingLUISClientDirectly.xaml</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>

Просмотреть файл

@ -47,7 +47,9 @@ namespace Sample
_scenariosControl.SampleTitle = "LUIS SDK Sample App";
_scenariosControl.SampleScenarioList = new Scenario[]
{
new Scenario { Title = "Scenario 1: Make a prediction", PageClass=typeof(MakePredictionPage)}
new Scenario { Title = "Scenario 1: Using LuisClient Directly", PageClass=typeof(UsingLUISClientDirectly)},
new Scenario { Title = "Scenario 2: Using IntentRouter", PageClass=typeof(UsingIntentRouter)},
new Scenario { Title = "Scenario 3: Using static IntentRouter", PageClass=typeof(UsingStaticIntentRouter)}
};
_scenariosControl.Disclaimer = "Microsoft will receive the uploaded text and may use it to improve LUIS and related services. By submitting the text, you confirm that you consent.";
}

Просмотреть файл

@ -0,0 +1,35 @@
using System;
using System.Windows;
using Microsoft.Cognitive.LUIS;
namespace Sample
{
class StaticIntentHandlers
{
// 0.65 is the confidence score required by this intent in order to be activated
// Only picks out a single entity value
[IntentHandler(0.65, Name = "Book a flight")]
public void BookAFlight(LuisResult result, object context)
{
UsingStaticIntentRouter usingStaticIntentRouter = (UsingStaticIntentRouter)context;
usingStaticIntentRouter.queryTextBlock.Text = result.OriginalQuery;
usingStaticIntentRouter.topIntentTextBlock.Text = "Book a flight";
}
[IntentHandler(0.65, Name = "Book a cab")]
public void BookACab(LuisResult result, object context)
{
UsingStaticIntentRouter usingStaticIntentRouter = (UsingStaticIntentRouter)context;
usingStaticIntentRouter.queryTextBlock.Text = result.OriginalQuery;
usingStaticIntentRouter.topIntentTextBlock.Text = "Book a cab";
}
[IntentHandler(0.7, Name = "None")]
public static void None(LuisResult result, object context)
{
UsingStaticIntentRouter usingStaticIntentRouter = (UsingStaticIntentRouter)context;
usingStaticIntentRouter.queryTextBlock.Text = result.OriginalQuery;
usingStaticIntentRouter.topIntentTextBlock.Text = "None";
}
}
}

Просмотреть файл

@ -0,0 +1,59 @@
<Page x:Class="Sample.UsingIntentRouter"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Sample"
mc:Ignorable="d" d:DesignWidth="300"
Title="UsingIntentRouter" Height="403">
<Grid>
<TextBox x:Name="txtAppId" HorizontalAlignment="Left" Height="23" Margin="28,30,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240" ToolTip="">
<TextBox.Style>
<Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="Enter your Application Id" Foreground="DarkGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<TextBox x:Name="txtPredict" HorizontalAlignment="Left" Height="23" Margin="28,73,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240">
<TextBox.Style>
<Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="Enter the text to predict" Foreground="DarkGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<Button x:Name="btnPredict" Content="Predict" HorizontalAlignment="Left" Margin="28,130,0,0" VerticalAlignment="Top" Width="75" Click="btnPredict_Click"/>
<Label x:Name="queryLabel" Content="Query:" HorizontalAlignment="Left" Margin="28,170,0,0" VerticalAlignment="Top" FontWeight="Bold"/>
<TextBlock x:Name="queryTextBlock" HorizontalAlignment="Left" Margin="81,175,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
<Label x:Name="topIntentLabel" Content="Top Intent:" HorizontalAlignment="Left" Margin="28,200,0,0" VerticalAlignment="Top" FontWeight="Bold"/>
<TextBlock x:Name="topIntentTextBlock" HorizontalAlignment="Left" Margin="104,205,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
</Grid>
</Page>

Просмотреть файл

@ -0,0 +1,88 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services: http://www.microsoft.com/cognitive
//
// Microsoft Cognitive Services Github:
// https://github.com/Microsoft/Cognitive
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Windows;
using System.Windows.Controls;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Cognitive.LUIS;
namespace Sample
{
/// <summary>
/// Interaction logic for UsingLUISClientDirectly.xaml
/// </summary>
public partial class UsingIntentRouter : Page
{
public UsingIntentRouter()
{
InitializeComponent();
}
private void btnPredict_Click(object sender, RoutedEventArgs e)
{
Predict();
}
public async void Predict()
{
string _appId = txtAppId.Text;
string _subscriptionKey = ((MainWindow)Application.Current.MainWindow).SubscriptionKey;
string _textToPredict = txtPredict.Text;
IntentHandlers ih = new IntentHandlers();
try
{
using (var router = IntentRouter.Setup(_appId, _subscriptionKey, ih))
{
var handled = await router.Route(_textToPredict, this);
if (!handled)
{
queryTextBlock.Text = "";
topIntentTextBlock.Text = "";
((MainWindow)Application.Current.MainWindow).Log("Intent was not matched confidently, maybe more training required?");
}
else
{
((MainWindow)Application.Current.MainWindow).Log("Predicted successfully.");
}
}
}
catch (Exception exception)
{
((MainWindow)Application.Current.MainWindow).Log(exception.Message);
}
}
}
}

Просмотреть файл

@ -0,0 +1,85 @@
<Page x:Class="Sample.UsingLUISClientDirectly"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Sample"
mc:Ignorable="d" d:DesignWidth="300"
Title="UsingLUISClientDirectly" Height="403">
<Grid>
<TextBox x:Name="txtAppId" HorizontalAlignment="Left" Height="23" Margin="28,30,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240" ToolTip="">
<TextBox.Style>
<Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="Enter your Application Id" Foreground="DarkGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<TextBox x:Name="txtPredict" HorizontalAlignment="Left" Height="23" Margin="28,73,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240">
<TextBox.Style>
<Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="Enter the text to predict" Foreground="DarkGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<TextBox x:Name="txtForceSet" HorizontalAlignment="Left" Height="23" Margin="28,116,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240">
<TextBox.Style>
<Style xmlns:sys="clr-namespace:System;assembly=mscorlib" TargetType="{x:Type TextBox}">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="Enter a parameter name to reset it (optional)" Foreground="DarkGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<Button x:Name="btnPredict" Content="Predict" HorizontalAlignment="Left" Margin="28,150,0,0" VerticalAlignment="Top" Width="75" Click="btnPredict_Click"/>
<Button x:Name="btnReply" Content="Reply" HorizontalAlignment="Left" Margin="193,150,0,0" VerticalAlignment="Top" Width="75" Click="btnReply_Click"/>
<Label x:Name="queryLabel" Content="Query:" HorizontalAlignment="Left" Margin="28,170,0,0" VerticalAlignment="Top" FontWeight="Bold"/>
<TextBlock x:Name="queryTextBlock" HorizontalAlignment="Left" Margin="81,175,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
<Label x:Name="topIntentLabel" Content="Top Intent:" HorizontalAlignment="Left" Margin="28,200,0,0" VerticalAlignment="Top" FontWeight="Bold"/>
<TextBlock x:Name="topIntentTextBlock" HorizontalAlignment="Left" Margin="104,205,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
<Label x:Name="dialogLabel" Content="Dialog:" HorizontalAlignment="Left" Margin="28,230,0,0" VerticalAlignment="Top" FontWeight="Bold"/>
<TextBlock x:Name="dialogTextBlock" HorizontalAlignment="Left" Margin="83,235,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
<Label x:Name="entitiesLabel" Content="Entities:" HorizontalAlignment="Left" Margin="28,260,0,0" VerticalAlignment="Top" FontWeight="Bold"/>
<ListBox x:Name="entitiesListBox" HorizontalAlignment="Left" Height="85" Margin="34,286,0,0" VerticalAlignment="Top" Width="190"/>
</Grid>
</Page>

Просмотреть файл

@ -0,0 +1,144 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services: http://www.microsoft.com/cognitive
//
// Microsoft Cognitive Services Github:
// https://github.com/Microsoft/Cognitive
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Windows;
using System.Windows.Controls;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Cognitive.LUIS;
namespace Sample
{
/// <summary>
/// Interaction logic for UsingLUISClientDirectly.xaml
/// </summary>
public partial class UsingLUISClientDirectly : Page
{
private LuisResult prevResult { get; set; }
public UsingLUISClientDirectly()
{
InitializeComponent();
}
private void btnPredict_Click(object sender, RoutedEventArgs e)
{
Predict();
}
private void btnReply_Click(object sender, RoutedEventArgs e)
{
if (prevResult == null || (prevResult.DialogResponse != null
&& prevResult.DialogResponse.Status == "Finished"))
{
((MainWindow)Application.Current.MainWindow).Log("There is nothing to reply to.");
return;
}
try
{
Reply();
}
catch (Exception exception)
{
((MainWindow)Application.Current.MainWindow).Log(exception.Message);
}
}
public async void Predict()
{
string appId = txtAppId.Text;
string subscriptionKey = ((MainWindow)Application.Current.MainWindow).SubscriptionKey;
bool preview = true;
string textToPredict = txtPredict.Text;
string forceSetParameterName = txtForceSet.Text;
try
{
LuisClient client = new LuisClient(appId, subscriptionKey, preview);
LuisResult res = await client.Predict(textToPredict);
processRes(res);
((MainWindow)Application.Current.MainWindow).Log("Predicted successfully.");
}
catch (System.Exception exception)
{
((MainWindow)Application.Current.MainWindow).Log(exception.Message);
}
}
public async void Reply()
{
string appId = txtAppId.Text;
string subscriptionKey = ((MainWindow)Application.Current.MainWindow).SubscriptionKey;
bool preview = true;
string textToPredict = txtPredict.Text;
string forceSetParameterName = txtForceSet.Text;
try
{
LuisClient client = new LuisClient(appId, subscriptionKey, preview);
LuisResult res = await client.Reply(prevResult, textToPredict, forceSetParameterName);
processRes(res);
((MainWindow)Application.Current.MainWindow).Log("Replied successfully.");
}
catch (System.Exception exception)
{
((MainWindow)Application.Current.MainWindow).Log(exception.Message);
}
}
private void processRes(LuisResult res)
{
txtPredict.Text = "";
prevResult = res;
queryTextBlock.Text = res.OriginalQuery;
topIntentTextBlock.Text = res.TopScoringIntent.Name;
List<string> entitiesNames = new List<string>();
var entities = res.GetAllEntities();
foreach(Entity entity in entities)
{
entitiesNames.Add(entity.Name);
}
entitiesListBox.ItemsSource = entitiesNames;
if (res.DialogResponse != null)
{
if (res.DialogResponse.Status != "Finished")
{
dialogTextBlock.Text = res.DialogResponse.Prompt;
}
else
{
dialogTextBlock.Text = "Finished";
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,59 @@
<Page x:Class="Sample.UsingStaticIntentRouter"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Sample"
mc:Ignorable="d" d:DesignWidth="300"
Title="UsingStaticIntentRouter" Height="403">
<Grid>
<TextBox x:Name="txtAppId" HorizontalAlignment="Left" Height="23" Margin="28,30,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240" ToolTip="">
<TextBox.Style>
<Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="Enter your Application Id" Foreground="DarkGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<TextBox x:Name="txtPredict" HorizontalAlignment="Left" Height="23" Margin="28,73,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240">
<TextBox.Style>
<Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="Enter the text to predict" Foreground="DarkGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<Button x:Name="btnPredict" Content="Predict" HorizontalAlignment="Left" Margin="28,130,0,0" VerticalAlignment="Top" Width="75" Click="btnPredict_Click"/>
<Label x:Name="queryLabel" Content="Query:" HorizontalAlignment="Left" Margin="28,170,0,0" VerticalAlignment="Top" FontWeight="Bold"/>
<TextBlock x:Name="queryTextBlock" HorizontalAlignment="Left" Margin="81,175,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
<Label x:Name="topIntentLabel" Content="Top Intent:" HorizontalAlignment="Left" Margin="28,200,0,0" VerticalAlignment="Top" FontWeight="Bold"/>
<TextBlock x:Name="topIntentTextBlock" HorizontalAlignment="Left" Margin="104,205,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
</Grid>
</Page>

Просмотреть файл

@ -0,0 +1,89 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services: http://www.microsoft.com/cognitive
//
// Microsoft Cognitive Services Github:
// https://github.com/Microsoft/Cognitive
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Windows;
using System.Windows.Controls;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Cognitive.LUIS;
namespace Sample
{
/// <summary>
/// Interaction logic for UsingLUISClientDirectly.xaml
/// </summary>
public partial class UsingStaticIntentRouter : Page
{
public UsingStaticIntentRouter()
{
InitializeComponent();
}
private void btnPredict_Click(object sender, RoutedEventArgs e)
{
Predict();
}
public async void Predict()
{
string _appId = txtAppId.Text;
string _subscriptionKey = ((MainWindow)Application.Current.MainWindow).SubscriptionKey;
string _textToPredict = txtPredict.Text;
try
{
// Set up an intent router using the StaticIntentHandlers class to process intents
using (var router = IntentRouter.Setup<StaticIntentHandlers>(_appId, _subscriptionKey))
{
// Feed it into the IntentRouter to see if it was handled
var handled = await router.Route(_textToPredict, this);
if (!handled)
{
queryTextBlock.Text = "";
topIntentTextBlock.Text = "";
((MainWindow)Application.Current.MainWindow).Log("Intent was not matched confidently, maybe more training required?");
}
else
{
((MainWindow)Application.Current.MainWindow).Log("Predicted successfully.");
}
}
}
catch (Exception exception)
{
((MainWindow)Application.Current.MainWindow).Log(exception.Message);
}
}
}
}