Thursday, April 18, 2024
HomeC#Create a Place Explorer App Utilizing .NET MAUI and ChatGPT

Create a Place Explorer App Utilizing .NET MAUI and ChatGPT


On this weblog submit, we’ll discover the method of creating a .NET MAUI utility that leverages OpenAI’s ChatGPT APIs to ship place suggestions primarily based on the person’s location. The appliance will function a user-friendly interface the place customers can enter their geographical location, and in return, they’ll obtain details about widespread landmarks and sights close by.

To get began with creating the applying, there are a number of conditions that have to be fulfilled:

  • OpenAI account: You will want to have an account with OpenAI to entry their APIs and procure an API key.
  • OpenAI API key: After getting an account, generate an API key from OpenAI. This key will likely be used to authenticate your requests to their APIs.
  • .NET MAUI set up: Guarantee you’ve got the mandatory dependencies and instruments put in for .NET MAUI utility improvement. This consists of having the .NET SDK, MAUI workload, and associated libraries arrange in your improvement machine.

Subsequent, I’ll element tips on how to meet these conditions.

Be aware: To entry OpenAI’s APIs in your .NET MAUI utility, you want the API key, which isn’t free. If you’re contemplating a paid account, this weblog will provide you with an thought of the way you would possibly put it to use, even when you can’t comply with alongside. Examine the pricing web page for extra particulars.

The right way to create an Open AI account

To create an OpenAI account, comply with these steps:

  1. Go to the official OpenAI web site
  2. Search for the Signal Up button on the web site’s homepage and click on on it. It will direct you to the account creation web page.
  3. Fill out the required info within the sign-up type.
  4. Confirm your e-mail handle by clicking on a verification hyperlink despatched to your registered e-mail.
  5. As soon as your registration is profitable, it is best to have the ability to log in to your OpenAI account utilizing the credentials you offered through the sign-up course of.

By following these steps, you’ll be able to create an OpenAI account and achieve entry to their companies.

The right way to get an OpenAI API key

To acquire an OpenAI API key:

  1. Go to the OpenAI web site and sign up utilizing your account credentials.
  2. Navigate to the API part of the OpenAI platform. This may be discovered within the Account Settings.
  3. Create a brand new secret API key. That is the place you’re required to buy it.

Create a spot explorer app with .NET MAUI

Please create a .NET MAUI utility and comply with the directions throughout the mission.

Configuring ChatGPT APIs

To combine the ChatGPT library and name its APIs in your .NET MAUI mission, comply with these steps:

  1. Reference and bootstrap the ChatGptNet library. Open the Bundle Supervisor Console from the Instruments menu in Visible Studio, and run the next command to put in the ChatGptNet library.
    Set up-Bundle ChatGptNet
  1. Within the MauiProgram.cs file, find the CreateMauiApp Add the next code.
    builder.Providers.AddChatGpt(choices =>
    {
       choices.ApiKey = ""; // Your API Key Right here;
       choices.Group = null; // Elective
       choices.DefaultModel = ChatGptModels.Gpt35Turbo; // Default: ChatGptModels.Gpt35Turbo
       choices.MessageLimit = 10; // Default: 10
       choices.MessageExpiration = TimeSpan.FromMinutes(5); // Default: 1 hour
    });

Add vital NuGet packages

On this utility, I’ll make the most of the Syncfusion .NET MAUI controls, particularly the Maps, Busy Indicator, and Popup controls. These controls will play essential roles in enhancing the performance and person expertise of the app.

The Maps management would be the centerpiece of the applying, permitting customers to pick a particular location by choosing the latitude and longitude. With the Maps management, customers can have an interactive and visually interesting interface to navigate and discover totally different areas.

To offer a seamless person expertise, I’ll incorporate the Busy Indicator management. This management will likely be activated when the applying communicates with the ChatGPT API to retrieve suggestions primarily based on the chosen location. The Busy Indicator will show an animated loading indicator, assuring customers that the app is working within the background to fetch the specified info.

I’ll make the most of the Popup management to current the output akin to the chosen location. This management will allow me to show related info and suggestions in an organized and visually interesting method.

Syncfusion .NET MAUI elements can be found on NuGet.org. So as to add SfMaps to your mission, open the NuGet package deal supervisor in Visible Studio, seek for Syncfusion.Maui.Maps, after which set up it. Equally, SfBusyIndicator is accessible within the Syncfusion.Maui.Core NuGet package deal and SfPopup is accessible within the Syncfusion.Maui.Popup NuGet package deal.

Handler registration

Syncfusion.Maui.Core NuGet is a dependent package deal for all Syncfusion .NET MAUI controls. Within the MauiProgram.cs file, register the handler for Syncfusion core.

utilizing ChatGptNet;
utilizing ChatGptNet.Fashions;
utilizing Microsoft.Extensions.Logging;
utilizing Syncfusion.Maui.Core.Internet hosting;

namespace ChatGPTinMAUI;

public static class MauiProgram
{
   public static MauiApp CreateMauiApp()
   {
	var builder = MauiApp.CreateBuilder();
	builder.UseMauiApp<App>()
	
        builder.ConfigureSyncfusionCore();
        builder.Providers.AddChatGpt(choices =>
        {
            choices.ApiKey = ""; // Your API key right here;  choices.Group = null; // Elective
            choices.DefaultModel = ChatGptModels.Gpt35Turbo; // Default: ChatGptModels.Gpt35Turbo
            choices.MessageLimit = 10; // Default: 10
            choices.MessageExpiration = TimeSpan.FromMinutes(5); // Default: 1 hour
        });
       #if DEBUG
         builder.Logging.AddDebug();
       #endif
         return builder.Construct();
    }
}

Designing the UI

Create the required UI:

  1. Declare the required namespaces within the ContentPage, which represents a web page within the utility’s person interface.

    The XAML code begins with declaring the mandatory namespaces utilizing the xmlns attribute. The required namespaces are:

    • clr-namespace:Syncfusion.Maui.Maps;meeting=Syncfusion.Maui.Maps” for the Syncfusion Maps management.
    • clr-namespace:Syncfusion.Maui.Core;meeting=Syncfusion.Maui.Core” for the Syncfusion BusyIndicator management.
    • clr-namespace:Syncfusion.Maui.Popup;meeting=Syncfusion.Maui.Popup” for the Syncfusion Popup management.
      <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                   xmlns:maps="clr-namespace:Syncfusion.Maui.Maps;meeting=Syncfusion.Maui.Maps"
                   xmlns:busy="clr-namespace:Syncfusion.Maui.Core;meeting=Syncfusion.Maui.Core"
                   xmlns:syncfusion="clr-namespace:Syncfusion.Maui.Popup;meeting=Syncfusion.Maui.Popup"
                   x:Class="ChatGPTinMAUI.MainPage">
      </ContentPage>
      
  1. Contained in the ContentPage, add an occasion of the busy:SfBusyIndicator management. Right here, I’m naming it busyIndicator.
    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:maps="clr-namespace:Syncfusion.Maui.Maps;meeting=Syncfusion.Maui.Maps"
                 xmlns:busy="clr-namespace:Syncfusion.Maui.Core;meeting=Syncfusion.Maui.Core"
                 xmlns:syncfusion="clr-namespace:Syncfusion.Maui.Popup;meeting=Syncfusion.Maui.Popup"
                 x:Class="ChatGPTinMAUI.MainPage">
     <busy:SfBusyIndicator x:Identify="busyIndicator">
     </busy:SfBusyIndicator>
    </ContentPage>
  1. Add a ScrollView ingredient to offer vertical scrolling performance for the content material throughout the web page. Throughout the ScrollView, add a Grid ingredient. The Grid is a container for different controls and permits versatile structure preparations.
    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:maps="clr-namespace:Syncfusion.Maui.Maps;meeting=Syncfusion.Maui.Maps"
                 xmlns:busy="clr-namespace:Syncfusion.Maui.Core;meeting=Syncfusion.Maui.Core"
                 xmlns:syncfusion="clr-namespace:Syncfusion.Maui.Popup;meeting=Syncfusion.Maui.Popup"
                 x:Class="ChatGPTinMAUI.MainPage">
     <busy:SfBusyIndicator x:Identify="busyIndicator">
      <ScrollView>
       <Grid>
       </Grid>
      </ScrollView>
     </busy:SfBusyIndicator>
    </ContentPage>
  1. Contained in the grid, add a maps:SfMaps management. This management shows a map utilizing OpenStreetMap tiles. The MapTileLayer ingredient defines the URL template for the map tiles, and the MapZoomPanBehavior specifies the zooming and panning habits.
    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:maps="clr-namespace:Syncfusion.Maui.Maps;meeting=Syncfusion.Maui.Maps"
                 xmlns:busy="clr-namespace:Syncfusion.Maui.Core;meeting=Syncfusion.Maui.Core"
                 xmlns:syncfusion="clr-namespace:Syncfusion.Maui.Popup;meeting=Syncfusion.Maui.Popup"
                 x:Class="ChatGPTinMAUI.MainPage">
     <busy:SfBusyIndicator x:Identify="busyIndicator">
      <ScrollView>
       <Grid >
        <maps:SfMaps x:Identify="maps">
         <maps:SfMaps.Layer>
          <maps:MapTileLayer UrlTemplate="https://tile.openstreetmap.org/{z}/{x}/{y}.png">
           <maps:MapTileLayer.ZoomPanBehavior>
            <maps:MapZoomPanBehavior MinZoomLevel="3"
                                     MaxZoomLevel="10"
                                     EnableDoubleTapZooming="True"
                                     ZoomLevel="3">
            </maps:MapZoomPanBehavior>
           </maps:MapTileLayer.ZoomPanBehavior>
          </maps:MapTileLayer>
         </maps:SfMaps.Layer>
        </maps:SfMaps>
       </Grid>
      </ScrollView>
     </busy:SfBusyIndicator>
    </ContentPage>
  1. Contained in the Grid, add a syncfusion:SfPopup management. I’m naming popupDisplay. It shows a pop-up window when triggered. The SfPopup.ContentTemplate defines the content material that will likely be displayed within the pop-up. It incorporates a grid with a label displaying the locations to go to within the chosen location and a scroll view with a label sure to a ContentText property for displaying the content material.
    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:maps="clr-namespace:Syncfusion.Maui.Maps;meeting=Syncfusion.Maui.Maps"
                 xmlns:busy="clr-namespace:Syncfusion.Maui.Core;meeting=Syncfusion.Maui.Core"
                 xmlns:syncfusion="clr-namespace:Syncfusion.Maui.Popup;meeting=Syncfusion.Maui.Popup"
                 x:Class="ChatGPTinMAUI.MainPage">
     <busy:SfBusyIndicator x:Identify="busyIndicator">
      <ScrollView>
       <Grid >
        <maps:SfMaps x:Identify="maps">
         <maps:SfMaps.Layer>
          <maps:MapTileLayer UrlTemplate="https://tile.openstreetmap.org/{z}/{x}/{y}.png">
           <maps:MapTileLayer.ZoomPanBehavior>
            <maps:MapZoomPanBehavior MinZoomLevel="3"
                                     MaxZoomLevel="10"
                                     EnableDoubleTapZooming="True"
                                     ZoomLevel="3">
            </maps:MapZoomPanBehavior>
           </maps:MapTileLayer.ZoomPanBehavior>
          </maps:MapTileLayer>
         </maps:SfMaps.Layer>
        </maps:SfMaps>
        <syncfusion:SfPopup x:Identify="popupDisplay" 
                            IsOpen="false" 
                            ShowHeader="False"
                            WidthRequest="500"
                            HeightRequest="300">
         <syncfusion:SfPopup.ContentTemplate>
          <DataTemplate>
           <Grid RowDefinitions="20,*">
            <Label Textual content="5 locations to go to on this location :" FontSize="14" FontAttributes="Daring" />
            <ScrollView Grid.Row="1" >
             <Label Textual content="{Binding ContentText}" Margin="0,10,0,10" />
            </ScrollView>
           </Grid>
          </DataTemplate>
         </syncfusion:SfPopup.ContentTemplate>
        </syncfusion:SfPopup>
       </Grid>
      </ScrollView>
     </busy:SfBusyIndicator>
    </ContentPage>

General, the XAML code creates a content material web page with a Busy Indicator management, a scroll view, a Maps management, and a Popup management.

Implementing the code-behind

  1. Declare the next namespaces within the code-behind file:
    • ChatGptNet and ChatGptNet.Fashions: Namespaces for the ChatGptNet library, which supplies performance for making calls to OpenAI’s ChatGPT API.
    • Syncfusion.Maui.Maps: The Syncfusion Maps management’s namespace for displaying maps.
      utilizing ChatGptNet;
      utilizing ChatGptNet.Fashions;
      utilizing Syncfusion.Maui.Maps;
      

      The code is throughout the ChatGPTinMAUI namespace, and the MainPage class is outlined as a partial class extending the ContentPage class.

      utilizing ChatGptNet;
      utilizing ChatGptNet.Fashions;
      utilizing Syncfusion.Maui.Maps;
      namespace ChatGPTinMAUI;
      
      public partial class MainPage : ContentPage { }
  1. Outline the Title and ContentText properties. The Title is a bindable property outlined utilizing the BindableProperty.Create methodology. It represents the title of the web page and permits binding, animation, and styling. The ContentText property can be a bindable property, representing the content material textual content displayed on the web page.
    utilizing ChatGptNet;
    utilizing ChatGptNet.Fashions;
    utilizing Syncfusion.Maui.Maps;
    
    namespace ChatGPTinMAUI;
    
    public partial class MainPage : ContentPage
    {
        public String Title
        {
            get { return (String)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, worth); }
        }
        
        public static readonly BindableProperty TitleProperty =
            BindableProperty.Create("Title", typeof(String), typeof(MainPage), String.Empty);
        
        public String ContentText
        {
            get { return (String)GetValue(ContentTextProperty); }
            set { SetValue(ContentTextProperty, worth); }
        }
        
        public static readonly BindableProperty ContentTextProperty =
            BindableProperty.Create("ContentText", typeof(String), typeof(MainPage), String.Empty);
    }
  1. Within the MainPage constructor, initialize the web page by calling InitializeComponent and subscribe to the Loaded occasion.
    utilizing ChatGptNet;
    utilizing ChatGptNet.Fashions;
    utilizing Syncfusion.Maui.Maps;
    
    namespace ChatGPTinMAUI;
    
    public partial class MainPage : ContentPage
    {
        public String Title
        {
            get { return (String)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, worth); }
        }
        
        public static readonly BindableProperty TitleProperty =
            BindableProperty.Create("Title", typeof(String), typeof(MainPage), String.Empty);
        
        public String ContentText
        {
            get { return (String)GetValue(ContentTextProperty); }
            set { SetValue(ContentTextProperty, worth); }
        }
        
        public static readonly BindableProperty ContentTextProperty =
            BindableProperty.Create("ContentText", typeof(String), typeof(MainPage), String.Empty);
        
        personal IChatGptClient _chatGptClient;
        personal Guid _sessionGuid = Guid.Empty;
        MapMarkerCollection mapMarkers = new MapMarkerCollection();
        MapMarker mapMarker = new MapMarker();
        
        public MainPage()
        {
            InitializeComponent();
           
            this.Loaded += MainPage_Loaded;
            mapMarkers.Add(mapMarker);
            this.BindingContext = this;
        }
    }
  1. The MainPage_Loaded occasion handler is invoked when the web page is loaded. Retrieve an occasion of the IChatGptClient service utilizing dependency injection on this occasion.
    utilizing ChatGptNet;
    utilizing ChatGptNet.Fashions;
    utilizing Syncfusion.Maui.Maps;
    
    namespace ChatGPTinMAUI;
    
    public partial class MainPage : ContentPage
    {
        public String Title
        {
            get { return (String)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, worth); }
        }
        
        public static readonly BindableProperty TitleProperty =
            BindableProperty.Create("Title", typeof(String), typeof(MainPage), String.Empty);
        
        public String ContentText
        {
            get { return (String)GetValue(ContentTextProperty); }
            set { SetValue(ContentTextProperty, worth); }
        }
        
         public static readonly BindableProperty ContentTextProperty =
            BindableProperty.Create("ContentText", typeof(String), typeof(MainPage), String.Empty);
        
        personal IChatGptClient _chatGptClient;
        personal Guid _sessionGuid = Guid.Empty;
        MapMarkerCollection mapMarkers = new MapMarkerCollection();
        MapMarker mapMarker = new MapMarker();
       
        public MainPage()
        {
            InitializeComponent();
           
            this.Loaded += MainPage_Loaded;
            mapMarkers.Add(mapMarker);
            this.BindingContext = this;
        }
        
         personal void MainPage_Loaded(object sender, EventArgs e)
         {
            _chatGptClient = Handler.MauiContext.Providers.GetService<IChatGptClient>();
         }
    }
  1. Add the MainPage_Tapped occasion handler. The MainPage_Tapped occasion handler is named when the person faucets on the map. It retrieves the latitude and longitude of the tapped location and calls the GetNearByTouristAttraction methodology.
    utilizing ChatGptNet;
    utilizing ChatGptNet.Fashions;
    utilizing Syncfusion.Maui.Maps;
    
    namespace ChatGPTinMAUI;
    
    public partial class MainPage : ContentPage
    {
        public String Title
        {
            get { return (String)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, worth); }
        }
        
        public static readonly BindableProperty TitleProperty =
            BindableProperty.Create("Title", typeof(String), typeof(MainPage), String.Empty);
        
        public String ContentText
        {
            get { return (String)GetValue(ContentTextProperty); }
            set { SetValue(ContentTextProperty, worth); }
        }
        
        public static readonly BindableProperty ContentTextProperty =
            BindableProperty.Create("ContentText", typeof(String), typeof(MainPage), String.Empty);
        
        personal IChatGptClient _chatGptClient;
        personal Guid _sessionGuid = Guid.Empty;
        MapMarkerCollection mapMarkers = new MapMarkerCollection();
        MapMarker mapMarker = new MapMarker();
        
        public MainPage()
        {
            InitializeComponent();
           
            this.Loaded += MainPage_Loaded;
            mapMarkers.Add(mapMarker);
            
            this.BindingContext = this;
        }
       
        personal void MainPage_Loaded(object sender, EventArgs e)
        {
            _chatGptClient = Handler.MauiContext.Providers.GetService<IChatGptClient>();
        }
        
        personal async void MainPage_Tapped(object sender, Syncfusion.Maui.Maps.TappedEventArgs e)
        {
            var latlong = (this.maps.Layer as MapTileLayer).GetLatLngFromPoint(e.Place);
            var geoLocation = "Latitude:"+ latlong.Latitude.ToString() + ",Longitude:" + latlong.Longitude.ToString();
            
            await GetNearByTouristAttraction(geoLocation);
            this.popupDisplay.Present(e.Place.X, e.Place.Y);
            this.popupDisplay.Present(e.Place.X, e.Place.Y);
        }
    }

    The GetNearByTouristAttraction methodology is an asynchronous methodology that fetches close by vacationer sights primarily based on the offered geolocation. It shows a loading indicator whereas the request is being processed. It makes a request to the ChatGPT Shopper to get suggestions for vacationer sights after which updates the ContentText property with the response.

    utilizing ChatGptNet;
    utilizing ChatGptNet.Fashions;
    utilizing Syncfusion.Maui.Maps;
    
    namespace ChatGPTinMAUI;
    
    public partial class MainPage : ContentPage
    {
        public String Title
        {
            get { return (String)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, worth); }
        }
        
        public static readonly BindableProperty TitleProperty =
            BindableProperty.Create("Title", typeof(String), typeof(MainPage), String.Empty);
        
        public String ContentText
        {
            get { return (String)GetValue(ContentTextProperty); }
            set { SetValue(ContentTextProperty, worth); }
        }
        
        public static readonly BindableProperty ContentTextProperty =
            BindableProperty.Create("ContentText", typeof(String), typeof(MainPage), String.Empty);
        
        personal IChatGptClient _chatGptClient;
        personal Guid _sessionGuid = Guid.Empty;
        MapMarkerCollection mapMarkers = new MapMarkerCollection();
        MapMarker mapMarker = new MapMarker();
       
        public MainPage()
        {
            InitializeComponent();
           
            this.Loaded += MainPage_Loaded;
            mapMarkers.Add(mapMarker);
            this.BindingContext = this;
        }
           
        personal void MainPage_Loaded(object sender, EventArgs e)
        {
            _chatGptClient = Handler.MauiContext.Providers.GetService<IChatGptClient>();
        }
        
        personal async void MainPage_Tapped(object sender, Syncfusion.Maui.Maps.TappedEventArgs e)
        {
            var latlong = (this.maps.Layer as MapTileLayer).GetLatLngFromPoint(e.Place);
            var geoLocation = "Latitude:"+ latlong.Latitude.ToString() + ",Longitude:" + latlong.Longitude.ToString();
            
            await GetNearByTouristAttraction(geoLocation);
            this.popupDisplay.Present(e.Place.X, e.Place.Y);
            this.popupDisplay.Present(e.Place.X, e.Place.Y);
        }
        
        personal async Process GetNearByTouristAttraction(string geoLocation)
        {
            this.busyIndicator.IsRunning = true;
            if (string.IsNullOrWhiteSpace(geoLocation))
            {
                await DisplayAlert("Empty location", "No Recommendations", "OK");
                return;
            }
            
            if (_sessionGuid == Guid.Empty)
            {
                _sessionGuid = Guid.NewGuid();
            }
            
            var question = "Inform me 5 locations close to the next location (Every with 20 phrases) " + geoLocation;
            ChatGptResponse response = await _chatGptClient.AskAsync(_sessionGuid, question);
            this.ContentText = response.GetMessage();
            this.busyIndicator.IsRunning = false;
        }
    }

Creating a place explorer app using .NET MAUI and ChatGPTThat’s it; we now have efficiently created a .NET MAUI utility with a map management that shows widespread vacationer sights close to a specific location.

Reference

For extra particulars, consult with the mission on GitHub.

Conclusion

This weblog guided you in making a .NET MAUI utility that leverages the facility of the OpenAI ChatGPT API to ship vacationer suggestions primarily based on the person’s location.

Be happy to experiment by modifying the prompts to reinforce the standard of the solutions. Moreover, you’ll be able to discover the choice of fixing the ChatGptModels enum worth throughout the AddChatGpt methodology in MauiProgram.cs to watch if totally different fashions yield improved outcomes.

Syncfusion’s assortment of .NET MAUI controls gives a complete suite of instruments that allow builders to create sturdy and feature-rich purposes. With their intensive customization choices and intuitive APIs, Syncfusion controls present seamless integration into the .NET MAUI framework, making constructing cross-platform purposes with enhanced performance simpler.

Please check out the steps on this weblog and share your suggestions within the remark part beneath. You can too attain us via our assist discussion board, assist portal, or suggestions portal. We’re at all times completely satisfied to help you!

Associated blogs

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments