|
| 1 | +--- |
| 2 | +title: Tutorial--Create a recommendation app with .NET MAUI and ChatGPT |
| 3 | +description: In this tutorial, you'll learn how to create a .NET MAUI app for Windows in Visual Studio that calls OpenAI's ChatGPT APIs to provide recommendations based on the user's location. |
| 4 | +ms.topic: tutorial |
| 5 | +ms.date: 04/26/2023 |
| 6 | +ms.custom: template-tutorial |
| 7 | +--- |
| 8 | + |
| 9 | +# Tutorial: Create a recommendation app with .NET MAUI and ChatGPT |
| 10 | + |
| 11 | +In this tutorial, you'll learn how to create a .NET MAUI app for Windows in Visual Studio that calls OpenAI's ChatGPT APIs to provide recommendations based on the user's location. The app will have a simple UI that allows the user to enter a location and get recommendations for restaurants, hotels, and attractions. |
| 12 | + |
| 13 | +In this tutorial, you learn how to: |
| 14 | + |
| 15 | +> [!div class="checklist"] |
| 16 | +> * Create a simple user interface for your .NET MAUI app |
| 17 | +> * Reference and bootstrap the ChatGptNet library |
| 18 | +> * Use an API key to link your app to an OpenAI API account |
| 19 | +> * Make calls to the ChatGptNet library to get recommendations |
| 20 | +
|
| 21 | +## Prerequisites |
| 22 | + |
| 23 | +* An OpenAI [account](https://platform.openai.com/signup) |
| 24 | +* An OpenAI [API key](https://platform.openai.com/docs/guides/production-best-practices/api-keys) |
| 25 | +* The .NET MAUI [installation requirements](/dotnet/maui/get-started/installation) |
| 26 | +* If you are new to .NET MAUI on Windows, you should start with the [Build your first .NET MAUI app for Windows](/windows/apps/windows-dotnet-maui/walkthrough-first-app) tutorial. |
| 27 | + |
| 28 | +## Create a new .NET MAUI project with the required UI elements |
| 29 | + |
| 30 | +We're going to start by creating a new .NET MAUI project in Visual Studio. We'll use the **.NET MAUI App** template and add some UI elements to the **MainPage** to provide users with some recommendations based on a provided location. The UI will have buttons to get recommendations for restaurants, hotels, and attractions. |
| 31 | + |
| 32 | +1. In Visual Studio, create a new **.NET MAUI App** project named **ChatGptRecommendationApp**. |
| 33 | +1. Run the new project to make sure the app builds and runs successfully. |
| 34 | +1. Open **MainPage.xaml** from the Solution Explorer. |
| 35 | +1. Replace the contents of the `VerticalStackLayout` with the following XAML markup: |
| 36 | + |
| 37 | + ```xaml |
| 38 | + <Label |
| 39 | + Text="Local AI recommendations" |
| 40 | + SemanticProperties.HeadingLevel="Level1" |
| 41 | + FontSize="32" |
| 42 | + HorizontalOptions="Center" /> |
| 43 | + |
| 44 | + <Entry |
| 45 | + x:Name="LocationEntry" |
| 46 | + Placeholder="Enter your location" |
| 47 | + SemanticProperties.Hint="Enter the location for recommendations" |
| 48 | + HorizontalOptions="Center"/> |
| 49 | + |
| 50 | + <Button |
| 51 | + x:Name="RestaurantBtn" |
| 52 | + Text="Get restaurant recommendations" |
| 53 | + SemanticProperties.Hint="Gets restaurant recommendations when you click" |
| 54 | + Clicked="OnRestaurantClicked" |
| 55 | + HorizontalOptions="Center" /> |
| 56 | + |
| 57 | + <Button |
| 58 | + x:Name="HotelBtn" |
| 59 | + Text="Get hotel recommendations" |
| 60 | + SemanticProperties.Hint="Gets hotel recommendations when you click" |
| 61 | + Clicked="OnHotelClicked" |
| 62 | + HorizontalOptions="Center" /> |
| 63 | + |
| 64 | + <Button |
| 65 | + x:Name="AttractionBtn" |
| 66 | + Text="Get attraction recommendations" |
| 67 | + SemanticProperties.Hint="Gets attraction recommendations when you click" |
| 68 | + Clicked="OnAttractionClicked" |
| 69 | + HorizontalOptions="Center" /> |
| 70 | + |
| 71 | + <Label x:Name="SmallLabel" |
| 72 | + Text="Click a button for recommendations!" |
| 73 | + SemanticProperties.HeadingLevel="Level2" |
| 74 | + FontSize="18" |
| 75 | + HorizontalOptions="Center" /> |
| 76 | + ``` |
| 77 | + |
| 78 | +1. In order to build the project, you will need to add `Clicked` event handlers for each of the buttons. Add the following code to the **MainPage.xaml.cs** file and remove the existing event handler: |
| 79 | + |
| 80 | + ```csharp |
| 81 | + private async void OnRestaurantClicked(object sender, EventArgs e) |
| 82 | + { |
| 83 | + } |
| 84 | + |
| 85 | + private async void OnHotelClicked(object sender, EventArgs e) |
| 86 | + { |
| 87 | + } |
| 88 | + |
| 89 | + private async void OnAttractionClicked(object sender, EventArgs e) |
| 90 | + { |
| 91 | + } |
| 92 | + ``` |
| 93 | + |
| 94 | +The event handlers are all marked as `async` because we will be making asynchronous calls to the ChatGptNet library. Now when you run the app, you should see the following UI: |
| 95 | + |
| 96 | + |
| 97 | + |
| 98 | +Users can enter their location in the `Entry` control and click one of the buttons to get recommendations for restaurants, hotels, or attractions. The `Label` control at the bottom of the UI will display the results. |
| 99 | + |
| 100 | +Next, let's add the ChatGptNet library to the project and get it ready to make some API calls. |
| 101 | + |
| 102 | +## Reference and bootstrap the ChatGptNet library |
| 103 | + |
| 104 | +To call OpenAI's ChatGPT APIs, we're going to use an open-source library from the .NET community called [ChatGPT for .NET (ChatGptNet)](https://github.com/marcominerva/ChatGptNet). This library provides a simple interface for making calls to the OpenAI API. We'll add the library to our project and bootstrap it with our API key. |
| 105 | + |
| 106 | +1. Open the **Package Manager Console** from the **Tools** menu in Visual Studio. |
| 107 | +1. Install the ChatGptNet library by running the following command: |
| 108 | + |
| 109 | + ```powershell |
| 110 | + Install-Package ChatGptNet |
| 111 | + ``` |
| 112 | + |
| 113 | +1. Open **MauiProgram.cs** and add the following code to the CreateMauiApp method before the `#if DEBUG` statement: |
| 114 | + |
| 115 | + ```csharp |
| 116 | + builder.Services.AddChatGpt(options => |
| 117 | + { |
| 118 | + options.ApiKey = "<your-api-key-here>"; |
| 119 | + options.Organization = null; // Optional |
| 120 | + options.DefaultModel = ChatGptModels.Gpt35Turbo; // Default: ChatGptModels.Gpt35Turbo |
| 121 | + options.MessageLimit = 10; // Default: 10 |
| 122 | + options.MessageExpiration = TimeSpan.FromMinutes(5); // Default: 1 hour |
| 123 | + }); |
| 124 | + ``` |
| 125 | + |
| 126 | + This will bootstrap the ChatGptNet library with your API key and set some default options. You can create your API key on the [OpenAI API settings page](https://beta.openai.com/account/api-keys). The `builder` class is part of .NET MAUI's dependency injection system. We're using it to add the ChatGptNet library to the dependency injection container so that we can use it in our app. |
| 127 | + |
| 128 | +1. In order to compile the project, you will need to add the following `using` statements to the top of the **MauiProgram.cs** file: |
| 129 | + |
| 130 | + ```csharp |
| 131 | + using ChatGptNet; |
| 132 | + using ChatGptNet.Models; |
| 133 | + ``` |
| 134 | + |
| 135 | +Now we're ready to put it all together. In the next section, we'll add some code to the three event handlers to make calls to the ChatGptNet library and display the recommendation results. |
| 136 | + |
| 137 | +## Add ChatGPT API calls and test the app |
| 138 | + |
| 139 | +It's time to add the code to our code-behind file that will use the ChatGptNet library to make calls to the OpenAI ChatGPT API. We'll add the code to the three event handlers we created earlier. The code will get the user's location from the `Entry` control and pass it to the ChatGptNet library to get recommendations. Then we'll display the results in the `Label` control at the bottom of the UI. |
| 140 | + |
| 141 | +1. First, we need some code to get an instance of the ChatGptNet library. Add the following code to the top of the **MainPage.xaml.cs** file: |
| 142 | + |
| 143 | + ```csharp |
| 144 | + private IChatGptClient _chatGptClient; |
| 145 | + |
| 146 | + public MainPage() |
| 147 | + { |
| 148 | + InitializeComponent(); |
| 149 | + this.Loaded += MainPage_Loaded; |
| 150 | + } |
| 151 | + |
| 152 | + private void MainPage_Loaded(object sender, EventArgs e) |
| 153 | + { |
| 154 | + _chatGptClient = Handler.MauiContext.Services.GetService<IChatGptClient>(); |
| 155 | + } |
| 156 | + ``` |
| 157 | + |
| 158 | + This code uses the dependency injection (DI) system to get an instance of the ChatGptNet library. The DI system won't be initialized until after the `MainPage` has loaded, so we'll put the code in an event handler for the `Loaded` event. We'll use this instance to make calls to the OpenAI ChatGPT API |
| 159 | + |
| 160 | +1. Next, we'll create an async method named `GetRecommendation` and call it from each of the event handlers: |
| 161 | + |
| 162 | + ```csharp |
| 163 | + private async void OnRestaurantClicked(object sender, EventArgs e) |
| 164 | + { |
| 165 | + await GetRecommendation("restaurant"); |
| 166 | + } |
| 167 | + |
| 168 | + private async void OnHotelClicked(object sender, EventArgs e) |
| 169 | + { |
| 170 | + await GetRecommendation("hotel"); |
| 171 | + } |
| 172 | + |
| 173 | + private async void OnAttractionClicked(object sender, EventArgs e) |
| 174 | + { |
| 175 | + await GetRecommendation("attraction"); |
| 176 | + } |
| 177 | + |
| 178 | + private async Task GetRecommendation(string recommendationType) |
| 179 | + { |
| 180 | + if (string.IsNullOrWhiteSpace(LocationEntry.Text)) |
| 181 | + { |
| 182 | + await DisplayAlert("Empty location", "Please enter a location (city or postal code)", "OK"); |
| 183 | + return; |
| 184 | + } |
| 185 | + |
| 186 | + if (_sessionGuid == Guid.Empty) |
| 187 | + { |
| 188 | + _sessionGuid = Guid.NewGuid(); |
| 189 | + } |
| 190 | + |
| 191 | + ChatGptResponse response = await _chatGptClient.AskAsync(_sessionGuid, |
| 192 | + ""What is a recommended " + recommendationType + " near " + LocationEntry.Text); |
| 193 | + var message = response.GetMessage(); |
| 194 | + SmallLabel.Text = message; |
| 195 | + } |
| 196 | + |
| 197 | + private Guid _sessionGuid = Guid.Empty; |
| 198 | + ``` |
| 199 | + |
| 200 | + This code first checks to make sure the user has entered a location in the `Entry` control. If not, it displays an alert and returns. If the user has entered a location, it calls the `AskAsync` method on the ChatGptNet library to make a call to the OpenAI ChatGPT API. The `AskAsync` method takes two parameters: a `Guid` that identifies the user's session and a string containing the question to ask the API. The `AskAsync` method returns a `ChatGptResponse` object that contains the response from the API. We'll use the `GetMessage` method on the `ChatGptResponse` object to get the response text and display it in the `Label` control at the bottom of the UI. |
| 201 | + |
| 202 | +1. Add the following `using` statements to the top of the **MainPage.xaml.cs** file: |
| 203 | + |
| 204 | + ```csharp |
| 205 | + using ChatGptNet; |
| 206 | + using ChatGptNet.Models; |
| 207 | + ``` |
| 208 | + |
| 209 | +1. Run the app, enter a location, and test the recommendation buttons. You should see a response from the API in the `Label` control at the bottom of the UI: |
| 210 | + |
| 211 | +  |
| 212 | + |
| 213 | +That's it! You've successfully created a Windows .NET MAUI app that uses the OpenAI ChatGPT API to provide recommendations for restaurants, hotels, and attractions. Try changing the prompts to see if you can improve the results. You can also try changing the `ChatGptModels` enum value in the `AddChatGpt` method in **MauiProgram.cs** to see if you get better results from a different model. |
| 214 | + |
| 215 | +>[!NOTE] |
| 216 | +>Remember to keep an eye on your API usage after your trial period has expired. You can also set monthly spending limits on your OpenAI account to avoid unexpected charges. |
| 217 | + |
| 218 | +## Next steps |
| 219 | + |
| 220 | +Advance to the next article to learn how to... |
| 221 | +> [!div class="nextstepaction"] |
| 222 | +> [Create a .NET MAUI app with C# Markup and the Community Toolkit](tutorial-csharp-ui-maui-toolkit.md) |
| 223 | + |
| 224 | +## See also |
| 225 | + |
| 226 | +[Build Windows apps with .NET MAUI](index.md) |
| 227 | + |
| 228 | +[ChatGPT for .NET](https://github.com/marcominerva/ChatGptNet) |
0 commit comments