Function

Appwrite function is the soul behind Patronus performing every task and managing the data transportation.

Overview

In Patronus, Appwrite Functions enable us to execute custom backend logic. This is particularly useful for processing complex tasks, like querying flight data or interacting with the AI model for price predictions. These functions run server-side in response to specific triggers or can be called directly from the frontend, providing a seamless way to handle resource-intensive operations.

Appwrite Function Workflow

The Appwrite function, flightQueryFunction, is central to the workflow in Patronus. Here’s a breakdown of how it operates:

  1. Handling Flight Requests: Once a flight request is received, the function retrieves both historical and real-time flight data.

  2. AI Prediction Execution: The function then sends this data to our Hugging Face AI model to predict the optimal time for booking and the cheapest price.

  3. User Notification and Database Update: After receiving the AI response, the function updates the Appwrite database and, if needed, notifies the user.

Setting Up the Appwrite Function in Patronus

  1. Creating the flightQueryFunction in Appwrite:

    • Navigate to the "Functions" section in the Appwrite console.

    • Create a new function named flightQueryFunction with Node.js as the runtime, which aligns with our backend requirements.

  2. Environment Variables:

    • For secure access to external APIs and services, environment variables are added directly in the Appwrite function’s settings.

    • The following are some of the key environment variables:

      HUGGING_FACE_API_KEY=<Hugging Face API Key>
      AMADEUS_API_KEY=<Amadeus API Key>
  3. Writing the Function Logic in main.js:

    • The main.js script within flightQueryFunction fetches flight data based on the user’s request, queries our AI model for predictions, and returns the result.

    • Example of main.js code in Patronus:

      javascriptCopy codeconst { Client } = require('node-appwrite');
      const fetch = require('node-fetch');
      
      module.exports = async function (req, res) {
        const client = new Client();
        client.setEndpoint(process.env.APPWRITE_ENDPOINT).setProject(process.env.APPWRITE_PROJECT_ID);
      
        // Fetch flight data
        const flightData = await fetchFlightData(req.payload);
      
        // Send data to Hugging Face AI model for prediction
        const aiResponse = await getPredictionFromAI(flightData);
      
        // Respond with AI data or save to Appwrite
        res.json({ data: aiResponse });
      };
      
      async function fetchFlightData(payload) {
        // Logic for fetching data from Amadeus API
      }
      
      async function getPredictionFromAI(flightData) {
        // Logic for interacting with Hugging Face model
      }
  4. Function Testing in Patronus:

    • After writing the logic, the function is tested with sample flight data requests. This verifies that it correctly fetches, processes, and returns data from the AI model.

    • Tests cover scenarios like missing data fields, invalid dates, and unsupported locations.

  5. Invoking the Function from the Frontend:

    • From the frontend, we use Appwrite’s Functions API to trigger the function with specific flight request data.

    • Example of invoking flightQueryFunction from the frontend:

      typescriptCopy codeimport { Functions } from 'appwrite';
      
      async function sendFlightQuery(fromLocation: string, toLocation: string, departureDate: string, arrivalDate: string) {
        const functions = new Functions(client);
        try {
          const response = await functions.createExecution('flightQueryFunction', JSON.stringify({
            fromLocation, toLocation, departureDate, arrivalDate
          }));
          console.log(response);
        } catch (error) {
          console.error('Error executing function:', error);
        }
      }

Use Cases in Patronus

  • Flight Data Collection: Calls the Amadeus API to gather both historical and live flight data based on the user’s inputs.

  • AI-Powered Prediction: Sends data to a Hugging Face model to get predictions on price trends, helping users determine the best booking time.

  • Database Update and Notification: Stores the AI results in the Appwrite database and notifies users with predicted flight details.

Testing and Error Handling in Patronus

  • To ensure reliability, we regularly test this function in different scenarios, particularly focusing on edge cases.

  • Detailed error handling and logging are implemented, making it easier to identify and troubleshoot any issues promptly.


This section highlights the Appwrite functions used in Patronus and provides insights into how they contribute to the overall project functionality. Let me know if this aligns with your documentation style!

Last updated