Main site

Sample AI prompts

Maximize the efficiency of the JsRates AI (Artificial Intelligence) code generator with these sample prompts designed to inspire and guide your prompt creation process.

Helpful Hints:

  • Refinement: If the initial AI response doesn't meet your expectations, tweak your prompt by incorporating elements from the response to improve accuracy.
  • Repetition for Clarity: Don't hesitate to submit the same prompt again; occasionally, a repeated prompt can lead to a more precise response.
  • Simplicity and Precision: Aim for prompts that are direct, brief, and clear, avoiding any potential for misunderstanding.
  • Specificity is Key: When referring to JsRates built-in modules, always use the exact function or variable names to ensure the AI understands the context correctly.

By following these tips, you'll enhance the AI's ability to generate useful and accurate code snippets, making your development process smoother and more efficient.

As with any LLM AI model outputs, always verify the generated code for accuracy before deploying it live.

For the sample prompts here, your might get different responses since AI models have random elements.

1. Multiple vendors

Prompt:

I'd like a shipping rate calculator function.
If the items product tags array field includes "esty", use ETSY shipping rates.
The items product tags array can be accessed in the "product" field after enriching the input data.
Enrich the data with metafield namespace "shop" with size 10, and metafield namespace "market" with size 5.
The etsy product id and etsy shop id for each items is saved in the data items object metafield in the "shop" namespace with keys named "esty_product_id" and "etsy_shop_id", respectively.

If the items product tags array field includes "dhgate", use DHGate shipping rates.
The product id for each dhgate items is saved in the data items object metafield in the "shop" namespace with key named "dhgate_product_id". 

If the items product tags array field includes "Dsers", use Dsers shipping rates.
The Dsers product id for each items is saved in the data items object metafield in the "market" namespace with keys named "dsers_product_id".
The Dsers email and password can be access from the environment variable object with keys "dsers_email" and "dsers_password", respectively. 

If items tags do not include "esty", "dhgate" and "Dsers", calculate the distance in km between the origin and destination using Google Distance Matrix API (in driving mode) and the resulting distance in km is multiplied by 0.02 cents for shipping cost.
You will implement the Google Distance Matrix distance calculator. The Google API access key is provided a field in the environment variable object of the shipping rate calculator function argument with key name "google_api_key".

If the total items price is more than $500, provide 5% discount from the shipping cost. The total item price is the sum of each item price.

If there are multiple shipping rates, the function should combine the rates by adding each shipping fees and generate one shipping rate. For this case, the maximum delivery date is 8 days from now, and the minimum delivery date is 5 days from now.

AI Output:

import { enrichItemDetails } from "./modules.js";
import { DHgate } from "./modules.js";
import { Etsy } from "./modules.js";
import { Dsers } from "./modules.js";

// Function to calculate shipping rates
export async function calculateShippingRates(DATA, env) {
  // Enrich the data with metafield namespace "shop" with size 10, and metafield namespace "market" with size 5
  DATA = await enrichItemDetails(DATA, [
    { namespace: "shop", size: 10 },
    { namespace: "market", size: 5 },
  ]);

  // Initialize the shipping rates array
  let rates = [];

  // Loop through the items
  for (const item of DATA.items) {
    // Check if the item's product tags array field includes "esty"
    if (item.product.tags.includes("esty")) {
      // Get the Etsy product id and shop id from the item's metafield
      const etsyProductId = item.metafields.shop.esty_product_id;
      const etsyShopId = item.metafields.shop.etsy_shop_id;

      // Create an Etsy instance
      const etsy = new Etsy(DATA.destination, DATA.currency);

      // Get the Etsy shipping rates
      const etsyRates = await etsy.getRates([
        { etsy_product_id: etsyProductId, etsy_shop_id: etsyShopId, quantity: item.quantity },
      ]);

      // Add the Etsy shipping rates to the rates array
      rates = [...rates, ...etsyRates];
    }

    // Check if the item's product tags array field includes "dhgate"
    else if (item.product.tags.includes("dhgate")) {
      // Get the DHgate product id from the item's metafield
      const dhgateProductId = item.metafields.shop.dhgate_product_id;

      // Create a DHgate instance
      const dhgate = new DHgate(DATA.destination, DATA.currency);

      // Get the DHgate shipping rates
      const dhgateRates = await dhgate.getRates([
        { dhgate_product_id: dhgateProductId, quantity: item.quantity },
      ]);

      // Add the DHgate shipping rates to the rates array
      rates = [...rates, ...dhgateRates];
    }

    // Check if the item's product tags array field includes "Dsers"
    else if (item.product.tags.includes("Dsers")) {
      // Get the Dsers product id from the item's metafield
      const dsersProductId = item.metafields.market.dsers_product_id;

      // Create a Dsers instance
      const dsers = new Dsers(
        env.dsers_email,
        env.dsers_password,
        DATA.destination,
        DATA.currency
      );

      // Get the Dsers shipping rates
      const dsersRates = await dsers.getRates([
        { dsers_product_id: dsersProductId, quantity: item.quantity },
      ]);

      // Add the Dsers shipping rates to the rates array
      rates = [...rates, ...dsersRates];
    }

    // If the item's product tags array field does not include "esty", "dhgate" and "Dsers", calculate the distance in km between the origin and destination using Google Distance Matrix API and multiply the resulting distance in km by 0.02 cents for shipping cost
    else {
      // Get the origin and destination addresses
      const origin = `${DATA.origin.address1}, ${DATA.origin.city}, ${DATA.origin.province}, ${DATA.origin.country}`;
      const destination = `${DATA.destination.address1}, ${DATA.destination.city}, ${DATA.destination.province}, ${DATA.destination.country}`;

      // Calculate the distance between the origin and destination using Google Distance Matrix API
      const distance = await getDistance(origin, destination, env.google_api_key);

      // Add the shipping rate to the rates array
      rates.push({
        service_name: "Google Distance Matrix API",
        service_code: "GDM",
        total_price: (distance * 0.02).toFixed(2),
        description: `Shipping cost calculated using Google Distance Matrix API. Distance: ${distance} km.`,
        currency: DATA.currency,
        min_delivery_date: "",
        max_delivery_date: "",
      });
    }
  }

  // If the total items price is more than $500, provide 5% discount from the shipping cost
  const totalItemsPrice = DATA.items.reduce((acc, item) => acc + item.price * item.quantity, 0);
  if (totalItemsPrice > 50000) {
    rates = rates.map((rate) => {
      rate.total_price = (rate.total_price * 0.95).toFixed(2);
      return rate;
    });
  }

  // If there are multiple shipping rates, combine the rates by adding each shipping fees and generate one shipping rate
  if (rates.length > 1) {
    const combinedRate = {
      service_name: "Combined Shipping",
      service_code: "COMBINED",
      total_price: rates.reduce((acc, rate) => acc + parseFloat(rate.total_price), 0).toFixed(2),
      description: "Combined shipping rates from multiple carriers.",
      currency: DATA.currency,
      min_delivery_date: "",
      max_delivery_date: "",
    };

    // Set the maximum delivery date to 8 days from now
    const maxDeliveryDate = new Date();
    maxDeliveryDate.setDate(maxDeliveryDate.getDate() + 8);
    combinedRate.max_delivery_date = maxDeliveryDate.toISOString();

    // Set the minimum delivery date to 5 days from now
    const minDeliveryDate = new Date();
    minDeliveryDate.setDate(minDeliveryDate.getDate() + 5);
    combinedRate.min_delivery_date = minDeliveryDate.toISOString();

    // Add the combined rate to the rates array
    rates = [combinedRate];
  }

  // Return the shipping rates
  return { rates };
}

// Function to get the distance between two addresses using Google Distance Matrix API
async function getDistance(origin, destination, apiKey) {
  // Make a request to the Google Distance Matrix API
  const response = await fetch(
    `https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=${origin}&destinations=${destination}&key=${apiKey}`
  );

  // Parse the response
  const data = await response.json();

  // Return the distance in km
  return data.rows[0].elements[0].distance.value;
}

2. Using product types

Prompt:

I want a shipping calculator function.
Enrich the data and use the product type field in the items product object.
If the item product type is "furniture", multiply the kilogram weight of that item with 1.5 to get the shipping fee of that item.
If the item product type is "fashion", multiply the kilogram weight of that item with 0.2 to get the shipping fee of that item.

If the item is neither fashion or furniture, its shipping price is free.
Add the items shipping fees, and generate one shipping rate.

If the items include at least one furniture item, the delivery takes 1 to 2 weeks. Otherwise, the delivery takes 3 to 5 business days.
Make sure to convert the delivery times to delivery dates from now and correctly implement it.
Make sure to convert grams to kilograms.

AI Output:

import { enrichItemDetails } from "./modules.js";

export async function calculateShippingRates(DATA, env) {
  try {
    // Enrich the data with additional fields
    DATA = await enrichItemDetails(DATA);

    // Initialize the shipping rates
    let rates = [];

    // Calculate the shipping fee for each item
    let totalWeight = 0;
    let isFurniture = false;
    for (const item of DATA.items) {
      let weight = item.grams / 1000;
      totalWeight += weight;
      let shippingFee = 0;
      if (item.product.productType === "furniture") {
        isFurniture = true;
        shippingFee = weight * 1.5;
      } else if (item.product.productType === "fashion") {
        shippingFee = weight * 0.2;
      }
      item.shippingFee = shippingFee;
    }

    // Calculate the total shipping fee
    let totalShippingFee = 0;
    for (const item of DATA.items) {
      totalShippingFee += item.shippingFee;
    }

    // Set the delivery dates
    let minDeliveryDate = "";
    let maxDeliveryDate = "";
    if (isFurniture) {
      minDeliveryDate = new Date();
      minDeliveryDate.setDate(minDeliveryDate.getDate() + 7);
      maxDeliveryDate = new Date();
      maxDeliveryDate.setDate(maxDeliveryDate.getDate() + 14);
    } else {
      minDeliveryDate = new Date();
      minDeliveryDate.setDate(minDeliveryDate.getDate() + 3);
      maxDeliveryDate = new Date();
      maxDeliveryDate.setDate(maxDeliveryDate.getDate() + 5);
    }

    // Create the shipping rate
    rates.push({
      service_name: "Standard Shipping",
      service_code: "standard_shipping",
      total_price: totalShippingFee * 100,
      description: "Standard shipping",
      currency: DATA.currency,
      min_delivery_date: minDeliveryDate.toISOString(),
      max_delivery_date: maxDeliveryDate.toISOString(),
    });

    // Return the shipping rates
    return { rates };
  } catch (error) {
    // Return a rate with price equals to null in case of errors
    return { rates: [{ total_price: null }] };
  }
}

3. Using product weights

Prompt:

I'd like a shipping rate calculator that uses the items total weight, the items total cubic weight and items total price as parameters.
The calculator compares the items total weight in kg to the items total cubic weight. The calculator takes the larger of the two and multiply it by 0.2 cents to calculate the total shipping cost.
If the total items price is more than $500, the calculator provides 10% discount from the total shipping cost. The total item price is the sum of each item price.

The dimension and weight of the each item is contained in the item's metafield namespace object called "shipping". Get the first 15 values in the namespace.
The dimensions are given in cm and the weight is given kilograms.
The delivery date is between 5 to 8 days from now.
Use the cubic conversion rate of 250kg per cubic meter. Make sure to convert units correctly, for example, centimeter to meter.
The rates should be in converted to cents.

AI Output:

import { enrichItemDetails } from "./modules.js";

export async function calculateShippingRates(DATA, env) {
  try {
    // Enrich items with additional details
    DATA = await enrichItemDetails(DATA, [{ namespace: "shipping", size: 15 }]);

    // Calculate total weight and cubic weight
    let totalWeight = 0;
    let totalCubicWeight = 0;
    for (const item of DATA.items) {
      const shippingMetafield = item.metafields.shipping;
      if (shippingMetafield) {
        const length = parseFloat(shippingMetafield.length) / 100; // Convert cm to m
        const width = parseFloat(shippingMetafield.width) / 100; // Convert cm to m
        const height = parseFloat(shippingMetafield.height) / 100; // Convert cm to m
        const weight = parseFloat(shippingMetafield.weight);
        totalWeight += weight;
        totalCubicWeight += length * width * height * 250; // Convert kg to m^3 and multiply by 250kg/m^3
      }
    }

    // Calculate shipping cost
    let shippingCost = Math.max(totalWeight, totalCubicWeight) * 0.2;

    // Apply discount if total price is over $500
    const totalPrice = DATA.items.reduce((acc, item) => acc + item.price, 0);
    if (totalPrice > 50000) {
      shippingCost *= 0.9;
    }

    // Convert shipping cost to cents
    shippingCost = Math.ceil(shippingCost * 100);

    // Calculate delivery dates
    const minDeliveryDate = new Date();
    minDeliveryDate.setDate(minDeliveryDate.getDate() + 5);
    const maxDeliveryDate = new Date();
    maxDeliveryDate.setDate(maxDeliveryDate.getDate() + 8);

    // Return shipping rates
    return {
      rates: [
        {
          service_name: "Standard Shipping",
          service_code: "standard",
          total_price: shippingCost.toString(),
          description: "Standard shipping",
          currency: DATA.currency,
          min_delivery_date: minDeliveryDate.toISOString(),
          max_delivery_date: maxDeliveryDate.toISOString(),
        },
      ],
    };
  } catch (error) {
    // Return error rate
    return {
      rates: [
        {
          service_name: "Error",
          service_code: "error",
          total_price: null,
          description: error.message,
          currency: DATA.currency,
          min_delivery_date: "",
          max_delivery_date: "",
        },
      ],
    };
  }
}

4. Sample Vendor - AliExpress

Prompt:

I'd like a shipping rate calculator for items from AliExpress products.
The AliExpress product id is contained as part of the items sku separated with a hyphen. Split the sku and take the first part as AliExpress product id.

AI Output:

import { enrichItemDetails } from "./modules.js";
import { AliExpress } from "./modules.js";

export async function calculateShippingRates(DATA, env) {
  try {
    // Enrich item details with additional fields
    DATA = await enrichItemDetails(DATA);

    // Extract AliExpress product ids from item skus
    const aliexpressProducts = DATA.items.map((item) => {
      const [aliexpressProductId] = item.sku.split("-");
      return { aliexpress_product_id: aliexpressProductId, quantity: item.quantity };
    });

    // Initialize AliExpress instance with destination and currency
    const aliexpress = new AliExpress(DATA.destination, DATA.currency);

    // Get shipping rates from AliExpress
    const rates = await aliexpress.getRates(aliexpressProducts);

    // Return shipping rates in Shopify format
    return { rates };
  } catch (error) {
    // Return error rate
    return {
      rates: [
        {
          service_name: "Error",
          service_code: "error",
          total_price: null,
          description: error.message,
          currency: DATA.currency,
          min_delivery_date: "",
          max_delivery_date: "",
        },
      ],
    };
  }
}

5. Sample Courier - Canada Post

Prompt:

I'd like a shipping rate calculator that uses the Canada Post rates.
The dimensions of the parcels are contained in the items metafield namespace object called "carton". Get the first 15 values in the namespace.

AI Output:

import { enrichItemDetails, CanadaPost } from "./modules.js";

export async function calculateShippingRates(DATA, env) {
  try {
    // Enrich items with additional fields
    DATA = await enrichItemDetails(DATA, [{ namespace: "carton", size: 15 }]);

    // Get origin and destination addresses
    const origin = DATA.origin;
    const destination = DATA.destination;

    // Create Canada Post instance
    const canadaPost = new CanadaPost(origin, destination);

    // Get parcels dimensions and weight
    const parcels = DATA.items.map((item) => {
      const metafields = item.metafields?.carton;
      return {
        length: metafields?.length ? parseFloat(metafields.length) : null,
        width: metafields?.width ? parseFloat(metafields.width) : null,
        height: metafields?.height ? parseFloat(metafields.height) : null,
        weight: item.grams / 1000,
        quantity: item.quantity,
      };
    });

    // Get shipping rates
    const rates = await canadaPost.getRates(parcels);

    // Format rates in Shopify format
    const formattedRates = rates.map((rate) => ({
      service_name: rate.service_name,
      service_code: rate.service_code,
      total_price: rate.total_price,
      description: rate.description,
      currency: rate.currency,
      min_delivery_date: rate.min_delivery_date || "",
      max_delivery_date: rate.max_delivery_date || "",
    }));

    return { rates: formattedRates };
  } catch (error) {
    console.error(error);
    return { rates: [{ total_price: null }] };
  }
}