TL;DR: Let’s see tips on how to implement AI-powered good search utilizing Syncfusion .NET MAUI Autocomplete management. We’ll cowl customized filtering and combine AI search with Azure OpenAI for seamless, related strategies—even when actual matches aren’t discovered. The submit explains tips on how to create a enterprise mannequin, customise the filter conduct, and arrange Azure OpenAI. Comply with alongside to reinforce consumer expertise with clever strategies!
Syncfusion .NET MAUI Autocomplete management is designed to effectively load and show strategies from giant datasets based mostly on consumer enter. It enhances consumer expertise by permitting choice from a instructed listing of related gadgets.
On this weblog, we’ll discover tips on how to implement the AI-powered good looking out function within the .NET MAUI Autocomplete management, which delivers seamless outcomes even when no actual matches are discovered.
Observe: Earlier than continuing, check with getting began with the .NET MAUI Autocomplete documentation.
Implementing good AI looking out in .NET MAUI Autocomplete
We’ll implement the AI-powered looking out utilizing the customized filtering function of the .NET MAUI Autocomplete management. First, we’ll cowl tips on how to implement customized filtering, after which we’ll combine AI search into this filtering course of.
On this weblog, I’ve used Azure OpenAI to offer the enter prompts and retrieve the filtering outcomes.
Implementing customized filtering in .NET MAUI Autocomplete
The .NET MAUI Autocomplete management permits you to apply customized filter logic to recommend gadgets based mostly in your particular filter standards by using the FilterBehavior property.
Step 1: Let’s create a brand new enterprise mannequin to go looking nation names. Check with the next code instance.
//Mannequin.cs
public class CountryModel { public string? Title { get; set; } }
//ViewModel.cs
public class CountryViewModel : INotifyPropertyChanged { non-public ObservableCollection<CountryModel> nations; public ObservableCollection<CountryModel> Nations { get { return nations; } set { nations = worth; OnPropertyChanged(nameof(Nations)); } } public CountryViewModel() { nations = new ObservableCollection<CountryModel> { new CountryModel { Title = "Afghanistan" }, new CountryModel { Title = "Akrotiri" }, new CountryModel { Title = "Albania" }, new CountryModel { Title = "Algeria" }, ….. }; } }
Step 2: Now, create a brand new class that derives from the IAutocompleteFilterBehavior interface.
public class CountryFilterBehavior: IAutocompleteFilterBehavior { }
Step 3: Subsequent, implement the GetMatchingItemsAsync technique from the IAutocompleteFilterBehavior interface to generate a suggestion listing. This listing ought to embody the filtered gadgets based mostly in your customized logic, which will probably be displayed within the Autocomplete management’s drop-down. The GetMatchingItemsAsync technique contains the next arguments:
- supply: Represents the proprietor of the filter conduct, offering entry to properties comparable to ItemsSource and different associated info.
- filterInfo: Accommodates particulars concerning the textual content entered within the Autocomplete management. You need to use this textual content to organize the suggestion listing, which will probably be displayed within the drop-down listing.
The next code demonstrates tips on how to show a drop-down listing of nations utilizing the .NET MAUI Autocomplete management. The listing is filtered based mostly on the textual content entered, displaying solely the nations that start with the enter.
public class CountryFilterBehavior : IAutocompleteFilterBehavior { public async Process<object> GetMatchingItemsAsync(SfAutocomplete supply, AutocompleteFilterInfo filterInfo) { IEnumerable itemssource = supply.ItemsSource as IEnumerable; var filteredItems = (from CountryModel merchandise in itemssource the place merchandise.Title.StartsWith(filterInfo.Textual content, StringComparison.CurrentCultureIgnoreCase) choose merchandise); return await Process.FromResult(filteredItems); } }
Step 4: Lastly, apply customized filtering to the .NET MAUI Autocomplete management utilizing the FilterBehavior property.
<ContentPage.BindingContext> <native: CountryViewModel /> </ContentPage.BindingContext> <VerticalStackLayout> <syncfusion:SfTextInputLayout Trace="Enter Nation Title" ContainerType="Outlined" WidthRequest="248" ContainerBackground="Clear"> <editors:SfAutocomplete x:Title="autoComplete" DropDownPlacement="Backside" MaxDropDownHeight="200" TextSearchMode="StartsWith" DisplayMemberPath="Title" ItemsSource="{Binding Nations}"> <editors:SfAutocomplete.FilterBehavior> <native: CountryFilterBehavior /> </editors:SfAutocomplete.FilterBehavior> </editors:SfAutocomplete> </syncfusion:SfTextInputLayout> </VerticalStackLayout>
The next picture demonstrates the output of the above customized filtering pattern.
Integrating Azure OpenAI together with your .NET MAUI App
First, guarantee you could have entry to Azure OpenAI and have created a deployment within the Azure portal.
In case you don’t have entry, please check with the create and deploy Azure OpenAI service information to arrange a brand new account.
On this weblog, we’ll use the Azure.AI.OpenAI NuGet bundle from the NuGet Gallery. So, earlier than getting began, set up the Azure.AI.OpenAI NuGet bundle in your .NET MAUI app.
Organising Azure OpenAI
Let’s start creating the Azure OpenAI service.
Step 1: We’ll assume that the GPT-35 mannequin, deployed beneath GPT35Turbo, is getting used. You should definitely change the endpoint, deployment title, and key together with your particular particulars.
Step 2: Subsequent, use the ChatCompletionsOptions to specify the immediate format for the system, consumer, and assistant messages within the Azure OpenAI. In our app, we’ve used the next messages as enter.
- ChatRequestSystemMessage – You’re a filtering assistant.
- ChatRequestUserMessage – Filter the listing gadgets based mostly on the consumer enter utilizing characters Beginning with and Phonetic algorithms like Soundex or Damerau-Levenshtein Distance. ” +r$”The filter ought to ignore spelling errors and be case insensitive.
- ChatRequestAssistantMessage – AfghanistannAkrotirinAlbanianAlgerianAmerican Samoa nAndorranAngolanAnguilla
Step 3: Then, use the OpenAIClient to handle the ChatCompletionsOptions and acquire the completion outcomes with the GetChatCompletionsAsync technique. We’ve beforehand outlined the ChatRequestAssistantMessage format for the AI response. This enables us to obtain the correct format of the response message. The next is the code for the AzureOpenAIService class.
public class AzureOpenAIService { const string endpoint = "https://{YOUR_END_POINT}.openai.azure.com"; const string deploymentName = "GPT35Turbo"; const string key = ""; non-public OpenAIClient? shopper; non-public ChatCompletionsOptions? chatCompletions;
public AzureOpenAIService() { InitializeClient(); } public void InitializeClient() { shopper = new OpenAIClient(new Uri(endpoint), new AzureKeyCredential(key)); chatCompletions = new ChatCompletionsOptions { DeploymentName = deploymentName, Temperature = (float)1.2f, MaxTokens = 120, NucleusSamplingFactor = (float)0.9, FrequencyPenalty = 0.8f, PresencePenalty = 0.8f }; // Add the system message to the choices. chatCompletions.Messages.Add(new ChatRequestSystemMessage("You're a filtering assistant.")); chatCompletions.Messages.Add(new ChatRequestUserMessage("$"Filter the listing gadgets based mostly on the consumer enter utilizing character Beginning with and Phonetic algorithms like Soundex or Damerau-Levenshtein Distance. " +r$"The filter ought to ignore spelling errors and be case insensitive.")); chatCompletions.Messages.Add(newChatRequestAssistantMessage( "nAfghanistannAkrotirinAlbanianAlgerianAmerican Samoa nAndorranAngolanAnguilla")); } public async Process<string> GetCompletion(string immediate, CancellationToken cancellationToken) { if (chatCompletions != null && shopper != null) { if (chatCompletions.Messages.Depend > 5) { //Take away the message historical past to keep away from exceeding the token restrict. chatCompletions.Messages.RemoveAt(1); chatCompletions.Messages.RemoveAt(1); } // Add the consumer message to the choices. chatCompletions.Messages.Add(new ChatRequestUserMessage(immediate)); attempt { //Right here, cancelling the earlier request to proceed our search. cancellationToken.ThrowIfCancellationRequested(); var chatresponse = await shopper.GetChatCompletionsAsync(chatCompletions); cancellationToken.ThrowIfCancellationRequested(); string chatcompletionText = chatresponse.Worth.Selections[0].Message.Content material.Trim(); chatCompletions.Messages.Add(new ChatRequestAssistantMessage(chatcompletionText)); return chatcompletionText; } catch (RequestFailedException ex) { // Log the error message and rethrow the exception or deal with it appropriately. Debug.WriteLine($"Request failed: {ex.Message}"); throw; } catch (Exception ex) { // Deal with different potential exceptions. Debug.WriteLine($"An error occurred: {ex.Message}"); throw; } } return ""; } }
Connecting to Azure OpenAI
In our .NET MAUI app, we will set up a connection to the Azure OpenAI service by way of a customized filtering class.
The customized filtering class makes use of the GetMatchingItemsAsync technique, which is invoked every time after we present enter textual content into the Autocomplete management. By connecting to Azure OpenAI service, we create a immediate based mostly on the entered textual content and retrieve the response message. After which, we convert the response message to an output assortment.
So, modify the present CountryFilterBehavior to hook up with Azure OpenAI service. Check with the next code instance.
public class CountryFilterBehavior: IAutocompleteFilterBehavior { non-public readonly AzureAIService _azureAIService; public ObservableCollection<CountryModel> Nations { get; set; } public ObservableCollection<CountryModel> FilteredCountries { get; set; } = new ObservableCollection<CountryModel>(); non-public CancellationTokenSource? _cancellationTokenSource; public CountryFilterBehavior () { _azureAIService = new AzureAIService(); Nations = new ObservableCollection<CountryModel>(); _cancellationTokenSource = new CancellationTokenSource(); } public async Process<object?> GetMatchingItemsAsync(SfAutocomplete supply, AutocompleteFilterInfo filterInfo) { if (string.IsNullOrEmpty(filterInfo.Textual content)) { _cancellationTokenSource?.Cancel(); FilteredCountries.Clear(); return await Process.FromResult(FilteredCountries); } Nations = (ObservableCollection<CountryModel>)supply.ItemsSource; string listItems = string.Be a part of(", ", Nations!.Choose(c => c.Title)); // Be a part of the primary 5 gadgets with newline characters for the demo output template for AI string outputTemplate = string.Be a part of("n", Nations.Take(5).Choose(c => c.Title)); //The cancellationToken was used for cancelling the API request if consumer sorts repeatedly _cancellationTokenSource?.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; // Filter the nation listing utilizing the Azure open AI var filterCountries = await FilterCountriesUsingAzureOpenAI(filterInfo.Textual content, listItems, outputTemplate, cancellationToken); return await Process.FromResult(filterCountries); } /// <abstract> /// Filters nation names based mostly on consumer enter utilizing Azure AI. /// </abstract> public async Process<ObservableCollection<CountryModel>> FilterCountriesUsingAzureOpenAI(string userInput, string itemsList, string outputTemplate, CancellationToken cancellationToken) { if (!string.IsNullOrEmpty(userInput)) { //Add the immediate based mostly in your filtering var immediate = $"Filter the listing gadgets based mostly on the consumer enter utilizing character Beginning with and Phonetic algorithms like Soundex or Damerau-Levenshtein Distance. " + $"The filter ought to ignore spelling errors and be case insensitive. " + $"Return solely the filtered gadgets with every merchandise in new line with none further content material like explanations, Hyphen, Numberings and - Minus signal. Ignore the content material 'Listed below are the filtered gadgets or related issues' " + $"Solely return gadgets which are current within the Checklist Gadgets. " + $"Be certain that every filtered merchandise is returned in its entirety with out lacking any a part of its content material. " + $"Organize the filtered gadgets that beginning with the consumer enter's first letter are on the first index, adopted by different matches. " + $"Examples of filtering conduct: " + $"The instance knowledge are for reference, dont present these as output. Filter the merchandise from listing gadgets correctly" + $"Right here is the Consumer enter: {userInput}, " + $"Checklist of Gadgets: {itemsList}" + $"If no gadgets discovered, return "Empty" " + $"Dont use 'Listed below are the filtered gadgets:' within the output. Verify this demo output template, you must return output like this: {outputTemplate} "; var completion = await _azureAIService.GetCompletion(immediate, cancellationToken); var filteredCountryNames = completion.Break up('n').Choose(x => x.Trim()).The place(x => !string.IsNullOrEmpty(x)).ToList(); if (FilteredCountries.Depend > 0) FilteredCountries.Clear(); if (completion.ToLower().Trim() != "empty")
{ foreach (var nation in filteredCountryNames) { FilteredCountries.Add(new CountryModel { Title = nation }); } } } return FilteredCountries; }
The next picture demonstrates the output of the above AI-based search utilizing a customized filtering pattern.
GitHub reference
For extra particulars, check with the AI-powered good looking out within the .NET MAUI Autocomplete management GitHub demo.
Conclusion
Thanks for studying! On this weblog, we explored tips on how to implement AI-powered good looking out within the .NET MAUI Autocomplete management. This can ship seamless outcomes, even when no actual matches are discovered. This function is offered within the 2024 Quantity 3 launch. Check out the steps shared right here, and go away your suggestions within the feedback part beneath!
The prevailing prospects can obtain the most recent model of Important Studio from the License and Downloads web page. If you’re new, attempt our 30-day free trial to discover our unimaginable options.
In case you want help, please don’t hesitate to contact us through our assist discussion board, assist portal, or suggestions portal. We’re all the time keen that will help you!
Associated blogs