Skip to main content

Widget Integration for Developers

Learn how to integrate the AgentsGT widget into your application with full customization and advanced features.

What is the AgentsGT Widget?

The AgentsGT widget is a customizable chat interface that you can embed in any web application. It supports multiple UI modes, custom actions, context injection, and multi-language support.

Built with:

  • React 19
  • CopilotKit
  • TypeScript
  • Tailwind CSS

Installation Methods

Method 1: NPM Package (React Apps)

For React applications, install the widget as an npm package:

npm install @ddrinnova/agentsgt-widget

Usage in React:

import { App as AgentSGTWidget } from "@ddrinnova/agentsgt-widget";
import "@ddrinnova/agentsgt-widget/dist/agentsgt-widget.css";

function MyApp() {
return (
<div>
<h1>My Application</h1>
<AgentSGTWidget
title="My Assistant"
initialMessage="How can I help you today?"
runtimeUrl="https://agentsgt.com/api/copilotkit/your-agent-id"
apiKey="your-api-key"
/>
</div>
);
}

Method 2: CDN (Any Website)

For any website, use the CDN version with a simple script:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Website</title>
</head>
<body>
<!-- Your content -->

<!-- Widget Container -->
<div id="agentsgt-container"></div>

<script>
const widgetVersion = "0.1.6";
const basePath = `https://cdn.jsdelivr.net/npm/@ddrinnova/agentsgt-widget@${widgetVersion}`;

(function(w, d, c, v, o) {
var l = d.createElement('link'),
s = d.createElement('script');
l.rel = 'stylesheet';
l.href = v + '/dist/agentsgt-widget.css';
s.src = v + '/dist/widget.umd.js';
l.onload = function() { d.body.appendChild(s) };
s.onload = function() {
w.AgentSGTWidget && w.AgentSGTWidget.loadWidget(c, o)
};
d.head.appendChild(l);
})(window, document, 'agentsgt-container', basePath, {
name: 'My Assistant',
initialMessage: 'How can I help?',
runtimeUrl: 'https://agentsgt.com/api/copilotkit/your-agent-id',
apiKey: 'your-api-key',
basePath: basePath
});
</script>
</body>
</html>

Configuration Options

Basic Configuration

OptionTypeRequiredDescription
titlestringNoThe title displayed in the widget header
initialMessagestringNoThe first message displayed in the chat
runtimeUrlstringYesYour agent's runtime URL from AgentsGT
apiKeystringYesYour API key from AgentsGT
basePathstringNoBase path for loading widget resources (CDN only)

Example:

{
title: "Support Assistant",
initialMessage: "Hi! How can I help you today?",
runtimeUrl: "https://agentsgt.com/api/copilotkit/asst_abc123",
apiKey: "pk_xxx:sk_yyy"
}

UI Modes

The widget supports three different UI modes:

ModeDescriptionUse Case
popupFloating chat bubble (default)Most websites
sidebarFixed sidebar panelDashboards, admin panels
chatFullscreen chat interfaceDedicated chat pages

Example:

{
// ... other options
uiMode: "sidebar" // or "popup" or "chat"
}

A small chat bubble that floats in the corner of the screen.

{
uiMode: "popup", // or omit this option
title: "Chat with us",
initialMessage: "Need help?"
}

A fixed sidebar that slides in from the side.

{
uiMode: "sidebar",
title: "Assistant",
initialMessage: "How can I assist you?"
}

Chat Mode

Fullscreen chat interface that takes up the entire container.

{
uiMode: "chat",
title: "Customer Support",
initialMessage: "Welcome! Ask me anything."
}

Advanced Features

Properties (Context Injection)

Properties allow you to inject custom context into the agent's knowledge. The agent can access this data when responding to users.

Structure:

properties: {
propertyName: {
value: any, // The actual data
description: string // What this data represents
}
}

Example - User Context:

{
properties: {
user: {
value: "John Doe",
description: "The current user's name"
},
userEmail: {
value: "john@example.com",
description: "The user's email address"
},
accountType: {
value: "Premium",
description: "The user's subscription level"
}
}
}

Example - Product Catalog:

{
properties: {
products: {
value: [
{ id: 1, name: "Product A", price: 29.99, stock: 15 },
{ id: 2, name: "Product B", price: 49.99, stock: 8 },
{ id: 3, name: "Product C", price: 19.99, stock: 50 }
],
description: "Available products in the catalog"
},
storeLocation: {
value: "New York, NY",
description: "Current store location"
}
}
}

Example - Custom Instructions:

{
properties: {
instructions: {
value: "You are a helpful assistant for TechStore. Always be polite and offer to help with product recommendations. If asked about shipping, mention we offer free shipping over $50.",
description: "Additional instructions for the assistant's behavior"
}
}
}

The agent will automatically have access to this data and can reference it in responses!

Actions (Custom Functions)

Actions allow the agent to trigger custom JavaScript functions in your application. This enables interactive features like opening URLs, submitting forms, or calling APIs.

Structure:

actions: [
{
name: string, // Unique action name
description: string, // What this action does
parameters: [ // Array of parameters
{
name: string,
type: "string" | "number" | "boolean" | "object",
description: string
}
],
handler: (args) => any, // Function to execute
render: (opts) => ReactElement | string // Optional: custom rendering
}
]

Example - Open URL:

{
actions: [
{
name: "openUrl",
description: "Open a URL in a new browser tab",
parameters: [
{
name: "url",
type: "string",
description: "The URL to open"
}
],
handler: ({ url }) => {
window.open(url, "_blank");
return { success: true, message: "Opened URL" };
}
}
]
}

Example - Search Products:

{
actions: [
{
name: "searchProducts",
description: "Search for products in the catalog",
parameters: [
{
name: "query",
type: "string",
description: "Search term"
},
{
name: "maxResults",
type: "number",
description: "Maximum number of results to return"
}
],
handler: async ({ query, maxResults }) => {
// Call your API
const response = await fetch(`/api/products/search?q=${query}&limit=${maxResults}`);
const products = await response.json();
return { success: true, products };
}
}
]
}

Example - Submit Form:

{
actions: [
{
name: "submitContactForm",
description: "Submit a contact form with user information",
parameters: [
{
name: "name",
type: "string",
description: "User's full name"
},
{
name: "email",
type: "string",
description: "User's email address"
},
{
name: "message",
type: "string",
description: "The message content"
}
],
handler: async ({ name, email, message }) => {
const response = await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, email, message })
});

if (response.ok) {
return { success: true, message: "Form submitted successfully!" };
} else {
throw new Error("Failed to submit form");
}
}
}
]
}

Example - Show Notification:

{
actions: [
{
name: "showNotification",
description: "Display a browser notification to the user",
parameters: [
{
name: "title",
type: "string",
description: "Notification title"
},
{
name: "body",
type: "string",
description: "Notification message"
}
],
handler: ({ title, body }) => {
if ('Notification' in window && Notification.permission === 'granted') {
new Notification(title, { body });
return { success: true };
} else {
return { success: false, message: "Notifications not supported" };
}
}
}
]
}

The agent will intelligently determine when to call these actions based on the user's messages!

Custom Components (React Only)

For React applications, you can inject custom React components that will be rendered within the widget.

{
customComponents: [
{
name: "customHeader",
component: MyCustomHeader,
props: { theme: "dark" }
}
]
}

Cards Rendering

Enable card-based UI rendering for displaying structured data visually.

{
enableCardsRender: true,
cardsJson: {
context_array: [
{
title: "Product A",
description: "Amazing product",
image: "https://example.com/image.jpg",
price: "$29.99"
},
// More cards...
]
}
}

When enabled, the agent can display cards in the chat for better visual presentation.

Complete Example

Here's a full example combining multiple features:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My E-commerce Site</title>
</head>
<body>
<h1>Welcome to TechStore</h1>

<div id="agentsgt-container"></div>

<script>
// Define context data
const userContext = {
user: {
value: "Jane Smith",
description: "Current user's name"
},
cartItems: {
value: 3,
description: "Number of items in shopping cart"
},
products: {
value: [
{ id: 1, name: "Laptop", price: 999, inStock: true },
{ id: 2, name: "Mouse", price: 29, inStock: true },
{ id: 3, name: "Keyboard", price: 79, inStock: false }
],
description: "Available products"
},
instructions: {
value: "You are a helpful shopping assistant. Help users find products and answer questions about orders. Always mention free shipping for orders over $100.",
description: "Assistant behavior instructions"
}
};

// Define custom actions
const customActions = [
{
name: "addToCart",
description: "Add a product to the shopping cart",
parameters: [
{ name: "productId", type: "number", description: "The product ID" },
{ name: "quantity", type: "number", description: "Quantity to add" }
],
handler: async ({ productId, quantity }) => {
const response = await fetch('/api/cart/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId, quantity })
});

if (response.ok) {
return { success: true, message: `Added ${quantity} item(s) to cart` };
} else {
throw new Error("Failed to add to cart");
}
}
},
{
name: "viewProduct",
description: "Navigate to a product detail page",
parameters: [
{ name: "productId", type: "number", description: "The product ID" }
],
handler: ({ productId }) => {
window.location.href = `/products/${productId}`;
}
},
{
name: "checkShipping",
description: "Check shipping status for an order",
parameters: [
{ name: "orderId", type: "string", description: "The order ID" }
],
handler: async ({ orderId }) => {
const response = await fetch(`/api/orders/${orderId}/shipping`);
const data = await response.json();
return {
success: true,
status: data.status,
estimatedDelivery: data.estimatedDelivery
};
}
}
];

// Load the widget
const widgetVersion = "0.1.6";
const basePath = `https://cdn.jsdelivr.net/npm/@ddrinnova/agentsgt-widget@${widgetVersion}`;

(function(w, d, c, v, o) {
var l = d.createElement('link'),
s = d.createElement('script');
l.rel = 'stylesheet';
l.href = v + '/dist/agentsgt-widget.css';
s.src = v + '/dist/widget.umd.js';
l.onload = function() { d.body.appendChild(s) };
s.onload = function() {
w.AgentSGTWidget && w.AgentSGTWidget.loadWidget(c, o)
};
d.head.appendChild(l);
})(window, document, 'agentsgt-container', basePath, {
title: 'Shopping Assistant',
initialMessage: 'Hi! I can help you find products and track orders.',
runtimeUrl: 'https://agentsgt.com/api/copilotkit/your-agent-id',
apiKey: 'your-api-key',
basePath: basePath,
uiMode: 'popup',
properties: userContext,
actions: customActions
});
</script>
</body>
</html>

Multi-Language Support

The widget automatically detects the agent's language setting and adjusts the UI accordingly.

Supported Languages:

  • English
  • Spanish (Español)
  • French (Français)
  • German (Deutsch)
  • Portuguese (Português)
  • Italian (Italiano)

The language is automatically set based on your agent's language configuration in AgentsGT. No additional setup required!

Session Persistence

The widget automatically saves conversation history in the browser's session storage. This means:

  • Conversations persist during page navigation (same session)
  • No data loss when users refresh the page
  • Automatic cleanup when the browser session ends

The session data is stored locally and never sent to external servers (except the messages themselves to your agent).

Getting Your Credentials

Runtime URL

Your runtime URL is available in AgentsGT:

  1. Go to your agent in AgentsGT
  2. Click on Integrations
  3. Click on Embed Code
  4. Copy the runtimeUrl from the code snippet

It looks like: https://agentsgt.com/api/copilotkit/asst_xxxxx

API Key

Your API key is available in your organization settings:

  1. Go to SettingsAPI Keys in AgentsGT
  2. Create a new API key if you don't have one
  3. Copy the full key (format: pk_xxx:sk_yyy)

Security Note: Never expose your secret key (sk_) in client-side code! For public websites, create a separate API key with limited permissions.

Best Practices

1. Keep API Keys Secure

For production websites:

  • Use environment variables for API keys
  • Create separate API keys for development and production
  • Rotate keys periodically
  • Never commit keys to version control

2. Optimize Context Data

When using properties:

  • Only include data the agent needs
  • Keep data structures simple
  • Avoid huge arrays or objects
  • Update context dynamically when data changes

3. Action Handler Error Handling

Always handle errors in action handlers:

{
name: "myAction",
handler: async (args) => {
try {
const result = await doSomething(args);
return { success: true, result };
} catch (error) {
console.error('Action failed:', error);
return {
success: false,
message: "Sorry, something went wrong."
};
}
}
}

4. Test Different UI Modes

Try all three UI modes to find what works best for your use case:

  • Popup: Great for general websites
  • Sidebar: Perfect for dashboards and SaaS apps
  • Chat: Ideal for support pages or dedicated chat sections

5. Progressive Enhancement

Load the widget asynchronously to avoid blocking page load:

  • Widget loads after the page content
  • Graceful fallback if JavaScript is disabled
  • No impact on initial page render time

6. Monitor Performance

Keep an eye on:

  • Widget load time
  • Action execution time
  • User engagement metrics
  • Error rates in action handlers

Troubleshooting

Widget Not Loading

Check:

  1. Container element exists (<div id="agentsgt-container"></div>)
  2. Runtime URL is correct
  3. API key is valid
  4. No JavaScript errors in console
  5. CDN is accessible (check network tab)

Agent Not Responding

Check:

  1. Agent is active in AgentsGT
  2. You have sufficient credits
  3. Runtime URL matches your agent ID
  4. API key has proper permissions

Actions Not Working

Check:

  1. Action handler is defined correctly
  2. Parameter types match
  3. Handler returns proper format
  4. Check console for errors
  5. Action description is clear for the AI

Context Not Available

Check:

  1. Properties are properly formatted
  2. Value and description are provided
  3. Data is serializable (no functions or circular references)
  4. Try logging the properties object

TypeScript Support

The widget is built with TypeScript and exports all necessary types:

import { App as AgentSGTWidget } from "@ddrinnova/agentsgt-widget";
import type {
CopilotPropertyConfig,
CopilotActionConfig,
ChatMessage
} from "@ddrinnova/agentsgt-widget";

const properties: Record<string, CopilotPropertyConfig> = {
user: {
value: "John",
description: "User name"
}
};

const actions: CopilotActionConfig[] = [
{
name: "myAction",
description: "Does something",
parameters: [
{ name: "param", type: "string", description: "A parameter" }
],
handler: async (args) => {
// Typed args
return { success: true };
}
}
];

What's Next?

Now that you know how to integrate the widget with advanced features:


Need help? Contact support or check our GitHub repository for examples and issues.