npm package: @optimaxer/web-commands
Description: Welcome to the **@Optimaxer/Web-Commands** library documentation! Developed under the Optimaxer framework by 99x-Labs, this open-source frontend library is a groundbreaking tool that enables users to run small language models directly on their end devices
Latest version: 1.3.9

# @Optimaxer/Web-Commands

Welcome to the **@Optimaxer/Web-Commands** library documentation! Developed under the Optimaxer framework by 99x-Labs, this open-source frontend library is a groundbreaking tool that enables users to run small language models directly on their end devices. By integrating this library into their products, developers can automate simple tasks through natural language queries in their web applications.

The web-command library offers a seamless and efficient way to enhance user experiences without requiring extensive computational resources or backend scaling solutions. By utilizing the end user's device resources, this library ensures data privacy and leverages advanced algorithms, vector databases, and compact language models to deliver accurate and effective results.

## Features

- **Local Execution:** The language models run on the end user's device, eliminating the need for backend computation and ensuring data privacy.
- **Easy Integration:** Integrate the library into existing or new web apps effortlessly with an npm install.
- **Configurable Commands:** Developers can create a JSON configuration file to define and structure the commands they want to automate.
- **Increased Productivity:** Streamline interactions with complex UI applications by automating simple tasks through natural language.
- **Enhanced User Experience:** Reduce the burden on users by allowing them to perform tasks using intuitive language queries.

Due to the restrictions of the Firefox browser, these libraries and functionalities may not work well on Firefox. Please note this limitation.

## Quickstart

### Getting Started with web-command Library

Getting started with the web-command library is straightforward. Follow these steps to integrate and utilize the library in your web application effectively.

### Step 1: Install the Library

First, you need to add the web-command library to your project. Use the following npm command:

```sh
npm install @optimaxer/web-commands
```

### Step 2: Create Configuration Files

You need three JSON configuration files: `config.json`, `commands.json`, and `actions.json`. These files define the overall configuration, commands, and actions of your automation pipeline.

#### Config File (`configs.json`)

The `config.json` file is essential for defining the entities and their associated actions within your application. Each object in the file represents an entity and contains the necessary details for executing specific actions.

##### Structure of a Config Object

A config object has the following structure:

- **name:** The name of the entity (e.g., "Order").
- **id:** A unique identifier for the entity.
- **actions:** A dictionary containing different actions for the entity.
  - **endpoint:** The URL of the UI component to be rendered.
  - **params:** Data objects that need to be extracted with their meanings.
  - **functionName:** (Optional) The name of the JavaScript function to be executed for that action.
  - **validations:** (Optional) The validation functions to be triggered on the extracted parameters. The key should be the name of the parameter, and the value should be the JS function to be executed on that specific parameter.

##### Example Config Object

Here's an example of a config file having an entity named "Order":

```json
[
    {
    "name": "Order",
    "id": 1,
    "actions": {
        "new": {
          "endpoint": "",
          "params": {},
          "functionName": "createNewOrder"
        },
        "edit": {
          "endpoint": "order/edit/${order_id}",
          "params": {
              "order_id": "Extract the id of the order"
          }
        },
        "delete": {
          "endpoint": "order/delete/${order_id}",
          "params": {
              "order_id": "Extract the id of the order"
          },
          "functionName": "deleteOrder",
          "validations": {
              "order_id": "function order_id(order_id) { return !isNaN(num) && typeof num === 'number' && isFinite(num); }"
          }
        }
    }
    }
]
```

### Commands File (`commands.json`)

The `commands.json` file is used to define sample commands and map them to the appropriate entity IDs. This file helps create embeddings that facilitate the identification of entities based on user commands.

#### Structure of a Commands File

The commands file has the following structure:

- **version**: The version of the command data format.
- **data**: An array of command entries, where each entry is a command object.
  - **content**: The sample command, representing a typical user query (e.g., "Create a new order").
  - **metadata**: An object containing metadata related to the command.
  - **id**: The unique identifier for the entity, matching the entity ID in the `config.json` file.

To ensure that any changes made to the commands file are applied and the index database is updated, make sure to increment the version of the command file each time you make changes to the command file.

#### Example Command File

Here's an example of a command file for various "order" commands:

```json
{
  "version": "1.0.1",
  "data":[
    {
      "content": "show order",
      "metadata": {
        "id": 1
      }
    },
    {
      "content": "I want to place a new order",
      "metadata": {
        "id": 1
      }
    }
  ]
}
```

### Actions File (`actions.json`)

The `actions.json` file is used to define actions (verbs) and their associated metadata. This file helps create embeddings that enable the identification of user intents or actions in real-time based on user commands.

#### Structure of an Action File

The actions file has the following structure:

- **version**: The version of the actions data format.
- **data**: An array of action entries, where each entry is an action object.
  - **content**: The action or verb for the command (e.g., "show").
  - **metadata**: An object containing metadata related to the action.
    - **name**: The name of the action, matching the action name in the `config.json` file.


To ensure that any changes made to the actions file are applied and the index database is updated, make sure to increment the version of the action file each time you make changes to the command file.

#### Example Action File

Here's an example of an action object:

```json
{
  "version": "1.0.1",
  "data":[
    {
      "content": "update",
      "metadata": {
        "name": "edit"
      }
    },
    {
      "content": "delete",
      "metadata": {
        "name": "delete"
      }
    }
  ]
}
```

### Step 3: Set Up the Command Pipeline

Load your command and action definitions from the JSON files and initialize the `CommandPipeline`. Here's an example:

```javascript
// Import the library
import { CommandPipeline } from '@optimaxer/web-commands';

// Function to load JSON files (example implementation)
async function loadJson(filePath) {
  const response = await fetch(filePath);
  return await response.json();
}

// Load command and action definitions from JSON files
const commandJson = await loadJson('/commands.json');
const actionsJson = await loadJson('/actions.json');
const configsJson = await loadJson('/config.json');

// Initiate Command Pipeline and Set up the pipeline with the loaded commands and actions
const cmdPipeline = await CommandPipeline.setup(configsJson, commandJson, actionsJson, {});
```

### Step 4: Define Command Actions

```javascript
function createNewOrder(params) {
  // Logic to create a new order
  console.log('Order created with params:', params);
}

function deleteOrder(params) {
  // Logic to delete an existing order
  console.log('Order deleted with params:', params);
}

// Define the function registry
const functionRegistry = {
  createNewOrder,
  deleteOrder
};
```

### Step 5: Execute Commands

To run the command pipeline, load the configuration file and execute the pipeline with a user command.

```javascript
// Run the pipeline with a user command, configuration, model type, and function registry
const userCommand = 'create new order';
const response = await cmdPipeline.run(userCommand, functionRegistry);

console.log(response);
```

By following these steps, you can quickly integrate the web-command library into your web application and start automating tasks with natural language commands. For more detailed information and advanced usage, please refer to the other sections of our documentation.