-
Notifications
You must be signed in to change notification settings - Fork 310
Add Notes App for AppContentSearch Samples #566
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
Open
karkarl
wants to merge
6
commits into
microsoft:release/experimental
Choose a base branch
from
karkarl:user/karkarl/ACSSamples
base: release/experimental
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| --- | ||
| page_type: sample | ||
| languages: | ||
| - csharp | ||
| products: | ||
| - windows | ||
| - windows-app-sdk | ||
| name: "AppContentSearch Sample" | ||
| urlFragment: AppContentSearchSample | ||
| description: "Demonstrates how to use the AppContentSearch APIs in Windows App SDK to index and semantically search text content and images in a WinUI3 notes application." | ||
| extendedZipContent: | ||
| - path: LICENSE | ||
| target: LICENSE | ||
| --- | ||
|
|
||
|
|
||
| # AppContentSearch Sample Application | ||
|
|
||
| This sample demonstrates how to use App Content Search's **AppContentIndex APIs** in a **WinUI3** notes application. It shows how to create, manage, and semantically search through the index that includes both text content and images. It also shows how to use use the search results to enable retrieval augmented genaration (RAG) scenarios with language models. | ||
|
|
||
| > **Note**: This sample is targeted and tested for **Windows App SDK 2.0 Experimental2** and **Visual Studio 2022**. The AppContentSearch APIs are experimental and available in Windows App SDK 2.0 experimental2. | ||
|
|
||
|
|
||
| ## Features | ||
|
|
||
| This sample demonstrates: | ||
|
|
||
| - **Creating Index**: Create an index with optional settings. | ||
| - **Indexing Content**: Add, update, and remove content from the index | ||
| - **Text Content Search**: Query the index for text-based results. | ||
| - **Image Content Search**: Query the index for image-based results. | ||
| - **Search Results Display**: Display both text and image search results with relevance highlighting and bounding boxes for image matches | ||
| - **Retrieval Augmented Generation (RAG)**: Use query search results with language models for retrieval augmented generation (RAG) scenarios. | ||
|
|
||
|
|
||
| ## Prerequisites | ||
|
|
||
| * See [System requirements for Windows app development](https://docs.microsoft.com/windows/apps/windows-app-sdk/system-requirements). | ||
| * Make sure that your development environment is set up correctly—see [Install tools for developing apps for Windows 10 and Windows 11](https://docs.microsoft.com/windows/apps/windows-app-sdk/set-up-your-development-environment). | ||
| * This sample requires Visual Studio 2022 and .NET 9. | ||
|
|
||
|
|
||
| ## Building and Running the Sample | ||
|
|
||
| * Open the solution file (`AppContentSearch.sln`) in Visual Studio. | ||
| * Press Ctrl+Shift+B, or select **Build** \> **Build Solution**. | ||
| * Run the application to see the Notes app with integrated search functionality. | ||
|
|
||
|
|
||
| ## Related Documentation and Code Samples | ||
|
|
||
| * [Windows App SDK](https://docs.microsoft.com/windows/apps/windows-app-sdk/) | ||
| * [AppContentSearch API Documentation](https://learn.microsoft.com/en-us/windows/ai/apis/app-content-search) | ||
242 changes: 242 additions & 0 deletions
242
Samples/AppContentSearch/cs-winui/AI/IChatClient/PhiSilicaClient.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,242 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
|
|
||
| using Microsoft.Extensions.AI; | ||
| using Microsoft.Windows.AI.ContentSafety; | ||
| using Microsoft.Windows.AI.Text; | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Runtime.CompilerServices; | ||
| using System.Text; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Windows.Foundation; | ||
|
|
||
| namespace Notes.AI; | ||
|
|
||
| internal class PhiSilicaClient : IChatClient | ||
| { | ||
| // Search Options | ||
| private const int DefaultTopK = 50; | ||
| private const float DefaultTopP = 0.9f; | ||
| private const float DefaultTemperature = 1; | ||
|
|
||
| private LanguageModel? _languageModel; | ||
|
|
||
| public ChatClientMetadata Metadata { get; } | ||
|
|
||
| private PhiSilicaClient() | ||
| { | ||
| Metadata = new ChatClientMetadata("PhiSilica", new Uri($"file:///PhiSilica")); | ||
| } | ||
|
|
||
| private static ChatOptions GetDefaultChatOptions() | ||
| { | ||
| return new ChatOptions | ||
| { | ||
| Temperature = DefaultTemperature, | ||
| TopP = DefaultTopP, | ||
| TopK = DefaultTopK, | ||
| }; | ||
| } | ||
|
|
||
| public static async Task<PhiSilicaClient?> CreateAsync(CancellationToken cancellationToken = default) | ||
| { | ||
| #pragma warning disable CA2000 // Dispose objects before losing scope | ||
| var phiSilicaClient = new PhiSilicaClient(); | ||
| #pragma warning restore CA2000 // Dispose objects before losing scope | ||
|
|
||
| try | ||
| { | ||
| await phiSilicaClient.InitializeAsync(cancellationToken); | ||
| } | ||
| catch | ||
| { | ||
| return null; | ||
| } | ||
karkarl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return phiSilicaClient; | ||
| } | ||
|
|
||
| public Task<ChatResponse> GetResponseAsync(IList<ChatMessage> chatMessages, ChatOptions? options = null, CancellationToken cancellationToken = default) => | ||
| GetStreamingResponseAsync(chatMessages, options, cancellationToken).ToChatResponseAsync(cancellationToken: cancellationToken); | ||
|
|
||
| public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IList<ChatMessage> chatMessages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) | ||
| { | ||
| if (_languageModel == null) | ||
| { | ||
| throw new InvalidOperationException("Language model is not loaded."); | ||
| } | ||
|
|
||
| string prompt = GetPromptAsString(chatMessages); | ||
|
|
||
| await foreach (var part in GenerateStreamResponseAsync(prompt, options, cancellationToken)) | ||
| { | ||
| yield return new ChatResponseUpdate | ||
| { | ||
| Role = ChatRole.Assistant, | ||
| Text = part, | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| private (LanguageModelOptions? ModelOptions, ContentFilterOptions? FilterOptions) GetModelOptions(ChatOptions options) | ||
| { | ||
| if (options == null) | ||
| { | ||
| return (null, null); | ||
| } | ||
|
|
||
| var languageModelOptions = new LanguageModelOptions | ||
| { | ||
| Temperature = options.Temperature ?? DefaultTemperature, | ||
| TopK = (uint)(options.TopK ?? DefaultTopK), | ||
| TopP = (uint)(options.TopP ?? DefaultTopP), | ||
| }; | ||
|
|
||
| var contentFilterOptions = new ContentFilterOptions(); | ||
|
|
||
| if (options?.AdditionalProperties?.TryGetValue("input_moderation", out SeverityLevel inputModeration) == true && inputModeration != SeverityLevel.Low) | ||
karkarl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| contentFilterOptions.PromptMaxAllowedSeverityLevel = new TextContentFilterSeverity | ||
| { | ||
| Hate = inputModeration, | ||
| Sexual = inputModeration, | ||
| Violent = inputModeration, | ||
| SelfHarm = inputModeration | ||
| }; | ||
| } | ||
|
|
||
| if (options?.AdditionalProperties?.TryGetValue("output_moderation", out SeverityLevel outputModeration) == true && outputModeration != SeverityLevel.Low) | ||
karkarl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| contentFilterOptions.ResponseMaxAllowedSeverityLevel = new TextContentFilterSeverity | ||
| { | ||
| Hate = outputModeration, | ||
| Sexual = outputModeration, | ||
| Violent = outputModeration, | ||
| SelfHarm = outputModeration | ||
| }; | ||
| } | ||
|
|
||
| return (languageModelOptions, contentFilterOptions); | ||
| } | ||
|
|
||
| private string GetPromptAsString(IEnumerable<ChatMessage> chatHistory) | ||
| { | ||
| if (!chatHistory.Any()) | ||
| { | ||
| return string.Empty; | ||
| } | ||
|
|
||
| StringBuilder prompt = new StringBuilder(); | ||
|
|
||
| for (var i = 0; i < chatHistory.Count(); i++) | ||
| { | ||
| var message = chatHistory.ElementAt(i); | ||
|
|
||
| if (!string.IsNullOrEmpty(message.Text)) | ||
| { | ||
| prompt.AppendLine(message.Text); | ||
| } | ||
| } | ||
|
|
||
| return prompt.ToString(); | ||
| } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| _languageModel?.Dispose(); | ||
| _languageModel = null; | ||
| } | ||
|
|
||
| public object? GetService(Type serviceType, object? serviceKey = null) | ||
| { | ||
| return | ||
| serviceKey is not null ? null : | ||
| _languageModel is not null && serviceType?.IsInstanceOfType(_languageModel) is true ? _languageModel : | ||
| serviceType?.IsInstanceOfType(this) is true ? this : | ||
| serviceType?.IsInstanceOfType(typeof(ChatOptions)) is true ? GetDefaultChatOptions() : | ||
| null; | ||
| } | ||
|
|
||
| public static bool IsAvailable() | ||
| { | ||
| try | ||
| { | ||
| return LanguageModel.GetReadyState() == Microsoft.Windows.AI.AIFeatureReadyState.Ready; | ||
| } | ||
| catch | ||
| { | ||
| return false; | ||
| } | ||
karkarl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| private async Task InitializeAsync(CancellationToken cancellationToken = default) | ||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| if (!IsAvailable()) | ||
| { | ||
| await LanguageModel.EnsureReadyAsync(); | ||
| } | ||
|
|
||
| cancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| _languageModel = await LanguageModel.CreateAsync(); | ||
| } | ||
|
|
||
| #pragma warning disable IDE0060 // Remove unused parameter | ||
| public async IAsyncEnumerable<string> GenerateStreamResponseAsync(string prompt, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) | ||
| #pragma warning restore IDE0060 // Remove unused parameter | ||
| { | ||
| if (_languageModel == null) | ||
| { | ||
| throw new InvalidOperationException("Language model is not loaded."); | ||
| } | ||
|
|
||
| string currentResponse = string.Empty; | ||
| using var newPartEvent = new ManualResetEventSlim(false); | ||
|
|
||
| IAsyncOperationWithProgress<LanguageModelResponseResult, string>? progress; | ||
| if (options == null) | ||
| { | ||
| progress = _languageModel.GenerateResponseAsync(prompt, new LanguageModelOptions()); | ||
| } | ||
| else | ||
| { | ||
| var (modelOptions, filterOptions) = GetModelOptions(options); | ||
karkarl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| progress = _languageModel.GenerateResponseAsync(prompt, modelOptions); | ||
| } | ||
|
|
||
| progress.Progress = (result, value) => | ||
| { | ||
| currentResponse = value; | ||
| newPartEvent.Set(); | ||
| if (cancellationToken.IsCancellationRequested) | ||
| { | ||
| progress.Cancel(); | ||
| } | ||
| }; | ||
|
|
||
| while (progress.Status != AsyncStatus.Completed) | ||
| { | ||
| await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding); | ||
|
|
||
| if (newPartEvent.Wait(10, cancellationToken)) | ||
| { | ||
| yield return currentResponse; | ||
| newPartEvent.Reset(); | ||
| } | ||
| } | ||
|
|
||
| var response = await progress; | ||
|
|
||
| yield return response?.Status switch | ||
| { | ||
| LanguageModelResponseStatus.BlockedByPolicy => "\nBlocked by policy", | ||
| LanguageModelResponseStatus.PromptBlockedByContentModeration => "\nPrompt blocked by content moderation", | ||
| LanguageModelResponseStatus.ResponseBlockedByContentModeration => "\nResponse blocked by content moderation", | ||
| _ => string.Empty, | ||
| }; | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we put this folder under Samples/WindowsAIFoundry?
Since that's how I discover Windows AI related feature.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would I be moving the other sample under
Samples/WindowsAIFoundry/cs-winuiin its own directory and placing the AppContentSearch sample in that same folder?