Friday, 1 August 2025

.NET MAUI app that connects to an AI service (like ChatGPT via OpenAI API)

Create a cross-platform MAUI app (Windows, Android, macOS, iOS) that:

  • Accepts a user prompt.

  • Sends it to an AI engine (e.g., OpenAI).

  • Displays the AI response.


πŸ“¦ Prerequisites

  • .NET 8 SDK

  • Visual Studio 2022/2025 with MAUI workload

  • An API Key (e.g., from OpenAI)


πŸ”§ Step-by-Step Setup

1. Create the MAUI App

dotnet new maui -n MauiAIChatApp cd MauiAIChatApp

2. Add Dependencies

Edit the .csproj to include System.Net.Http.Json (or add OpenAI.Net via NuGet for simplicity):

dotnet add package OpenAI.Net --version 7.0.1

OR, if using direct HTTP:

dotnet add package Newtonsoft.Json

3. Add the API Service

Create a service to call the AI engine.

πŸ”Ή Services/OpenAIService.cs

using System.Net.Http.Headers; using System.Text; using System.Text.Json; public class OpenAIService { private readonly HttpClient _httpClient; private const string apiKey = "sk-REPLACE_WITH_YOUR_KEY"; private const string endpoint = "https://api.openai.com/v1/chat/completions"; public OpenAIService() { _httpClient = new HttpClient(); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); } public async Task<string> AskChatGPT(string userPrompt) { var requestBody = new { model = "gpt-3.5-turbo", messages = new[] { new { role = "user", content = userPrompt } }, max_tokens = 100 }; var json = JsonSerializer.Serialize(requestBody); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync(endpoint, content); var result = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) return $"Error: {result}"; using var doc = JsonDocument.Parse(result); return doc.RootElement .GetProperty("choices")[0] .GetProperty("message") .GetProperty("content") .GetString() ?.Trim(); } }

4. Update MainPage.xaml UI

<VerticalStackLayout Padding="20" Spacing="20"> <Label Text="Ask AI Anything" FontSize="24" HorizontalOptions="Center" /> <Entry x:Name="PromptEntry" Placeholder="Enter your prompt..." /> <Button Text="Ask" Clicked="OnAskClicked" /> <ScrollView HeightRequest="300"> <Label x:Name="ResponseLabel" FontSize="18" /> </ScrollView> </VerticalStackLayout>

5. Update MainPage.xaml.cs

public partial class MainPage : ContentPage { private readonly OpenAIService _openAIService; public MainPage() { InitializeComponent(); _openAIService = new OpenAIService(); } private async void OnAskClicked(object sender, EventArgs e) { var prompt = PromptEntry.Text; if (string.IsNullOrWhiteSpace(prompt)) return; ResponseLabel.Text = "Thinking..."; var response = await _openAIService.AskChatGPT(prompt); ResponseLabel.Text = response; } }

✅ Run the App

dotnet build dotnet maui run


No comments:

Post a Comment

Cricket Streaming MAUI App: Complete Solution

This document outlines a comprehensive solution for building a cricket streaming MAUI app with subscription plans, geo-restrictions, and pre...

Ads2