Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup and tests #33

Merged
merged 5 commits into from
Apr 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion app/app.sln
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
.editorconfig = .editorconfig
..\.gitignore = ..\.gitignore
..\.github\workflows\dotnet-build.yml = ..\.github\workflows\dotnet-build.yml
..\LICENSE = ..\LICENSE
..\README.md = ..\README.md
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Shared", "shared\Shared\Shared.csproj", "{B54798B7-C176-4373-86D4-9D7376AD2E17}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClientApp.Tests", "tests\ClientApp.Tests\ClientApp.Tests.csproj", "{E74A1913-C9C9-4B58-8E0D-D42F8176D7A7}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClientApp.Tests", "tests\ClientApp.Tests\ClientApp.Tests.csproj", "{E74A1913-C9C9-4B58-8E0D-D42F8176D7A7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down
34 changes: 14 additions & 20 deletions app/backend/Extensions/SearchClientExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,15 @@ internal static async Task<string> QueryDocumentsAsync(
RequestOverrides? overrides = null,
CancellationToken cancellationToken = default)
{
SearchResults<SearchDocument> searchResult;
var documentContents = string.Empty;
var top = overrides?.Top ?? 3;
var exclude_category = overrides?.ExcludeCategory;
var filter = exclude_category == null ? string.Empty : $"category ne '{exclude_category}'";
var useSemanticRanker = overrides?.SemanticRanker ?? false;
var useSemanticCaptions = overrides?.SemanticCaptions ?? false;
SearchOptions searchOption;
if (useSemanticRanker)
{
searchOption = new SearchOptions

SearchOptions searchOption = useSemanticRanker
? new SearchOptions
{
Filter = filter,
QueryType = SearchQueryType.Semantic,
Expand All @@ -29,24 +27,20 @@ internal static async Task<string> QueryDocumentsAsync(
SemanticConfigurationName = "default",
Size = top,
QueryCaption = useSemanticCaptions ? QueryCaptionType.Extractive : QueryCaptionType.None,
};
}
else
{
searchOption = new SearchOptions
}
: new SearchOptions
{
Filter = filter,
Size = top,
};
}

var searchResultResponse = await searchClient.SearchAsync<SearchDocument>(query, searchOption, cancellationToken);

if (searchResultResponse.Value is null)
{
throw new InvalidOperationException("fail to get search result");
}

searchResult = searchResultResponse.Value;
SearchResults<SearchDocument> searchResult = searchResultResponse.Value;

// Assemble sources here.
// Example output for each SearchDocument:
Expand All @@ -67,13 +61,13 @@ internal static async Task<string> QueryDocumentsAsync(
{
if (useSemanticCaptions)
{
IEnumerable<string> docs = (IEnumerable<string>)doc.Captions.Select(c => c.Text);
var docs = doc.Captions.Select(c => c.Text);
contentValue = string.Join(" . ", docs);
}
else
{
doc.Document.TryGetValue("content", out var _contentValue);
contentValue = (string)_contentValue;
doc.Document.TryGetValue("content", out var value);
contentValue = (string)value;
}
}
catch (Exception)
Expand Down Expand Up @@ -121,15 +115,15 @@ internal static async Task<string> LookupAsync(
}

var searchResult = searchResultResponse.Value;
if(searchResult.Answers is var answers && answers.Count > 0)
if (searchResult is { Answers.Count: > 0 })
{
return answers[0].Text;
return searchResult.Answers[0].Text;
}

if(searchResult.TotalCount > 0)
if (searchResult.TotalCount > 0)
{
var contents = new List<string>();
foreach(var doc in searchResult.GetResults())
await foreach (var doc in searchResult.GetResultsAsync())
{
doc.Document.TryGetValue("content", out var contentValue);
if (contentValue is string content)
Expand Down
4 changes: 2 additions & 2 deletions app/backend/Services/Skills/LookupSkill.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ public LookupSkill(SearchClient searchClient, RequestOverrides? requestOverrides
[SKFunctionInput(Description = "lookup query")]
public async Task<string> ExecAsync(string lookupQuery, SKContext context)
{
if (lookupQuery is string)
if (lookupQuery is string query)
{
return await _searchClient.LookupAsync(lookupQuery, _requestOverrides);
return await _searchClient.LookupAsync(query, _requestOverrides);
}

throw new AIException(
Expand Down
2 changes: 1 addition & 1 deletion app/frontend/ClientApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
</ItemGroup>

<Target Name="WriteBackendUriToEmbedding" BeforeTargets="PrepareForBuild">
<Message Importance="high" Text="Write: $(BACKEND_URI) to embedding" />
<Message Importance="high" Text="Writing $(BACKEND_URI) as an embedded resource." />
<WriteLinesToFile File="BackendUri" Lines="$(BACKEND_URI)" Overwrite="true" Encoding="Unicode" />
<ItemGroup>
<EmbeddedResource Include="BackendUri" />
Expand Down
4 changes: 2 additions & 2 deletions app/frontend/Components/Answer.razor
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
: null;
<MudChip Variant="Variant.Text" Color="Color.Info"
Icon="@icon" OnClick="@(_ => OnShowCitation(citation))">
@($"{citation.Index}. {citation.Name}")
@($"{citation.Number}. {citation.Name}")
</MudChip>
}
</div>
Expand Down Expand Up @@ -58,7 +58,7 @@
<MudTabPanel Icon="@Icons.Material.Filled.TextSnippet" Text="Supporting Content"
ToolTip="Show the supporting content." Disabled="@(Retort is { DataPoints: null } or { DataPoints.Length: 0 })">
<ChildContent>
<MudPaper Class="pa-6" Elevation="3">
<MudPaper Elevation="3">
<SupportingContent DataPoints="Retort.DataPoints" />
</MudPaper>
</ChildContent>
Expand Down
10 changes: 5 additions & 5 deletions app/frontend/Components/Answer.razor.Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace ClientApp.Components;

public sealed partial class Answer
{
internal HtmlParsedAnswer ParseAnswerToHtml(string answer)
internal static HtmlParsedAnswer ParseAnswerToHtml(string answer)
{
var citations = new List<CitationDetails>();
var followupQuestions = new HashSet<string>();
Expand All @@ -27,20 +27,20 @@ internal HtmlParsedAnswer ParseAnswerToHtml(string answer)
}
else
{
var citationIndex = citations.Count + 1;
var citationNumber = citations.Count + 1;
var existingCitation = citations.FirstOrDefault(c => c.Name == part);
if (existingCitation is not null)
{
citationIndex = existingCitation.Index;
citationNumber = existingCitation.Number;
}
else
{
var citation = new CitationDetails(part, citationIndex);
var citation = new CitationDetails(part, citationNumber);
citations.Add(citation);
}

return $"""
<sup class="mud-chip mud-chip-text mud-chip-color-info rounded pa-1">{citationIndex}</sup>
<sup class="mud-chip mud-chip-text mud-chip-color-info rounded pa-1">{citationNumber}</sup>
""";
}
});
Expand Down
2 changes: 1 addition & 1 deletion app/frontend/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
global using Microsoft.AspNetCore.Components.Web;
global using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Options;
global using Microsoft.JSInterop;
global using MudBlazor;
global using MudBlazor.Services;
global using Shared.Models;

[assembly: System.Runtime.Versioning.SupportedOSPlatform("browser")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClientApp.Tests")]
2 changes: 1 addition & 1 deletion app/frontend/Models/CitationDetails.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

namespace ClientApp.Models;

public record CitationDetails(string Name, int Index = 0);
public record CitationDetails(string Name, int Number = 0);
30 changes: 20 additions & 10 deletions app/frontend/Program.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,6 @@
var builder = WebAssemblyHostBuilder.CreateDefault(args);

// load backend from embedded resource
var assembly = typeof(Program).Assembly;
var resourceName = "ClientApp.BackendUri";
using (Stream stream = assembly.GetManifestResourceStream(resourceName)!)
using (StreamReader reader = new StreamReader(stream))
{
// and set environment variables
var backendUri = await reader.ReadToEndAsync();
Environment.SetEnvironmentVariable("BACKEND_URI", backendUri ?? "https://localhost:7181");
}
await LoadBackendUriFromResourceAsync();

builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
Expand Down Expand Up @@ -37,3 +28,22 @@ await JSHost.ImportAsync(

var host = builder.Build();
await host.RunAsync();

static async ValueTask LoadBackendUriFromResourceAsync()
{
#if DEBUG
// When debugging, use localhost.
var backendUri = "https://localhost:7181";

await ValueTask.CompletedTask;
#else
// when in release mode, read from embedded resource.
using Stream stream = typeof(Program).Assembly.GetManifestResourceStream("ClientApp.BackendUri")!;
using StreamReader reader = new(stream);

var backendUri = await reader.ReadToEndAsync();
#endif

Environment.SetEnvironmentVariable(
"BACKEND_URI", backendUri ?? "https://localhost:7181");
}
10 changes: 0 additions & 10 deletions app/frontend/wwwroot/appsettings.Development.json

This file was deleted.

10 changes: 0 additions & 10 deletions app/frontend/wwwroot/appsettings.json

This file was deleted.

5 changes: 5 additions & 0 deletions app/frontend/wwwroot/css/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ pre {
padding-bottom: 1.2rem;
}

div.mud-tabs-panels > div > pre {
padding-top: initial;
padding-bottom: initial;
}

blockquote:empty {
display: none;
pointer-events: none;
Expand Down
58 changes: 58 additions & 0 deletions app/tests/ClientApp.Tests/AnswerParserTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Copyright (c) Microsoft. All rights reserved.

namespace ClientApp.Tests;

#pragma warning disable CA1416 // Validate platform compatibility

public class AnswerParserTests
{
public static IEnumerable<object[]> AnswerParserInput
{
get
{
yield return new object[]
{
"",
"",
new List<CitationDetails>(),
new HashSet<string>()
};

yield return new object[]
{
"""
Northwind Health Plus does not guarantee the amount charged by an out-of-network provider, and the member is responsible for any balance remaining after the plan has paid its portion [Northwind_Health_Plus_Benefits_Details-70.pdf].
Northwind Health Plus also pays for services that are not listed in the plan documents, if the health care provider determines that such services are medically necessary [Northwind_Health_Plus_Benefits_Details-102.pdf].
This includes services that are not covered under the plan, such as experimental treatments and services for cosmetic purposes [Northwind_Health_Plus_Benefits_Details-25.pdf].
""",
"""
Northwind Health Plus does not guarantee the amount charged by an out-of-network provider, and the member is responsible for any balance remaining after the plan has paid its portion <sup class="mud-chip mud-chip-text mud-chip-color-info rounded pa-1">1</sup>.
Northwind Health Plus also pays for services that are not listed in the plan documents, if the health care provider determines that such services are medically necessary <sup class="mud-chip mud-chip-text mud-chip-color-info rounded pa-1">2</sup>.
This includes services that are not covered under the plan, such as experimental treatments and services for cosmetic purposes <sup class="mud-chip mud-chip-text mud-chip-color-info rounded pa-1">3</sup>.
""",
new List<CitationDetails>
{
new CitationDetails("Northwind_Health_Plus_Benefits_Details-70.pdf", 1),
new CitationDetails("Northwind_Health_Plus_Benefits_Details-102.pdf", 2),
new CitationDetails("Northwind_Health_Plus_Benefits_Details-25.pdf", 3)
},
new HashSet<string>()
};
}
}

[Theory, MemberData(nameof(AnswerParserInput))]
public void AnswerCorrectlyParsesText(
string answerText,
string expectedHtml,
List<CitationDetails> expectedCitations,
HashSet<string> expectedFollowups)
{
var html = Answer.ParseAnswerToHtml(answerText);
Assert.Equal(expectedHtml, html.AnswerHtml);
Assert.Equal(html.Citations, expectedCitations);
Assert.Equal(html.FollowupQuestions, expectedFollowups);
}
}

#pragma warning restore CA1416 // Validate platform compatibility
3 changes: 2 additions & 1 deletion app/tests/ClientApp.Tests/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Copyright (c) Microsoft. All rights reserved.

global using Bunit;
global using Xunit;
global using ClientApp.Components;
global using ClientApp.Models;