Saturday, 23 August 2025

Integrating ChatGPT in a .NET MAUI Mobile App

 1. Set Up OpenAI API Access

First, you'll need an OpenAI API key:

  1. Sign up for an OpenAI account at platform.openai.com

  2. Generate an API key from the dashboard

  3. Add your API key securely (never hardcode it directly)

2. Install Required NuGet Packages

Add these packages to your .NET MAUI project:

xml
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />

3. Create a ChatGPT Service

Create a service class to handle API communication:

csharp
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;

public class ChatGptService
{
    private readonly HttpClient _httpClient;
    private const string ApiUrl = "https://api.openai.com/v1/chat/completions";

    public ChatGptService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<string> GetResponseAsync(string message, string apiKey)
    {
        try
        {
            _httpClient.DefaultRequestHeaders.Authorization = 
                new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);

            var requestBody = new
            {
                model = "gpt-3.5-turbo",
                messages = new[]
                {
                    new { role = "user", content = message }
                },
                max_tokens = 150
            };

            var json = JsonConvert.SerializeObject(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await _httpClient.PostAsync(ApiUrl, content);
            response.EnsureSuccessStatusCode();

            var responseContent = await response.Content.ReadAsStringAsync();
            var result = JsonConvert.DeserializeObject<OpenAiResponse>(responseContent);

            return result?.Choices?[0]?.Message?.Content ?? "No response received";
        }
        catch (Exception ex)
        {
            return $"Error: {ex.Message}";
        }
    }
}

// Response classes
public class OpenAiResponse
{
    [JsonProperty("choices")]
    public List<Choice> Choices { get; set; }
}

public class Choice
{
    [JsonProperty("message")]
    public Message Message { get; set; }
}

public class Message
{
    [JsonProperty("role")]
    public string Role { get; set; }
    
    [JsonProperty("content")]
    public string Content { get; set; }
}

4. Configure Dependency Injection

In MauiProgram.cs, register your services:

csharp
public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            });

        // Register HttpClient and ChatGptService
        builder.Services.AddHttpClient<ChatGptService>();
        builder.Services.AddSingleton<MainPage>();

        return builder.Build();
    }
}

5. Create the UI in XAML

Create a simple chat interface in your MainPage.xaml:

xml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="YourNamespace.MainPage"
             Title="ChatGPT MAUI App">

    <ScrollView>
        <VerticalStackLayout Spacing="20" Padding="30,0,30,30">
            
            <Entry x:Name="apiKeyEntry" 
                   Placeholder="Enter your OpenAI API key"
                   IsPassword="True"
                   Margin="0,20,0,0"/>
            
            <Editor x:Name="inputEditor" 
                    Placeholder="Type your message here..."
                    HeightRequest="100"/>
            
            <Button Text="Send Message" 
                    Clicked="OnSendButtonClicked"
                    HorizontalOptions="Center"/>
            
            <ActivityIndicator x:Name="loadingIndicator"
                               IsVisible="False"
                               IsRunning="False"/>
            
            <Label x:Name="responseLabel" 
                   Text="Response will appear here..."
                   TextColor="Gray"
                   FontSize="14"/>
            
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>

6. Implement the Code-Behind

In MainPage.xaml.cs:

csharp
public partial class MainPage : ContentPage
{
    private readonly ChatGptService _chatGptService;

    public MainPage(ChatGptService chatGptService)
    {
        InitializeComponent();
        _chatGptService = chatGptService;
    }

    private async void OnSendButtonClicked(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(apiKeyEntry.Text))
        {
            await DisplayAlert("Error", "Please enter your API key", "OK");
            return;
        }

        if (string.IsNullOrWhiteSpace(inputEditor.Text))
        {
            await DisplayAlert("Error", "Please enter a message", "OK");
            return;
        }

        loadingIndicator.IsVisible = true;
        loadingIndicator.IsRunning = true;

        try
        {
            var response = await _chatGptService.GetResponseAsync(
                inputEditor.Text, 
                apiKeyEntry.Text
            );

            responseLabel.Text = response;
        }
        catch (Exception ex)
        {
            responseLabel.Text = $"Error: {ex.Message}";
        }
        finally
        {
            loadingIndicator.IsVisible = false;
            loadingIndicator.IsRunning = false;
        }
    }
}

7. Add Internet Permission

For Android, add this to Platforms/Android/AndroidManifest.xml:

xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

For iOS, add this to Platforms/iOS/Info.plist:

xml
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

8. Secure API Key Storage (Recommended)

For better security, consider using secure storage:

csharp
// Save API key
await SecureStorage.SetAsync("openai_api_key", apiKey);

// Retrieve API key
var apiKey = await SecureStorage.GetAsync("openai_api_key");

9. Enhanced Version with Conversation History

For a more advanced implementation with conversation history:

csharp
public class ChatService
{
    private List<Message> _conversationHistory = new List<Message>();
    
    public async Task<string> SendMessageAsync(string userMessage, string apiKey)
    {
        _conversationHistory.Add(new Message { Role = "user", Content = userMessage });
        
        // Keep conversation history manageable
        if (_conversationHistory.Count > 10)
        {
            _conversationHistory = _conversationHistory.TakeLast(5).ToList();
        }
        
        var response = await GetChatResponseAsync(_conversationHistory, apiKey);
        _conversationHistory.Add(new Message { Role = "assistant", Content = response });
        
        return response;
    }
    
    private async Task<string> GetChatResponseAsync(List<Message> messages, string apiKey)
    {
        // Implementation similar to previous example but with full conversation history
    }
}

Important Considerations

  1. API Costs: Be aware of OpenAI API pricing

  2. Error Handling: Implement proper error handling for network issues

  3. Rate Limiting: Handle API rate limits appropriately

  4. Privacy: Be transparent about data sent to OpenAI

  5. Loading States: Provide good UX with loading indicators

  6. Offline Support: Consider what happens when there's no internet connection

This implementation provides a basic ChatGPT integration that you can extend with features like:

  • Conversation history

  • Multiple chat sessions

  • Different AI models

  • Custom prompts and parameters

  • File uploads (with GPT-4)

  • Voice input/output

Remember to handle your API keys securely and consider implementing additional features like caching or local storage for better performance.

No comments:

Post a Comment

Complete Guide: Building a Live Cricket Streaming App for 100M Users

Comprehensive guide to building a scalable live cricket streaming platform for 100M users, covering backend infrastructure, streaming techno...