Skip to content

Commit f2b730a

Browse files
committed
Add .NET MAUI ChatGPT tutorial
1 parent 77a8aeb commit f2b730a

File tree

6 files changed

+225
-2
lines changed

6 files changed

+225
-2
lines changed

hub/apps/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,8 @@ items:
310310
href: windows-dotnet-maui/walkthrough-first-app.md
311311
- name: "Integrate a .NET MAUI app with the Graph SDK"
312312
href: windows-dotnet-maui/tutorial-graph-api.md
313+
- name: "Tutorial: Create a simple AI recommendation app with .NET MAUI"
314+
href: windows-dotnet-maui/tutorial-maui-ai.md
313315
- name: "Create a .NET MAUI app with C# Markup"
314316
href: windows-dotnet-maui/tutorial-csharp-ui-maui-toolkit.md
315317
- name: App lifecycle and system services
26.7 KB
Loading
88.4 KB
Loading

hub/apps/windows-dotnet-maui/tutorial-csharp-ui-maui-toolkit.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Tutorial--Create a .NET MAUI app with C# Markup and the Community Toolkit
33
description: Build a .NET MAUI app with a user interface created without XAML by using C# Markup from the .NET MAUI Community Toolkit.
4-
ms.topic: article
4+
ms.topic: tutorial
55
ms.date: 11/11/2022
66
keywords: windows win32, desktop development, Windows App SDK, .net maui
77
ms.localizationpriority: medium

hub/apps/windows-dotnet-maui/tutorial-graph-api.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Tutorial--Create a .NET MAUI app integrating with the Microsoft Graph SDK
33
description: Get hands-on with .NET MAUI by building a cross-platform app on Windows that leverages the Microsoft Graph SDK to display user data.
4-
ms.topic: article
4+
ms.topic: tutorial
55
ms.date: 02/22/2023
66
keywords: windows win32, desktop development, Windows App SDK, .net maui
77
ms.localizationpriority: medium
Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
---
2+
title: Tutorial--Create a simple AI recommendation app with .NET MAUI on Windows
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 simple AI recommendation app with .NET MAUI on Windows
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.
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+
> * 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+
![Windows .NET MAUI app with the UI for providing recommendations.](images/maui-chatgpt-create-the-ui.png)
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. 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:
203+
204+
![Windows .NET MAUI app with the UI for providing recommendations.](images/maui-chatgpt-ui-with-results.png)
205+
206+
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.
207+
208+
>[!NOTE]
209+
>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.
210+
211+
## Next steps
212+
213+
Advance to the next article to learn how to...
214+
> [!div class="nextstepaction"]
215+
> [Create a .NET MAUI app with C# Markup and the Community Toolkit](tutorial-csharp-ui-maui-toolkit.md)
216+
217+
## See also
218+
219+
[Build Windows apps with .NET MAUI](index.md)
220+
221+
[ChatGPT for .NET](https://github.com/marcominerva/ChatGptNet)

0 commit comments

Comments
 (0)