diff --git a/ai-agents/chat-widget.mdx b/ai-agents/chat-widget.mdx index fedcb06e8..a86472378 100644 --- a/ai-agents/chat-widget.mdx +++ b/ai-agents/chat-widget.mdx @@ -1,214 +1,26 @@ --- title: "Integrate an AI Agent into the Chat Widget" sidebarTitle: "Integration" -description: "Add an AI Agent (Mastra) to the CometChat Chat Widget using the no‑code builder and a simple embed." +description: "Embed your AI Agent (Agent Builder or Bring Your Own Agent) into the CometChat Chat Widget." --- ## Prerequisites - CometChat app (App ID, Region, Auth Key). -- Chat Widget variant (will produce a Widget / Variant ID). -- A running Mastra agent endpoint (public or tunneled URL). -- Mastra Agent ID (e.g. `chef`) and any required API key(s). +- Chat Widget variant configured in UI Kit Builder. +- An AI Agent already created and enabled in your app via: + - [Agent Builder](/ai-agents/agent-builder/overview) — build and host inside CometChat, or + - [Bring Your Own Agent](/ai-agents/mastra) — connect your own hosted agent. +- Agent ID and (optional) variant set to default to that agent. - (Optional) Frontend Action definitions if you want UI‑bound behaviors. ---- - -## Step 1 - Create / Verify Your Mastra Agent - -Have a Mastra project ready (example using the “Chef” agent): - - - -```ts -// tools/suggest-substitute.ts & tools/recipe-from-pantry.ts (omitted for brevity) -// agents/chef-agent.ts (export chefAgent) -// mastra/index.ts -import { Mastra } from '@mastra/core/mastra'; -import { chefAgent } from './agents/chef-agent'; - -export const mastra = new Mastra({ - agents: { chef: chefAgent } // 'chef' becomes /api/agents/chef/* -}); -``` - - -```bash -npx mastra dev -curl -X POST http://localhost:4111/api/agents/chef/generate \ - -H "Content-Type: application/json" \ - -d '{"messages":[{"role":"user","content":"Hello chef"}]}' -``` - - - -You now have: -- Agent ID (e.g. `chef`) -- Base URL (e.g. `http://localhost:4111/api` or public tunnel) - ---- - -## Step 2 - Deploy / Expose Your Agent - -Choose one path so the Dashboard & Widget can reach your Mastra endpoint. - - - -Install a tunnel & expose port 4111 (pick one): - -```bash -# ngrok -ngrok http 4111 - -# cloudflared -cloudflared tunnel --url http://localhost:4111 - -# loca.lt -ssh -R 80:localhost:4111 nokey@localhost.run -``` - -Copy the public HTTPS URL (e.g. `https://abc123.ngrok.io`) – this becomes your **Deployment URL**. - - -Project structure (excerpt): - -```txt -mastra/ (project root) -api/agents/[agent]/generate.ts (Vercel function) -``` - -Example handler: - -```ts -// api/agents/[agent]/generate.ts -import { mastra } from '../../mastra/index'; - -export default async function handler(req, res) { - if (req.method !== 'POST') return res.status(405).end(); - const { agent } = req.query; - const body = req.body; - try { - const response = await mastra.agents[agent].generate(body); - res.json(response); - } catch (e) { - res.status(500).json({ error: e.message }); - } -} -``` - -Deploy: - -```bash -vercel deploy --prod -``` - -Use the deployed base URL (e.g. `https://your-app.vercel.app/api`). - - -Add a simple Express server & Dockerfile: - -```ts -// server.ts -import express from 'express'; -import bodyParser from 'body-parser'; -import { mastra } from './mastra'; - -const app = express(); -app.use(bodyParser.json()); - -app.post('/api/agents/:agent/generate', async (req, res) => { - const agent = req.params.agent; - try { - const out = await mastra.agents[agent].generate(req.body); - res.json(out); - } catch (e) { - res.status(500).json({ error: e.message }); - } -}); - -app.listen(4111, () => console.log('Mastra listening on 4111')); -``` - -```dockerfile -FROM node:20-alpine -WORKDIR /app -COPY package*.json ./ -RUN npm ci --omit=dev -COPY . . -EXPOSE 4111 -CMD ["node","dist/server.js"] -``` - -Build & run: - -```bash -docker build -t mastra-agent . -docker run -p 4111:4111 mastra-agent -``` - - - - - - -For fastest iteration start with a tunnel, then move to serverless or container for staging/production. +Finish agent creation first in Agent Builder or Bring Your Own Agent, then continue here to embed the widget. -You now have a **public base URL** to use in the Dashboard. - ---- - -## Step 3 - Configure in CometChat - - Open the CometChat Dashboard. - Go to your App → AI Agents. - Set Provider=Mastra, Agent ID=chef, Deployment URL=public base URL from Step 2. - Add greeting, starter prompts, or map frontend actions/tools for richer UI. - Save and ensure the agent toggle shows Enabled. - - ---- - -## Step 4 - Attach Agent in UI Kit Builder (No‑Code) - - Launch UI Kit Builder from the Dashboard. - Choose an existing Widget Variant or create a new one. - In the AI / Agents panel toggle on your Mastra agent. - Set display name & avatar so users recognize the agent. - Save to persist the agent attachment. - - --- -## Step 5 - Frontend Actions & Tools (Optional) - - In Dashboard add actions (name + optional schema) that represent UI behaviors. - Ensure Mastra tool id matches the action name for invocation context. - Implement handlers in custom UI or rely on widget defaults when available. - - ---- - -## Step 6 - Customize in UI Kit Builder - - From AI Agents click the variant (or Get Started) to enter UI Kit Builder. - Select Customize and Deploy. - Theme, layout, features; ensure the Mastra agent is attached. - Use live preview to validate responses and appearance, then save. - - - - - - ---- - -## Step 7 - Export & Embed +## Step 1 - Export & Embed In UI Kit Builder click **Get Embedded Code** → copy credentials: - App ID @@ -227,62 +39,138 @@ Example embed (HTML): ``` -```html +Choose the auth flow that matches your site: + +### Option A - Anonymous (Guest Mode) + +**Use this when:** +- Let anyone chat anonymously without signing up or logging in. +- Perfect for marketing pages, help centers, or demo sites. + +```html lines highlight={7-8, 10, 14-16, 21-22, 25-26}
- +``` + +### Option B - Create + Log In User On The Fly (Auth Key + UID) + +**Use this when:** +- Use your existing user IDs (email, username etc.) to create and log in users automatically. +- No backend needed—CometChat creates users the first time they visit. + +```html lines highlight={7-8, 10, 13, 17-19, 24-25, 28-29} +
+ + +``` + +### Option C - Backend-Created User (Auth Token Login) + +**Use this when:** +- Create your users via server and login them using secure auth token on frontend. +- Ideal for sites with existing login systems and backends. - // Optional advanced settings: - // dockedAlignment: "right", // For docked mode: "left" or "right" +```html lines highlight={7-8, 12, 16-17, 20-21} +
+ + ``` -> Replace the placeholder values (``, etc.) with the credentials, user UID, default chat ID, and variant ID from your deployment. +> Replace the placeholder values (app ID, region, auth key or auth token, UID, agent ID, and variant ID) with values from your deployment. Keep `chatType: "user"` and set `defaultChatID` to your agent for an AI-first experience. --- -## Step 8 - Verify +## Step 2 - Verify | Check | How | |:------|:----| | Agent appears | Open widget → new conversation / agent entry available | | Basic reply | Send a prompt → response under a few seconds | -| Tool logic works | Ask for ingredient substitution / recipe (Chef example) | -| Error free | Browser console + Mastra logs have no unhandled errors | +| Tool logic works | Ask for a tool-backed request (e.g., recipe lookup or data fetch) | +| Error free | Browser console + agent logs have no unhandled errors | If responses fail, confirm the endpoint is publicly reachable and the Agent ID matches the Dashboard configuration. @@ -295,18 +183,8 @@ If responses fail, confirm the endpoint is publicly reachable and the Agent ID m | Issue | Fix | |:------|:----| | Agent not listed | Confirm it’s enabled in Dashboard + variant saved | -| 404 from Mastra | Endpoint path or agent key mismatch | +| 404 from agent | Endpoint path or agent key mismatch | | Timeout | Expose via a tunnel or deploy to a public host | | Tool not invoked | Ensure tool ID referenced in agent instructions & code | | Auth error | Re-check Auth Key / App credentials in embed snippet | ---- - -## Next Steps - -- Add more tools (search, summarization, domain knowledge). -- Introduce Frontend Actions for richer UI control. -- Move from tunnel to production deployment. -- Add analytics / observability (latency, error tracking). - -Need code export (React UI Kit) instead of Widget? See the “Export & Integrate” guide in AI Agents diff --git a/chat-call.mdx b/chat-call.mdx index c4d5ec650..a1386dc95 100644 --- a/chat-call.mdx +++ b/chat-call.mdx @@ -294,22 +294,22 @@ import { CardGroup, Card, Icon, Badge, Steps, Columns, AccordionGroup, Accordion
    -
  • Add users directly from the CometChat Dashboard.
  • -
  • Ideal for quick testing or small teams.
  • + - Add users directly from the CometChat Dashboard. + - Ideal for quick testing or small teams.
    -
  • Create users via the SDK methods.
  • -
  • Perfect for auto-provisioning during sign-up or login.
  • + - Create users via the SDK methods. + - Perfect for auto-provisioning during sign-up or login.
    -
  • Create users using the REST API.
  • -
  • Best for batch imports or admin workflows.
  • + - Create users using the REST API. + - Best for batch imports or admin workflows.