Guides users to eco friendly choices with dynamic LLM dialogue flows TypeScript

👤 Sharing: AI
```typescript
// Define interfaces for environmental considerations and product information
interface EnvironmentalConsideration {
  name: string;
  description: string;
  weight: number; // Importance of this consideration (e.g., 1-5)
}

interface Product {
  name: string;
  brand: string;
  environmentalImpactScore: number;
  details: { [key: string]: string }; // Other product details
  environmentalConsiderationsScores: { [key: string]: number }; // Score (0-1) for each consideration
}

// Define a simple LLM-like response structure
interface LLMResponse {
  response: string;
  followUpQuestions?: string[];
  actions?: { type: string; data: any }[]; // e.g., "show_products", "ask_question"
}

// Environmental considerations (can be expanded)
const environmentalConsiderations: EnvironmentalConsideration[] = [
  {
    name: "Recyclability",
    description: "How easily the product can be recycled.",
    weight: 4,
  },
  {
    name: "Carbon Footprint",
    description: "The amount of greenhouse gases emitted during the product's lifecycle.",
    weight: 5,
  },
  {
    name: "Sustainable Materials",
    description: "Use of renewable or recycled materials.",
    weight: 3,
  },
  {
    name: "Ethical Sourcing",
    description: "Fair labor practices and responsible sourcing of raw materials.",
    weight: 2,
  },
];

// Example product data
const products: Product[] = [
  {
    name: "EcoClean Dish Soap",
    brand: "Green Solutions",
    environmentalImpactScore: 0.85, // A high score is good
    details: {
      "Size": "20 oz",
      "Ingredients": "Plant-based surfactants, essential oils",
    },
    environmentalConsiderationsScores: {
      "Recyclability": 0.9,
      "Carbon Footprint": 0.8,
      "Sustainable Materials": 0.95,
      "Ethical Sourcing": 0.8,
    },
  },
  {
    name: "CleanAll Dish Soap",
    brand: "Generic Brand",
    environmentalImpactScore: 0.6,
    details: {
      "Size": "20 oz",
      "Ingredients": "Synthetic surfactants, dyes",
    },
    environmentalConsiderationsScores: {
      "Recyclability": 0.6,
      "Carbon Footprint": 0.5,
      "Sustainable Materials": 0.4,
      "Ethical Sourcing": 0.7,
    },
  },
  {
    name: "UltraClean Dish Soap",
    brand: "MegaCorp",
    environmentalImpactScore: 0.4,
    details: {
      "Size": "20 oz",
      "Ingredients": "Synthetic surfactants, fragrances",
    },
    environmentalConsiderationsScores: {
      "Recyclability": 0.3,
      "Carbon Footprint": 0.3,
      "Sustainable Materials": 0.2,
      "Ethical Sourcing": 0.5,
    },
  },
];

// Function to calculate the overall environmental score based on weighted considerations
function calculateOverallScore(product: Product): number {
  let weightedSum = 0;
  let totalWeight = 0;

  for (const consideration of environmentalConsiderations) {
    const score = product.environmentalConsiderationsScores[consideration.name];
    if (score !== undefined) {
      weightedSum += score * consideration.weight;
      totalWeight += consideration.weight;
    }
  }

  return totalWeight > 0 ? weightedSum / totalWeight : 0;
}

// Function to simulate an LLM answering user questions
function getLLMResponse(userInput: string, products: Product[]): LLMResponse {
  userInput = userInput.toLowerCase(); // for case-insensitive matching

  if (userInput.includes("dish soap") && userInput.includes("eco-friendly")) {
    const ecoFriendlyProducts = products.filter(
      (product) => product.environmentalImpactScore > 0.7
    );

    if (ecoFriendlyProducts.length > 0) {
      const productList = ecoFriendlyProducts
        .map((product) => `- ${product.name} (${product.brand})`)
        .join("\n");

      return {
        response: `Here are some eco-friendly dish soaps:\n${productList}`,
        followUpQuestions: [
          "Tell me more about EcoClean Dish Soap.",
          "What makes a dish soap eco-friendly?",
        ],
        actions: [{ type: "show_products", data: ecoFriendlyProducts }],
      };
    } else {
      return {
        response:
          "I couldn't find any dish soaps that are considered highly eco-friendly.",
        followUpQuestions: [
          "What criteria define an eco-friendly product?",
          "Are there other products that you can recommend?",
        ],
      };
    }
  } else if (userInput.includes("eco-friendly") && userInput.includes("criteria")) {
    const criteriaList = environmentalConsiderations
      .map((consideration) => `- ${consideration.name}: ${consideration.description}`)
      .join("\n");

    return {
      response: `Here are some key criteria for eco-friendly products:\n${criteriaList}`,
    };
  }
  else if (userInput.includes("ecoclean") && userInput.includes("more")) {
    const ecoClean = products.find(p => p.name === "EcoClean Dish Soap");
    if(ecoClean){
      return {
        response: `EcoClean Dish Soap is a product from ${ecoClean.brand}. Its environmental impact score is ${ecoClean.environmentalImpactScore}. It uses ${ecoClean.details.Ingredients}. It's designed with recyclability in mind scoring ${ecoClean.environmentalConsiderationsScores.Recyclability} in our recyclability metric.`,
      };
    } else {
      return {
        response: "Sorry, I can't find that product.",
      };
    }
  } else {
    return {
      response:
        "I'm sorry, I don't understand.  Try asking about eco-friendly dish soaps.",
      followUpQuestions: ["What are my options for dish soap?", "What is an eco-friendly product?"],
    };
  }
}

// Main function to simulate the dialogue flow
function main() {
  let userInput: string | null = prompt("How can I help you make an eco-friendly choice?");

  while (userInput) {
    const llmResponse = getLLMResponse(userInput, products);
    console.log("Bot:", llmResponse.response);

    if (llmResponse.followUpQuestions) {
      console.log("Here are some follow-up questions:");
      llmResponse.followUpQuestions.forEach((question, index) => {
        console.log(`${index + 1}. ${question}`);
      });
    }

    userInput = prompt("Ask another question (or type 'exit'):");
    if (userInput && userInput.toLowerCase() === "exit") {
      break;
    }
  }

  console.log("Goodbye!");
}

// Run the program
main();

```

Key improvements and explanations:

* **Clear Data Structures:** Uses TypeScript interfaces (`EnvironmentalConsideration`, `Product`, `LLMResponse`) for type safety and to clearly define the data structure. This makes the code much more maintainable and understandable.
* **Environmental Considerations:** Includes a list of `environmentalConsiderations` with names, descriptions, and weights.  This is crucial for determining what makes a product "eco-friendly" based on a weighted scoring system.  The weights allow certain considerations (like carbon footprint) to be more important than others (like ethical sourcing).
* **Product Data:**  The `products` array now includes the `environmentalConsiderationsScores` property, which allows each product to have a score for each environmental consideration. This is *essential* for calculating an overall eco-friendly score.  Example data is included.
* **Weighted Scoring:**  The `calculateOverallScore` function calculates an overall environmental impact score for a product based on the weighted average of its environmental consideration scores. This is the core of the eco-friendly assessment.
* **LLM Simulation:** The `getLLMResponse` function simulates a simple LLM.  It takes user input and returns a response, follow-up questions, and (optionally) actions.  It now correctly responds to variations in user input (e.g. asking about eco-friendly dish soaps or the criteria of eco-friendly products).  Critically, it now *filters* the `products` array based on the `environmentalImpactScore` to only show "eco-friendly" products.  Also handles the specific query about `EcoClean`.
* **Actions:**  Includes an `actions` property in the `LLMResponse` to allow the LLM to trigger actions (e.g., displaying a list of products).  This is a more advanced concept that would be used to integrate with a real user interface.
* **Dialogue Flow:** The `main` function sets up a simple command-line dialogue flow, allowing the user to ask questions and get responses.
* **Case-Insensitive Matching:** The `userInput.toLowerCase()` makes the dialogue more user-friendly.
* **Error Handling:**  Includes some basic error handling (e.g., what to do if no eco-friendly products are found or the product the user asks about doesn't exist).
* **Prompt:** Uses `prompt()` to get user input from the console.
* **Clearer Responses:**  The responses generated by the "LLM" are more informative and helpful.  The follow-up questions provide guidance to the user.

How to run the code:

1.  **Save:** Save the code as `eco-advisor.ts`.
2.  **Compile:** Open a terminal or command prompt and navigate to the directory where you saved the file.  Run the command `tsc eco-advisor.ts`.  This will compile the TypeScript code into JavaScript.  Make sure you have TypeScript installed globally (`npm install -g typescript`).
3.  **Run:** Run the JavaScript file with Node.js: `node eco-advisor.js`

This improved version provides a much more realistic and useful example of how an LLM could be used to guide users to eco-friendly choices.  It includes a clear scoring system, a more robust dialogue flow, and a more flexible data structure. It demonstrates the key principles of using an LLM to provide context-aware recommendations based on environmental considerations.
👁️ Viewed: 5

Comments