0.1.151 • Published 22 days ago

@smartdatahq/embedded-agent v0.1.151

Weekly downloads
-
License
AGPL-3.0
Repository
-
Last release
22 days ago

npm license

Installation Guide: Embedded Agent

The @smartdatahq/embedded-agent package is a powerful tool for integrating AI-driven conversational agents into your web applications. This guide will walk you through the installation and setup process.

Table of Contents

Prerequisites

Before using the @smartdatahq/embedded-agent package, ensure the following:

  1. You have Node.js (version 14 or higher) and npm installed on your system.
  2. You have a valid identifier to connect to the @smartdatahq/embedded-agent service. Make sure you contact us to get your identifier.

Installation

To install the package, use npm or yarn:

Using npm

npm install @smartdatahq/embedded-agent

Using yarn

yarn add @smartdatahq/embedded-agent

Basic Usage

Here is an example of how to integrate the embedded agent into your React application:

Import the Component
import { EmbeddedAgent } from "@smartdatahq/embedded-agent";
import "@smartdatahq/embedded-agent/dist/index.css";

If your application is mostly SSR, you might need to dynamically import the package since it needs to run on the browser. For example, in next.js, you would want to import it like this

const EmbeddedAgent = dynamic(
  () => import("@smartdatahq/embedded-agent").then((mod) => mod.EmbeddedAgent),
  {
    ssr: false,
  },
);
Integrating the embedded agent (minimal example)

Use the following example to set up the agent in your application:

const App = () => {
  const [minimized, setMinimized] = useState(true);

  const handleSearchResults = (result: any) => {
    // Search Results
    console.log('Search Results:', result);
  };

  return (
    <div style={{ height: minimized ? 68 : 400 }}>
      <h1>My Embedded Agent Application</h1>
      <EmbeddedAgent
        identifier="YOUR_IDENTIFIER" // Replace with your unique identifier
        onSearchResult={handleSearchResults}
        minimized={minimized}
        onMinimizedChange={() => setMinimized(!minimized)}
      />
    </div>
  );
};

Browser Tools Integration

The Embedded Agent supports browser tools integration, allowing the AI agent to interact with your application's functionality directly. This powerful feature enables the agent to perform actions like navigation, data manipulation, API calls, and more.

Overview

Browser tools integration consists of three main components:

  1. browserToolsRegistration: Define available tools with their schemas
  2. onBrowserToolCall: Handle when the agent wants to use a tool
  3. browserToolCallResponse: Send the tool execution result back to the agent

Basic Browser Tools Example

const App = () => {
  const [minimized, setMinimized] = useState(true);
  const [toolResponse, setToolResponse] = useState(undefined);
  const [shoppingCart, setShoppingCart] = useState([]);

  const handleBrowserToolCall = (data) => {
    console.log("Tool called:", data);

    if (data.name === "add_to_cart") {
      // Add item to shopping cart
      const newItem = {
        id: Math.random().toString(36).substr(2, 9),
        product_sku: data.args.product_sku,
        quantity: data.args.quantity || 1,
        addedAt: new Date().toISOString()
      };

      setShoppingCart(prev => [...prev, newItem]);

      setToolResponse({
        id: data.id,
        output: {
          success: true,
          message: `Added ${data.args.product_sku} to cart`,
          cartCount: shoppingCart.length + 1
        }
      });
    }
  };

  return (
    <EmbeddedAgent
      identifier="YOUR_IDENTIFIER"
      minimized={minimized}
      onMinimizedChange={() => setMinimized(!minimized)}
      browserToolsRegistration={[
        {
          title: "add_to_cart",
          scope: "agent",
          description: "Adds a product to the shopping cart. Call this tool whenever the user has confirmed that he wants to buy the product with the product SKU identifier. Ask the user how many items he wants, if it is not clear from the context of the conversation.",
          type: "object",
          properties: {
            product_sku: {
              title: "Product SKU",
              description: "The product identifier to add to cart",
              type: "string"
            },
            quantity: {
              title: "Quantity",
              description: "Number of items to add",
              type: "integer",
              minimum: 1,
              default: 1
            }
          },
          required: ["product_sku"]
        }
      ]}
      onBrowserToolCall={handleBrowserToolCall}
      browserToolCallResponse={toolResponse}
    />
  );
};

Advanced Browser Tools Example

Here's a more comprehensive example showing multiple tool types:

const App = () => {
  const [minimized, setMinimized] = useState(true);
  const [toolResponse, setToolResponse] = useState(undefined);
  const [shoppingCart, setShoppingCart] = useState([]);
  const [userProfile, setUserProfile] = useState({
    name: "John Doe",
    email: "john@example.com"
  });

  const handleBrowserToolCall = (data) => {
    const { name, args, id } = data;

    switch (name) {
      case "get_weather":
        // Simulate weather API call
        const weatherData = {
          temperature: "72°F",
          condition: "sunny",
          humidity: "45%",
          city: args.city
        };

        setToolResponse({
          id,
          output: weatherData
        });
        break;

      case "manage_cart":
        if (args.action === "add") {
          const newItem = {
            id: Math.random().toString(36).substr(2, 9),
            product_sku: args.product_sku,
            addedAt: new Date().toISOString()
          };
          setShoppingCart(prev => [...prev, newItem]);
          setToolResponse({
            id,
            output: {
              success: true,
              action: "added",
              product_sku: args.product_sku,
              cartCount: shoppingCart.length + 1
            }
          });
        } else if (args.action === "view") {
          // Navigate to cart page
          window.history.pushState({}, '', '/cart');
          setToolResponse({
            id,
            output: {
              success: true,
              items: shoppingCart,
              cartCount: shoppingCart.length,
              navigatedTo: "/cart"
            }
          });
        }
        break;

      case "view_item":
        // Navigate to item page
        window.history.pushState({}, '', `/product/${args.product_sku}`);
        setToolResponse({
          id,
          output: {
            success: true,
            product_sku: args.product_sku,
            navigatedTo: `/product/${args.product_sku}`,
            message: `Viewing details for ${args.product_sku}`
          }
        });
        break;

      case "update_user_profile":
        setUserProfile(prev => ({
          ...prev,
          [args.field]: args.value
        }));
        setToolResponse({
          id,
          output: {
            success: true,
            updatedProfile: { ...userProfile, [args.field]: args.value }
          }
        });
        break;

      case "api_request":
        // Simulate API call
        fetch(args.endpoint, {
          method: args.method,
          headers: args.headers,
          body: args.body ? JSON.stringify(args.body) : undefined
        })
        .then(response => response.json())
        .then(data => {
          setToolResponse({
            id,
            output: {
              success: true,
              response: data,
              status: 200
            }
          });
        })
        .catch(error => {
          setToolResponse({
            id,
            output: {
              success: false,
              error: error.message
            }
          });
        });
        break;

      default:
        setToolResponse({
          id,
          output: {
            success: false,
            error: `Unknown tool: ${name}`
          }
        });
    }
  };

  return (
    <EmbeddedAgent
      identifier="YOUR_IDENTIFIER"
      minimized={minimized}
      onMinimizedChange={() => setMinimized(!minimized)}
      browserToolsRegistration={[
        {
          title: "get_weather",
          scope: "agent",
          description: "Get current weather information for a city",
          type: "object",
          properties: {
            city: {
              title: "City",
              description: "The name of the city",
              type: "string"
            },
            units: {
              title: "Temperature Units",
              description: "Temperature units for the weather data",
              type: "string",
              enum: ["celsius", "fahrenheit"],
              default: "fahrenheit"
            }
          },
          required: ["city"]
        },
        {
          title: "manage_cart",
          scope: "agent",
          description: "Manage shopping cart operations",
          type: "object",
          properties: {
            action: {
              title: "Cart Action",
              description: "The action to perform",
              type: "string",
              enum: ["add", "remove", "clear", "view"]
            },
            product_sku: {
              title: "Product SKU",
              description: "Product identifier",
              type: "string"
            }
          },
          required: ["action"]
        },
        {
          title: "view_item",
          scope: "agent",
          description: "View detailed information about a specific product",
          type: "object",
          properties: {
            product_sku: {
              title: "Product SKU",
              description: "The product identifier to view details for",
              type: "string"
            }
          },
          required: ["product_sku"]
        },
        {
          title: "update_user_profile",
          scope: "agent",
          description: "Update user profile information",
          type: "object",
          properties: {
            field: {
              title: "Profile Field",
              description: "The profile field to update",
              type: "string",
              enum: ["name", "email", "phone", "address"]
            },
            value: {
              title: "New Value",
              description: "The new value for the field",
              type: "string"
            }
          },
          required: ["field", "value"]
        },
        {
          title: "api_request",
          scope: "agent",
          description: "Make HTTP API requests",
          type: "object",
          properties: {
            endpoint: {
              title: "API Endpoint",
              description: "The API endpoint URL",
              type: "string",
              format: "uri"
            },
            method: {
              title: "HTTP Method",
              description: "HTTP method for the request",
              type: "string",
              enum: ["GET", "POST", "PUT", "PATCH", "DELETE"]
            },
            headers: {
              title: "Request Headers",
              description: "HTTP headers",
              type: "object",
              additionalProperties: { type: "string" }
            },
            body: {
              title: "Request Body",
              description: "Request body data",
              type: "object",
              additionalProperties: true
            }
          },
          required: ["endpoint", "method"]
        }
      ]}
      onBrowserToolCall={handleBrowserToolCall}
      browserToolCallResponse={toolResponse}
    />
  );
};

Tool Schema Format

Browser tools use JSON Schema format for defining parameters. Each tool should include:

  • title: Unique identifier for the tool
  • scope: Either "agent" or "conversation". This registers the tool for either the current conversation or globally for the agent.
  • description: Clear description of what the tool does and when to call it. Describe under what conditions the AI should use the tool and explain the goal of calling the tool. For example, if it's for adding a product to the cart, then explain that it should be called once the user has confirmed that he wishes to buy a product.
  • type: Should be "object" for complex tools
  • properties: Object defining all parameters
  • required: Array of required parameter names

Parameter Types

You can use various JSON Schema types and constraints:

// String with enum constraints
{
  type: "string",
  enum: ["option1", "option2", "option3"],
  description: "Choose from predefined options"
}

// Number with range constraints
{
  type: "number",
  minimum: 0,
  maximum: 100,
  description: "Value between 0 and 100"
}

// Complex nested objects
{
  type: "object",
  properties: {
    nested_field: {
      type: "string",
      description: "Nested parameter"
    }
  },
  required: ["nested_field"]
}

// Arrays with item constraints
{
  type: "array",
  items: {
    type: "string",
    enum: ["item1", "item2"]
  },
  description: "Array of predefined items"
}

Error Handling

Always include error handling in your tool call handler:

const handleBrowserToolCall = (data) => {
  try {
    // Your tool logic here
    setToolResponse({
      id: data.id,
      output: { success: true, result: "..." },
    });
  } catch (error) {
    setToolResponse({
      id: data.id,
      output: {
        success: false,
        error: error.message,
      },
    });
  }
};

Best Practices

  1. Clear Descriptions: Provide clear, detailed descriptions for tools and parameters
  2. Validation: Use JSON Schema constraints to validate inputs
  3. Error Handling: Always handle errors gracefully
  4. Response Format: Maintain consistent response format with success/error indicators
  5. Async Operations: Handle asynchronous operations properly
  6. State Management: Update your application state based on tool results

Context Schema Integration

The Embedded Agent supports context schema integration, allowing you to extract structured parameters from conversations. The agent can understand and extract specific information based on the schema you provide.

Context Schema Example

const App = () => {
  const [minimized, setMinimized] = useState(true);

  const handleSearchResults = (result: any) => {
    // Search Results
    console.log('Search Results:', result);
  };

  const handleContextUpdate = (schema: any) => {
    // Updated Context Schema to keep track of the filters applied/current state
    console.log('Updated Context Schema:', schema);
  };

  return (
    <div style={{ height: minimized ? 68 : 400 }}>
      <h1>My Embedded Agent Application</h1>
      <EmbeddedAgent
        identifier="YOUR_IDENTIFIER" // Replace with your unique identifier
        onSearchResult={handleSearchResults}
        onContextJsonUpdate={handleContextUpdate}
        minimized={minimized}
        onMinimizedChange={() => setMinimized(!minimized)}
        contextSchema={{
            "$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                 "maximum_price": {
                  "type": ["integer", "null"],
                  "minimum": 0,
                  "description": "Maximum Price for the article. Optional."
                },
                "manufacturer": {
                    "type": "array",
                    "description": "Manufacturer name (e.g., Samsung, Apple).",
                    "items": {
                        "type": "string",
                         "enum": ["Samsung", "Apple", "Nokia", "Philips"],
                    },

                },
                "screen_type": {
                    "type": "string",
                    "enum": ["OLED", "LCD", "AMOLED"],
                    "description": "Type of screen (e.g., OLED, LCD, AMOLED)."
                },
                "color": {
                    "type": "string",
                    "description": "Color of the product (e.g., black, white)."
                },
                "size": {
                    "type": "string",
                    "description": "Size of the product (e.g., 13-inch, 15-inch)."
                },
                "manufacturing_date": {
                  "type": "string",
                  "format": "date",
                "description": "Manufacturing date of this product"
                },
            },
            "required": ["price", "manufacturer", "manufacturing_date", "screen_type", "color", "size"],
        }}
      />
    </div>
  );
};

Context Schema Notes

The contextSchema is defined in compliance with JSON Schema. This ensures the agent uses a well-defined schema for extracting and validating context data. Learn more here: https://tour.json-schema.org/

API

Core Properties

identifier (Required)
type: string
Description: Unique identifier for connecting to the embedded agent server.

Browser Tools Properties

browserToolsRegistration
Type: Array<{ scope: "agent" | "conversation"; [key: string]: any; }>
Description: Array of tool definitions using JSON Schema format. Each tool defines parameters and constraints for browser-based actions the agent can perform.
onBrowserToolCall
Type: (data: { name: string; type: string; id: string; args?: Record<string, any>; [key: string]: any; }) => void
Description: Callback function triggered when the agent wants to execute a browser tool. Handle the tool execution and update browserToolCallResponse with the result.
browserToolCallResponse
Type: { id: string; output: any; } | undefined
Description: Response object containing the result of a browser tool execution. The id should match the tool call request id, and output contains the execution result.

Context Schema Properties

contextSchema
type: Record<string, any>
Description: Defines the schema for extracting parameters from the conversation.
onContextJsonUpdate
Type: (schema: any) => void
Description: Callback function triggered when the context schema updates.
onSearchResult
Type: (result: any) => void
Description: Callback function triggered with a result when the agent resolves the user's request.

Additional API

You can also customize the embedded agent with additional props, including:\ className: Custom class for styling the embedded agent container.\ minimized: Default minimized state of the embedded agent. If being used, you need to update it to match the value you get from the onMinimizedChange function.\ onMinimizedChange: Callback for changes in the minimized state.\ conversationId: Unique conversation ID for the session. This is generated internally if not provided. It should preferably be a UUID string.\ isRendered: boolean. You can set this to false if you don't want the agent to show on render. Instead, we will display a message that can be clicked to load the agent. This is false by default. If set to true, the agent is displayed instead of the message prompt.\ onChatbotRender: This function is called when the agent is rendered. It only runs if you set render to false and manually click the message that displays in place of the agent.\ onError: Callback for handling errors.\ inactiveText: The text to display when the agent is inactive (not rendered). This is useful for overwriting the configured message shown to users before they interact with the agent.\ showInPopup: This boolean determines whether the agent is shown as a popup on the page or embedded directly in the content. When true, the agent will appear in a floating popup window that can be moved around the page.\ processingIcon: Optional JSX element to customize the loading indicator shown while the agent is processing responses.\ contextSchemaData: Optional data object that matches the structure defined in contextSchema. This can be used to pre-populate context data for the conversation.\ existingFilters: Optional array of filter objects to be applied to the conversation. Each filter should match the structure defined in your contextSchema.\ offset: Optional object to determine the left and bottom offset of the agent when it's a popup.\ draggable: Optional boolean that enables dragging functionality for the chat window. When true, the window can be dragged around the screen. When false, the window stays in a fixed position based on the offset prop.\ resizeable: Optional boolean that enables resizing functionality for the chat window. When true, the window can be resized using the resize handle in the bottom-right corner. When false, the window maintains a fixed size. Note that resizing is only available when the window is not minimized.\ height: Optional number that sets the initial height of the chat window in pixels. If not provided, defaults to 600px.\ devMode: Optional boolean that allows us to enable devMode features.\

0.1.151

22 days ago

0.1.149

22 days ago

0.1.147

22 days ago

0.1.146

23 days ago

0.1.145

25 days ago

0.1.144

25 days ago

0.1.143

25 days ago

0.1.142

25 days ago

0.1.141

1 month ago

0.1.140

1 month ago

0.1.139

1 month ago

0.1.138

2 months ago

0.1.137

2 months ago

0.1.136

2 months ago

0.1.135

2 months ago

0.1.134

2 months ago

0.1.133

2 months ago

0.1.132

2 months ago

0.1.131

2 months ago

0.1.130

2 months ago

0.1.129

2 months ago

0.1.128

2 months ago

0.1.127

2 months ago

0.1.126

2 months ago

0.1.125

2 months ago

0.1.124

2 months ago

0.1.123

2 months ago

0.1.122

2 months ago

0.1.121

2 months ago

0.1.120

2 months ago

0.1.119

2 months ago

0.1.118

2 months ago

0.1.117

2 months ago

0.1.116

2 months ago

0.1.111-j

2 months ago

0.1.111-i

2 months ago

0.1.115

2 months ago

0.1.111-h

2 months ago

0.1.111-g

2 months ago

0.1.111-f

2 months ago

0.1.111-e

2 months ago

0.1.111-d

2 months ago

0.1.111-c

2 months ago

0.1.111-b

2 months ago

0.1.111-a

2 months ago

0.1.114

2 months ago

0.1.113

2 months ago

0.1.112

2 months ago

0.1.111

2 months ago

0.1.110

2 months ago

0.1.109

3 months ago

0.1.108

3 months ago

0.1.107

3 months ago

0.1.106

3 months ago

0.1.105

3 months ago

0.1.103

3 months ago

0.1.102

3 months ago

0.1.101

3 months ago

0.1.100

3 months ago

0.1.99

3 months ago

0.1.98

3 months ago

0.1.97

3 months ago

0.1.96

3 months ago

0.1.95

3 months ago

0.1.94

3 months ago

0.1.93

3 months ago

0.1.92

3 months ago

0.1.91

3 months ago

0.1.90

3 months ago

0.1.89

3 months ago

0.1.88

3 months ago

0.1.87

3 months ago

0.1.86

4 months ago

0.1.85

4 months ago

0.1.84

4 months ago

0.1.83

4 months ago

0.1.82

4 months ago

0.1.81

4 months ago

0.1.80

4 months ago

0.1.79

4 months ago

0.1.78

4 months ago

0.1.77

4 months ago

0.1.76

4 months ago

0.1.75

4 months ago

0.1.74

4 months ago

0.1.73

4 months ago

0.1.72

4 months ago

0.1.71

4 months ago

0.1.70

4 months ago

0.1.69

4 months ago

0.1.68

4 months ago

0.1.67

4 months ago

0.1.66

4 months ago

0.1.65

5 months ago

0.1.64

5 months ago

0.1.63

5 months ago

0.1.62

5 months ago

0.1.61

5 months ago

0.1.60

5 months ago

0.1.59

5 months ago

0.1.57

5 months ago

0.1.56

5 months ago

0.1.55

5 months ago

0.1.54

5 months ago

0.1.53

5 months ago

0.1.52

5 months ago

0.1.51

5 months ago

0.1.50

5 months ago

0.1.49

5 months ago

0.1.48

5 months ago

0.1.47

5 months ago

0.1.46

5 months ago

0.1.45

5 months ago

0.1.44

5 months ago

0.1.43

5 months ago

0.1.42

5 months ago

0.1.41

5 months ago

0.1.40

5 months ago

0.1.39

5 months ago

0.1.38

5 months ago

0.1.37

5 months ago

0.1.36

5 months ago

0.1.35

5 months ago

0.1.34

5 months ago

0.1.33

5 months ago

0.1.32

5 months ago

0.1.31

6 months ago

0.1.30

6 months ago

0.1.29

6 months ago

0.1.28

6 months ago

0.1.27

6 months ago

0.1.20

6 months ago

0.1.19

6 months ago

0.1.18

6 months ago

0.1.17

6 months ago

0.1.16

6 months ago

0.1.15

6 months ago