Ads2

Saturday, 2 August 2025

Creating an AI Travel Agent in .NET MAUI with Google Cloud: A to Z Guide

This comprehensive guide will walk you through creating a complete AI-powered travel agent application using .NET MAUI for the frontend and Google Cloud services for the backend.

Step 1: Project Planning and Architecture

1.1 Define Application Features

  • Travel recommendations based on preferences

  • Itinerary generation

  • Flight/hotel booking integration

  • Natural language processing for queries

  • Real-time weather and location data

  • User profile and preferences

1.2 Architecture Design

text
Frontend: .NET MAUI App (Android/iOS/Windows)
Backend Services:
  - Google Cloud Functions (API endpoints)
  - Google Cloud Run (Containerized services)
  - Google Dialogflow (Conversational AI)
  - Google Cloud SQL (PostgreSQL database)
  - Google Vertex AI (Custom ML models)
  - Google Maps Platform (Location services)
  - Firebase (Authentication, notifications)

Step 2: Set Up Google Cloud Environment

2.1 Create Google Cloud Project

  1. Go to Google Cloud Console

  2. Click "Create Project"

  3. Name your project (e.g., "TravelAgentAI")

  4. Enable billing (required for most services)

2.2 Enable Required APIs

Enable these APIs in Google Cloud Console:

  • Cloud Functions API

  • Cloud Run API

  • Dialogflow API

  • Vertex AI API

  • Maps JavaScript API

  • Places API

  • Firebase API

  • Cloud SQL Admin API

2.3 Set Up Service Account

  1. Go to IAM & Admin > Service Accounts

  2. Create new service account "travel-agent-backend"

  3. Assign roles:

    • Cloud Functions Admin

    • Cloud Run Admin

    • Dialogflow API Admin

    • Vertex AI User

    • Cloud SQL Client

  4. Create and download JSON key file

Step 3: Backend Development

3.1 Set Up Cloud SQL Database

  1. Go to Cloud SQL

  2. Create PostgreSQL instance

  3. Configure connection:

    • Instance ID: travel-agent-db

    • Password: set secure password

    • Region: choose nearest to your users

  4. Create database "travel_agent"

  5. Create tables:

sql
CREATE TABLE users (
    user_id VARCHAR(255) PRIMARY KEY,
    name VARCHAR(255),
    email VARCHAR(255) UNIQUE,
    preferences JSONB
);

CREATE TABLE itineraries (
    itinerary_id SERIAL PRIMARY KEY,
    user_id VARCHAR(255) REFERENCES users(user_id),
    destinations JSONB,
    activities JSONB,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

3.2 Create Cloud Functions for API Endpoints

3.2.1 Initialize Functions

bash
mkdir travel-agent-functions
cd travel-agent-functions
gcloud init
npm init -y
npm install @google-cloud/functions-framework express pg cors

3.2.2 Create User Service (users.js)

javascript
const express = require('express');
const { Pool } = require('pg');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.json());

const pool = new Pool({
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  password: process.env.DB_PASS,
  port: process.env.DB_PORT,
});

// Get user by ID
app.get('/users/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const result = await pool.query('SELECT * FROM users WHERE user_id = $1', [id]);
    res.json(result.rows[0]);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Update user preferences
app.put('/users/:id/preferences', async (req, res) => {
  try {
    const { id } = req.params;
    const { preferences } = req.body;
    await pool.query(
      'UPDATE users SET preferences = $1 WHERE user_id = $2',
      [preferences, id]
    );
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

exports.users = (req, res) => {
  app(req, res);
};

3.2.3 Deploy Functions

bash
gcloud functions deploy users \
  --runtime nodejs16 \
  --trigger-http \
  --allow-unauthenticated \
  --set-env-vars DB_USER=postgres,DB_HOST=[YOUR_DB_IP],DB_NAME=travel_agent,DB_PASS=[YOUR_PASSWORD],DB_PORT=5432

3.3 Set Up Dialogflow for Conversational AI

  1. Go to Dialogflow Console

  2. Create new agent "TravelAgent"

  3. Set up intents:

    • "PlanTrip" - handles trip planning requests

    • "FindFlights" - handles flight queries

    • "HotelSearch" - handles accommodation requests

  4. Enable fulfillment and connect to your Cloud Function

  5. Set up entities:

    • Destination

    • TravelDate

    • BudgetRange

    • TravelCompanions

3.4 Create Itinerary Generator with Vertex AI

  1. Go to Vertex AI in Google Cloud Console

  2. Create a custom model or use the Generative AI service

  3. Create a Cloud Function that integrates with Vertex AI:

javascript
const { PredictionServiceClient } = require('@google-cloud/aiplatform');

async function generateItinerary(userPreferences) {
  const client = new PredictionServiceClient();
  
  const endpoint = `projects/${process.env.PROJECT_ID}/locations/us-central1/publishers/google/models/text-bison@001`;
  
  const prompt = {
    prompt: `Generate a 3-day travel itinerary based on these preferences: 
             Destination: ${userPreferences.destination}
             Budget: ${userPreferences.budget}
             Interests: ${userPreferences.interests.join(', ')}
             Travel style: ${userPreferences.travelStyle}`,
    maxOutputTokens: 1024,
    temperature: 0.2,
  };
  
  const request = {
    endpoint,
    instances: [{ content: JSON.stringify(prompt) }],
    parameters: { temperature: 0.2, maxOutputTokens: 1024 },
  };
  
  const [response] = await client.predict(request);
  return response.predictions[0].content;
}

exports.itineraryGenerator = async (req, res) => {
  try {
    const { preferences } = req.body;
    const itinerary = await generateItinerary(preferences);
    res.json({ itinerary });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

Step 4: .NET MAUI Frontend Development

4.1 Set Up .NET MAUI Project

  1. Install prerequisites:

    • Visual Studio 2022 with .NET MAUI workload

    • .NET 7 SDK or later

  2. Create new project:

    • Select ".NET MAUI App" template

    • Name: "TravelAgentAI"

    • Target platforms: Android, iOS, Windows

4.2 Configure App Structure

4.2.1 Create ViewModels

csharp
// MainViewModel.cs
public class MainViewModel : ObservableObject
{
    private string _userQuery;
    public string UserQuery
    {
        get => _userQuery;
        set => SetProperty(ref _userQuery, value);
    }

    private ObservableCollection<TravelRecommendation> _recommendations;
    public ObservableCollection<TravelRecommendation> Recommendations
    {
        get => _recommendations;
        set => SetProperty(ref _recommendations, value);
    }

    public ICommand SearchCommand { get; }
    
    public MainViewModel()
    {
        Recommendations = new ObservableCollection<TravelRecommendation>();
        SearchCommand = new Command(async () => await SearchTravelOptions());
    }
    
    private async Task SearchTravelOptions()
    {
        var service = new TravelAIService();
        var results = await service.GetRecommendations(UserQuery);
        Recommendations.Clear();
        foreach (var item in results)
        {
            Recommendations.Add(item);
        }
    }
}

4.2.2 Create Models

csharp
// TravelRecommendation.cs
public class TravelRecommendation
{
    public string Destination { get; set; }
    public string ImageUrl { get; set; }
    public string Description { get; set; }
    public decimal EstimatedCost { get; set; }
    public string BestSeason { get; set; }
}

// UserPreferences.cs
public class UserPreferences
{
    public List<string> Interests { get; set; }
    public string BudgetRange { get; set; }
    public string TravelCompanions { get; set; }
    public string PreferredSeason { get; set; }
}

4.3 Create Services for Backend Communication

4.3.1 Base HTTP Service

csharp
public class HttpService
{
    private readonly HttpClient _httpClient;
    private const string BaseUrl = "https://your-cloud-run-url.com";
    
    public HttpService()
    {
        _httpClient = new HttpClient();
    }
    
    protected async Task<T> GetAsync<T>(string endpoint)
    {
        var response = await _httpClient.GetAsync($"{BaseUrl}{endpoint}");
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<T>();
    }
    
    protected async Task<TResponse> PostAsync<TRequest, TResponse>(string endpoint, TRequest data)
    {
        var response = await _httpClient.PostAsJsonAsync($"{BaseUrl}{endpoint}", data);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<TResponse>();
    }
}

4.3.2 Travel AI Service

csharp
public class TravelAIService : HttpService
{
    public async Task<List<TravelRecommendation>> GetRecommendations(string query)
    {
        return await PostAsync<string, List<TravelRecommendation>>("/api/recommendations", query);
    }
    
    public async Task<string> GenerateItinerary(UserPreferences preferences)
    {
        return await PostAsync<UserPreferences, string>("/api/generate-itinerary", preferences);
    }
    
    public async Task<string> ChatWithAgent(string message)
    {
        return await PostAsync<string, string>("/api/chat", message);
    }
}

4.4 Create UI Pages

4.4.1 Main Page (Chat Interface)

xml
<!-- MainPage.xaml -->
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TravelAgentAI.MainPage"
             Title="Travel Agent AI">
    
    <Grid RowDefinitions="*,Auto">
        <CollectionView ItemsSource="{Binding Messages}">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Frame Padding="10" 
                           Margin="5"
                           HorizontalOptions="{Binding IsUserMessage, 
                           Converter={StaticResource MessageAlignmentConverter}}">
                        <Label Text="{Binding Text}" />
                    </Frame>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
        
        <Grid Grid.Row="1" ColumnDefinitions="*,Auto" Padding="10">
            <Entry Text="{Binding UserQuery}" 
                   Placeholder="Ask me about travel..." 
                   ReturnCommand="{Binding SearchCommand}"/>
            <Button Grid.Column="1" 
                    Text="Send" 
                    Command="{Binding SearchCommand}"/>
        </Grid>
    </Grid>
</ContentPage>

4.4.2 Recommendations Page

xml
<!-- RecommendationsPage.xaml -->
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TravelAgentAI.RecommendationsPage"
             Title="Recommendations">
    
    <RefreshView Command="{Binding LoadRecommendationsCommand}"
                 IsRefreshing="{Binding IsBusy}">
        <CollectionView ItemsSource="{Binding Recommendations}"
                        SelectionMode="Single"
                        SelectionChangedCommand="{Binding ViewDetailsCommand}">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10" ColumnDefinitions="Auto,*">
                        <Image Source="{Binding ImageUrl}"
                               HeightRequest="80"
                               WidthRequest="80"
                               Aspect="AspectFill"/>
                        <StackLayout Grid.Column="1" Padding="10">
                            <Label Text="{Binding Destination}" FontSize="Medium"/>
                            <Label Text="{Binding Description}" FontSize="Small"/>
                            <Label Text="{Binding EstimatedCost, StringFormat='Estimated: {0:C}'}"/>
                        </StackLayout>
                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </RefreshView>
</ContentPage>

4.5 Implement Google Maps Integration

  1. Install NuGet package: Xamarin.GooglePlayServices.Maps

  2. Add API key to AndroidManifest.xml:

xml
<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="YOUR_GOOGLE_MAPS_API_KEY" />
  1. Create MapPage:

csharp
public class MapPage : ContentPage
{
    private readonly GoogleMap _map;
    
    public MapPage()
    {
        var mapView = new MapView(Context);
        _map = mapView.Map;
        
        if (_map != null)
        {
            _map.UiSettings.ZoomControlsEnabled = true;
            _map.UiSettings.CompassEnabled = true;
            _map.MoveCamera(CameraUpdateFactory.NewLatLngZoom(
                new LatLng(37.7749, -122.4194), 10));
        }
        
        Content = mapView;
    }
    
    public void AddDestinationMarker(double lat, double lng, string title)
    {
        var markerOptions = new MarkerOptions()
            .SetPosition(new LatLng(lat, lng))
            .SetTitle(title);
        _map.AddMarker(markerOptions);
    }
}

Step 5: Authentication with Firebase

5.1 Set Up Firebase Authentication

  1. Go to Firebase Console and create new project

  2. Enable Email/Password and Google Sign-In authentication

  3. Download google-services.json (Android) and GoogleService-Info.plist (iOS)

5.2 Implement Authentication in MAUI

  1. Install NuGet package: Xamarin.Firebase.Auth

  2. Create AuthService:

csharp
public class AuthService
{
    private readonly FirebaseAuth _auth;
    
    public AuthService()
    {
        _auth = FirebaseAuth.Instance;
    }
    
    public async Task<bool> SignInWithEmail(string email, string password)
    {
        try
        {
            var result = await _auth.SignInWithEmailAndPasswordAsync(email, password);
            return result.User != null;
        }
        catch (Exception)
        {
            return false;
        }
    }
    
    public async Task<bool> SignUpWithEmail(string email, string password)
    {
        try
        {
            var result = await _auth.CreateUserWithEmailAndPasswordAsync(email, password);
            return result.User != null;
        }
        catch (Exception)
        {
            return false;
        }
    }
    
    public async Task SignOut()
    {
        await _auth.SignOut();
    }
}

Step 6: Testing and Deployment

6.1 Test Backend Services

  1. Test Cloud Functions locally using Functions Framework

  2. Test Dialogflow agent in the simulator

  3. Verify database connections

6.2 Test MAUI App

  1. Test on Android emulator

  2. Test on physical iOS device (requires Mac)

  3. Test on Windows machine

6.3 Deploy Backend

  1. Deploy Cloud Functions:

bash
gcloud functions deploy travelAgentApi --runtime nodejs16 --trigger-http --allow-unauthenticated
  1. Deploy any containerized services to Cloud Run:

bash
gcloud run deploy travel-agent-service --image gcr.io/your-project/travel-agent --platform managed

6.4 Deploy MAUI App

  1. Android:

    • Build in Release mode

    • Generate signed APK or AAB

    • Upload to Google Play Store

  2. iOS:

    • Archive in Visual Studio

    • Distribute through App Store Connect

  3. Windows:

    • Create MSIX package

    • Publish to Microsoft Store

Step 7: Monitoring and Maintenance

  1. Set up Google Cloud Monitoring for backend services

  2. Implement logging in both frontend and backend

  3. Set up error tracking with Firebase Crashlytics

  4. Monitor usage and scale services as needed

Additional Considerations

  1. Security:

    • Implement proper API key management

    • Use Firebase App Check to prevent abuse

    • Encrypt sensitive user data

  2. Performance:

    • Implement caching for frequently accessed data

    • Optimize images and assets in MAUI app

    • Use CDN for static content

  3. Localization:

    • Add multi-language support in MAUI

    • Configure Dialogflow for multiple languages

    • Localize content and recommendations

This complete guide provides all the steps needed to build a production-ready AI travel agent using .NET MAUI and Google Cloud services. The implementation can be further customized based on specific requirements and additional features.

No comments:

Post a Comment

Fantasy Cricket Mobile App in .NET

  1. Planning the Fantasy Cricket App Key Features to Include: User registration and authentication Player selection interface Match schedul...