diff --git a/ai-agents.mdx b/ai-agents.mdx index e55237d6..4e05e4d2 100644 --- a/ai-agents.mdx +++ b/ai-agents.mdx @@ -58,9 +58,11 @@ With model-agnostic flexibility, CometChat AI Agents let you upgrade your AI sta } href="/ai-agents/mastra" horizontal /> - } horizontal>Coming Soon - } horizontal>Coming Soon - } horizontal>Coming Soon + {/* } horizontal>Coming Soon */} + } href="/ai-agents/agno" horizontal /> + {/* } horizontal>Coming Soon */} + } href="/ai-agents/vercel" horizontal /> + } href="/ai-agents/ag2" horizontal />

More providers coming…

@@ -79,17 +81,17 @@ With model-agnostic flexibility, CometChat AI Agents let you upgrade your AI sta

Customize the agent’s appearance and copy the embed code to integrate it into your app.

- } description="No‑code" href="/ai-agents/chat-widget" horizontal /> + } description="No‑code" href="/ai-agents/chat-widget" horizontal /> } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components - } horizontal>Coming Soon + } href="https://www.cometchat.com/docs/sdk/javascript/ai-agents" horizontal>Ready to use SDK Methods - } horizontal>Coming Soon - } horizontal>Coming Soon + } href="https://www.cometchat.com/docs/ui-kit/react-native/guide-ai-agent" horizontal>Pre Built UI Components + } href="https://www.cometchat.com/docs/ui-kit/android/guide-ai-agent" horizontal>Pre Built UI Components } horizontal>Coming Soon - } horizontal>Coming Soon + } href="https://www.cometchat.com/docs/ui-kit/flutter/guide-message-agentic-flow" horizontal>Pre Built UI Components diff --git a/ai-agents/ag2-knowledge-agent.mdx b/ai-agents/ag2-knowledge-agent.mdx new file mode 100644 index 00000000..cf95e6c6 --- /dev/null +++ b/ai-agents/ag2-knowledge-agent.mdx @@ -0,0 +1,281 @@ +--- +title: "Build Your Knowledge Agent with AG2" +sidebarTitle: "Knowledge Agent" +description: "Create an AG2 Knowledge Agent that answers documentation questions, then connect it to CometChat." +--- + +Imagine an assistant that reads your product docs, returns cited answers when mentioned in chat, and streams context back to the UI in real time. That’s what the AG2 Knowledge Agent delivers. + +*** + +## What You’ll Build + +* An **AG2 (AutoGen 2)** agent that behaves like a documentation expert. +* Triggered only when invoked (e.g., `@knowledge`). +* Retrieves & cites snippets from an on-disk knowledge store. +* Integrated into **CometChat** conversations with streaming responses. + +*** + +## Prerequisites + +* Python 3.10+ and `pip`. +* `OPENAI_API_KEY` in a `.env` file (used for embeddings + chat completions). +* Optional overrides: + * `KNOWLEDGE_AGENT_MODEL` (default `gpt-4o-mini`) + * `KNOWLEDGE_AGENT_EMBEDDING_MODEL` (default `text-embedding-3-small`) + * `KNOWLEDGE_AGENT_TOP_K`, `KNOWLEDGE_AGENT_TEMPERATURE`, etc. +* CometChat app credentials (App ID, Region, Auth Key). + +*** + +## Quick links + +- Repo (examples): [ai-agent-ag2-examples/ag2-knowledge-agent](https://github.com/cometchat/ai-agent-ag2-examples/tree/main/ag2-knowledge-agent) +- Agent source: [agent.py](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/ag2-knowledge-agent/agent.py) +- FastAPI server: [server.py](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/ag2-knowledge-agent/server.py) +- Sample web embed: [web/index.html](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/ag2-knowledge-agent/web/index.html) + +*** + +## How it works + +This project packages a retrieval-augmented AG2 agent that: + +- **Ingests sources** into namespaces using the `KnowledgeStore`. POST payloads to `/tools/ingest` with URLs, local files, or raw text. Files (`.pdf`, `.md`, `.txt`) are parsed and chunked before embeddings are stored under `knowledge//index.json`. +- **Searches namespaces** via `/tools/search`, ranking chunks with cosine similarity on OpenAI embeddings (defaults to top 4 results). +- **Streams answers** from `/agent`. The server wraps AG2’s `ConversableAgent`, emits SSE events for tool calls (`tool_call_start`, `tool_call_result`) and text chunks, and always terminates with `[DONE]`. +- **Cites sources**. The agent compiles the retrieved snippets, instructs the LLM to cite them with bracketed numbers, and appends a `Sources:` line. +- **Hardens operations**: namespaces are sanitized, ingestion is thread-safe, and errors are surfaced as SSE `error` events so the client can render fallbacks. + +Key modules: + +- `agent.py` — KnowledgeAgent, store helpers, embedding + retrieval logic. +- `server.py` — FastAPI app hosting `/agent`, `/tools/ingest`, `/tools/search`, `/health`. +- `knowledge/` — default storage root (persisted chunks + index). +- `web/index.html` — CometChat Chat Embed sample that points to your deployed agent. + +*** + +## Setup + + + + git clone https://github.com/cometchat/ai-agent-ag2-examples.git then cd ai-agent-ag2-examples/ag2-knowledge-agent. Create a virtualenv and run pip install -r requirements.txt. + + + Create a .env file, set OPENAI_API_KEY, and override other knobs as needed (model, temperature, namespace). + + + Run python server.py once (or uvicorn server:app) to initialize folders. Use the ingest endpoint or the provided knowledge samples as a starting point. + + + Start FastAPI: uvicorn server:app --reload --host 0.0.0.0 --port 8000. Verify GET /health returns `{"status": "healthy"}`. + + + Expose /agent publicly with ngrok, Cloudflare Tunnel, or Render so CometChat can reach it. + + + +*** + +## Project structure + +- Dependencies: [requirements.txt](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/ag2-knowledge-agent/requirements.txt) +- Agent logic: [agent.py](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/ag2-knowledge-agent/agent.py) +- Knowledge store: [knowledge/](https://github.com/cometchat/ai-agent-ag2-examples/tree/main/ag2-knowledge-agent/knowledge) +- API server: [server.py](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/ag2-knowledge-agent/server.py) +- Web sample: [web/index.html](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/ag2-knowledge-agent/web/index.html) + +*** + +## Core configuration + + + + +```bash +OPENAI_API_KEY=sk-your-key +KNOWLEDGE_AGENT_MODEL=gpt-4o +KNOWLEDGE_AGENT_TEMPERATURE=0.2 +KNOWLEDGE_AGENT_TOP_K=4 +KNOWLEDGE_AGENT_EMBEDDING_MODEL=text-embedding-3-small +KNOWLEDGE_AGENT_DEFAULT_NAMESPACE=docs +KNOWLEDGE_AGENT_STORAGE_PATH=knowledge +``` + + + + +```json +POST /tools/ingest +{ + "namespace": "docs", + "sources": [ + { + "type": "url", + "value": "https://example.com/handbook", + "title": "Handbook" + }, + { + "type": "file", + "path": "/absolute/path/to/policies.pdf" + }, + { + "type": "text", + "title": "Inline FAQ", + "value": "Q: How do refunds work?\nA: ..." + } + ] +} +``` + + + + +```text +data: {"type":"tool_call_start","tool_call_id":"call_123","tool_name":"search_docs","args":{"namespace":"docs","query":"@agent refund policy"}} + +data: {"type":"tool_call_result","tool_call_id":"call_123","result":{"matches":[{"chunk_id":"...","score":0.82,"source":"knowledge/docs/...","title":"Refund Policy","preview":"..."}]},"is_frontend_tool":false} + +data: {"type":"text_message","delta":"Refunds are processed within 5 business days "} +data: {"type":"text_message","delta":"once the request is approved.[1] Sources: [1] Refund Policy"} +data: [DONE] +``` + + + + +*** + +## Step 1 - Ingest documentation + + + + Stick with docs or choose a sanitized string (alphanumeric, -, _). + + + Supply a mix of URLs, file paths, and inline text. The server fetches, parses (PDF/Markdown/Text), chunks, embeds, and persists everything. + + + Confirm knowledge/<namespace> contains generated .md copies and an updated index.json. + + + +*** + +## Step 2 - Ask the knowledge agent + + + + +```bash +curl -N -X POST http://localhost:8000/agent \ + -H "Content-Type: application/json" \ + -d '{ + "thread_id": "demo-thread", + "run_id": "demo-run", + "messages": [ + { "role": "user", "content": "@knowledge What does our refund policy cover?" } + ], + "tool_params": { "namespace": "docs" } + }' +``` + + + + Streamed events include tool telemetry and text deltas. Buffer them until you receive [DONE]. + + + Replies contain bracketed numbers matching the matches payload returned by the retrieval tool. + + + +*** + +## Step 3 - Deploy the API + +- Host the FastAPI app (Render, Fly.io, ECS, etc.) or wrap it in a serverless function. +- Expose /agent, /tools/ingest, and /tools/search over HTTPS. +- Keep KNOWLEDGE_AGENT_STORAGE_PATH on a persistent volume so ingested docs survive restarts. +- Harden CORS, rate limiting, and authentication before opening the endpoints to the public internet. + +*** + +## Step 4 - Configure CometChat + + + Go to app.cometchat.com. + Navigation: AI Agents → Add Agent. + Set Provider=AG2 (AutoGen), Agent ID=knowledge, Deployment URL=public /agent endpoint. + Add greeting, intro, or suggested prompts such as “@knowledge Summarize the onboarding guide.” + Save then confirm the toggle shows Enabled. + + +> For more on CometChat AI Agents, see: [Overview](/ai-agents/overview) · [Instructions](/ai-agents/instructions) · [Custom agents](/ai-agents/custom-agents) + +*** + +## Step 5 - Customize in UI Kit Builder + + + From the Dashboard variant card, click Customize and Deploy. + Themes, layouts, attachment rules, and action bindings—all reflect in exports. + Run conversations and confirm the knowledge agent responds only when invoked. + + + + + + +*** + +## Step 6 - Integrate + +Once configured, embed the agent in your product using the exported configuration. + + + } description="Embed / script" href="/widget/ai-agents" horizontal /> + } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components + + +> The AG2 Knowledge agent you connected is bundled automatically. End-users will see it immediately after deployment. + +*** + +## Step 7 - Test end-to-end + + + POST to /agent returns cited answers. + POST to /tools/search returns ranked snippets. + In CometChat, ensure the agent appears as a selectable bot. + Preview in UI Kit Builder or your app and confirm streaming + citations behave as expected. + + +*** + +## Security & production checklist + +- Protect ingestion routes with auth (API key/JWT) and restrict who can write to each namespace. +- Validate URLs and file paths before fetching to avoid SSRF or untrusted uploads. +- Rate limit the `/agent` and `/tools/*` endpoints to prevent abuse. +- Keep OpenAI keys server-side; never ship them in browser code or UI Kit Builder exports. +- Log tool calls (namespace, duration) for debugging and monitoring. + +*** + +## Troubleshooting + +* **Agent replies without citations**: confirm the retrieval step returns matches; check embeddings or namespace. +* **Empty or slow results**: ensure documents were ingested successfully and the top-k limit isn’t set to 0. +* **`503 Agent not initialized`**: verify server logs—`KnowledgeAgent` requires `OPENAI_API_KEY` during startup. +* **SSE errors in widget**: make sure your reverse proxy supports streaming and disables response buffering. + +*** + +## Next steps + +* Add new tools (e.g., `summarize`, `link_to_source`) by extending the AG2 agent before responding. +* Swap in enterprise vector stores by replacing `KnowledgeStore` with Pinecone, Qdrant, or Postgres. +* Schedule re-ingestion jobs when docs change, or watch folders for automatic refreshes. +* Layer analytics: log `tool_call_result.matches` for insight into content coverage. diff --git a/ai-agents/ag2-product-hunt-agent.mdx b/ai-agents/ag2-product-hunt-agent.mdx new file mode 100644 index 00000000..0352ee59 --- /dev/null +++ b/ai-agents/ag2-product-hunt-agent.mdx @@ -0,0 +1,158 @@ +--- +title: "Build a Product Hunt Agent with AG2" +sidebarTitle: "Product Hunt Agent" +description: "Create an AG2 agent that can fetch Product Hunt posts, answer launch questions, and trigger frontend actions (confetti), then plug it into CometChat." +--- + +Give your Product Hunt launch conversations a Python-first co-pilot: fetch live leaderboards, search the catalog, trigger confetti, and stream guidance straight into CometChat using the AG2 agent pattern. + +--- + +## Quick links + +- Repo: [ai-agent-ag2-examples/product-hunt](https://github.com/cometchat/ai-agent-ag2-examples/tree/main/product-hunt) +- README: [README.md](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/product-hunt/README.md) +- Agent core: [agent.py](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/product-hunt/agent.py) +- FastAPI server: [server.py](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/product-hunt/server.py) +- Sample UI: [web/index.html](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/product-hunt/web/index.html) + +--- + +## What you’ll build + +- A Python **ProductHuntAgent** that decides when to fetch top posts, run timeframe queries, search Algolia, or fire the confetti action. +- A `ProductHuntService` that talks to Product Hunt’s GraphQL API (with optional token) and its public Algolia index. +- A FastAPI backend exposing `/tools/*` JSON endpoints plus a streaming `/agent` SSE route tuned for CometChat. +- A Product Hunt–inspired static UI that mounts the CometChat widget and interprets the `CONFETTI` action payload. + +--- + +## Prerequisites + +- Python 3.10 or newer and `pip`. +- Environment variables: + - `OPENAI_API_KEY` (required). + - Optional: `PRODUCTHUNT_API_TOKEN` (enables live top-post queries), `PRODUCT_HUNT_AGENT_MODEL` (default `gpt-4o-mini`), `PRODUCT_HUNT_AGENT_TEMPERATURE` (default `0.3`), `PRODUCT_HUNT_AGENT_MAX_ITEMS` (default `5`). +- Install dependencies with `pip install -r requirements.txt`. +- A CometChat app where you’ll register the agent and embed the widget. + +--- + +## How it works + +- `ProductHuntService` clamps user input, builds GraphQL queries for top posts, translates natural-language timeframes to UTC windows, and falls back gracefully when credentials are missing. +- The `ProductHuntAgent` inspects each message, emits structured `tool_call_*` SSE events around tool invocations, and streams OpenAI-generated answers grounded in tool output. +- Confetti requests stay server-driven: the agent returns an `action: "CONFETTI"` payload that frontends can render safely. +- `server.py` hosts FastAPI routes for REST access and a `/agent` endpoint that batches SSE events so CometChat can replay them in real time. +- The static `web/index.html` mocks a Product Hunt landing page, mounts CometChat, and demonstrates how to consume leaderboard data plus the confetti action. + +--- + +## Step 1 — Talk to Product Hunt + +File: [`agent.py`](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/product-hunt/agent.py) + +- `ProductHuntService` signs GraphQL calls when `PRODUCTHUNT_API_TOKEN` is present; otherwise it returns empty lists and logs helpful warnings. +- `get_top_products_by_timeframe` normalizes phrases like `today`, `last week`, `2024-09-01`, or `from:2024-08-01 to:2024-08-15`, generating the ISO timestamps Product Hunt expects. +- `search_products` wraps the public Algolia index using the bundled app ID/key, trimming the response to the requested limit. +- `to_markdown_table` converts product lists into Markdown tables so chat replies stay scannable (and safe for CometChat rendering). + +--- + +## Step 2 — Build the AG2 agent + +Also in [`agent.py`](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/product-hunt/agent.py): + +- `ProductHuntAgent` loads configuration from environment variables, enforces sane limits, and initializes the OpenAI client. +- `_decide_action` uses lightweight heuristics to route messages to `top`, `top_timeframe`, `search`, `confetti`, or fallback `advice`. +- Each tool call yields `tool_call_start` and `tool_call_result` SSE frames with deterministic IDs, mirroring CometChat’s expectations. +- `_generate_answer` calls OpenAI with a Product Hunt–specific system prompt, grounding responses with the structured payload when available. +- `_stream_text` breaks completions into word chunks so the frontend sees incremental updates instead of one large blob. + +--- + +## Step 3 — Serve tools and SSE with FastAPI + +File: [`server.py`](https://github.com/cometchat/ai-agent-ag2-examples/blob/main/product-hunt/server.py) + +- FastAPI spins up with permissive CORS and a lifespan hook that instantiates `ProductHuntAgent` once. +- `/tools/top`, `/tools/top_timeframe`, `/tools/search`, and `/tools/confetti` validate input via Pydantic models and return the raw tool payloads (including Markdown tables or action structures). +- `/agent` extracts the latest user message, streams the agent’s SSE output via `StreamingResponse`, and keeps buffers disabled for true real-time delivery. +- `/health` and `/` provide lightweight diagnostics you can hit from monitoring or your deployment platform. + +--- + +## Step 4 — Run the agent locally + +```bash +pip install -r requirements.txt +export OPENAI_API_KEY=sk-your-key +# Optional for live Product Hunt data +export PRODUCTHUNT_API_TOKEN=phc_your_token +uvicorn server:app --reload --port 8000 +``` + +Visit `http://localhost:8000/` to confirm the service and keep an eye on logs for Product Hunt token warnings. + +--- + +## Step 5 — Stream a conversation + +```bash +curl -N http://localhost:8000/agent \ + -H "Content-Type: application/json" \ + -d '{ + "thread_id": "chat_123", + "messages": [ + { "role": "user", "content": "Show today'\''s top Product Hunt launches and celebrate them." } + ], + "tool_params": { + "timeframe": "today", + "tz": "America/New_York", + "limit": 3 + } + }' +``` + +You’ll see `tool_call_*` events with Product Hunt data followed by streaming `text_message` chunks and a `[DONE]` sentinel—exactly what CometChat’s AI agents API consumes. + +--- + +## Step 6 — Plug into CometChat + +- In your CometChat dashboard: **AI Agents → Add Agent → AG2**. +- Set the Agent ID (e.g., `producthunt-ag2`) and point the deployment URL to your `/agent` endpoint (must be HTTPS in production). +- Map the `CONFETTI` action to your widget handler; the sample UI demonstrates how to read the payload and execute `canvas-confetti`. +- Optionally preload greetings, suggested prompts (“What are today’s top 3 launches?”), and any additional frontend actions you want to support. + +--- + +## Step 7 — Test the REST tools + +- `GET /health` → `{"status":"healthy","agent_initialized":true}` +- `POST /tools/top` with `{"limit":3}` → current leaders by total votes (empty if no Product Hunt token). +- `POST /tools/top_timeframe` with `{"timeframe":"yesterday","tz":"America/Los_Angeles"}` → timeframe metadata plus ranked posts. +- `POST /tools/search` with `{"query":"notion","limit":5}` → Algolia search results. +- `POST /tools/confetti` with overrides like `{"colors":["#ff577f","#7b5cff"],"particleCount":400}` → structured frontend action payload. + +Use these routes to populate dashboards or to warm caches before handing conversations to the agent. + +--- + +## Security & production checklist + +- Keep `OPENAI_API_KEY` and `PRODUCTHUNT_API_TOKEN` server-side only; never expose them in the web embed. +- Add CORS restrictions and authentication (API keys, JWT, or CometChat-signed requests) before deploying. +- Rate-limit `/agent` and `/tools/*`, and cache Product Hunt responses to avoid repeatedly hitting the GraphQL API. +- Log tool usage and errors without storing sensitive conversation content; monitor for expired Product Hunt tokens. +- Run behind HTTPS with streaming-friendly proxies (e.g., Nginx with buffering disabled on `/agent`). + +--- + +## Troubleshooting + +- **Empty top-product responses**: set `PRODUCTHUNT_API_TOKEN`; without it, GraphQL queries return no edges. +- **Algolia search is blank**: confirm outbound network access and that you stay within Algolia’s public rate limits. +- **SSE stops instantly**: make sure your hosting provider allows streaming and preserves `Cache-Control: no-cache` headers. +- **Confetti never fires in the UI**: ensure your frontend listens for `action === "CONFETTI"` and passes the payload to `canvas-confetti`. +- **Replies feel generic**: check server logs to verify tool calls succeeded; the agent falls back to advice mode when payloads are empty. diff --git a/ai-agents/ag2.mdx b/ai-agents/ag2.mdx new file mode 100644 index 00000000..a3255332 --- /dev/null +++ b/ai-agents/ag2.mdx @@ -0,0 +1,294 @@ +--- +title: "Create an AI Agent with AG2" +sidebarTitle: "Create AI Agent" +description: "Connect an AG2 (AutoGen) agent to CometChat, customize it with UI Kit Builder, and ship it as React UI Kit code or a Chat Widget." +--- + +## What you’ll build + +- An **AG2 ConversableAgent** with callable tools +- The same agent **connected to CometChat** (Agent ID + Deployment URL) +- A **customized chat experience** using **UI Kit Builder** +- An export to **React UI Kit code** _or_ **Chat Widget** for integration + +--- + +## Prerequisites + +- A CometChat account and an app: **[Create App](https://app.cometchat.com/apps)** +- Python 3.10+ and `pip` +- Environment variables: + - `OPENAI_API_KEY` (required for AG2 LLM calls) + - `WEATHER_API_KEY` (optional — enables real weather data in the sample tool) +- Git (to clone the example project) + +--- + +{/*

+ Step 1 +

*/} + +## Step 1 - Create your CometChat app + + + + Sign in at app.cometchat.com. Create a new app or open an existing one. + + + Note your App ID, Region, and Auth Key (needed if you export the Chat Widget later). + + + +--- + +{/*

+ Step 2 +

*/} + +## Step 2 - Connect your AG2 Agent + +Navigate to **AI Agent → Get Started** and then **AI Agents → Add Agent**. + + + + Select **AG2 (AutoGen)**. + + + Provide: +
    +
  • Name and optional Icon
  • +
  • (Optional) Greeting and Introductory Message
  • +
  • (Optional) Suggested messages such as “What’s the weather in Austin?”
  • +
+
+ + Paste the following from your deployment: +
    +
  • Agent ID — for the sample project, use weather.
  • +
  • Deployment URL — the HTTPS endpoint that proxies to /agent on your server.
  • +
+
+ + Click Save, then ensure the agent’s toggle is ON in the **AI Agents** list. + +
+ +> **Tip:** Keep your Deployment URL stable (e.g., `https://your-domain.tld/agent`). Update server logic without changing the URL to avoid reconfiguration. + +--- + +{/*

+ Step 3 (Optional) +

*/} + +## Step 3 - Define Frontend Actions (Optional) + + + + Go to AI Agent → Actions and click Add to create a frontend action your agent can call (e.g., “Open Product,” “Start Demo,” “Book Slot”). + + + Include: +
    +
  • Display Name — Shown to users (e.g., “Open Product Page”).
  • +
  • Execution Text — How the agent describes running it.
  • +
  • Name — A unique, code-friendly key (e.g., open_product).
  • +
  • Description — What the tool does and when to use it.
  • +
  • Parameters — JSON Schema describing inputs (the agent will fill these).
  • +
+
+ + Example parameters JSON: + +```json +{ + "type": "object", + "required": ["location"], + "properties": { + "location": { + "type": "string", + "description": "City, zip code, or coordinates" + } + } +} +``` + + + Listen for tool calls at runtime and execute them client-side (route changes, dashboards, highlights). + +
+ +--- + +{/*

+ Step 4 +

*/} + +## Step 4 - 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 AG2 agent is attached. + Use live preview to validate responses & tool triggers. + + + + + + +--- + +{/*

+ Step 5 +

*/} + +## Step 5 - Export & Integrate + +Choose how you’ll ship the experience (Widget or React UI Kit export). + + + } description="Embed / script" href="/widget/ai-agents" horizontal /> + } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components + + +> The AG2 agent from Step 2 is included automatically in exported variants—no extra code needed for basic conversations. + + + Pick Chat Widget (fastest) or export React UI Kit for code-level customization. + Open UI Kit Builder → Get Embedded Code → copy script + credentials. + Export the variant as code (UI Kit) if you need deep theming or custom logic. + Preview: the AG2 agent should appear without extra config. + + +--- + +{/*

+ Step 6 +

*/} + +## Step 6 - Run Your AG2 Agent (Reference) + + + +
    +
  1. git clone https://github.com/cometchat/ai-agent-ag2-examples.git
  2. +
  3. cd ai-agent-ag2-examples/ag2-cometchat-agent
  4. +
  5. python -m venv .venv && source .venv/bin/activate (or .venv\\Scripts\\activate on Windows)
  6. +
  7. pip install -r requirements.txt
  8. +
+
+ +

Create a .env file:

+ +```bash +OPENAI_API_KEY=sk-your-key +# Optional: enables live data from OpenWeatherMap +WEATHER_API_KEY=your-openweather-key +``` + +

Without WEATHER_API_KEY, the tool still returns stubbed error messages that the agent can surface gracefully.

+
+ + +```python +# agent.py (excerpt) +llm_config = LLMConfig( + config_list=[{ + "api_type": "openai", + "model": "gpt-4o-mini", + "api_key": self.openai_api_key, + }], + temperature=0.7, +) + +self.agent = ConversableAgent( + name="WeatherAssistant", + system_message="You are a helpful assistant that can provide weather information...", + llm_config=llm_config, + human_input_mode="NEVER", +) + +@self.agent.register_for_llm +def get_weather(location: Annotated[str, "City name, zip code, or coordinates"]) -> Dict[str, Any]: + return self.get_weather(location) +``` + +

The agent streams Server-Sent Events (SSE) with tool call telemetry and message chunks so CometChat can render partial replies in real time.

+
+ +
    +
  1. uvicorn server:app --reload --host 0.0.0.0 --port 8000
  2. +
  3. Verify health: curl http://localhost:8000/health
  4. +
  5. Trigger a message (SSE response):
  6. +
+ +```bash +curl -N -X POST http://localhost:8000/agent \ + -H "Content-Type: application/json" \ + -d '{ + "thread_id": "demo-thread", + "run_id": "demo-run", + "messages": [ + { "role": "user", "content": "What is the weather in Austin?" } + ], + "tools": [] + }' +``` + +

Use a tunneling tool (ngrok, Cloudflare Tunnel, etc.) to create the public Deployment URL CometChat needs.

+
+ +
    +
  • Configure logging, rate limiting, and auth (API key/JWT) on the `/agent` route.
  • +
  • Store secrets in server-side env vars only; never expose them in client code.
  • +
  • Namespace tool calls and sanitize user input before hitting external APIs.
  • +
  • Scale the FastAPI app behind your preferred hosting (Render, Fly.io, Vercel functions, etc.).
  • +
+
+
+ +--- + +## Test your setup + + + In AI Agents, ensure your AG2 agent shows Enabled. + Open UI Kit Builder and start a preview session. + Send a message; confirm the agent responds. + Trigger a Frontend Action and verify your UI handles the tool call. + + +--- + +## Troubleshooting + + + +
    +
  • Verify your Deployment URL is publicly reachable (no VPN/firewall).
  • +
  • Check server logs for 4xx/5xx errors or missing API keys.
  • +
+
+ +
    +
  • Confirm the Action’s Name matches the tool name emitted by AG2.
  • +
  • Ensure your agent registers tools via register_for_llm and proxies execution.
  • +
+
+ +
    +
  • Use authKey only for development. For production, implement a secure token flow for user login.
  • +
+
+
+ +{/* ## Next Steps + + + + Define and handle custom frontend actions your AI agent can invoke. + + Create and manage tools your AI agent can use to enhance conversations. + + */} \ No newline at end of file diff --git a/ai-agents/agno-knowledge-agent.mdx b/ai-agents/agno-knowledge-agent.mdx new file mode 100644 index 00000000..33b9ed8f --- /dev/null +++ b/ai-agents/agno-knowledge-agent.mdx @@ -0,0 +1,160 @@ +--- +title: "Build Your Knowledge Agent with Agno" +sidebarTitle: "Knowledge Agent" +description: "Spin up an Agno-powered knowledge agent with FastAPI, ingest docs into namespaces, and stream grounded answers (with citations) into CometChat." +--- + +Imagine a FastAPI service that ingests your documentation, stores it in a vector database, and streams Agno agent responses with citations that CometChat can consume in real time. + +*** + +## What You'll Build + +* An **Agno** agent that joins conversations as a documentation expert. +* An ingestion pipeline that writes markdown artifacts into `knowledge_agent/data/knowledge/`. +* Retrieval and answering logic that always cites the sources it used. +* A `/stream` endpoint that outputs newline-delimited JSON events so CometChat can subscribe without changes. + +*** + +## Prerequisites + +* Python 3.10 or newer (3.11 recommended). +* `OPENAI_API_KEY` with access to GPT-4o or any compatible model. +* Optional: alternate OpenAI base URL or model IDs if you self-host OpenAI-compatible APIs. +* curl or an API client (Hoppscotch, Postman) to call the FastAPI endpoints. + +*** + +## Quick links + +- Repo root: [ai-agent-agno-examples](https://github.com/cometchat/ai-agent-agno-examples) +- Project folder: [`knowledge_agent/`](https://github.com/cometchat/ai-agent-agno-examples/tree/main/knowledge_agent) +- Server guide: [`README.md#knowledge-agent`](https://github.com/cometchat/ai-agent-agno-examples#knowledge-agent) +- API reference: [`knowledge_agent/main.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/knowledge_agent/main.py) +- Knowledge helpers: [`knowledge_agent/knowledge_manager.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/knowledge_agent/knowledge_manager.py) + +*** + +## How it works + +This example recreates the Vercel knowledge base workflow using Agno: + +- **Ingest** — `collect_documents` accepts URLs, markdown, plain text, uploads, or multipart forms. Sources are deduplicated by a SHA-256 hash and normalized into markdown. +- **Store** — `KnowledgeManager` keeps one `ChromaDb` collection per namespace, with metadata persisted under `knowledge_agent/data/knowledge/`. +- **Retrieve** — Searches hit the vector DB via Agno's `Knowledge` class, returning ranked snippets and the metadata used for citations. +- **Answer** — `create_agent` enables `search_knowledge` and `add_knowledge_to_context`, forcing every response to cite sources via the system prompt. +- **Stream** — `/stream` emits newline-delimited JSON events (`text_delta`, `tool_*`, `text_done`, `done`, `error`) that match CometChat’s Bring Your Own Agent expectations. Every event echoes the caller’s `thread_id` and `run_id`. + +*** + +## Setup + + + + git clone https://github.com/cometchat/ai-agent-agno-examples.git, then inside the repo run:
python3 -m venv .venv && source .venv/bin/activate && pip install -e . +
+ + Create .env (or export env vars) with at least OPENAI_API_KEY. Optional overrides: OPENAI_BASE_URL, KNOWLEDGE_OPENAI_MODEL, KNOWLEDGE_STORAGE_PATH, KNOWLEDGE_CHROMA_PATH. + + + Launch FastAPI with uvicorn knowledge_agent.main:app --host 0.0.0.0 --port 8000 --reload. The app exposes health, ingestion, search, generate, and `/stream` endpoints (newline-delimited JSON). + +
+ +*** + +## Project Structure + +- FastAPI & wiring + - [`knowledge_agent/main.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/knowledge_agent/main.py) + - [`knowledge_agent/schemas.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/knowledge_agent/schemas.py) + - [`knowledge_agent/config.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/knowledge_agent/config.py) +- Knowledge + ingestion + - [`knowledge_agent/knowledge_manager.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/knowledge_agent/knowledge_manager.py) + - [`knowledge_agent/ingestion.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/knowledge_agent/ingestion.py) + - [`knowledge_agent/data/`](https://github.com/cometchat/ai-agent-agno-examples/tree/main/knowledge_agent/data) +- Constants & helpers + - [`KnowledgeAgentSettings`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/knowledge_agent/config.py#L7) + - [`collect_documents`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/knowledge_agent/ingestion.py#L147) + - [`KnowledgeManager.create_agent`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/knowledge_agent/knowledge_manager.py#L101) + +*** + +## Step 1 - Configure the Knowledge Agent + +`KnowledgeManager.create_agent` builds an Agno agent bound to the current namespace: + +- Uses `OpenAIChat` with `OPENAI_API_KEY`, optional custom base URL, and temperature from settings. +- Enables `search_knowledge=True` and `add_knowledge_to_context=True` so retrieved snippets feed the model. +- Injects a system prompt that demands a knowledge search before every reply and enforces the `"Sources: .md"` footer. +- Reuses the namespace-specific `ChromaDb` collection initialised in `_get_namespace`. + +*** + +## Step 2 - Ingest Knowledge + +`POST /api/tools/ingest` accepts JSON or multipart payloads. Highlights: + +- Up to 30 sources per call, 6 MB per file, 200 kB per inline text/markdown. +- URLs, PDFs, HTML pages, plain text, and uploads are normalized to markdown with metadata and timestamps. +- Duplicate hashes are skipped with a `"duplicate-content"` reason; existing files return `"already-ingested"`. +- Responses provide `saved`, `skipped`, `errors`, and the resolved namespace. + +Example JSON payload: + +```bash +curl -X POST http://localhost:8000/api/tools/ingest \ + -H "Content-Type: application/json" \ + -d '{ + "namespace": "default", + "sources": [ + { "type": "url", "value": "https://docs.agno.com/concepts/agents/overview" }, + { "type": "markdown", "title": "Playbook", "value": "# Notes\n\nAgno rocks!" } + ] + }' +``` + +*** + +## Step 3 - Search & Validate + +`POST /api/tools/searchDocs` lets you confirm retrieval before opening the agent to users: + +- Required body: `{"query": "How do I add tools?"}` with optional `namespace` and `max_results`. +- Returns ranked snippets with metadata (hashes, distances converted to scores). +- Empty queries immediately return an error so the UI can prompt the operator. + +*** + +## Step 4 - Chat & Stream + +- `POST /api/agents/knowledge/generate` handles non-streaming responses. +- `POST /stream` streams newline-delimited JSON events that include tool calls, intermediate reasoning, text deltas, and completion markers. + +Streaming example (newline-delimited JSON): + +```bash +curl -N http://localhost:8000/stream \ + -H "Content-Type: application/json" \ + -d '{ + "thread_id": "thread_1", + "run_id": "run_001", + "messages": [ + { "role": "user", "content": "Summarize the agent lifecycle." } + ] + }' +``` + +Each line is a JSON object with a `type` field such as `text_delta`, `tool_call_start`, `tool_result`, `text_done`, or `done`. `thread_id` and `run_id` are echoed back so CometChat can correlate partial events. + +*** + +## Step 5 - Connect to CometChat + +- Deploy the FastAPI service behind HTTPS (e.g., Fly.io, Render, Railway, or your own Kubernetes cluster). +- Add auth headers or gateway middleware if you need to validate incoming requests from CometChat. +- In the CometChat dashboard, point the Agno agent’s **Deployment URL** at the `/stream` endpoint; use **Headers** for bearer tokens or basic auth if required. +- Provide `namespace` (or `toolParams.namespace` from CometChat) when you need to target non-default knowledge stores; the service normalizes values before lookup. + +With that, you have a fully grounded Agno agent that streams CometChat-compatible events into your UI. diff --git a/ai-agents/agno-product-hunt-agent.mdx b/ai-agents/agno-product-hunt-agent.mdx new file mode 100644 index 00000000..f534fc43 --- /dev/null +++ b/ai-agents/agno-product-hunt-agent.mdx @@ -0,0 +1,154 @@ +--- +title: "Launch a Product Hunt Agent with Agno" +sidebarTitle: "Product Hunt Agent" +description: "Build an Agno Product Hunt assistant that queries live launch data, triggers celebrations, and streams into CometChat." +--- + +An Agno agent can double as a launch strategist—fetching Product Hunt rankings, answering questions, and firing confetti when it is time to celebrate. + +*** + +## What You'll Build + +* A **FastAPI** service that wraps an Agno agent with Product Hunt tools. +* Tooling for Algolia search, GraphQL leaderboards, natural timeframe parsing, and confetti payloads. +* `/api/chat` and `/stream` endpoints that share CometChat-compatible newline-delimited JSON payloads. +* Optional Product Hunt GraphQL integration (falls back gracefully when no token is provided). + +*** + +## Prerequisites + +* Python 3.10 or newer. +* `OPENAI_API_KEY` with GPT-4o (or similar) access. +* Optional `PRODUCTHUNT_API_TOKEN` for live leaderboard queries. +* curl or an API client to verify endpoints. + +*** + +## Quick links + +- Repo root: [ai-agent-agno-examples](https://github.com/cometchat/ai-agent-agno-examples) +- Project folder: [`product_hunt_agent/`](https://github.com/cometchat/ai-agent-agno-examples/tree/main/product_hunt_agent) +- Server entrypoint: [`product_hunt_agent/main.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/product_hunt_agent/main.py) +- Agent builder: [`product_hunt_agent/agent_builder.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/product_hunt_agent/agent_builder.py) +- Services & queries: [`product_hunt_agent/services.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/product_hunt_agent/services.py) + +*** + +## How it works + +- **Agent** — `create_product_hunt_agent` configures an `OpenAIChat` model, system prompt, and five tools (`getTopProducts`, `getTopProductsThisWeek`, `getTopProductsByTimeframe`, `searchProducts`, `triggerConfetti`). +- **Data** — `services.py` wraps Product Hunt’s GraphQL API (with token), Algolia search, timezone-aware timeframe parsing, and safe fallbacks when the API token is missing. +- **API** — FastAPI routes in `main.py` expose REST endpoints for ranked lists and search, plus `/api/chat` and `/stream` for conversations and newline-delimited event streaming. +- **Parity** — The streaming payload mirrors CometChat’s Bring Your Own Agent format (`text_delta`, `tool_*`, `text_done`, `done`, `error`), so existing UI logic can be reused. + +*** + +## Setup + + + + From your workspace: git clone https://github.com/cometchat/ai-agent-agno-examples.git. Inside the repo: python3 -m venv .venv && source .venv/bin/activate && pip install -e . + + + Create .env with OPENAI_API_KEY. Add PRODUCTHUNT_API_TOKEN for GraphQL access. Optional knobs: PRODUCTHUNT_DEFAULT_TIMEZONE, OPENAI_BASE_URL, PRODUCT_OPENAI_MODEL. + + + Start FastAPI: uvicorn product_hunt_agent.main:app --host 0.0.0.0 --port 8001 --reload. Health check: GET /healthz; streaming lives at POST /stream. + + + +*** + +## Project Structure + +- FastAPI routes & schemas + - [`product_hunt_agent/main.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/product_hunt_agent/main.py) + - [`product_hunt_agent/schemas.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/product_hunt_agent/schemas.py) + - [`product_hunt_agent/config.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/product_hunt_agent/config.py) +- Agent behavior + - [`product_hunt_agent/agent_builder.py`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/product_hunt_agent/agent_builder.py) +- Product Hunt services + - [`get_top_products_by_votes`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/product_hunt_agent/services.py#L72) + - [`get_top_products_by_timeframe`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/product_hunt_agent/services.py#L123) + - [`search_products`](https://github.com/cometchat/ai-agent-agno-examples/blob/main/product_hunt_agent/services.py#L201) + +*** + +## Step 1 - Configure Settings + +`ProductHuntSettings` centralizes configuration (API keys, timeouts, default timezone). The FastAPI app loads it once and injects it via `Depends`, so each route reuses the same validated settings. + +*** + +## Step 2 - Understand the Agent Tools + +`agent_builder.py` clamps incoming arguments, calls service helpers, and returns structured dictionaries the UI can render. Highlights: + +- `getTopProducts` — All-time votes. +- `getTopProductsThisWeek` — Rolling window controlled by `days`. +- `getTopProductsByTimeframe` — Natural language inputs such as `yesterday`, `last-week`, or ISO dates. +- `searchProducts` — Uses Product Hunt’s public Algolia index (no token required). +- `triggerConfetti` — Returns payloads that UI Kit Builder variants can pass to your frontend celebration handler. + +The system prompt instructs the agent to cite sources and explain data gaps whenever a tool returns empty results. + +*** + +## Step 3 - Product Hunt Data Services + +`services.py` wraps the external APIs with resilient defaults: + +- `parse_timeframe` translates natural strings into UTC ranges using `pendulum`. +- `fetch_graphql` only runs when `PRODUCTHUNT_API_TOKEN` is present; otherwise, helper functions return empty lists so the agent can respond gracefully. +- `search_products` hits the public Algolia index (`Post_production`) with rate-limit friendly defaults. + +*** + +## Step 4 - Test the API + +List top launches from the past week: + +```bash +curl "http://localhost:8001/api/top-week?limit=5&days=7" +``` + +Ask the agent a question (non-streaming): + +```bash +curl -X POST http://localhost:8001/api/chat \ + -H "Content-Type: application/json" \ + -d '{ + "messages": [ + { "role": "user", "content": "What should I highlight in my launch post?" } + ] + }' +``` + +Stream responses (newline-delimited JSON): + +```bash +curl -N http://localhost:8001/stream \ + -H "Content-Type: application/json" \ + -d '{ + "thread_id": "launch-room", + "run_id": "run-457", + "messages": [ + { "role": "user", "content": "Show me the top launches last week." } + ] + }' +``` + +Each line is a JSON object with `type` (e.g., `text_delta`, `tool_call_start`, `tool_result`, `text_done`, `done`) plus the echoed `thread_id` and `run_id`. + +*** + +## Step 5 - Connect to CometChat + +- Deploy the service behind HTTPS and protect it with auth headers (use the agent’s **Headers** field when registering in CometChat). +- Point the Agno agent variant at your `/stream` endpoint; reuse the same **Agent ID** from UI Kit Builder. +- When the agent triggers `triggerConfetti`, listen for the tool event in your frontend to launch celebratory animations. +- Echo `thread_id` and `run_id` in every streamed line so CometChat can correlate partial tool events and message chunks. + +You now have an Agno Product Hunt agent ready to ship inside CometChat-powered experiences. diff --git a/ai-agents/agno.mdx b/ai-agents/agno.mdx new file mode 100644 index 00000000..cbd446ba --- /dev/null +++ b/ai-agents/agno.mdx @@ -0,0 +1,191 @@ +--- +title: "Create an AI Agent with Agno" +sidebarTitle: "Create AI Agent" +description: "Connect an Agno agent to CometChat, customize it with UI Kit Builder, and ship it as React UI Kit code or a Chat Widget." +--- + +## What you’ll build + +- An **Agno** agent served with **FastAPI** that streams responses and exposes tools. +- The same agent **connected to CometChat** through Agent ID + Deployment URL routing. +- A **customized chat experience** using **UI Kit Builder**. +- An export to **React UI Kit code** _or_ **Chat Widget** for integration. + +--- + +## Prerequisites + +- A CometChat account and an app: **[Create App](https://app.cometchat.com/apps)** +- An Agno agent endpoint (see Step 6 for the example services). +- Python 3.10+ with `pip`, plus access to an OpenAI-compatible model (`OPENAI_API_KEY`). + +--- + +## Step 1 - Create your CometChat app + + + + Sign in at app.cometchat.com. Create a new app or open an existing one. + + + Note your App ID, Region, and Auth Key (needed if you export the Chat Widget later). + + + +--- + +## Step 2 - Connect your Agno Agent + +Navigate to **AI Agent → Get Started** and then **AI Agents → Add Agent**. + + + + Select **Agno**. + + + Provide: +
    +
  • Name and optional Icon
  • +
  • (Optional) Greeting and Introductory Message
  • +
  • (Optional) Suggested messages
  • +
+
+ + Paste/define: +
    +
  • Agent ID — a unique handle that matches how you route traffic (e.g., support).
  • +
  • Deployment URL — the public HTTPS endpoint exposed by your Agno service.
  • +
  • (Optional) Headers — JSON auth headers that your FastAPI deployment expects.
  • +
+
+ + Click Save, then ensure the agent’s toggle is ON in the AI Agents list. + +
+ +> **Tip:** The Agno examples stream newline-delimited JSON events using CometChat’s Bring Your Own Agent format. Keep the **Agent ID** and **Deployment URL** stable so you don’t need to reconnect. + +CometChat includes `thread_id`, `run_id`, the recent `messages`, and optional `namespace` (or `toolParams.namespace`) in every `/stream` request. Echo those IDs back in each event so UI Kit Builder variants can stitch partial responses correctly. + +--- + +## Step 3 - Define Frontend Actions (Optional) + + + + Go to AI Agent → Actions and click Add to create a frontend action your agent can call (e.g., “Open Product,” “Start Demo,” “Book Slot”). + + + Include: +
    +
  • Display Name — Shown to users (e.g., “Open Product Page”).
  • +
  • Execution Text — How the agent describes running it (e.g., “Opening product details for the user.”).
  • +
  • Name — A unique, code-friendly key (e.g., open_product).
  • +
  • Description — What the tool does and when to use it.
  • +
  • Parameters — JSON Schema describing inputs (the agent will fill these).
  • +
+
+ + Example parameters JSON: + +```json +{ + "type": "object", + "required": ["productId"], + "properties": { + "productId": { + "type": "string", + "description": "The internal product ID to open" + }, + "utm": { + "type": "string", + "description": "Optional tracking code" + } + } +} +``` + + + At runtime, listen for tool calls and execute them client-side (e.g., route changes, modals, highlights). + +
+ +--- + +## Step 4 - Customize in UI Kit Builder + + From AI Agents click the variant (or Get Started) to enter UI Kit Builder. + Select Customize and Deploy. + Update theme, layout, and features; confirm the Agno agent is attached. + Use live preview to validate responses & any tool triggers. + + + + + + +--- + +## Step 5 - Export & Integrate + +Choose how you’ll ship the experience (Widget or React UI Kit export). + + + } description="Embed / script" href="/widget/ai-agents" horizontal /> + } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components + + +> The Agno agent from Step 2 is included automatically in exported variants—no extra code needed for basic conversations. + + + Pick Chat Widget (fastest) or export React UI Kit for code-level customization. + Open UI Kit Builder → Get Embedded Code → copy script + credentials. + Export the variant as code (UI Kit) if you need deep theming or custom logic. + Preview: the Agno agent should appear without extra config. + + +--- + +## Step 6 - Deploy & Secure (Reference) + + +Need an Agno backend? Use these reference projects to define, expose, and deploy FastAPI services that stream directly into CometChat. + + + + + + Clone the examples, install dependencies, and start the FastAPI server: + +```bash +git clone https://github.com/cometchat/ai-agent-agno-examples.git +cd ai-agent-agno-examples +python3 -m venv .venv +source .venv/bin/activate +pip install -e . +uvicorn knowledge_agent.main:app --host 0.0.0.0 --port 8000 --reload +``` + + Key points: + + - `knowledge_agent/main.py` exposes `/api/tools/ingest`, `/api/tools/searchDocs`, `/api/agents/knowledge/generate`, and `/stream` (newline-delimited JSON with `text_delta`, `tool_*`, `text_done`, `done`, `error`). + - `KnowledgeManager` creates an Agno agent bound to a per-namespace vector store and enforces retrieval-before-answer behavior with citations. + - Configure secrets via `.env` (`OPENAI_API_KEY`, optional `KNOWLEDGE_*` overrides). The example persists markdown under `knowledge_agent/data/knowledge/`. + + + + Launch the Product Hunt assistant on another port: + +```bash +uvicorn product_hunt_agent.main:app --host 0.0.0.0 --port 8001 --reload +``` + + Highlights: + + - `/api/top`, `/api/top-week`, `/api/top-range`, and `/api/search` surface Algolia + GraphQL data for Product Hunt launches. + - `/api/chat` and `/stream` share the same newline-delimited event schema as the knowledge agent, so CometChat receives consistent payloads (`text_delta`, `tool_*`, `text_done`, `done`). + - Provide `PRODUCTHUNT_API_TOKEN` for live data (the agent falls back gracefully when it’s absent) and customize tool prompts in `agent_builder.py`. + + + +> Deploy behind HTTPS and secure with auth headers or gateway middleware before pointing CometChat at the `/stream` endpoint. diff --git a/ai-agents/chat-widget.mdx b/ai-agents/chat-widget.mdx index 0fd01359..fca75dd7 100644 --- a/ai-agents/chat-widget.mdx +++ b/ai-agents/chat-widget.mdx @@ -174,9 +174,9 @@ You now have a **public base URL** to use in the Dashboard. --- -## Step 4 - Attach Agent in Chat Builder (No‑Code) +## Step 4 - Attach Agent in UI Kit Builder (No‑Code) - Launch Chat Builder from the Dashboard. + 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. @@ -194,9 +194,9 @@ You now have a **public base URL** to use in the Dashboard. --- -## Step 6 - Customize in Chat Builder +## Step 6 - Customize in UI Kit Builder - From AI Agents click the variant (or Get Started) to enter Chat 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. @@ -210,7 +210,7 @@ You now have a **public base URL** to use in the Dashboard. ## Step 7 - Export & Embed -In Chat Builder click **Get Embedded Code** → copy credentials: +In UI Kit Builder click **Get Embedded Code** → copy credentials: - App ID - Auth Key - Region @@ -224,7 +224,7 @@ Example embed (HTML): ```html - + ``` ```html diff --git a/ai-agents/cometchat-ag-ui-byoa.mdx b/ai-agents/cometchat-ag-ui-byoa.mdx new file mode 100644 index 00000000..124b0185 --- /dev/null +++ b/ai-agents/cometchat-ag-ui-byoa.mdx @@ -0,0 +1,122 @@ +--- +title: "CometChat AG-UI Agents" +sidebarTitle: "CometChat AG-UI Agents" +description: "Bring your own agent to CometChat and build AG-UI compatible agents." +--- + +### Overview + +CometChat's "Bring Your Own Agent" (BYOA) feature allows you to integrate your custom AI agent with CometChat's full-stack platform. This approach provides: + +- **Complete Control**: Host and manage your own agent logic +- **Flexibility**: Use any AI provider or custom model +- **Self-Service**: Configure everything through the CometChat dashboard +- **Production-Ready UI**: CometChat handles chat interface, moderation, and analytics +- **Security**: Secure communication via headers and authentication + +### How It Works + +1. **Host Your Agent**: Deploy an AG-UI compatible agent on your infrastructure +2. **Configure in CometChat**: Add agent details in the CometChat dashboard +3. **Secure Connection**: Set up authentication headers +4. **Seamless Integration**: CometChat sends AG-UI messages to your agent and streams responses + +### Key Benefits + +- **No Infrastructure Headaches**: CometChat provides the UI, moderation, and monitoring +- **Model Agnostic**: Works with OpenAI, Anthropic, Mastra, LangGraph, or custom models +- **Multi-Agent Support**: Connect multiple specialized agents +- **Real-Time Streaming**: Token-by-token response streaming +- **Tool Integration**: Execute frontend tools from your agent + +--- + +## Building an AG-UI Compatible Agent + +### Core Requirements + +An AG-UI compatible agent must: + +1. **Accept POST requests** with `RunAgentInput` body +2. **Return streaming responses** as Server-Sent Events (SSE) +3. **Emit AG-UI events** in the correct sequence +4. **Handle errors gracefully** with `RUN_ERROR` events + +### RunAgentInput Interface + +Every AG-UI agent receives this input: + +```typescript +interface RunAgentInput { + threadId: string // ID of the conversation thread + runId: string // ID of the current run + state: any // Current state of the agent + messages: Message[] // Array of messages in conversation + tools: Tool[] // Array of tools available to agent + context: Context[] // Array of context objects + forwardedProps: any // Additional properties +} +``` + +### Tool Interface + +```typescript +interface Tool { + name: string + description: string + parameters: { + type: "object" + properties: Record + required?: string[] + } +} +``` + +### Basic Agent Implementation Pattern + +```typescript +// 1. Accept POST request with RunAgentInput +app.post('/agent', async (req, res) => { + const input: RunAgentInput = req.body; + + // 2. Set up Server-Sent Events + res.setHeader('Content-Type', 'text/event-stream'); + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('Connection', 'keep-alive'); + + // 3. Create event encoder + const encoder = new EventEncoder(); + + try { + // 4. Emit RUN_STARTED + res.write(encoder.encode({ + type: EventType.RUN_STARTED, + threadId: input.threadId, + runId: input.runId + })); + + // 5. Process request and stream response + // ... your agent logic here ... + + // 6. Emit RUN_FINISHED + res.write(encoder.encode({ + type: EventType.RUN_FINISHED, + threadId: input.threadId, + runId: input.runId + })); + + res.end(); + + } catch (error) { + // 7. Handle errors with RUN_ERROR + res.write(encoder.encode({ + type: EventType.RUN_ERROR, + message: error.message + })); + res.end(); + } +}); +``` + +--- + diff --git a/ai-agents/cometchat-ag-ui-express.mdx b/ai-agents/cometchat-ag-ui-express.mdx new file mode 100644 index 00000000..ca920fd8 --- /dev/null +++ b/ai-agents/cometchat-ag-ui-express.mdx @@ -0,0 +1,280 @@ +--- +title: "AG-UI Express.js Implementation" +sidebarTitle: "Express.js" +description: "Implementation guide for building an AG-UI agent with Express.js." +--- + +### Prerequisites + +- Node.js (v16 or higher) +- npm or pnpm +- OpenAI API key (or other AI service) + +### Step 1: Project Setup + +```bash +# Create project directory +mkdir my-ag-ui-agent +cd my-ag-ui-agent + +# Initialize package.json +npm init -y + +# Install dependencies +npm install express @ag-ui/core openai uuid cors dotenv +npm install -D typescript @types/node @types/express ts-node nodemon +``` + +### Step 2: TypeScript Configuration + +Create `tsconfig.json`: + +```json +{ + "compilerOptions": { + "target": "ES2020", + "module": "commonjs", + "lib": ["ES2020"], + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} +``` + +### Step 3: Create Express Server + +Create `src/server.ts`: + +```typescript +import express, { Request, Response } from 'express'; +import cors from 'cors'; +import { OpenAI } from 'openai'; +import { EventType, RunAgentInput } from '@ag-ui/core'; +import { v4 as uuidv4 } from 'uuid'; + +const app = express(); +const port = process.env.PORT || 8000; + +// Middleware +app.use(cors()); +app.use(express.json()); + +// Initialize OpenAI +const openai = new OpenAI({ + apiKey: process.env.OPENAI_API_KEY, +}); + +// Event encoder for AG-UI events +class EventEncoder { + encode(event: any): string { + return `data: ${JSON.stringify(event)}\n\n`; + } + + getContentType(): string { + return 'text/event-stream'; + } +} + +// AG-UI Agent Endpoint +app.post('/agent', async (req: Request, res: Response) => { + const input: RunAgentInput = req.body; + const encoder = new EventEncoder(); + + // Set up SSE headers + res.setHeader('Content-Type', encoder.getContentType()); + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('Connection', 'keep-alive'); + res.setHeader('X-Accel-Buffering', 'no'); // Disable buffering for nginx + + try { + // Emit RUN_STARTED + res.write(encoder.encode({ + type: EventType.RUN_STARTED, + threadId: input.threadId, + runId: input.runId, + })); + + // Convert AG-UI messages to OpenAI format + const openaiMessages = input.messages.map((msg) => ({ + role: msg.role as 'user' | 'assistant' | 'system', + content: msg.content || '', + ...(msg.role === 'assistant' && msg.toolCalls ? { + tool_calls: msg.toolCalls + } : {}), + ...(msg.role === 'tool' ? { + tool_call_id: msg.toolCallId + } : {}) + })); + + // Convert AG-UI tools to OpenAI format + const openaiTools = input.tools?.map((tool) => ({ + type: 'function' as const, + function: { + name: tool.name, + description: tool.description, + parameters: tool.parameters, + }, + })) || []; + + // Call OpenAI with streaming + const stream = await openai.chat.completions.create({ + model: 'gpt-4o', + messages: openaiMessages, + tools: openaiTools.length > 0 ? openaiTools : undefined, + stream: true, + }); + + const messageId = uuidv4(); + let hasStartedMessage = false; + + // Stream the response + for await (const chunk of stream) { + const delta = chunk.choices[0]?.delta; + + // Handle text content + if (delta?.content) { + if (!hasStartedMessage) { + res.write(encoder.encode({ + type: EventType.TEXT_MESSAGE_START, + messageId, + role: 'assistant', + })); + hasStartedMessage = true; + } + + res.write(encoder.encode({ + type: EventType.TEXT_MESSAGE_CONTENT, + messageId, + delta: delta.content, + })); + } + + // Handle tool calls + if (delta?.tool_calls) { + for (const toolCall of delta.tool_calls) { + if (toolCall.function?.name) { + res.write(encoder.encode({ + type: EventType.TOOL_CALL_START, + toolCallId: toolCall.id, + toolCallName: toolCall.function.name, + parentMessageId: messageId, + })); + } + + if (toolCall.function?.arguments) { + res.write(encoder.encode({ + type: EventType.TOOL_CALL_ARGS, + toolCallId: toolCall.id, + delta: toolCall.function.arguments, + })); + } + } + } + } + + // End message if it was started + if (hasStartedMessage) { + res.write(encoder.encode({ + type: EventType.TEXT_MESSAGE_END, + messageId, + })); + } + + // Emit RUN_FINISHED + res.write(encoder.encode({ + type: EventType.RUN_FINISHED, + threadId: input.threadId, + runId: input.runId, + })); + + res.end(); + + } catch (error: any) { + // Emit RUN_ERROR + res.write(encoder.encode({ + type: EventType.RUN_ERROR, + message: error.message || 'An error occurred', + })); + res.end(); + } +}); + +// Health check endpoint +app.get('/health', (req: Request, res: Response) => { + res.json({ status: 'ok', timestamp: new Date().toISOString() }); +}); + +// Start server +app.listen(port, () => { + console.log(`🚀 AG-UI Agent server running on port ${port}`); + console.log(`📍 Agent endpoint: http://localhost:${port}/agent`); + console.log(`💚 Health check: http://localhost:${port}/health`); +}); +``` + +### Step 4: Environment Configuration + +Create `.env`: + +```bash +OPENAI_API_KEY=your-openai-api-key-here +PORT=8000 +``` + +### Step 5: Package Scripts + +Update `package.json`: + +```json +{ + "name": "my-ag-ui-agent", + "version": "1.0.0", + "scripts": { + "dev": "nodemon --exec ts-node src/server.ts", + "build": "tsc", + "start": "node dist/server.js" + } +} +``` + +### Step 6: Run the Server + +```bash +# Development mode +npm run dev + +# Production mode +npm run build && npm start +``` + +### Step 7: Test Your Agent + +```bash +curl -X POST http://localhost:8000/agent \ + -H "Content-Type: application/json" \ + -d '{ + "threadId": "test_thread_123", + "runId": "test_run_456", + "messages": [ + { + "id": "msg_1", + "role": "user", + "content": "Hello! Can you help me?" + } + ], + "tools": [], + "context": [], + "state": {}, + "forwardedProps": {} + }' +``` + +--- + diff --git a/ai-agents/cometchat-ag-ui-integration.mdx b/ai-agents/cometchat-ag-ui-integration.mdx new file mode 100644 index 00000000..4ebfcaa5 --- /dev/null +++ b/ai-agents/cometchat-ag-ui-integration.mdx @@ -0,0 +1,402 @@ +--- +title: "CometChat AG-UI Integration Steps" +sidebarTitle: "Integration" +description: "Integrating AG-UI agents with CometChat, security practices, and deployment checklist." +--- + +### Step 1: Deploy Your Agent + +Before integrating with CometChat, ensure your agent is: +- **Publicly accessible** over HTTPS +- **Running on a stable server** (AWS, Google Cloud, Azure, etc.) +- **Protected with authentication** headers + +### Step 2: Configure Agent in CometChat Dashboard + +1. **Login to CometChat Dashboard** + - Navigate to https://app.cometchat.com + - Select your application + +2. **Navigate to AI Agents** + - Go to **AI Agents** in the left-hand menu + - Click **"Add Agent"** or **"Custom Agents"** + +3. **Configure Agent Settings** + + **Basic Information:** + - **Agent Name**: Give your agent a memorable name (e.g., "Support Assistant") + - **Provider**: Select "Custom" or "AG-UI Compatible" + - **Deployment URL**: Enter your agent's public URL + ``` + https://your-domain.com/agent + ``` + + **Agent Identity:** + - **Display Name**: Name shown to users (e.g., "AI Assistant") + - **Avatar**: Upload an avatar image for your agent + - **Greeting Message**: Set a welcome message + ``` + "Hello! I'm your AI assistant. How can I help you today?" + ``` + +4. **Configure Security Headers** + + CometChat allows you to securely access your agent using custom headers. This is **highly recommended** for production. + + **Headers Configuration (JSON format):** + ```json + { + "Authorization": "Bearer your-secret-api-key", + "X-API-Key": "your-custom-api-key", + "X-Client-ID": "cometchat-client" + } + ``` + + **Example with Basic Auth:** + ```json + { + "Authorization": "Basic base64-encoded-credentials" + } + ``` + +5. **Enable the Agent** + - Toggle the agent status to **"Enabled"** + - Click **"Save"** + +### Step 3: Implement Header Validation in Your Agent + +**Express.js Example:** + +```typescript +import express from 'express'; + +const app = express(); + +// Middleware to validate headers +app.use('/agent', (req, res, next) => { + const apiKey = req.headers['x-api-key']; + const expectedKey = process.env.API_KEY; + + if (apiKey !== expectedKey) { + return res.status(401).json({ + error: 'Unauthorized', + message: 'Invalid API key' + }); + } + + next(); +}); + +// Your agent endpoint +app.post('/agent', async (req, res) => { + // Agent logic here +}); +``` + +**NestJS Example:** + +```typescript +import { Injectable, NestMiddleware, UnauthorizedException } from '@nestjs/common'; +import { Request, Response, NextFunction } from 'express'; +import { ConfigService } from '@nestjs/config'; + +@Injectable() +export class AuthMiddleware implements NestMiddleware { + constructor(private configService: ConfigService) {} + + use(req: Request, res: Response, next: NextFunction) { + const apiKey = req.headers['x-api-key']; + const expectedKey = this.configService.get('API_KEY'); + + if (apiKey !== expectedKey) { + throw new UnauthorizedException('Invalid API key'); + } + + next(); + } +} + +// In your module: +export class AgentModule implements NestModule { + configure(consumer: MiddlewareConsumer) { + consumer + .apply(AuthMiddleware) + .forRoutes('agent'); + } +} +``` + +### Step 4: Test Integration + +1. **Access CometChat in your app** +2. **Start a conversation** with your AI agent +3. **Send a message** and verify the agent responds correctly +4. **Check streaming** - messages should appear token-by-token +5. **Test tools** - if your agent uses tools, verify they execute properly + +### Step 5: Monitor and Debug + +**Check Agent Logs:** +```typescript +// Add logging to your agent +console.log('Received request:', { + threadId: input.threadId, + runId: input.runId, + messageCount: input.messages.length, + toolCount: input.tools.length +}); +``` + +**CometChat Analytics:** +- Navigate to **Analytics** in CometChat dashboard +- Monitor agent performance, response times, and error rates + +--- + +## Best Practices and Security + +### Security Best Practices + +#### 1. Use HTTPS +Always deploy your agent with HTTPS. Never expose HTTP endpoints in production. + +#### 2. Implement Authentication +Use strong authentication headers: + +```typescript +// Environment variables +API_KEY=your-strong-random-key-here +CLIENT_SECRET=another-strong-secret + +// Validate in your agent +const validateAuth = (req: Request): boolean => { + const apiKey = req.headers['x-api-key']; + const clientId = req.headers['x-client-id']; + + return apiKey === process.env.API_KEY && + clientId === process.env.CLIENT_ID; +}; +``` + +#### 3. Rate Limiting +Implement rate limiting to prevent abuse: + +```typescript +import rateLimit from 'express-rate-limit'; + +const limiter = rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, // Limit each IP to 100 requests per windowMs + message: 'Too many requests, please try again later.' +}); + +app.use('/agent', limiter); +``` + +#### 4. Input Validation +Validate all inputs: + +```typescript +import { IsString, IsArray, ValidateNested } from 'class-validator'; + +export class RunAgentInputDto { + @IsString() + threadId: string; + + @IsString() + runId: string; + + @IsArray() + @ValidateNested({ each: true }) + messages: Message[]; + + // ... other validations +} +``` + +#### 5. Error Handling +Never expose sensitive information in errors: + +```typescript +try { + // Agent logic +} catch (error) { + console.error('Internal error:', error); // Log internally + + // Return generic error to client + res.write(encoder.encode({ + type: EventType.RUN_ERROR, + message: 'An unexpected error occurred. Please try again.' + })); +} +``` + +### Performance Best Practices + +#### 1. Streaming Optimization +Stream responses as soon as possible: + +```typescript +// Good: Start streaming immediately +res.write(encoder.encode({ type: EventType.RUN_STARTED })); + +// Bad: Wait for all processing before streaming +// processEverything().then(() => startStreaming()); +``` + +#### 2. Connection Management +Handle client disconnections gracefully: + +```typescript +app.post('/agent', async (req, res) => { + let isCancelled = false; + + req.on('close', () => { + isCancelled = true; + console.log('Client disconnected'); + }); + + // Check cancellation in your loops + for await (const chunk of stream) { + if (isCancelled) break; + res.write(encoder.encode(chunk)); + } +}); +``` + +#### 3. Timeout Configuration +Set appropriate timeouts: + +```typescript +const server = app.listen(port); +server.timeout = 300000; // 5 minutes +server.keepAliveTimeout = 65000; // 65 seconds +``` + +#### 4. Memory Management +Clean up resources properly: + +```typescript +try { + // Process stream + for await (const chunk of stream) { + // ... + } +} finally { + // Clean up resources + stream.destroy(); + res.end(); +} +``` + +### Development Best Practices + +#### 1. Environment Variables +Use environment variables for all sensitive data: + +```bash +# .env +OPENAI_API_KEY=sk-... +API_KEY=your-secret-key +PORT=8000 +NODE_ENV=production +``` + +#### 2. TypeScript Strict Mode +Enable strict TypeScript checking: + +```json +{ + "compilerOptions": { + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true + } +} +``` + +#### 3. Logging +Implement structured logging: + +```typescript +import winston from 'winston'; + +const logger = winston.createLogger({ + level: 'info', + format: winston.format.json(), + transports: [ + new winston.transports.File({ filename: 'error.log', level: 'error' }), + new winston.transports.File({ filename: 'combined.log' }) + ] +}); + +logger.info('Agent request received', { + threadId: input.threadId, + messageCount: input.messages.length +}); +``` + +#### 4. Testing +Write tests for your agent: + +```typescript +import request from 'supertest'; +import app from './server'; + +describe('AG-UI Agent', () => { + it('should respond with RUN_STARTED event', async () => { + const response = await request(app) + .post('/agent') + .send({ + threadId: 'test_123', + runId: 'run_456', + messages: [{ id: '1', role: 'user', content: 'Hello' }], + tools: [], + context: [], + state: {}, + forwardedProps: {} + }); + + expect(response.status).toBe(200); + expect(response.text).toContain('RUN_STARTED'); + }); +}); +``` + +### Deployment Checklist + +- [ ] Agent is accessible over HTTPS +- [ ] Authentication headers are configured +- [ ] Rate limiting is enabled +- [ ] Input validation is implemented +- [ ] Error handling doesn't expose sensitive data +- [ ] Logging is configured +- [ ] Environment variables are set +- [ ] Timeouts are configured appropriately +- [ ] Health check endpoint is available +- [ ] Agent is tested with real CometChat integration + +--- + +## Conclusion + +You now have a comprehensive understanding of: + +1. **AG-UI Protocol** - Event types, message formats, and patterns +2. **CometChat Integration** - "Bring Your Own Agent" approach +3. **Agent Implementation** - Complete Express.js and NestJS examples +4. **Security & Best Practices** - Production-ready configurations + +Your AG-UI compatible agent can now be seamlessly integrated with CometChat, providing a powerful, self-served AI agent experience with full control over your agent logic while benefiting from CometChat's production-ready chat infrastructure. + +### Additional Resources + +- **AG-UI Documentation**: https://docs.ag-ui.com +- **CometChat Documentation**: https://www.cometchat.com/docs +- **AG-UI GitHub**: https://github.com/ag-ui-protocol/ag-ui +- **CometChat Dashboard**: https://app.cometchat.com + +--- + +**Happy Building! 🚀** diff --git a/ai-agents/cometchat-ag-ui-nestjs.mdx b/ai-agents/cometchat-ag-ui-nestjs.mdx new file mode 100644 index 00000000..0f6bbf5e --- /dev/null +++ b/ai-agents/cometchat-ag-ui-nestjs.mdx @@ -0,0 +1,336 @@ +--- +title: "AG-UI NestJS Implementation" +sidebarTitle: "NestJS" +description: "Implementation guide for building an AG-UI agent with NestJS." +--- + +### Prerequisites + +- Node.js (v16 or higher) +- npm or pnpm +- NestJS CLI +- OpenAI API key (or other AI service) + +### Step 1: Create NestJS Project + +```bash +# Install NestJS CLI +npm i -g @nestjs/cli + +# Create new project +nest new my-ag-ui-agent + +# Navigate to project +cd my-ag-ui-agent + +# Install additional dependencies +npm install @ag-ui/core openai uuid @nestjs/config +``` + +### Step 2: Configure Environment + +Create `.env`: + +```bash +OPENAI_API_KEY=your-openai-api-key-here +PORT=8000 +``` + +Update `src/app.module.ts`: + +```typescript +import { Module } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { AgentModule } from './agent/agent.module'; + +@Module({ + imports: [ + ConfigModule.forRoot({ + isGlobal: true, + }), + AgentModule, + ], +}) +export class AppModule {} +``` + +### Step 3: Create Agent Module + +```bash +nest g module agent +nest g service agent +nest g controller agent +``` + +### Step 4: Implement Agent Service + +Update `src/agent/agent.service.ts`: + +```typescript +import { Injectable } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { OpenAI } from 'openai'; +import { EventType, RunAgentInput } from '@ag-ui/core'; +import { v4 as uuidv4 } from 'uuid'; + +export class EventEncoder { + encode(event: any): string { + return `data: ${JSON.stringify(event)}\n\n`; + } + + getContentType(): string { + return 'text/event-stream'; + } +} + +@Injectable() +export class AgentService { + private openai: OpenAI; + + constructor(private configService: ConfigService) { + const apiKey = this.configService.get('OPENAI_API_KEY'); + if (!apiKey) { + throw new Error('OPENAI_API_KEY is required'); + } + this.openai = new OpenAI({ apiKey }); + } + + async *runAgent(input: RunAgentInput): AsyncGenerator { + const encoder = new EventEncoder(); + + try { + // Emit RUN_STARTED + yield encoder.encode({ + type: EventType.RUN_STARTED, + threadId: input.threadId, + runId: input.runId, + }); + + // Convert AG-UI messages to OpenAI format + const openaiMessages = input.messages.map((msg) => ({ + role: msg.role as 'user' | 'assistant' | 'system', + content: msg.content || '', + ...(msg.role === 'assistant' && msg.toolCalls ? { + tool_calls: msg.toolCalls + } : {}), + ...(msg.role === 'tool' ? { + tool_call_id: msg.toolCallId + } : {}) + })); + + // Convert AG-UI tools to OpenAI format + const openaiTools = input.tools?.map((tool) => ({ + type: 'function' as const, + function: { + name: tool.name, + description: tool.description, + parameters: tool.parameters, + }, + })) || []; + + // Call OpenAI with streaming + const stream = await this.openai.chat.completions.create({ + model: 'gpt-4o', + messages: openaiMessages, + tools: openaiTools.length > 0 ? openaiTools : undefined, + stream: true, + }); + + const messageId = uuidv4(); + let hasStartedMessage = false; + + // Stream the response + for await (const chunk of stream) { + const delta = chunk.choices[0]?.delta; + + // Handle text content + if (delta?.content) { + if (!hasStartedMessage) { + yield encoder.encode({ + type: EventType.TEXT_MESSAGE_START, + messageId, + role: 'assistant', + }); + hasStartedMessage = true; + } + + yield encoder.encode({ + type: EventType.TEXT_MESSAGE_CONTENT, + messageId, + delta: delta.content, + }); + } + + // Handle tool calls + if (delta?.tool_calls) { + for (const toolCall of delta.tool_calls) { + if (toolCall.function?.name) { + yield encoder.encode({ + type: EventType.TOOL_CALL_START, + toolCallId: toolCall.id, + toolCallName: toolCall.function.name, + parentMessageId: messageId, + }); + } + + if (toolCall.function?.arguments) { + yield encoder.encode({ + type: EventType.TOOL_CALL_ARGS, + toolCallId: toolCall.id, + delta: toolCall.function.arguments, + }); + } + } + } + } + + // End message if it was started + if (hasStartedMessage) { + yield encoder.encode({ + type: EventType.TEXT_MESSAGE_END, + messageId, + }); + } + + // Emit RUN_FINISHED + yield encoder.encode({ + type: EventType.RUN_FINISHED, + threadId: input.threadId, + runId: input.runId, + }); + + } catch (error: any) { + // Emit RUN_ERROR + yield encoder.encode({ + type: EventType.RUN_ERROR, + message: error.message || 'An error occurred', + }); + } + } +} +``` + +### Step 5: Implement Agent Controller + +Update `src/agent/agent.controller.ts`: + +```typescript +import { Controller, Post, Body, Res, HttpStatus } from '@nestjs/common'; +import { Response } from 'express'; +import { AgentService, EventEncoder } from './agent.service'; +import { RunAgentInput } from '@ag-ui/core'; + +@Controller('agent') +export class AgentController { + constructor(private readonly agentService: AgentService) {} + + @Post() + async runAgent( + @Body() input: RunAgentInput, + @Res() res: Response, + ) { + const encoder = new EventEncoder(); + + // Set SSE headers + res.setHeader('Content-Type', encoder.getContentType()); + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('Connection', 'keep-alive'); + res.setHeader('X-Accel-Buffering', 'no'); + + res.status(HttpStatus.OK); + + // Stream events + try { + for await (const event of this.agentService.runAgent(input)) { + res.write(event); + } + } catch (error) { + console.error('Error streaming agent response:', error); + } finally { + res.end(); + } + } +} +``` + +### Step 6: Update Agent Module + +Update `src/agent/agent.module.ts`: + +```typescript +import { Module } from '@nestjs/common'; +import { AgentService } from './agent.service'; +import { AgentController } from './agent.controller'; + +@Module({ + controllers: [AgentController], + providers: [AgentService], +}) +export class AgentModule {} +``` + +### Step 7: Update Main Configuration + +Update `src/main.ts`: + +```typescript +import { NestFactory } from '@nestjs/core'; +import { AppModule } from './app.module'; +import { ConfigService } from '@nestjs/config'; + +async function bootstrap() { + const app = await NestFactory.create(AppModule); + + // Enable CORS + app.enableCors({ + origin: '*', + methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', + credentials: true, + }); + + const configService = app.get(ConfigService); + const port = configService.get('PORT') || 8000; + + await app.listen(port); + + console.log(`🚀 AG-UI Agent server running on port ${port}`); + console.log(`📍 Agent endpoint: http://localhost:${port}/agent`); +} + +bootstrap(); +``` + +### Step 8: Run the Server + +```bash +# Development mode +npm run start:dev + +# Production mode +npm run build && npm run start:prod +``` + +### Step 9: Test Your Agent + +```bash +curl -X POST http://localhost:8000/agent \ + -H "Content-Type: application/json" \ + -d '{ + "threadId": "test_thread_123", + "runId": "test_run_456", + "messages": [ + { + "id": "msg_1", + "role": "user", + "content": "Hello! Can you help me?" + } + ], + "tools": [], + "context": [], + "state": {}, + "forwardedProps": {} + }' +``` + +--- + diff --git a/ai-agents/cometchat-ag-ui-overview.mdx b/ai-agents/cometchat-ag-ui-overview.mdx new file mode 100644 index 00000000..67d5c63f --- /dev/null +++ b/ai-agents/cometchat-ag-ui-overview.mdx @@ -0,0 +1,431 @@ +--- +title: "CometChat AG-UI Integration" +sidebarTitle: "CometChat AG-UI" +description: "Overview of the CometChat AG-UI integration protocol, event categories, and message formats." +--- + +CometChat has integrated support for **AG-UI (Agent-User Interaction Protocol)**, making it easier than ever to bring your own AI agents into your applications. With the "Bring Your Own Agent" (BYOA) approach, you can now host your own AG-UI compatible agent and seamlessly integrate it with CometChat's full-stack platform. + +This documentation provides a comprehensive guide on: +- Understanding the AG-UI protocol +- Creating AG-UI compatible agents using TypeScript +- Hosting agents on Express.js or NestJS +- Connecting your agent to CometChat + +--- + +## What is AG-UI? + +### Overview + +**AG-UI (Agent-User Interaction Protocol)** is an open-source, lightweight, event-based protocol developed to standardize real-time communication between AI agents and user interfaces. It provides a vendor-neutral format that works across different AI providers (OpenAI, Anthropic, custom models, etc.) without requiring changes to client-side implementations. + +### Key Features + +- **Event-Driven Architecture**: Streams JSON-encoded events over HTTP or WebSocket +- **Real-Time Streaming**: Supports token-by-token streaming of agent responses +- **Tool Integration**: Enables agents to call frontend tools and functions +- **State Management**: Synchronizes state between agents and UI +- **Framework Agnostic**: Works with Node.js, browsers, and any agent framework +- **Vendor Neutral**: Compatible with any AI service provider + +### Core Concepts + +AG-UI operates on three fundamental concepts: + +1. **Events**: Standardized messages that flow from agent to frontend +2. **Messages**: Conversation history between users and agents +3. **Tools**: Functions that agents can invoke to perform actions + +--- + +## AG-UI Event Types + +AG-UI defines **16+ standardized event types** organized into six categories. Understanding these events is crucial for implementing AG-UI compatible agents. + +### 1. Lifecycle Events + +These events monitor the progression of agent runs. + +#### **RUN_STARTED** +Signals the start of an agent run. + +```typescript +interface RunStartedEvent { + type: EventType.RUN_STARTED + threadId: string // ID of the conversation thread + runId: string // ID of the agent run + timestamp?: string +} +``` + +#### **RUN_FINISHED** +Signals successful completion of an agent run. + +```typescript +interface RunFinishedEvent { + type: EventType.RUN_FINISHED + threadId: string + runId: string + result?: any // Optional result data from run + timestamp?: string +} +``` + +#### **RUN_ERROR** +Signals an error during an agent run. + +```typescript +interface RunErrorEvent { + type: EventType.RUN_ERROR + message: string // Error message + code?: string // Optional error code + timestamp?: string +} +``` + +#### **STEP_STARTED** & **STEP_FINISHED** +Optional events for tracking discrete steps within a run. + +```typescript +interface StepStartedEvent { + type: EventType.STEP_STARTED + stepName: string // Name of the step +} + +interface StepFinishedEvent { + type: EventType.STEP_FINISHED + stepName: string +} +``` + +### 2. Text Message Events + +These events handle streaming textual content between agents and users. + +#### **TEXT_MESSAGE_START** +Signals the start of a text message. + +```typescript +interface TextMessageStartEvent { + type: EventType.TEXT_MESSAGE_START + messageId: string + role: "assistant" | "user" | "system" | "tool" | "developer" +} +``` + +#### **TEXT_MESSAGE_CONTENT** +Represents a chunk of content in a streaming message. + +```typescript +interface TextMessageContentEvent { + type: EventType.TEXT_MESSAGE_CONTENT + messageId: string + delta: string // Text content chunk (non-empty) +} +``` + +#### **TEXT_MESSAGE_END** +Signals the end of a text message. + +```typescript +interface TextMessageEndEvent { + type: EventType.TEXT_MESSAGE_END + messageId: string +} +``` + +#### **TEXT_MESSAGE_CHUNK** +A convenience event that combines start, content, and end in one. + +```typescript +interface TextMessageChunkEvent { + type: EventType.TEXT_MESSAGE_CHUNK + messageId?: string + role?: string + delta?: string +} +``` + +### 3. Tool Call Events + +These events manage tool executions by agents. + +#### **TOOL_CALL_START** +Signals the start of a tool call. + +```typescript +interface ToolCallStartEvent { + type: EventType.TOOL_CALL_START + toolCallId: string + toolCallName: string + parentMessageId?: string +} +``` + +#### **TOOL_CALL_ARGS** +Streams the arguments for a tool call. + +```typescript +interface ToolCallArgsEvent { + type: EventType.TOOL_CALL_ARGS + toolCallId: string + delta: string // JSON fragment to append to arguments +} +``` + +#### **TOOL_CALL_END** +Marks the completion of a tool call. + +```typescript +interface ToolCallEndEvent { + type: EventType.TOOL_CALL_END + toolCallId: string +} +``` + +#### **TOOL_CALL_CHUNK** +A convenience event for tool calls (similar to TEXT_MESSAGE_CHUNK). + +```typescript +interface ToolCallChunkEvent { + type: EventType.TOOL_CALL_CHUNK + toolCallId: string + toolCallName?: string + parentMessageId?: string + delta?: string +} +``` + +#### **TOOL_CALL_RESULT** +Provides the result of a tool call execution. + +```typescript +interface ToolCallResultEvent { + type: EventType.TOOL_CALL_RESULT + messageId: string + toolCallId: string + content: string // The actual result/output + role?: "tool" +} +``` + +### 4. State Management Events + +These events synchronize agent state with the frontend. + +#### **STATE_SNAPSHOT** +Provides a complete snapshot of agent state. + +```typescript +interface StateSnapshotEvent { + type: EventType.STATE_SNAPSHOT + snapshot: any // Complete state snapshot +} +``` + +#### **STATE_DELTA** +Provides incremental state updates using JSON Patch (RFC 6902). + +```typescript +interface StateDeltaEvent { + type: EventType.STATE_DELTA + delta: Array<{ + op: "add" | "remove" | "replace" | "move" | "copy" | "test" + path: string + value?: any + }> +} +``` + +#### **MESSAGES_SNAPSHOT** +Provides a snapshot of all messages in a conversation. + +```typescript +interface MessagesSnapshotEvent { + type: EventType.MESSAGES_SNAPSHOT + messages: Message[] +} +``` + +### 5. Special Events + +#### **CUSTOM** +Used for application-specific custom events. + +```typescript +interface CustomEvent { + type: EventType.CUSTOM + name: string + value: any +} +``` + +#### **RAW** +Used to pass through events from external systems. + +```typescript +interface RawEvent { + type: EventType.RAW + event: any + source?: string +} +``` + +### Event Flow Patterns + +AG-UI events follow specific patterns: + +1. **Start-Content-End Pattern**: Used for streaming (text messages, tool calls) + - Start event initiates the stream + - Content events deliver data chunks + - End event signals completion + +2. **Snapshot-Delta Pattern**: Used for state synchronization + - Snapshot provides complete state + - Delta events provide incremental updates + +3. **Lifecycle Pattern**: Used for monitoring agent runs + - Started events signal beginnings + - Finished/Error events signal endings + +--- + +## AG-UI Message Types + +Messages form the backbone of communication in the AG-UI protocol. They represent the conversation history between users and AI agents. + +### Base Message Structure + +```typescript +interface BaseMessage { + id: string // Unique identifier for the message + role: string // The role of the sender + content?: string // Optional text content + name?: string // Optional name of the sender +} +``` + +### Message Types + +#### **User Messages** +Messages from the end user to the agent. + +```typescript +interface UserMessage { + id: string + role: "user" + content: string // Text input from the user + name?: string // Optional user identifier +} +``` + +#### **Assistant Messages** +Messages from the AI assistant to the user. + +```typescript +interface AssistantMessage { + id: string + role: "assistant" + content?: string // Optional if using tool calls + name?: string + toolCalls?: ToolCall[] // Optional tool calls +} +``` + +#### **System Messages** +Instructions or context provided to the agent. + +```typescript +interface SystemMessage { + id: string + role: "system" + content: string // Instructions or context for the agent + name?: string +} +``` + +#### **Tool Messages** +Results from tool executions. + +```typescript +interface ToolMessage { + id: string + role: "tool" + content: string // Result from tool execution + toolCallId: string // ID of the tool call this responds to +} +``` + +#### **Developer Messages** +Internal messages used for development or debugging. + +```typescript +interface DeveloperMessage { + id: string + role: "developer" + content: string + name?: string +} +``` + +### Tool Call Structure + +```typescript +interface ToolCall { + id: string // Unique ID for this tool call + type: "function" // Type of tool call + function: { + name: string // Name of the function to call + arguments: string // JSON-encoded string of arguments + } +} +``` + +### Example Conversation with Tool Usage + +```typescript +const conversation = [ + // User query + { + id: "msg_1", + role: "user", + content: "What's the weather in New York?" + }, + + // Assistant response with tool call + { + id: "msg_2", + role: "assistant", + content: "Let me check the weather for you.", + toolCalls: [ + { + id: "call_1", + type: "function", + function: { + name: "get_weather", + arguments: '{"location": "New York", "unit": "celsius"}' + } + } + ] + }, + + // Tool result + { + id: "result_1", + role: "tool", + content: '{"temperature": 22, "condition": "Partly Cloudy", "humidity": 65}', + toolCallId: "call_1" + }, + + // Assistant's final response + { + id: "msg_3", + role: "assistant", + content: "The weather in New York is partly cloudy with a temperature of 22°C and 65% humidity." + } +] +``` + +--- + diff --git a/ai-agents/mastra-backend-tools-agent.mdx b/ai-agents/mastra-backend-tools-agent.mdx index 2b5b00b8..78bd4099 100644 --- a/ai-agents/mastra-backend-tools-agent.mdx +++ b/ai-agents/mastra-backend-tools-agent.mdx @@ -129,9 +129,9 @@ Ensure your public route: **`/api/agents/deals/generate`** is reachable. --- -## Step 6 - Customize in Chat Builder +## Step 6 - Customize in UI Kit Builder - From AI Agents click the variant (or Get Started) to enter Chat Builder. + From AI Agents click the variant (or Get Started) to enter UI Kit Builder. Select Customize and Deploy. Theme, layout, features; ensure the Backend Tools agent is attached. Use live preview to validate responses and scenarios that trigger backend actions. @@ -141,10 +141,10 @@ Ensure your public route: **`/api/agents/deals/generate`** is reachable. ## Step 7 - Integrate -Once your Backend Tools Agent is configured, you can integrate it into your app using the CometChat No Code - Widget: +Once your Backend Tools Agent is configured, you can integrate it into your app using the CometChat Widget Builder: - } description="Embed / script" href="/widget/ai-agents" horizontal /> + } description="Embed / script" href="/widget/ai-agents" horizontal /> } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components diff --git a/ai-agents/mastra-chef-agent.mdx b/ai-agents/mastra-chef-agent.mdx index 2a87a7f0..b70db7ce 100644 --- a/ai-agents/mastra-chef-agent.mdx +++ b/ai-agents/mastra-chef-agent.mdx @@ -254,9 +254,9 @@ export default async function handler(req: VercelRequest, res: VercelResponse) { Step 7 -## Customize in Chat Builder +## Customize in UI Kit Builder - From AI Agents click the variant (or Get Started) to enter Chat 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 & any tool triggers. @@ -274,10 +274,10 @@ export default async function handler(req: VercelRequest, res: VercelResponse) { ## Integrate -Once your agent is configured, you can integrate it into your app using the CometChat No Code - Widget +Once your agent is configured, you can integrate it into your app using the CometChat Widget Builder - } description="Embed / script" href="/widget/ai-agents" horizontal /> + } description="Embed / script" href="/widget/ai-agents" horizontal /> } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components diff --git a/ai-agents/mastra-coordinator-agent.mdx b/ai-agents/mastra-coordinator-agent.mdx index 6e9f6961..d074471b 100644 --- a/ai-agents/mastra-coordinator-agent.mdx +++ b/ai-agents/mastra-coordinator-agent.mdx @@ -184,9 +184,9 @@ Ensure your public route: **`/api/agents/relay/generate`** is reachable. --- -## Step 7 - Customize in Chat Builder +## Step 7 - Customize in UI Kit Builder - From AI Agents click the variant (or Get Started) to enter Chat Builder. + From AI Agents click the variant (or Get Started) to enter UI Kit Builder. Select Customize and Deploy. Theme, layout, features; ensure the Multi-agent Orchestration (relay) agent is attached. Use live preview to validate routing and responses. @@ -196,10 +196,10 @@ Ensure your public route: **`/api/agents/relay/generate`** is reachable. ## Step 8 - Integrate -Once your Multi-agent Orchestration Agent is configured, you can integrate it into your app using the CometChat No Code - Widget: +Once your Multi-agent Orchestration Agent is configured, you can integrate it into your app using the CometChat Widget Builder: - } description="Embed / script" href="/widget/ai-agents" horizontal /> + } description="Embed / script" href="/widget/ai-agents" horizontal /> } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components diff --git a/ai-agents/mastra-frontend-actions-agent.mdx b/ai-agents/mastra-frontend-actions-agent.mdx index 08bca4e6..d34f297e 100644 --- a/ai-agents/mastra-frontend-actions-agent.mdx +++ b/ai-agents/mastra-frontend-actions-agent.mdx @@ -153,9 +153,9 @@ Ensure your public route: **`/api/agents/celebration/generate`** is reachable. --- -## Step 7 - Customize in Chat Builder +## Step 7 - Customize in UI Kit Builder - From AI Agents click the variant (or Get Started) to enter Chat Builder. + From AI Agents click the variant (or Get Started) to enter UI Kit Builder. Select Customize and Deploy. Theme, layout, features; ensure the Frontend Actions agent is attached. Use live preview to validate messages and any tool triggers. @@ -165,10 +165,10 @@ Ensure your public route: **`/api/agents/celebration/generate`** is reachable. ## Step 8 - Integrate -Once your Frontend Actions Agent is configured, you can integrate it into your app using the CometChat No Code - Widget: +Once your Frontend Actions Agent is configured, you can integrate it into your app using the CometChat Widget Builder: - } description="Embed / script" href="/widget/ai-agents" horizontal /> + } description="Embed / script" href="/widget/ai-agents" horizontal /> } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components diff --git a/ai-agents/mastra-knowledge-agent.mdx b/ai-agents/mastra-knowledge-agent.mdx index e3b93277..10f7d6fc 100644 --- a/ai-agents/mastra-knowledge-agent.mdx +++ b/ai-agents/mastra-knowledge-agent.mdx @@ -186,9 +186,9 @@ Ensure the public route: **`/api/agents/knowledge/generate`** is reachable. --- -## Step 6 - Customize in Chat Builder +## Step 6 - Customize in UI Kit Builder - From AI Agents click the variant (or Get Started) to enter Chat 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 Knowledge agent is attached. Use live preview to validate responses & any tool triggers. @@ -202,10 +202,10 @@ Ensure the public route: **`/api/agents/knowledge/generate`** is reachable. ## Step 7 - Integrate -Once your Knowledge Agent is configured, you can integrate it into your app using the CometChat No Code - Widget: +Once your Knowledge Agent is configured, you can integrate it into your app using the CometChat Widget Builder: - } description="Embed / script" href="/widget/ai-agents" horizontal /> + } description="Embed / script" href="/widget/ai-agents" horizontal /> } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components diff --git a/ai-agents/mastra-knowlege-agent-pdf.mdx b/ai-agents/mastra-knowlege-agent-pdf.mdx new file mode 100644 index 00000000..464b4f4b --- /dev/null +++ b/ai-agents/mastra-knowlege-agent-pdf.mdx @@ -0,0 +1,346 @@ +--- +title: "Build a PDF Knowledge Agent with Mastra" +sidebarTitle: "PDF Knowledge Agent" +description: "Create a Mastra agent that ingests PDFs, performs hybrid (semantic + BM25) retrieval, and answers grounded questions in CometChat." +--- + +Give your chat experience document intelligence: ingest PDFs, run hybrid semantic + lexical retrieval, and stream grounded answers into CometChat. + +--- + +## Quick links + +- Live (UI served from `docs/` if deployed to GitHub Pages): static upload + ask demo +- Source code: [GitHub repository](https://github.com/cometchat/ai-agent-mastra-examples/tree/main/mastra-knowledge-agent-pdf) +- Agent files: `src/mastra/agents/*` +- Tools: `src/mastra/tools/*` +- Workflow: `src/mastra/workflows/pdf-workflow.ts` +- Server: `src/server.ts` + +--- + +## What you’ll build + +- Dual Mastra agents: + - `pdfAgent` (multi‑PDF retrieval across all uploaded docs) + - `singlePdfAgent` (restricted to latest uploaded PDF) +- Deterministic retrieval + answer workflow (`pdfWorkflow`) +- Express API with upload, ask (JSON), and streaming (SSE) endpoints +- Persisted hybrid vector + BM25 store (`.data/` namespace `pdf`) +- Integration with CometChat AI Agents (endpoint wiring) + +--- + +--- + +## How it works + +- Users upload PDF(s) → server parses pages → chunks + embeddings generated → persisted in vector + manifest store. +- Hybrid retrieval ranks candidate chunks: `score = α * cosine + (1-α) * sigmoid(BM25)` where `α = hybridAlpha`. +- Multi‑query expansion (optional) generates paraphrased variants to boost recall. +- Tools (`retrieve-pdf-context`, `retrieve-single-pdf-context`) return stitched context + source metadata. +- Workflow (`pdfWorkflow`) orchestrates retrieval + answer; streaming endpoints emit `meta` then incremental `token` events. +- Mastra agent(s) are exposed via REST endpoints you wire into CometChat AI Agents. + +--- + +## Repo layout (key files) + +- `src/mastra/agents/pdf-agent.ts` – multi‑PDF agent +- `src/mastra/agents/single-pdf-agent.ts` – single latest PDF agent +- `src/mastra/tools/retrieve-pdf-context.ts` / `retrieve-single-pdf-context.ts` – hybrid retrieval tools +- `src/mastra/workflows/pdf-workflow.ts` – deterministic orchestration +- `src/lib/*` – vector store, embeddings, manifest, PDF parsing +- `src/server.ts` – Express API (upload, ask, streaming, manifest ops) +- `docs/index.html` – optional static UI +- `.data/` – persisted vectors + manifest JSON + +--- + +## Prerequisites + +- Node.js 20+ +- `OPENAI_API_KEY` (embeddings + chat model) +- A CometChat app (to register the agent) +- (Optional) `CORS_ORIGIN` if restricting browser origins + +--- + +## Step 1 — Clone & install + +Clone the example and install dependencies: + +```bash +git clone https://github.com/cometchat/ai-agent-mastra-examples.git +cd ai-agent-mastra-examples/mastra-knowledge-agent-pdf +npm install +``` + +> Create a `.env` with at least: +> ```env +> OPENAI_API_KEY=sk-... +> PORT=3000 +> ``` + +--- + +## Step 2 — Define retrieval tools + +File: `src/mastra/tools/retrieve-pdf-context.ts` (multi) & `retrieve-single-pdf-context.ts` (single) + +```ts +import { createTool } from '@mastra/core/tools'; +import { z } from 'zod'; + +export const retrieverTool = createTool({ /* simplified example for tutorial brevity */ }); +``` + +--- + +## Step 3 — Create agents + +Files: `src/mastra/agents/pdf-agent.ts`, `src/mastra/agents/single-pdf-agent.ts` + +```ts +import { Agent } from '@mastra/core/agent'; +import { openai } from '@ai-sdk/openai'; +import { retrieverTool } from '../tools/retriever-tool'; + +export const pdfAgent = new Agent({ /* instruct to use retrieve-pdf-context, cite sources */ }); +export const singlePdfAgent = new Agent({ /* restrict answers to latest doc */ }); +``` + +--- + +## Step 4 — Wire Mastra & workflow + +File: `src/mastra/index.ts` registers agents + `pdfWorkflow` with storage (LibSQL or file‑backed). + +```ts +import { Mastra } from '@mastra/core/mastra'; +import { LibSQLStore } from '@mastra/libsql'; +import { knowledgeAgent } from './agents/knowledge-agent'; + +export const mastra = new Mastra({ /* agents, workflow, storage */ }); +``` + +Start the dev server: + +```bash +npm run dev +``` + +--- + +## Step 5 — Run locally + +```text + ┌──────────────┐ ┌──────────────┐ + │ Express API │ upload → │ PDF Parser │ + └──────┬───────┘ └──────┬───────┘ + │ chunks + embeddings │ + ▼ │ + ┌──────────────┐ upsert/search ┌──────────────┐ + │ Vector Store │◀───────────────▶│ Embeddings │ + └──────┬───────┘ └──────────────┘ + │ hybrid retrieve + ▼ + ┌──────────────┐ tool calls ┌────────────────────┐ + │ Mastra Agent │─────────────▶│ retrieve-* tools │ + └──────┬───────┘ └─────────┬──────────┘ + │ stitched context │ fallback + ▼ │ broaden + ┌──────────────┐ answer tokens (SSE) ┌──────────────┐ + │ Workflow │────────────────────▶│ Client │ + └──────────────┘ └──────────────┘ +``` + +--- + +## Step 6 — Upload and ask (API) + +| Agent | File | Purpose | Tool | +|-------|------|---------|------| +| `pdfAgent` | `src/mastra/agents/pdf-agent.ts` | Multi‑PDF retrieval QA | `retrieve-pdf-context` | +| `singlePdfAgent` | `src/mastra/agents/single-pdf-agent.ts` | Latest single PDF QA | `retrieve-single-pdf-context` | + +Tool input examples: + +```ts +// retrieve-pdf-context +{ query, docIds?, topK=5, hybridAlpha=0.7, multiQuery=true, qVariants=3, maxContextChars=4000 } + +// retrieve-single-pdf-context +{ query, docId?, topK=5, hybridAlpha=0.7, multiQuery=true, qVariants=3, maxContextChars=4000 } +``` + +Fallback widens search (higher `topK`, more `qVariants`) if initial context is sparse. + +--- + +--- + +### JSON ask (Mastra dev agent route) + +Mastra automatically exposes the API: + +```bash +curl -X POST http://localhost:4111/api/agents/knowledge/generate -H "Content-Type: application/json" -d '{"messages":[{"role":"user","content":"What is covered in our docs?"}]}' +``` + +Expected response: + +```json +{ + "reply": "The docs cover..." +} +``` + +--- + +## Step 7 — Deploy & connect to CometChat + +1. Deploy the project (e.g., Vercel, Railway, or AWS). +2. Copy the deployed endpoint URL. +3. In **CometChat Dashboard → AI Agents**, add a new agent: + - Agent ID: `knowledge` + - Endpoint: `https://your-deployed-url/api/agents/knowledge/generate` + +--- + +## Step 8 — Optimize & extend + +- Add more documents to the `docs/` folder. +- Use embeddings + vector DB (Pinecone, Weaviate) for large datasets. +- Extend the agent with memory or multi-tool workflows. + +--- + +## Repository Links + +--- + +## Environment variables + +| Name | Description | +|------|-------------| +| `OPENAI_API_KEY` | Required for embeddings + model | +| `CORS_ORIGIN` | Optional allowed browser origin | +| `PORT` | Server port (default 3000) | + +`.env` example: + +```env +OPENAI_API_KEY=sk-... +CORS_ORIGIN=http://localhost:3000 +PORT=3000 +``` + +--- + +## Endpoint summary + +| Method | Path | Description | +|--------|------|-------------| +| POST | `/api/upload` | Upload a PDF (multipart) returns `{ docId, pages, chunks }` | +| GET | `/api/documents` | List ingested documents | +| DELETE | `/api/documents/:id` | Delete a document + vectors | +| GET | `/api/documents/:id/file` | Stream stored original PDF | +| POST | `/api/ask` | Multi‑PDF retrieval + answer (JSON) | +| POST | `/api/ask/full` | Same as `/api/ask` (deterministic path) | +| POST | `/api/ask/stream` | Multi‑PDF streaming (SSE) | +| POST | `/api/ask/single` | Single latest PDF answer (JSON) | +| POST | `/api/ask/single/stream` | Single latest PDF streaming (SSE) | + +### Curl Examples + +Upload: +```bash +curl -X POST http://localhost:3000/api/upload \ + -H "Content-Type: multipart/form-data" \ + -F "file=@/path/to/file.pdf" +``` + +Ask (multi): +```bash +curl -X POST http://localhost:3000/api/ask \ + -H 'Content-Type: application/json' \ + -d '{"question":"Summarize the abstract","topK":6}' +``` + +Stream (multi): +```bash +curl -N -X POST http://localhost:3000/api/ask/stream \ + -H 'Content-Type: application/json' \ + -d '{"question":"List key methods","multiQuery":true}' +``` + +Ask (single): +```bash +curl -X POST http://localhost:3000/api/ask/single \ + -H 'Content-Type: application/json' \ + -d '{"question":"What are the main conclusions?"}' +``` + +Stream (single): +```bash +curl -N -X POST http://localhost:3000/api/ask/single/stream \ + -H 'Content-Type: application/json' \ + -d '{"question":"Give me an outline"}' +``` + +### SSE Events + +| Event | Payload | Notes | +|-------|---------|-------| +| `meta` | `{ sources, docId? }` | First packet with retrieval metadata | +| `token` | `{ token }` | Incremental answer token chunk | +| `done` | `{}` | Completion marker | +| `error` | `{ error }` | Error occurred | + +--- + +## Tuning & retrieval knobs + +| Parameter | Effect | Trade‑off | +|-----------|--------|----------| +| `hybridAlpha` | Higher = more semantic weight | Too high reduces keyword recall | +| `topK` | More chunks = broader context | Larger responses, slower | +| `multiQuery` | Recall across paraphrases | Extra model + embedding cost | +| `qVariants` | Alternative queries for expansion | Diminishing returns >5 | +| `maxContextChars` | Caps stitched context size | Too small omits evidence | + +Tip: For exploratory QA try `topK=8`, `qVariants=5`. + +--- + +## Troubleshooting & debugging + +- Enable internal logging (if available) to inspect scoring. +- Inspect vectors: open `.data/pdf-vectors.json`. +- Manifest corrupted? Delete `.data/manifest.json` and re‑upload. +- Low lexical relevance? Lower `hybridAlpha` (e.g. 0.55). +- Noise / irrelevant chunks? Reduce `topK` or lower `qVariants`. + +--- + +## Hardening & roadmap + +- SSE/WebSocket answer token streaming to clients (UI consumption) +- Source highlighting + per‑chunk confidence +- Semantic / layout‑aware advanced chunking +- Vector deduplication & compression +- Auth layer (API keys / JWT) & per‑user isolation +- Background ingestion queue for large docs +- Retrieval quality regression tests + +--- + +**Repository Links** + +- Source: GitHub Repository +- Multi agent: `pdf-agent.ts` +- Single agent: `single-pdf-agent.ts` +- Tools: `retrieve-pdf-context.ts`, `retrieve-single-pdf-context.ts` +- Workflow: `pdf-workflow.ts` +- Server: `server.ts` diff --git a/ai-agents/mastra-orchestrator-agent.mdx b/ai-agents/mastra-orchestrator-agent.mdx index 6f142140..f36f59d4 100644 --- a/ai-agents/mastra-orchestrator-agent.mdx +++ b/ai-agents/mastra-orchestrator-agent.mdx @@ -179,9 +179,9 @@ Ensure your public route: **`/api/agents/orchestratorAgent/generate`** is reacha --- -## Step 7 - Customize in Chat Builder +## Step 7 - Customize in UI Kit Builder - From AI Agents click the variant (or Get Started) to enter Chat Builder. + From AI Agents click the variant (or Get Started) to enter UI Kit Builder. Select Customize and Deploy. Theme, layout, features; ensure the Orchestrator agent is attached. Use live preview to validate routing and responses. @@ -191,10 +191,10 @@ Ensure your public route: **`/api/agents/orchestratorAgent/generate`** is reacha ## Step 8 - Integrate -Once your Orchestrator Agent is configured, you can integrate it into your app using the CometChat No Code - Widget: +Once your Orchestrator Agent is configured, you can integrate it into your app using the CometChat Widget Builder: - } description="Embed / script" href="/widget/ai-agents" horizontal /> + } description="Embed / script" href="/widget/ai-agents" horizontal /> } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components diff --git a/ai-agents/mastra.mdx b/ai-agents/mastra.mdx index d791d83c..746764b4 100644 --- a/ai-agents/mastra.mdx +++ b/ai-agents/mastra.mdx @@ -1,18 +1,14 @@ --- title: "Create an AI Agent with Mastra" sidebarTitle: "Create AI Agent" -description: "Connect a Mastra agent to CometChat, customize it with Chat Builder, and ship it as React UI Kit code or a Chat Widget." +description: "Connect a Mastra agent to CometChat, customize it with UI Kit Builder, and ship it as React UI Kit code or a Chat Widget." --- - -**Developer Preview**: AI Agents currently support **Mastra**. OpenAI, Agno, and other providers are coming soon. - - ## What you’ll build - A **Mastra** agent with tools/actions - The same agent **connected to CometChat** (Agent ID + Deployment URL) -- A **customized chat experience** using **Chat Builder** +- A **customized chat experience** using **UI Kit Builder** - An export to **React UI Kit code** _or_ **Chat Widget** for integration --- @@ -125,9 +121,9 @@ Navigate to **AI Agent → Get Started** and then **AI Agents → Add Agent**. Step 4 */} -## Step 4 - Customize in Chat Builder +## Step 4 - Customize in UI Kit Builder - From AI Agents click the variant (or Get Started) to enter Chat 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 & any tool triggers. @@ -148,7 +144,7 @@ Navigate to **AI Agent → Get Started** and then **AI Agents → Add Agent**. Choose how you’ll ship the experience (Widget or React UI Kit export). - } description="Embed / script" href="/widget/ai-agents" horizontal /> + } description="Embed / script" href="/widget/ai-agents" horizontal /> } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components @@ -156,7 +152,7 @@ Choose how you’ll ship the experience (Widget or React UI Kit export). Pick Chat Widget (fastest) or export React UI Kit for code-level customization. - Open Chat Builder → Get Embedded Code → copy script + credentials. + Open UI Kit Builder → Get Embedded Code → copy script + credentials. Export the variant as code (UI Kit) if you need deep theming or custom logic. Preview: the Mastra agent should appear without extra config. @@ -311,7 +307,7 @@ export default async function handler(req: VercelRequest, res: VercelResponse) { In AI Agents, ensure your Mastra agent shows Enabled. - Open Chat Builder and start a preview session. + Open UI Kit Builder and start a preview session. Send a message; confirm the agent responds. Trigger a Frontend Action and verify your UI handles the tool call. @@ -340,3 +336,12 @@ export default async function handler(req: VercelRequest, res: VercelResponse) { +{/* ## Next Steps + + + + Define and handle custom frontend actions your AI agent can invoke. + + Create and manage tools your AI agent can use to enhance conversations. + + */} \ No newline at end of file diff --git a/ai-agents/vercel-knowledge-agent.mdx b/ai-agents/vercel-knowledge-agent.mdx new file mode 100644 index 00000000..35b6e9ed --- /dev/null +++ b/ai-agents/vercel-knowledge-agent.mdx @@ -0,0 +1,219 @@ +--- +title: "Build Your Knowledge Agent with Vercel AI SDK" +sidebarTitle: "Knowledge Agent" +description: "Create a Vercel AI SDK knowledge agent that ingests docs, streams grounded answers with citations, and connects to CometChat." +--- + +Imagine an Express service that indexes your docs, streams precise answers with citations, and plugs into CometChat so teams can summon it mid-conversation without losing context. + +*** + +## What You'll Build + +* A **Vercel AI SDK** agent that joins conversations as a documentation expert. +* A repeatable ingestion pipeline that writes sources into `knowledge/`. +* Retrieval and answer generation that stay grounded in stored snippets and cite sources. +* A streaming `/agent` endpoint that converts Vercel AI SDK chunks into CometChat events via `@cometchat/vercel-adapter`. + +*** + +## Prerequisites + +* Node.js 18 or newer. +* OpenAI API key available locally (e.g., `.env` with `OPENAI_API_KEY`). +* A CometChat app with access to the **AI Agents** dashboard. +* curl or an API client to call the Express endpoints. + +*** + +## Quick links + +- Repo root: [ai-agent-vercel-examples](https://github.com/cometchat/ai-agent-vercel-examples) +- Project folder: [vercel-knowledge-agent](https://github.com/cometchat/ai-agent-vercel-examples/tree/main/vercel-knowledge-agent) +- Server guide: [agent/README.md#run-the-server](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/README.md#run-the-server) +- API reference: [agent/README.md#apis](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/README.md#apis) +- Adapter: [`@cometchat/vercel-adapter` on npm](https://www.npmjs.com/package/@cometchat/vercel-adapter) +- Sample knowledge: [agent/knowledge/default](https://github.com/cometchat/ai-agent-vercel-examples/tree/main/vercel-knowledge-agent/agent/knowledge) + +*** + +## How it works + +This example builds a retrieval-augmented assistant around the Vercel AI SDK: + +- **Ingest** - `POST /api/tools/ingest` accepts URLs, markdown, plain text, or file uploads. Content is converted to markdown, deduplicated by hash, and stored under `knowledge/`. Limits enforce 6 MB per file and 200 kB per text snippet. +- **Store** - `lib/knowledge/storage.js` resolves the knowledge root (override with `KNOWLEDGE_DIR`), enforces namespace patterns, and exposes helpers for listing and reading documents. +- **Retrieve** - `lib/knowledge/retrieve.js` tokenizes the query, ranks markdown files lexically, and returns excerpts plus filenames for citations. Requests default to the `default` namespace unless a different one is supplied. +- **Answer** - `lib/knowledge/agent.js` wires the `docsRetriever` tool into an `Experimental_Agent`, forcing a retrieval call before every response and appending a "Sources:" footer. `routes/agent.js` wraps `streamText` and uses `@cometchat/vercel-adapter` to stream Server-Sent Events (SSE) that CometChat consumes. + +*** + +## Setup + + + + Clone the repo, then run npm install inside vercel-knowledge-agent/agent. + + + Create .env with OPENAI_API_KEY. Optional knobs: PORT (default 3000), OPENAI_MODEL, TEMPERATURE, and KNOWLEDGE_DIR. + + + Launch with npm start. The Express app loads environment variables via bin/www and exposes APIs at http://localhost:3000. + + + Call POST /api/tools/ingest with a namespace, sources array, and/or multipart uploads. Responses report saved, skipped, and per-source errors. + + + Use POST /api/tools/searchDocs to verify retrieval scoring before enabling the agent. + + + Send messages to POST /api/agents/knowledge/generate. Include toolParams.namespace to target a specific knowledge folder. + + + Point CometChat at the /agent endpoint for SSE streaming once you are ready to integrate. + + + +*** + +## Project Structure + +- Environment & config + - [agent/README.md](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/README.md) + - [agent/package.json](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/package.json) + - [agent/bin/www](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/bin/www) +- Express & routing + - [agent/app.js](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/app.js) + - [agent/routes/knowledge.js](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/routes/knowledge.js) + - [agent/routes/agent.js](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/routes/agent.js) +- Knowledge pipeline + - [agent/lib/knowledge/ingest.js](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/lib/knowledge/ingest.js) + - [agent/lib/knowledge/retrieve.js](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/lib/knowledge/retrieve.js) + - [agent/lib/knowledge/storage.js](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/lib/knowledge/storage.js) +- Agent logic + - [agent/lib/knowledge/agent.js](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/lib/knowledge/agent.js) + - [agent/routes/agent.js](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/routes/agent.js) +- Samples & front-end + - [agent/knowledge/default](https://github.com/cometchat/ai-agent-vercel-examples/tree/main/vercel-knowledge-agent/agent/knowledge) + - [web/index.html](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/web/index.html) + +*** + +## Step 1 - Configure the Knowledge Agent + +**`agent/lib/knowledge/agent.js`** ([view in repo](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/lib/knowledge/agent.js)): + +- Registers a `docsRetriever` tool that defaults to the active namespace and caps results at 20. +- Hard-requires `OPENAI_API_KEY` before creating the `Experimental_Agent`. +- Sets the system prompt so every reply triggers retrieval, stays grounded, and cites sources (for example, `Sources: getting-started.md`). +- Honors `OPENAI_MODEL` and `TEMPERATURE` through the Express layer (`routes/agent.js`), so you can tune behaviour without code changes. + +*** + +## Step 2 - Expose Knowledge APIs + +**`agent/routes/knowledge.js`** ([view in repo](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/routes/knowledge.js)): + +- `POST /api/tools/ingest` handles JSON or multipart payloads, converts PDFs and HTML to markdown, deduplicates by content hash, and reports detailed counts. +- `POST /api/tools/searchDocs` validates namespace plus query, returning ranked excerpts and warnings for unreadable files. +- `POST /api/agents/knowledge/generate` sanitizes messages, composes a chat prompt, and returns the agent's grounded answer plus tool call traces. + +Supporting modules: + +- [`ingest.js`](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/lib/knowledge/ingest.js) - normalization, dedupe, PDF parsing, slug management. +- [`retrieve.js`](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/lib/knowledge/retrieve.js) - lexical scoring, excerpt creation, namespace fallbacks. +- [`storage.js`](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/vercel-knowledge-agent/agent/lib/knowledge/storage.js) - namespace validation and filesystem helpers (override the root with `KNOWLEDGE_DIR`). + +*** + +## Step 3 - Run the Server Locally + +Expected base URL: `http://localhost:3000` + + + + npm install inside agent/ (already covered in Setup if you completed it once). + + + Run npm start. Logs appear on stdout; bin/www loads .env before binding the port. + + + POST to /api/tools/ingest using JSON or multipart examples from the README. + + + POST to /api/tools/searchDocs and confirm excerpts plus filenames look correct. + + + POST to /api/agents/knowledge/generate with a messages array. Include toolParams.namespace to target non-default folders. + + + For CometChat testing, POST the same payload to /agent and consume the SSE stream (curl example is in the README under APIs). + + + +Key endpoints: + +- POST `/api/tools/ingest` - add docs into `knowledge/` +- POST `/api/tools/searchDocs` - retrieve ranked snippets plus citations +- POST `/api/agents/knowledge/generate` - non-streaming chat responses +- POST `/agent` - SSE stream compatible with `@cometchat/vercel-adapter` + +*** + +## Step 4 - Deploy the API + +- Keep `/api/agents/knowledge/generate` and `/agent` reachable over HTTPS. +- Store secrets (`OPENAI_API_KEY`, optional `OPENAI_MODEL`, `TEMPERATURE`, `KNOWLEDGE_DIR`) in your hosting provider's secret manager. +- Re-run ingestion whenever docs change; the dedupe logic skips unchanged content. + +*** + +## Step 5 - Configure in CometChat + + + Sign in at app.cometchat.com. + Choose your app → AI Agents. + Set Provider=Vercel AI SDK, choose an Agent ID (for example, knowledge), and paste the public /agent URL. + If your Express service expects auth headers, add them as JSON under Headers. + Save and ensure the toggle shows Enabled. + + +> The server auto-imports additional tools provided by CometChat, so you can layer chat actions on top of the docs retriever without changing backend code. + +--- + +## Step 6 - Customize in UI Kit Builder + + From AI Agents select your new agent to open UI Kit Builder. + Choose Customize and Deploy. + Theme, layout, behaviour - verify the Vercel Knowledge agent is attached to the variant. + Use live preview to test retrieval answers and any frontend actions. + + + + + + +--- + +## Step 7 - Integrate + +Once your agent is connected, embed it wherever users need doc answers: + + + } description="Embed / script" href="/widget/ai-agents" horizontal /> + } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components + + +> The knowledge agent you configured above is part of the exported configuration - no extra glue code required. + +--- + +## Step 8 - Test Your Setup + + + POST to /api/agents/knowledge/generate and confirm the response ends with Sources:. + Stream the same payload to /agent; events should include threadId, runId, and partial deltas. + Switch toolParams.namespace and verify documents load from the matching folder. + In CometChat → AI Agents, ensure your Vercel agent toggle remains ON. + diff --git a/ai-agents/vercel-product-hunt-agent.mdx b/ai-agents/vercel-product-hunt-agent.mdx new file mode 100644 index 00000000..cfde4d8a --- /dev/null +++ b/ai-agents/vercel-product-hunt-agent.mdx @@ -0,0 +1,204 @@ +--- +title: "Build a Product Hunt Agent with Vercel AI SDK" +sidebarTitle: "Product Hunt Agent" +description: "Create a Vercel AI SDK agent that fetches Product Hunt data, celebrates launches with confetti, and connects to CometChat." +--- + +Give your Product Hunt launch conversations real-time superpowers: fetch live rankings, search the catalog, answer launch questions, and trigger a confetti action your frontend can render instantly—all from a Vercel AI SDK agent that streams into CometChat. + +--- + +## Quick links + +- Repo: [ai-agent-vercel-examples/product-hunt-agent](https://github.com/cometchat/ai-agent-vercel-examples/tree/main/product-hunt-agent) +- Express app guide: [agent/README.md](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/product-hunt-agent/agent/README.md) +- Agent definition: [agent/lib/producthunt/agent.js](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/product-hunt-agent/agent/lib/producthunt/agent.js) +- Product Hunt services: [agent/lib/producthunt/services.js](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/product-hunt-agent/agent/lib/producthunt/services.js) +- Sample UI: [web/index.html](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/product-hunt-agent/web/index.html) + +--- + +## What you’ll build + +- A **Vercel AI SDK** `Experimental_Agent` that can: + - Pull top Product Hunt posts (all-time or timeframe aware) + - Search posts via Product Hunt’s public Algolia index + - Offer practical launch guidance grounded in tool output + - Emit a `CONFETTI` action payload for your frontend +- An Express API exposing `/api/top*`, `/api/search`, `/api/chat`, and a streaming `/agent` endpoint adapted for CometChat +- A Product Hunt–inspired static page that mounts the CometChat widget and handles the confetti tool + +--- + +## Prerequisites + +- Node.js 18 or newer +- Environment variables: + - `OPENAI_API_KEY` (required for all chat routes) + - `PRODUCTHUNT_API_TOKEN` (GraphQL token; endpoints return empty arrays if omitted) + - Optional: `OPENAI_MODEL` (defaults `gpt-4o-mini`), `TEMPERATURE` (defaults `0.7`), `PORT` (defaults `3000`) +- A CometChat app to host the agent/chat widget + +--- + +## How it works + +- `agent/lib/producthunt/agent.js` wires a Vercel AI SDK `Experimental_Agent` with four tools: `getTopProducts`, `getTopProductsByTimeframe`, `searchProducts`, and `triggerConfetti`. +- `agent/lib/producthunt/services.js` calls Product Hunt’s GraphQL API (with optional token), parses natural-language timeframes, and queries Algolia for search. +- `agent/routes/producthunt.js` exposes REST endpoints with JSON responses and permissive CORS for local development. +- `agent/routes/agent.js` converts CometChat payloads to Vercel AI SDK messages via `@cometchat/vercel-adapter`, streams Server-Sent Events (SSE), and merges any extra tools you forward. +- `web/index.html` mounts the CometChat Chat Embed, calls your API for leaderboard data, and executes the confetti action using `canvas-confetti` (with a fallback renderer when the CDN is unavailable). + +--- + +## Step 1 — Define Product Hunt tools + +File: [`agent/lib/producthunt/agent.js`](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/product-hunt-agent/agent/lib/producthunt/agent.js) + +- `getTopProducts` returns top posts by votes (1–10 items, default 3). +- `getTopProductsByTimeframe` accepts timeframes like `today`, `yesterday`, `this-week`, `YYYY-MM-DD`, or ranges (`from:2024-08-01 to:2024-08-15`), plus optional timezone and limit. +- `searchProducts` wraps Product Hunt’s public Algolia index and clamps results (1–50). +- `triggerConfetti` emits a structured payload (colors, particleCount, spread, origin, etc.) that your UI can interpret as an action. +- Helper utilities sanitize limits, build Markdown tables, and ensure empty results are handled gracefully. + +--- + +## Step 2 — Instantiate the agent + +Also in [`agent/lib/producthunt/agent.js`](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/product-hunt-agent/agent/lib/producthunt/agent.js): + +- `createProductHuntAgent()` asserts `OPENAI_API_KEY` before constructing an `Experimental_Agent`. +- System prompt (`buildSystemPrompt`) reminds the model when to call each tool, to summarise results as Markdown tables, and to fire confetti when users celebrate. +- Default model is `gpt-4o`, but you can override by passing `{ model: 'gpt-4o-mini' }` or setting `OPENAI_MODEL`. +- The agent returns both text and `toolResults`, letting the REST API surface raw data alongside the response. + +--- + +## Step 3 — Expose REST & streaming endpoints + +Files: + +- [`agent/app.js`](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/product-hunt-agent/agent/app.js) +- [`agent/routes/producthunt.js`](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/product-hunt-agent/agent/routes/producthunt.js) +- [`agent/routes/agent.js`](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/product-hunt-agent/agent/routes/agent.js) + +Highlights: + +- `GET /api/health` confirms the service. +- `GET /api/top`, `/api/top-week`, and `/api/top-range` return leaderboard JSON based on votes, rolling windows, or natural-language timeframes. +- `GET /api/search?q=...` performs Algolia-backed lookup with clamped limits and helpful validation errors. +- `POST /api/chat` accepts `{ message }` or `{ messages: [...] }` and responds with `{ reply, toolResults, usage }`. +- `POST /agent` streams SSE events that already match CometChat’s expectations (`text_message`, `tool_call_start`, `tool_call_result`, etc.), courtesy of `mapVercelStreamChunkToCometChatEvent`. +- Tool preferences such as timeframe, timezone, or limit can be supplied via `toolParams` in the SSE payload and are woven into the system prompt for that run. + +--- + +## Step 4 — Run locally + +1. Install deps: + ```bash + cd product-hunt-agent/agent + npm install + ``` +2. Create `.env` (or export vars): + ```bash + OPENAI_API_KEY=sk-... + PRODUCTHUNT_API_TOKEN=phc_... + PORT=3000 + ``` +3. Start the server: + ```bash + npm start + ``` +4. Open `http://localhost:3000` to view the default Jade page, or load `web/index.html` via a static server pointing `window.PH_AGENT_API` to `http://localhost:3000`. + +--- + +## Step 5 — Handle frontend actions + +File: [`web/index.html`](https://github.com/cometchat/ai-agent-vercel-examples/blob/main/product-hunt-agent/web/index.html) + +- Mounts CometChat Chat Embed and logs a demo user. +- Provides helper functions to fetch `/api/top-range` and render Product Hunt-style cards. +- Implements `actions.triggerConfetti` that lazily loads `canvas-confetti` (with a fallback canvas animation) and respects the agent’s payload (colors, particle count, etc.). +- Use this file as a reference when wiring confetti handlers into your own widget or UI Kit export. + +--- + +## Step 6 — API overview + +- `GET /api/health` → `{ ok: true }` +- `GET /api/top?limit=3` → top posts by votes +- `GET /api/top-week?limit=3&days=7` → rolling window ranking +- `GET /api/top-range?timeframe=today&tz=America/New_York&limit=3` → timeframe ranking + metadata +- `GET /api/search?q=notion&limit=10` → Algolia results +- `POST /api/chat` with `{ "message": "What should I prep before launch?" }` → `{ reply, toolResults }` +- `POST /agent` (SSE) → CometChat-compatible events for streaming responses and tool traces + +Example stream call: + +```bash +curl -N http://localhost:3000/agent \ + -H "Content-Type: application/json" \ + -d '{ + "threadId": "chat_123", + "messages": [ + { "role": "user", "content": "Show today\u0027s top Product Hunt launches and celebrate them." } + ], + "toolParams": { + "timeframe": "today", + "timezone": "America/New_York", + "limit": 3 + } + }' +``` + +--- + +## Step 7 — Deploy + +- Deploy the Express app (Node.js 18+) to your platform of choice (Vercel, Render, Fly.io, Railway, etc.). +- Set `OPENAI_API_KEY`, `PRODUCTHUNT_API_TOKEN`, `OPENAI_MODEL`, and `TEMPERATURE` as environment variables. +- Expose the streaming `/agent` endpoint over HTTPS (required by CometChat) and keep CORS permissive or scoped to your domains. +- Host the static Product Hunt UI (optional) on any CDN or static site host; point `window.PH_AGENT_API` to the deployed backend. + +--- + +## Step 8 — Connect in CometChat + +- Dashboard → your App → **AI Agents → Add Agent** +- Provider: **Vercel AI SDK** +- Agent ID: match the ID you’ll reference in your UI (e.g., `producthunt`) +- Deployment URL: `https://your-domain.tld/agent` +- Optional: add greetings, suggested prompts such as “Celebrate today’s top 3 Product Hunt launches,” and map frontend actions to the `triggerConfetti` handler. +- Save and toggle the agent to **Enabled**. + +--- + +## Step 9 — Test + +- Hit `/api/health` to confirm the service. +- Verify `/api/search?q=linear&limit=5` returns data (Algolia key is bundled). +- Call `/api/top-range?timeframe=today` to ensure the Product Hunt token works (expect empty arrays if the token is missing). +- Use the curl stream above and confirm CometChat renders partial replies plus the confetti action. +- In UI Kit Builder or your widget, send “Throw confetti for our launch” and verify the handler fires. + +--- + +## Security & production checklist + +- Keep `OPENAI_API_KEY` and `PRODUCTHUNT_API_TOKEN` server-side only; never expose them in the browser or widget exports. +- Add authentication (API key/JWT) and tighten CORS once deployed. +- Rate-limit `/agent` and `/api/top*` endpoints; clamp user-provided limits to sane values (already partially enforced in code). +- Log errors and tool usage without storing sensitive content; monitor for failed API calls so you can refresh credentials. +- For long-lived deployments, handle Product Hunt API quota/burst limits gracefully (retry with backoff, cache top results). + +--- + +## Troubleshooting + +- **`/api/top*` returns empty arrays**: ensure `PRODUCTHUNT_API_TOKEN` is set and valid. +- **Algolia search empty**: check outbound network access and confirm you didn’t hit rate limits. +- **Chat replies lack tables**: confirm tool calls succeed (inspect `toolResults` or server logs); the agent falls back to narrative answers if no posts are returned. +- **Confetti never fires**: double-check the action name (`triggerConfetti`) and that your handler loads `canvas-confetti` or provides a fallback. +- **SSE disconnects immediately**: verify your reverse proxy supports streaming and that `Cache-Control: no-cache` headers are preserved. diff --git a/ai-agents/vercel.mdx b/ai-agents/vercel.mdx new file mode 100644 index 00000000..4b04aeb7 --- /dev/null +++ b/ai-agents/vercel.mdx @@ -0,0 +1,430 @@ +--- +title: "Create an AI Agent with Vercel AI SDK" +sidebarTitle: "Create AI Agent" +description: "Connect a Vercel AI SDK agent to CometChat, customize it with UI Kit Builder, and ship it as React UI Kit code or a Chat Widget." +--- + +## What you’ll build + +- A **Vercel AI SDK** agent with streaming + tools +- The same agent **connected to CometChat** (Agent ID + Deployment URL) +- A **customized chat experience** using **UI Kit Builder** +- An export to **React UI Kit code** _or_ **Chat Widget** for integration + +--- + +## Prerequisites + +- A CometChat account and an app: **[Create App](https://app.cometchat.com/apps)** +- A Vercel AI SDK agent (HTTP endpoint) plus the adaptor package: + **[`vercel-cometchat-adaptor`](https://www.npmjs.com/package/@cometchat/vercel-adapter)** +- Node.js environment with: `ai`, `@ai-sdk/openai`, `zod`, and Express (or another HTTP framework) + +--- + +## Step 1 - Create your CometChat app + + + + Sign in at app.cometchat.com. Create a new app or open an existing one. + + + Note your App ID, Region, and Auth Key (needed if you export the Chat Widget later). + + + +--- + +## Step 2 - Connect your Vercel AI SDK Agent + +Navigate to **AI Agent → Get Started** and then **AI Agents → Add Agent**. + + + + Select **Vercel AI SDK**. + + + Provide: + - **Name** and optional **Icon** + - (Optional) **Greeting** and **Introductory Message** + - (Optional) **Suggested messages** + + + Paste/define: + - **Agent ID** — a unique handle that matches how you route traffic (e.g., support). + - **Deployment URL** — the public HTTPS endpoint that receives CometChat requests. + - (Optional) **Headers** — JSON auth headers that your endpoint expects. + + + Click **Save**, then ensure the agent’s toggle is **ON** in the **AI Agents** list. + + + +> **Tip:** The vercel-cometchat-adaptor handles conversion between CometChat events and the Vercel AI SDK. Keep the **Agent ID** and **Deployment URL** stable so you don’t need to reconnect. + +--- + +## Step 3 - Define Frontend Actions (Optional) + + + + Go to AI Agent → Actions and click Add to create a frontend action your agent can call (e.g., “Open Product,” “Start Demo,” “Book Slot”). + + + Include: +
    +
  • Display Name — Shown to users (e.g., “Open Product Page”).
  • +
  • Execution Text — How the agent describes running it (e.g., “Opening product details for the user.”).
  • +
  • Name — A unique, code-friendly key (e.g., open_product).
  • +
  • Description — What the tool does and when to use it.
  • +
  • Parameters — JSON Schema describing inputs (the agent will fill these).
  • +
+
+ + Example parameters JSON: + +```json +{ + "type": "object", + "required": ["productId"], + "properties": { + "productId": { + "type": "string", + "description": "The internal product ID to open" + }, + "utm": { + "type": "string", + "description": "Optional tracking code" + } + } +} +``` + + + At runtime, listen for tool calls and execute them client-side (e.g., route changes, modals, highlights). + +
+ +--- + +## Step 4 - Customize in UI Kit Builder + + From AI Agents click the variant (or Get Started) to enter UI Kit Builder. + Select Customize and Deploy. + Update theme, layout, and features; confirm the Vercel agent is attached. + Use live preview to validate responses & any tool triggers. + + + + + + +--- + +## Step 5 - Export & Integrate + +Choose how you’ll ship the experience (Widget or React UI Kit export). + + + } description="Embed / script" href="/widget/ai-agents" horizontal /> + } href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components + + +> The Vercel AI SDK agent from Step 2 is included automatically in exported variants—no extra code needed for basic conversations. + + + Pick Chat Widget (fastest) or export React UI Kit for code-level customization. + Open UI Kit Builder → Get Embedded Code → copy script + credentials. + Export the variant as code (UI Kit) if you need deep theming or custom logic. + Preview: the Vercel agent should appear without extra config. + + +--- + +## Step 6 - Deploy & Secure (Reference) + + +Need a public Vercel AI SDK agent? Use these reference blocks to define, expose, and deploy one securely. + + + + + +```ts +// vercel/agent.ts +import { streamText, stepCountIs, tool } from "ai"; +import { openai } from "@ai-sdk/openai"; +import { z } from "zod"; + +const weatherTool = tool({ + description: "Get a simple temperature estimate for a location", + inputSchema: z.object({ + location: z.string().describe("City or region to check"), + }), + outputSchema: z.object({ + location: z.string(), + temperature: z.number(), + }), + execute: async ({ location }) => { + // Replace with a real data source; this is a stub. + return { + location, + temperature: 72 + Math.floor(Math.random() * 10) - 5, + }; + }, +}); + +export async function runVercelAgent({ + messages, + tools = {}, +}: { + messages: any[]; + tools?: Record; +}) { + return streamText({ + model: openai("gpt-4o-mini"), + stopWhen: stepCountIs(100), + messages, + tools: { + weather: weatherTool, + ...tools, + }, + }); +} +``` + + + + + +```ts +// server.ts +import express from "express"; +import cors from "cors"; +import bodyParser from "body-parser"; +import { + convertCometChatMessagesToVercelMessages, + convertCometChatToolsToVercelAISDKTools, + mapVercelStreamChunkToCometChatEvent, +} from "vercel-cometchat-adaptor"; +import { runVercelAgent } from "./vercel/agent"; + +const app = express(); +const port = process.env.PORT || 4000; + +app.use(cors()); +app.use(bodyParser.json()); + +app.post("/agent/vercel", async (req, res) => { + try { + const cometChatTools = Array.isArray(req.body.tools) + ? convertCometChatToolsToVercelAISDKTools(req.body.tools) + : {}; + + const messages = convertCometChatMessagesToVercelMessages(req.body.messages); + if (!Array.isArray(messages) || messages.length === 0) { + return res.status(400).json({ error: "Invalid request" }); + } + + res.setHeader("Content-Type", "text/event-stream"); + res.setHeader("Cache-Control", "no-cache"); + res.setHeader("Connection", "keep-alive"); + + const runId = req.body.runId || `run_${Date.now()}`; + const threadId = req.body.threadId || "thread_1"; + + const stream = await runVercelAgent({ messages, tools: cometChatTools }); + + for await (const chunk of stream.fullStream) { + const events = mapVercelStreamChunkToCometChatEvent(chunk); + for (const event of events) { + event.runId = runId; + event.threadId = threadId; + event.timestamp = event.timestamp || Date.now(); + res.write(`data: ${JSON.stringify(event)}\n\n`); + } + } + + res.end(); + } catch (error) { + console.error(error); + res.write( + `data: ${JSON.stringify({ + type: "error", + message: "Agent processing failed", + timestamp: Date.now(), + })}\n\n` + ); + res.end(); + } +}); + +app.listen(port, () => { + console.log(`Server running at http://localhost:${port}/agent/vercel`); +}); +``` + + + + +```js +// server.js +const express = require("express"); +const cors = require("cors"); +const bodyParser = require("body-parser"); +const { + convertCometChatMessagesToVercelMessages, + convertCometChatToolsToVercelAISDKTools, + mapVercelStreamChunkToCometChatEvent, +} = require("vercel-cometchat-adaptor"); +const { runVercelAgent } = require("./vercel/agent"); + +const app = express(); +const port = process.env.PORT || 4000; + +app.use(cors()); +app.use(bodyParser.json()); + +app.post("/agent/vercel", async (req, res) => { + try { + const cometChatTools = Array.isArray(req.body.tools) + ? convertCometChatToolsToVercelAISDKTools(req.body.tools) + : {}; + + const messages = convertCometChatMessagesToVercelMessages(req.body.messages); + if (!Array.isArray(messages) || messages.length === 0) { + return res.status(400).json({ error: "Invalid request" }); + } + + res.setHeader("Content-Type", "text/event-stream"); + res.setHeader("Cache-Control", "no-cache"); + res.setHeader("Connection", "keep-alive"); + + const runId = req.body.runId || `run_${Date.now()}`; + const threadId = req.body.threadId || "thread_1"; + + const stream = await runVercelAgent({ messages, tools: cometChatTools }); + + for await (const chunk of stream.fullStream) { + const events = mapVercelStreamChunkToCometChatEvent(chunk); + for (const event of events) { + event.runId = runId; + event.threadId = threadId; + event.timestamp = event.timestamp || Date.now(); + res.write(`data: ${JSON.stringify(event)}\n\n`); + } + } + + res.end(); + } catch (error) { + console.error(error); + res.write( + `data: ${JSON.stringify({ + type: "error", + message: "Agent processing failed", + timestamp: Date.now(), + })}\n\n` + ); + res.end(); + } +}); + +app.listen(port, () => { + console.log(`Server running at http://localhost:${port}/agent/vercel`); +}); +``` + + + + + +

Local Development

+
    +
  1. npm install to pull dependencies (including vercel-cometchat-adaptor).
  2. +
  3. npm run dev (or vercel dev) to start the local server.
  4. +
+

Quick test against the Express route:

+```bash +curl -N -X POST http://localhost:4000/agent/vercel \ + -H "Content-Type: application/json" \ + -d '{"messages":[{"role":"user","content":"Say hi"}]}' +``` +

Temporary Public Tunnel

+```bash +ngrok http 4000 +cloudflared tunnel --url http://localhost:4000 +loca.lt --port 4000 +``` +

Append route (e.g. /agent/vercel) to the forwarded HTTPS URL.

+

Production Patterns

+
    +
  • Serverless: Convert the route to a Vercel /api handler or edge function.
  • +
  • Container: Run the Express app in Docker; add health checks.
  • +
  • Edge: Use @vercel/edge runtime and keep tools stateless.
  • +
+

Security

+
    +
  • Rate limit by IP + user.
  • +
  • Add auth (Bearer / JWT) for private agents.
  • +
  • Log tool calls (id, latency) for observability.
  • +
+

CometChat Mapping

+

Use the final HTTPS URL + path for Deployment URL. Reuse the same string you configured in code as the Agent ID.

+
+ + Deploy (Vercel, Render, Fly, etc.) then copy the public URL as your Deployment URL and confirm the Agent ID used in code. +
+
+ Docs: https://sdk.vercel.ai/docs +
+
+ +--- + +## Test your setup + + + In AI Agents, ensure your Vercel agent shows Enabled. + Open UI Kit Builder and start a preview session. + Send a message; confirm the agent streams responses. + Trigger a Frontend Action and verify your UI handles the tool call. + + +--- + +## Troubleshooting + + + +
    +
  • Verify your Deployment URL is publicly reachable and returns text/event-stream.
  • +
  • Check server logs for runtime errors or missing environment variables.
  • +
+
+ +
    +
  • Confirm the Action’s Name in CometChat exactly matches the tool name your UI listens for.
  • +
  • Validate the Parameters JSON Schema; the agent uses this to fill inputs.
  • +
+
+ +
    +
  • Use authKey only for development. For production, implement a secure token flow for user login.
  • +
+
+
+ +--- + +By combining the **CometChat Agentic Interface** with the **Vercel AI SDK**, you can connect intelligent agents with end users instantly and securely. +The vercel-cometchat-adaptor library simplifies message and event translation, creating a reliable bridge between CometChat and Vercel-powered AI systems. + +{/* ## Next Steps + + + + Define and handle custom frontend actions your AI agent can invoke. + + Create and manage tools your AI agent can use to enhance conversations. + + */} \ No newline at end of file diff --git a/assets/navigation.js b/assets/navigation.js index 711baff9..d15bcb46 100644 --- a/assets/navigation.js +++ b/assets/navigation.js @@ -9,7 +9,13 @@ function isHome(pathname) { if (!pathname) pathname = location.pathname; - return pathname === '/' || pathname === '/docs' || pathname === '/docs/' || pathname === '/index' || pathname === '/index.html'; + return pathname === '/' || + pathname === '/docs' || + pathname === '/docs/' || + pathname === '/index' || + pathname === '/index.html' || + pathname === '/home' || + pathname === '/docs/home'; } function setHtmlFlags() { diff --git a/chat-apis.json b/chat-apis.json index a0905001..5cc1cecb 100644 --- a/chat-apis.json +++ b/chat-apis.json @@ -2457,6 +2457,14 @@ "schema": { "type": "integer" } + }, + { + "name": "hideQuotedMessages", + "in": "query", + "description": "If set to true, the API response will exclude all quotedMessage nodes from the returned messages. This allows clients to fetch only the messages without any quoted messages.", + "schema": { + "type": "boolean" + } } ], "responses": { @@ -8001,6 +8009,14 @@ "type": "string" } } + }, + { + "name": "hideQuotedMessages", + "in": "query", + "description": "If set to true, the API response will exclude all quotedMessage nodes from the returned messages. This allows clients to fetch only the messages without any quoted messages.", + "schema": { + "type": "boolean" + } } ], "responses": { @@ -8471,6 +8487,14 @@ "type": "string" } } + }, + { + "name": "hideQuotedMessages", + "in": "query", + "description": "If set to true, the API response will exclude all quotedMessage nodes from the returned messages. This allows clients to fetch only the referenced messages without any quoted messages.", + "schema": { + "type": "boolean" + } } ], "responses": { @@ -16097,6 +16121,14 @@ "custom" ] }, + "quotedMessageId": { + "description": "ID of the message being quoted.\nIf provided, the send message response will include a `quotedMessage` node\nin the response containing the referenced message object.", + "type": "string", + "default": "message", + "enum": [ + "message" + ] + }, "type": { "description": "Type of the message.", "type": "string" @@ -17116,6 +17148,14 @@ "message" ] }, + "quotedMessageId": { + "description": "ID of the message being quoted.\nIf provided, the send message response will include a `quotedMessage` node\nin the response containing the referenced message object.", + "type": "string", + "default": "message", + "enum": [ + "message" + ] + }, "type": { "description": "Type of the message. The available values are text, image, file, audio, video.", "type": "string", diff --git a/chat-builder/android/integration.mdx b/chat-builder/android/integration.mdx index 4fbacfb7..c209ae91 100644 --- a/chat-builder/android/integration.mdx +++ b/chat-builder/android/integration.mdx @@ -1,9 +1,9 @@ --- -title: "Getting Started With Chat Builder" +title: "Getting Started With UI Kit Builder" sidebarTitle: "Integration" --- -Chat Builder streamlines integrating CometChat’s Android UI Kit into your app. Design the experience visually, export platform‑ready assets and settings, and wire them into your Android project with a few steps. +UI Kit Builder streamlines integrating CometChat’s Android UI Kit into your app. Design the experience visually, export platform‑ready assets and settings, and wire them into your Android project with a few steps. @@ -11,7 +11,7 @@ Chat Builder streamlines integrating CometChat’s Android UI Kit into your app. ## Complete Integration Workflow -1. Design your chat experience in Chat Builder. +1. Design your chat experience in UI Kit Builder. 2. Export your code and settings package. 3. Enable extra features in the CometChat Dashboard if needed. 4. Optionally preview the experience in a sample app. @@ -20,11 +20,11 @@ Chat Builder streamlines integrating CometChat’s Android UI Kit into your app. *** -## Launch the Chat Builder +## Launch the UI Kit Builder 1. Log in to your CometChat Dashboard: https://app.cometchat.com 2. Select your application. -3. Go to Integrate → Android → Launch Chat Builder. +3. Go to Integrate → Android → Launch UI Kit Builder. *** @@ -52,7 +52,7 @@ How to enable: *** -## Integration with CometChat Chat Builder (Android) +## Integration with CometChat UI Kit Builder (Android) Follow these steps in your existing Android app (from README): diff --git a/chat-builder/android/overview.mdx b/chat-builder/android/overview.mdx index 966faf75..828ac788 100644 --- a/chat-builder/android/overview.mdx +++ b/chat-builder/android/overview.mdx @@ -59,7 +59,7 @@ Choose one of the following paths to integrate: ## Try Live Demo -Experience the CometChat Builder in action: +Experience the CometChat UI Kit Builder in action: @@ -75,7 +75,7 @@ href="https://preview.cometchat.com/" ## Integration -A ready‑to‑use chat experience configured via Chat Builder and powered by our Android UI Kit. +A ready‑to‑use chat experience configured via UI Kit Builder and powered by our Android UI Kit. **How It Works** @@ -94,7 +94,7 @@ A ready‑to‑use chat experience configured via Chat Builder and powered by ou ## Next Steps for Developers 1. Learn the basics — Key Concepts: [Key Concepts](/fundamentals/key-concepts) -2. Follow the setup guide — Chat Builder (Android): [Integration](/chat-builder/android/integration) +2. Follow the setup guide — UI Kit Builder (Android): [Integration](/chat-builder/android/integration) 3. Customize UI — Theme and components: [Theme introduction](/ui-kit/android/theme-introduction), [UI Kit overview](/ui-kit/android/overview) 4. Test & ship — Run on device/emulator and deploy. diff --git a/chat-builder/flutter/integration.mdx b/chat-builder/flutter/integration.mdx new file mode 100644 index 00000000..d2f18e7d --- /dev/null +++ b/chat-builder/flutter/integration.mdx @@ -0,0 +1,237 @@ +--- +title: "Getting Started With UI Kit Builder" +sidebarTitle: "Integration" +--- + +UI Kit Builder streamlines integrating CometChat’s Flutter UI Kit into your cross-platform app. Design the experience visually, export platform-ready assets, and connect them to your Flutter project with just a few steps. + + + + + +## Complete Integration Workflow + +1. Design your chat experience in UI Kit Builder. +2. Export your Flutter package with configuration JSON, assets, and helper files. +3. Enable advanced features in the CometChat Dashboard if your experience requires them. +4. Optionally explore the sample module to preview the UI Kit Builder experience. +5. Integrate the UI Kit Builder module into your Flutter project. +6. Customize the UI further with the Flutter UI Kit components and styling APIs. + +*** + +## Launch the UI Kit Builder + +1. Log in to your CometChat Dashboard: https://app.cometchat.com +2. Select your application. +3. Go to Integrate → Flutter → Launch UI Kit Builder. + +*** + +## Enable Features in CometChat Dashboard + +If your app needs any of these, enable them from your Dashboard: https://app.cometchat.com + +- Stickers +- Polls +- Collaborative whiteboard +- Collaborative document +- Message translation +- AI User Copilot: Conversation starter, Conversation summary, Smart reply + +How to enable: + + + + + +1. Log in to the Dashboard. +2. Select your app. +3. Navigate to Chat → Features. +4. Toggle ON the required features and Save. + +*** + +## Integration with CometChat UI Kit Builder + +Follow these steps to wire the Builder output into your existing Flutter app. + +### Step 1: Download the Builder package + +From the Dashboard export, download the Flutter Builder bundle. Inside you will find a `chat_builder` module, assets, and helper utilities. + +### Step 2: Add the Builder module to your project + +Copy the `chat_builder` directory into the root of your Flutter project (for example, next to your `lib`, `ios`, and `android` folders). + +### Step 3: Copy Builder assets + +Move the contents of `chat_builder/assets/` into your app’s `assets/` directory. Keep the folder structure intact so fonts, JSON files, and images resolve correctly. + +### Step 4: Update `pubspec.yaml` + +Point to the local Builder module and register the assets and fonts supplied by the export: + +```yaml +dependencies: + # other dependencies + chat_builder: + path: ./chat_builder + +flutter: + uses-material-design: true + assets: + - assets/ + - assets/sample_app/ + fonts: + - family: arial + fonts: + - asset: assets/fonts/arial_regular.ttf + - asset: assets/fonts/arial_medium.ttf + - asset: assets/fonts/arial_bold.ttf + - family: inter + fonts: + - asset: assets/fonts/inter_regular.otf + - asset: assets/fonts/inter_medium.otf + - asset: assets/fonts/inter_bold.otf + - family: roboto + fonts: + - asset: assets/fonts/roboto_regular.ttf + - asset: assets/fonts/roboto_medium.ttf + - asset: assets/fonts/roboto_bold.ttf + - family: times New Roman + fonts: + - asset: assets/fonts/times_new_roman_regular.ttf + - asset: assets/fonts/times_new_roman_medium.otf + - asset: assets/fonts/times_new_roman_bold.otf +``` + +Ensure indentation is consistent—Flutter’s asset and font declarations are whitespace sensitive. + +### Step 5: Install dependencies + +Run the following commands at the root of your project: + +```bash +flutter pub get +cd ios && pod install +``` + +If your project uses scripting for iOS installs, adapt the second command accordingly. + +### Step 6: Initialize Builder settings before `runApp` + +Import the helper from the Builder module and load settings during app startup: + +```dart +import 'package:flutter/widgets.dart'; +import 'package:chat_builder/utils/builder_settings_helper.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await BuilderSettingsHelper.loadFromAsset(); + runApp(const MyApp()); +} +``` + +This ensures generated constants, themes, and resources are ready when your widgets build. + +### Step 7: Launch UI Kit Builder screens as needed + +Use the `ChatBuilder` APIs to open preconfigured experiences. + +- If CometChat is **not initialized** or the user is **not logged in**: + + ```dart + import 'package:chat_builder/chat_builder.dart'; + + ChatBuilder.launchBuilder(context); + ``` + +- If CometChat is initialized and the user is logged in: + + ```dart + ChatBuilder.launchMessages( + context: context, + user: user, // instance of CometChatUser + ); + + ChatBuilder.launchMessages( + context: context, + group: group, // instance of CometChatGroup + ); + ``` + +### Step 8: Refresh settings after configuration updates + +Whenever you export a new Builder configuration, replace the generated JSON, fonts, and assets in your project, then rerun `flutter pub get` to pick up changes. + +*** + +## Available Builder Settings Categories + +- Core Messaging Experience — typing indicators, attachments, media, polls. +- Deeper User Engagement — reactions, message translation, stickers, extensions. +- AI User Copilot — smart replies, conversation starters, summaries. +- Group Management — creation, roles, member controls. +- Moderator Controls — kick, ban, mute, report workflows. +- Voice & Video Calling — one-to-one and group calling toggles. +- Layout & Styling — colors, fonts, corner radii, spacing. + +*** + +## Benefits of Using CometChat UI Kit Builder + +- Easy configuration: Update experiences without touching Flutter code. +- Type-safe constants: Generated Dart helpers keep settings discoverable. +- Consistent styling: Centralized theming across modules. +- Feature toggling: Enable or disable capabilities dynamically. +- Faster iteration: Designers and developers stay aligned via visual config. + +*** + +## Alternative: Import the CometChatBuilder Sample App as a Module + +Prefer a plug-and-play starting point? Import the preconfigured sample module to explore the experience before wiring it into production. + +1. Download the sample from the CometChat Dashboard. +2. Open the sample in your IDE and run `flutter pub get` followed by `flutter run` to preview the flows. +3. When ready, add the sample module to your workspace and reference it from your main app via `path` dependencies. +4. Gradually migrate screens or copy utilities (like `BuilderSettingsHelper`) into your production package. + +*** + +## Run the App + +After integrating the module, run your Flutter project on an emulator or device: + +```bash +flutter run +``` + +Ensure a CometChat user is created and logged in via your authentication flow before launching message screens. + +*** + +## Additional Notes + +- Keep the Builder assets in sync with the latest export whenever you change configuration in the dashboard. +- Fonts supplied by the Builder can be swapped for your brand fonts—update the font family definitions in `pubspec.yaml`. +- For macOS or web targets, guard Builder-specific code with platform checks until those exports are supported. + +*** + +## Troubleshooting + +- Builder package not found: Confirm the `chat_builder` directory path in `pubspec.yaml` is correct. +- Assets missing at runtime: Verify the asset paths in `pubspec.yaml` and rerun `flutter pub get`. +- iOS build issues: Make sure you ran `pod install` inside the `ios` directory after adding the new dependency. +- Undefined symbols: Reimport or regenerate the `BuilderSettingsHelper` if package paths changed. + +*** + +## Next Steps + +- Customize theming with the Flutter UI Kit: [Theme introduction](/ui-kit/flutter/theme-introduction) +- Explore available components: [Components overview](/ui-kit/flutter/components-overview) +- Dig into API usage: [Methods & APIs](/ui-kit/flutter/methods) diff --git a/chat-builder/flutter/overview.mdx b/chat-builder/flutter/overview.mdx new file mode 100644 index 00000000..a0ca9b73 --- /dev/null +++ b/chat-builder/flutter/overview.mdx @@ -0,0 +1,135 @@ +--- +title: "CometChat UI Kit Builder For Flutter" +sidebarTitle: "Overview" +--- + +The CometChat UI Kit Builder for Flutter helps you deliver a polished chat experience across iOS and Android with prebuilt, customizable UI. Configure features visually, export ready-to-use assets, and plug everything into your Flutter project with minimal boilerplate. + +*** + +## Prerequisites + +- Flutter SDK (stable channel) with Dart 3+ +- macOS, Windows, or Linux with Flutter tooling (Android Studio, VS Code, or IntelliJ) +- For iOS builds: Xcode, CocoaPods, and an iOS 13+ simulator or device +- For Android builds: Android Studio and an Android 5.0 (API 21)+ emulator or device +- Internet connectivity for CometChat services + +*** + +## Why Choose CometChat UI Kit Builder? + +- Rapid integration: Export module-ready code and settings for Flutter. +- Cross-platform: One configuration powers iOS and Android builds. +- Customizable: Tune colors, typography, and feature toggles from the Builder. +- Scalable: Backed by CometChat’s reliable messaging infrastructure. + +*** + +## Setup Options + +Choose one of the following paths to integrate: + + + + Copy the generated Builder module into your Flutter project and load settings from assets. + + + + Import the sample module for a plug-and-play experience, then migrate features into your main app. + + + +*** + +## User Interface Preview + + + + + +*** + +## Try Live Demo + +Experience the CometChat UI Kit Builder in action: + + + + + + + +*** + +## Integration + +A ready-to-use chat experience configured in the Builder and powered by our Flutter UI Kit. + +**How It Works** + +- Toggle features such as reactions, polls, message translation, calling, and more. +- Export code, assets, and configuration JSON for your Flutter project. +- Iterate quickly without rewriting UI or state management. + +**Why It’s Great** + +- Minimal setup with reusable modules. +- Visual configuration keeps design and engineering aligned. +- Includes sensible defaults for typography, colors, and layout. + +*** + +## Next Steps for Developers + +1. Learn the basics — Key Concepts: [Key Concepts](/fundamentals/key-concepts) +2. Follow the setup guide — Chat UI Kit Builder (Flutter): [Integration](/chat-builder/flutter/integration) +3. Customize UI — Theme and components: [Theme introduction](/ui-kit/flutter/theme-introduction), [Components overview](/ui-kit/flutter/components-overview) +4. Test & ship — Run on device/emulator and deploy. + +*** + +## Helpful Resources + +Explore these resources to go deeper with CometChat on Flutter. + + + + + + Try the fully featured Flutter sample for reference implementations. + + + + + + Explore the complete Flutter UI Kit source code. + + + + + + Configure features, manage users, and launch the UI Kit Builder. + + + + + +*** + +## Need Help? + +- Developer Community: http://community.cometchat.com/ +- Support Portal: https://help.cometchat.com/hc/en-us/requests/new diff --git a/chat-builder/ios/integration.mdx b/chat-builder/ios/integration.mdx index 77c15176..f51a89b6 100644 --- a/chat-builder/ios/integration.mdx +++ b/chat-builder/ios/integration.mdx @@ -1,9 +1,9 @@ --- -title: "Getting Started With Chat Builder" +title: "Getting Started With UI Kit Builder" sidebarTitle: "Integration" --- -Chat Builder simplifies integrating CometChat’s iOS UI Kit using Visual Chat Builder (VCB) configuration. Design your experience, export settings, and wire them into your app via JSON or QR‑based live sync. +UI Kit Builder simplifies integrating CometChat’s iOS UI Kit using Visual UI Kit Builder configuration. Design your experience, export settings, and wire them into your app via JSON or QR‑based live sync. @@ -11,7 +11,7 @@ Chat Builder simplifies integrating CometChat’s iOS UI Kit using Visual Chat B ## Complete Integration Workflow -1. Design your chat experience in Chat Builder. +1. Design your chat experience in UI Kit Builder. 2. Export your code/settings or connect via QR. 3. Enable extra features in the CometChat Dashboard if needed. 4. Optionally preview on device/simulator. @@ -20,11 +20,11 @@ Chat Builder simplifies integrating CometChat’s iOS UI Kit using Visual Chat B *** -## Launch the Chat Builder +## Launch the UI Kit Builder 1. Log in to your CometChat Dashboard: https://app.cometchat.com 2. Select your application. -3. Go to Integrate → iOS → Launch Chat Builder. +3. Go to Integrate → iOS → Launch UI Kit Builder. *** @@ -52,7 +52,7 @@ How to enable: *** -## Integration with CometChat Chat Builder (iOS) +## Integration with CometChat UI Kit Builder (iOS) Installation and configuration options from README‑iOS: @@ -103,7 +103,7 @@ import CometChatBuilder CometChatBuilder.startScanning(from: self) { appliedStyle in // Apply theme or reload UI if needed - print("Chat Builder Style Applied:", appliedStyle.theme) + print("UI Kit Builder Style Applied:", appliedStyle.theme) } ``` diff --git a/chat-builder/ios/overview.mdx b/chat-builder/ios/overview.mdx index b0d984aa..4eeca9a8 100644 --- a/chat-builder/ios/overview.mdx +++ b/chat-builder/ios/overview.mdx @@ -102,7 +102,7 @@ Ship a ready‑to‑use chat experience configured in the Builder and powered by ## Next Steps for Developers 1. Learn the basics — Key Concepts: [Key Concepts](/fundamentals/key-concepts) -2. Follow the setup guide — Chat Builder (iOS): [Chat Builder (iOS)](/chat-builder/ios/integration) +2. Follow the setup guide — UI Kit Builder (iOS): [UI Kit Builder (iOS)](/chat-builder/ios/integration) 3. Customize UI — Theme and components: [Theme introduction](/ui-kit/ios/theme-introduction), [Components overview](/ui-kit/ios/overview) 4. Test & ship — Run on device/simulator and deploy. diff --git a/chat-builder/nextjs/builder-customisations.mdx b/chat-builder/nextjs/builder-customisations.mdx index 016cfa87..c0aab063 100644 --- a/chat-builder/nextjs/builder-customisations.mdx +++ b/chat-builder/nextjs/builder-customisations.mdx @@ -1,9 +1,9 @@ --- -title: "Customizing Your Chat Builder Integration" +title: "Customizing Your UI Kit Builder Integration" sidebarTitle: "Overview" --- -While the `CometChatSettings.ts` file allows basic toggling of features in the Chat Builder, **deeper customizations** require a more hands-on approach. Follow the steps below to tailor the UI Kit to your exact needs. +While the `CometChatSettings.ts` file allows basic toggling of features in the UI Kit Builder, **deeper customizations** require a more hands-on approach. Follow the steps below to tailor the UI Kit to your exact needs. *** @@ -25,8 +25,8 @@ While the `CometChatSettings.ts` file allows basic toggling of features in the C Applying Customizations -Changes made to the Chat Builder settings or components **will not reflect automatically** in your app.\ -If you make additional modifications in the Chat Builder after initial setup: +Changes made to the UI Kit Builder settings or components **will not reflect automatically** in your app.\ +If you make additional modifications in the UI Kit Builder after initial setup: * Re-download the updated code package * Reintegrate it into your application diff --git a/chat-builder/nextjs/builder-dir-structure.mdx b/chat-builder/nextjs/builder-dir-structure.mdx index 26e69c84..9ec131b6 100644 --- a/chat-builder/nextjs/builder-dir-structure.mdx +++ b/chat-builder/nextjs/builder-dir-structure.mdx @@ -1,13 +1,13 @@ --- -title: "CometChat Chat Builder Directory Structure" +title: "CometChat UI Kit Builder Directory Structure" sidebarTitle: "Directory Structure" --- -This document provides an overview of the CometChat Chat Builder directory structure, helping you understand the organization of the project and where to find specific files when you need to customize or extend functionality. +This document provides an overview of the CometChat UI Kit Builder directory structure, helping you understand the organization of the project and where to find specific files when you need to customize or extend functionality. ## Overview -The CometChat Chat Builder follows a modular structure organized by feature and functionality. All Chat Builder files are contained within the `src/CometChat/` directory. +The CometChat UI Kit Builder follows a modular structure organized by feature and functionality. All UI Kit Builder files are contained within the `src/CometChat/` directory. ``` src/ @@ -34,8 +34,8 @@ src/ | File | Description | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -| `CometChatApp.tsx` | The main entry point for the Chat Builder application. This is the component you import in your project to render the chat experience. | -| `CometChatSettings.ts` | Contains configuration settings for the Chat Builder, including UI elements, features, and theming options. | +| `CometChatApp.tsx` | The main entry point for the UI Kit Builder application. This is the component you import in your project to render the chat experience. | +| `CometChatSettings.ts` | Contains configuration settings for the UI Kit Builder, including UI elements, features, and theming options. | | `customHooks.ts` | Custom React hooks used throughout the application. | | `decl.d.ts` | TypeScript declaration file for type definitions. | | `styleConfig.ts` | Configuration file for styling across the application. | @@ -57,7 +57,7 @@ assets/ #### `components/` -Contains all React components that make up the UI of the Chat Builder. +Contains all React components that make up the UI of the UI Kit Builder. ``` components/ @@ -187,7 +187,7 @@ utils/ ## Customization Points -When customizing the Chat Builder, you'll typically work with: +When customizing the UI Kit Builder, you'll typically work with: 1. **`CometChatSettings.ts`**: To modify high-level configuration 2. **`styleConfig.ts`**: To change theme colors, fonts, and other styling variables @@ -199,13 +199,13 @@ When customizing the Chat Builder, you'll typically work with: * Avoid direct modification of core components when possible * Use the settings files for configuration changes * Use CSS overrides for styling customizations -* For extensive customizations, consider creating wrapper components that use the Chat Builder components as children +* For extensive customizations, consider creating wrapper components that use the UI Kit Builder components as children *** ## **Conclusion** -This structured breakdown of the **CometChat Chat Builder directory** helps developers understand the project layout, making it easier to navigate, extend, and customize as needed. +This structured breakdown of the **CometChat UI Kit Builder directory** helps developers understand the project layout, making it easier to navigate, extend, and customize as needed. For further customization and integration details, refer to: diff --git a/chat-builder/nextjs/integration.mdx b/chat-builder/nextjs/integration.mdx index e058bcef..0db49c57 100644 --- a/chat-builder/nextjs/integration.mdx +++ b/chat-builder/nextjs/integration.mdx @@ -1,11 +1,11 @@ --- -title: "Getting Started With Chat Builder" +title: "Getting Started With UI Kit Builder" sidebarTitle: "Integration" --- -**Chat Builder** is a powerful tool designed to simplify the integration of CometChat's UI Kit into your existing React application. +**UI Kit Builder** is a powerful tool designed to simplify the integration of CometChat's UI Kit into your existing React application. -With the **Chat Builder**, you can quickly set up chat functionalities, customize UI elements, and integrate essential features without extensive coding. +With the **UI Kit Builder**, you can quickly set up chat functionalities, customize UI elements, and integrate essential features without extensive coding. @@ -13,7 +13,7 @@ With the **Chat Builder**, you can quickly set up chat functionalities, customiz ## **Complete Integration Workflow** -1. **Design Your Chat Experience** - Use the Chat Builder to customize layouts, features, and styling. +1. **Design Your Chat Experience** - Use the **UI Kit Builder** to customize layouts, features, and styling. 2. **Export Your Code** - Once satisfied, download the generated code package. 3. **Enable Features** - Enable additional features in the CometChat Dashboard if required. 4. **Preview Customizations** - Optionally, preview the chat experience before integrating it into your project. @@ -22,11 +22,11 @@ With the **Chat Builder**, you can quickly set up chat functionalities, customiz *** -## **Launch the Chat Builder** +## **Launch the UI Kit Builder** 1. Log in to your [**CometChat Dashboard**](https://app.cometchat.com). 2. Select your application from the list. -3. Navigate to **Integrate** > **React** > **Launch Chat Builder**. +3. Navigate to **Integrate** > **React** > **Launch UI Kit Builder**. *** @@ -60,7 +60,7 @@ If your app requires any of the following features, make sure to enable them fro ## **Preview Customizations (Optional)** -Before integrating the Chat Builder into your project, you can preview the chat experience by following these steps. This step is completely optional and can be skipped if you want to directly integrate the Chat Builder into your project. +Before integrating the **UI Kit Builder** into your project, you can preview the chat experience by following these steps. This step is completely optional and can be skipped if you want to directly integrate the **UI Kit Builder** into your project. > You can preview the experience: > @@ -89,12 +89,12 @@ Before integrating the Chat Builder into your project, you can preview the chat *** -## **Integration with CometChat Chat Builder (Next.js)** +## **Integration with CometChat UI Kit Builder (Next.js)** ### **Step 1: Install Dependencies** ```ruby -npm install @cometchat/chat-uikit-react@6.0.7 @cometchat/calls-sdk-javascript +npm install @cometchat/chat-uikit-react@6.2.3 @cometchat/calls-sdk-javascript ``` ### **Step 2: Copy CometChat Folder** @@ -295,7 +295,7 @@ export default CometChatNoSSR; ### **Step 5: Disable SSR & Render CometChat Component** -In this step, we’ll render the `CometChatApp` component and specifically disable **Server-Side Rendering (SSR)** for `CometChatNoSSR.tsx`. This targeted approach ensures the CometChat Chat Builder components load only on the client side, while the rest of your application remains fully compatible with SSR. +In this step, we’ll render the `CometChatApp` component and specifically disable **Server-Side Rendering (SSR)** for `CometChatNoSSR.tsx`. This targeted approach ensures the CometChat UI Kit Builder components load only on the client side, while the rest of your application remains fully compatible with SSR. 1. **Create a Wrapper File**: Add a new file that houses the `CometChatApp` component. 2. **Dynamically Import `CometChatNoSSR.tsx`**: In this file, use dynamic imports with `{ ssr: false }` to disable SSR only for the CometChat component, preventing SSR-related issues but preserving SSR for the rest of your code. @@ -339,7 +339,7 @@ export default function Home() { Why disable SSR? -CometChat Chat Builder relies on browser APIs like `window`, `document`, and WebSockets. Since Next.js renders on the server by default, we disable SSR for this component to avoid runtime errors. +CometChat UI Kit Builder relies on browser APIs like `window`, `document`, and WebSockets. Since Next.js renders on the server by default, we disable SSR for this component to avoid runtime errors. @@ -454,6 +454,21 @@ When you enable the **Without Sidebar** option for the Sidebar, the following be * **User Chats (`chatType = "user"`)**: Displays one-on-one chats only, either for a currently selected user or the default user. * **Group Chats (`chatType = "group"`)**: Displays group chats exclusively, either for a currently selected group or the default group. + +**Group Action Messages** + +You can control the visibility of group action messages using the showGroupActionMessages prop: + +``` + +``` + +- If `showGroupActionMessages` is `true (default)`, group action messages will be **visible**. + +- If `showGroupActionMessages` is `false`, group action messages will be **hidden**. + *** ### **Step 6: Run Your App** diff --git a/chat-builder/nextjs/overview.mdx b/chat-builder/nextjs/overview.mdx index 032c8e9d..94349fec 100644 --- a/chat-builder/nextjs/overview.mdx +++ b/chat-builder/nextjs/overview.mdx @@ -1,13 +1,13 @@ --- -title: "CometChat Chat Builder For Next.js" +title: "CometChat UI Kit Builder For Next.js" sidebarTitle: "Overview" --- -The **CometChat Chat Builder** for Next.js is a powerful solution designed to seamlessly integrate chat functionality into applications. It provides a robust set of **prebuilt UI components** that are **modular, customizable, and highly scalable**, allowing developers to accelerate their development process with minimal effort. +The **CometChat UI Kit Builder** for Next.js is a powerful solution designed to seamlessly integrate chat functionality into applications. It provides a robust set of **prebuilt UI components** that are **modular, customizable, and highly scalable**, allowing developers to accelerate their development process with minimal effort. *** -## **Why Choose CometChat Chat Builder?** +## **Why Choose CometChat UI Kit Builder?** * **Rapid Integration** – Prebuilt UI components for faster deployment. * **Customizable & Flexible** – Modify the UI to align with your brand’s identity. @@ -26,7 +26,7 @@ The **CometChat Chat Builder** for Next.js is a powerful solution designed to se ## **Try Live Demo** -**Experience the CometChat Chat Builder in action:** +**Experience the CometChat UI Kit Builder in action:** @@ -42,7 +42,7 @@ href="https://preview.cometchat.com/" ## **Integration Options** -A ready-to-use chat interface—configured via a Chat Builder—built on top of our UI Kits. +A ready-to-use chat interface—configured via a UI Kit Builder—built on top of our UI Kits. @@ -70,7 +70,7 @@ A ready-to-use chat interface—configured via a Chat Builder—built on top of 3. **Follow the Setup Guide** – - * **Chat Builder** – [Next.js](/ui-kit/react/builder-integration-nextjs). + * **UI Kit Builder** – [Next.js](/ui-kit/react/builder-integration-nextjs). 4. **Customize UI** – Adjust [styles, themes](/ui-kit/react/theme), and [components](/ui-kit/react/components-overview). diff --git a/chat-builder/react-router/builder-customisations.mdx b/chat-builder/react-router/builder-customisations.mdx index 016cfa87..983d43e8 100644 --- a/chat-builder/react-router/builder-customisations.mdx +++ b/chat-builder/react-router/builder-customisations.mdx @@ -1,9 +1,9 @@ --- -title: "Customizing Your Chat Builder Integration" +title: "Customizing Your UI Kit Builder Integration" sidebarTitle: "Overview" --- -While the `CometChatSettings.ts` file allows basic toggling of features in the Chat Builder, **deeper customizations** require a more hands-on approach. Follow the steps below to tailor the UI Kit to your exact needs. +While the `CometChatSettings.ts` file allows basic toggling of features in the **UI Kit Builder**, **deeper customizations** require a more hands-on approach. Follow the steps below to tailor the UI Kit to your exact needs. *** @@ -25,8 +25,8 @@ While the `CometChatSettings.ts` file allows basic toggling of features in the C Applying Customizations -Changes made to the Chat Builder settings or components **will not reflect automatically** in your app.\ -If you make additional modifications in the Chat Builder after initial setup: +Changes made to the UI Kit Builder settings or components **will not reflect automatically** in your app.\ +If you make additional modifications in the UI Kit Builder after initial setup: * Re-download the updated code package * Reintegrate it into your application diff --git a/chat-builder/react-router/builder-dir-structure.mdx b/chat-builder/react-router/builder-dir-structure.mdx index 26e69c84..9ec131b6 100644 --- a/chat-builder/react-router/builder-dir-structure.mdx +++ b/chat-builder/react-router/builder-dir-structure.mdx @@ -1,13 +1,13 @@ --- -title: "CometChat Chat Builder Directory Structure" +title: "CometChat UI Kit Builder Directory Structure" sidebarTitle: "Directory Structure" --- -This document provides an overview of the CometChat Chat Builder directory structure, helping you understand the organization of the project and where to find specific files when you need to customize or extend functionality. +This document provides an overview of the CometChat UI Kit Builder directory structure, helping you understand the organization of the project and where to find specific files when you need to customize or extend functionality. ## Overview -The CometChat Chat Builder follows a modular structure organized by feature and functionality. All Chat Builder files are contained within the `src/CometChat/` directory. +The CometChat UI Kit Builder follows a modular structure organized by feature and functionality. All UI Kit Builder files are contained within the `src/CometChat/` directory. ``` src/ @@ -34,8 +34,8 @@ src/ | File | Description | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -| `CometChatApp.tsx` | The main entry point for the Chat Builder application. This is the component you import in your project to render the chat experience. | -| `CometChatSettings.ts` | Contains configuration settings for the Chat Builder, including UI elements, features, and theming options. | +| `CometChatApp.tsx` | The main entry point for the UI Kit Builder application. This is the component you import in your project to render the chat experience. | +| `CometChatSettings.ts` | Contains configuration settings for the UI Kit Builder, including UI elements, features, and theming options. | | `customHooks.ts` | Custom React hooks used throughout the application. | | `decl.d.ts` | TypeScript declaration file for type definitions. | | `styleConfig.ts` | Configuration file for styling across the application. | @@ -57,7 +57,7 @@ assets/ #### `components/` -Contains all React components that make up the UI of the Chat Builder. +Contains all React components that make up the UI of the UI Kit Builder. ``` components/ @@ -187,7 +187,7 @@ utils/ ## Customization Points -When customizing the Chat Builder, you'll typically work with: +When customizing the UI Kit Builder, you'll typically work with: 1. **`CometChatSettings.ts`**: To modify high-level configuration 2. **`styleConfig.ts`**: To change theme colors, fonts, and other styling variables @@ -199,13 +199,13 @@ When customizing the Chat Builder, you'll typically work with: * Avoid direct modification of core components when possible * Use the settings files for configuration changes * Use CSS overrides for styling customizations -* For extensive customizations, consider creating wrapper components that use the Chat Builder components as children +* For extensive customizations, consider creating wrapper components that use the UI Kit Builder components as children *** ## **Conclusion** -This structured breakdown of the **CometChat Chat Builder directory** helps developers understand the project layout, making it easier to navigate, extend, and customize as needed. +This structured breakdown of the **CometChat UI Kit Builder directory** helps developers understand the project layout, making it easier to navigate, extend, and customize as needed. For further customization and integration details, refer to: diff --git a/chat-builder/react-router/integration.mdx b/chat-builder/react-router/integration.mdx index 009eef53..b100a2e4 100644 --- a/chat-builder/react-router/integration.mdx +++ b/chat-builder/react-router/integration.mdx @@ -1,11 +1,11 @@ --- -title: "Getting Started With Chat Builder" +title: "Getting Started With UI Kit Builder" sidebarTitle: "Integration" --- -**Chat Builder** is a powerful tool designed to simplify the integration of CometChat's UI Kit into your existing React application. +**UI Kit Builder** is a powerful tool designed to simplify the integration of CometChat's UI Kit into your existing React application. -With the **Chat Builder**, you can quickly set up chat functionalities, customize UI elements, and integrate essential features without extensive coding. +With the **UI Kit Builder**, you can quickly set up chat functionalities, customize UI elements, and integrate essential features without extensive coding. @@ -13,7 +13,7 @@ With the **Chat Builder**, you can quickly set up chat functionalities, customiz ## **Complete Integration Workflow** -1. **Design Your Chat Experience** - Use the Chat Builder to customize layouts, features, and styling. +1. **Design Your Chat Experience** - Use the **UI Kit Builder** to customize layouts, features, and styling. 2. **Export Your Code** - Once satisfied, download the generated code package. 3. **Enable Features** - Enable additional features in the CometChat Dashboard if required. 4. **Preview Customizations** - Optionally, preview the chat experience before integrating it into your project. @@ -22,11 +22,11 @@ With the **Chat Builder**, you can quickly set up chat functionalities, customiz *** -## **Launch the Chat Builder** +## **Launch the UI Kit Builder** 1. Log in to your [**CometChat Dashboard**](https://app.cometchat.com). 2. Select your application from the list. -3. Navigate to **Integrate** > **React** > **Launch Chat Builder**. +3. Navigate to **Integrate** > **React** > **Launch UI Kit Builder**. *** @@ -60,7 +60,7 @@ If your app requires any of the following features, make sure to enable them fro ## **Preview Customizations (Optional)** -Before integrating the Chat Builder into your project, you can preview the chat experience by following these steps. This step is completely optional and can be skipped if you want to directly integrate the Chat Builder into your project. +Before integrating the UI Kit Builder into your project, you can preview the chat experience by following these steps. This step is completely optional and can be skipped if you want to directly integrate the UI Kit Builder into your project. > You can preview the experience: > @@ -89,12 +89,12 @@ Before integrating the Chat Builder into your project, you can preview the chat *** -## **Integration with CometChat Chat Builder (React Router)** +## **Integration with CometChat UI Kit Builder (React Router)** ### **Step 1: Install Dependencies** ```ruby -npm install @cometchat/chat-uikit-react@6.0.7 @cometchat/calls-sdk-javascript +npm install @cometchat/chat-uikit-react@6.3.2 @cometchat/calls-sdk-javascript ``` ### **Step 2: Copy CometChat Folder** @@ -354,7 +354,7 @@ export default [ -Why disable SSR? CometChat Chat Builder relies on browser APIs such as window, document, and WebSockets. Since React Router renders on the server by default, disabling SSR for this component prevents runtime errors. +Why disable SSR? CometChat UI Kit Builder relies on browser APIs such as window, document, and WebSockets. Since React Router renders on the server by default, disabling SSR for this component prevents runtime errors. @@ -471,6 +471,20 @@ When you enable the **Without Sidebar** option for the Sidebar, the following be *** +**Group Action Messages** + +You can control the visibility of group action messages using the showGroupActionMessages prop: + +``` + +``` + +- If `showGroupActionMessages` is `true (default)`, group action messages will be **visible**. + +- If `showGroupActionMessages` is `false`, group action messages will be **hidden**. + ### **Step 6: Run Your Application** 1. **Start the development server** diff --git a/chat-builder/react-router/overview.mdx b/chat-builder/react-router/overview.mdx index 960d4315..38c8b329 100644 --- a/chat-builder/react-router/overview.mdx +++ b/chat-builder/react-router/overview.mdx @@ -1,13 +1,13 @@ --- -title: "CometChat Chat Builder For React Router" +title: "CometChat UI Kit Builder For React Router" sidebarTitle: "Overview" --- -The **CometChat Chat Builder** for React Router is a powerful solution designed to seamlessly integrate chat functionality into applications. It provides a robust set of **prebuilt UI components** that are **modular, customizable, and highly scalable**, allowing developers to accelerate their development process with minimal effort. +The **CometChat UI Kit Builder** for React Router is a powerful solution designed to seamlessly integrate chat functionality into applications. It provides a robust set of **prebuilt UI components** that are **modular, customizable, and highly scalable**, allowing developers to accelerate their development process with minimal effort. *** -## **Why Choose CometChat Chat Builder?** +## **Why Choose CometChat UI Kit Builder?** * **Rapid Integration** – Prebuilt UI components for faster deployment. * **Customizable & Flexible** – Modify the UI to align with your brand’s identity. @@ -28,7 +28,7 @@ The **CometChat Chat Builder** for React Router is a powerful solution designed ## **Try Live Demo** -**Experience the CometChat Chat Builder in action:** +**Experience the CometChat UI Kit Builder in action:** @@ -44,7 +44,7 @@ href="https://preview.cometchat.com/" ## **Integration** -A ready-to-use chat interface—configured via a Chat Builder—built on top of our UI Kits. +A ready-to-use chat interface—configured via a UI Kit Builder—built on top of our UI Kits. @@ -70,7 +70,7 @@ A ready-to-use chat interface—configured via a Chat Builder—built on top of 2. **Follow the Setup Guide** – - * **Chat Builder** – [React Router](/ui-kit/react/builder-integration-react-router). + * **UI Kit Builder** – [React Router](/ui-kit/react/builder-integration-react-router). 4. **Customize UI** – Adjust [styles, themes](/ui-kit/react/theme), and [components](/ui-kit/react/components-overview). diff --git a/chat-builder/react/builder-customisations.mdx b/chat-builder/react/builder-customisations.mdx index 016cfa87..c0aab063 100644 --- a/chat-builder/react/builder-customisations.mdx +++ b/chat-builder/react/builder-customisations.mdx @@ -1,9 +1,9 @@ --- -title: "Customizing Your Chat Builder Integration" +title: "Customizing Your UI Kit Builder Integration" sidebarTitle: "Overview" --- -While the `CometChatSettings.ts` file allows basic toggling of features in the Chat Builder, **deeper customizations** require a more hands-on approach. Follow the steps below to tailor the UI Kit to your exact needs. +While the `CometChatSettings.ts` file allows basic toggling of features in the UI Kit Builder, **deeper customizations** require a more hands-on approach. Follow the steps below to tailor the UI Kit to your exact needs. *** @@ -25,8 +25,8 @@ While the `CometChatSettings.ts` file allows basic toggling of features in the C Applying Customizations -Changes made to the Chat Builder settings or components **will not reflect automatically** in your app.\ -If you make additional modifications in the Chat Builder after initial setup: +Changes made to the UI Kit Builder settings or components **will not reflect automatically** in your app.\ +If you make additional modifications in the UI Kit Builder after initial setup: * Re-download the updated code package * Reintegrate it into your application diff --git a/chat-builder/react/builder-dir-structure.mdx b/chat-builder/react/builder-dir-structure.mdx index 26e69c84..9ec131b6 100644 --- a/chat-builder/react/builder-dir-structure.mdx +++ b/chat-builder/react/builder-dir-structure.mdx @@ -1,13 +1,13 @@ --- -title: "CometChat Chat Builder Directory Structure" +title: "CometChat UI Kit Builder Directory Structure" sidebarTitle: "Directory Structure" --- -This document provides an overview of the CometChat Chat Builder directory structure, helping you understand the organization of the project and where to find specific files when you need to customize or extend functionality. +This document provides an overview of the CometChat UI Kit Builder directory structure, helping you understand the organization of the project and where to find specific files when you need to customize or extend functionality. ## Overview -The CometChat Chat Builder follows a modular structure organized by feature and functionality. All Chat Builder files are contained within the `src/CometChat/` directory. +The CometChat UI Kit Builder follows a modular structure organized by feature and functionality. All UI Kit Builder files are contained within the `src/CometChat/` directory. ``` src/ @@ -34,8 +34,8 @@ src/ | File | Description | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -| `CometChatApp.tsx` | The main entry point for the Chat Builder application. This is the component you import in your project to render the chat experience. | -| `CometChatSettings.ts` | Contains configuration settings for the Chat Builder, including UI elements, features, and theming options. | +| `CometChatApp.tsx` | The main entry point for the UI Kit Builder application. This is the component you import in your project to render the chat experience. | +| `CometChatSettings.ts` | Contains configuration settings for the UI Kit Builder, including UI elements, features, and theming options. | | `customHooks.ts` | Custom React hooks used throughout the application. | | `decl.d.ts` | TypeScript declaration file for type definitions. | | `styleConfig.ts` | Configuration file for styling across the application. | @@ -57,7 +57,7 @@ assets/ #### `components/` -Contains all React components that make up the UI of the Chat Builder. +Contains all React components that make up the UI of the UI Kit Builder. ``` components/ @@ -187,7 +187,7 @@ utils/ ## Customization Points -When customizing the Chat Builder, you'll typically work with: +When customizing the UI Kit Builder, you'll typically work with: 1. **`CometChatSettings.ts`**: To modify high-level configuration 2. **`styleConfig.ts`**: To change theme colors, fonts, and other styling variables @@ -199,13 +199,13 @@ When customizing the Chat Builder, you'll typically work with: * Avoid direct modification of core components when possible * Use the settings files for configuration changes * Use CSS overrides for styling customizations -* For extensive customizations, consider creating wrapper components that use the Chat Builder components as children +* For extensive customizations, consider creating wrapper components that use the UI Kit Builder components as children *** ## **Conclusion** -This structured breakdown of the **CometChat Chat Builder directory** helps developers understand the project layout, making it easier to navigate, extend, and customize as needed. +This structured breakdown of the **CometChat UI Kit Builder directory** helps developers understand the project layout, making it easier to navigate, extend, and customize as needed. For further customization and integration details, refer to: diff --git a/chat-builder/react/integration.mdx b/chat-builder/react/integration.mdx index 6b750d00..d6b36eb2 100644 --- a/chat-builder/react/integration.mdx +++ b/chat-builder/react/integration.mdx @@ -1,11 +1,11 @@ --- -title: "Getting Started With Chat Builder" +title: "Getting Started With UI Kit Builder" sidebarTitle: "Integration" --- -**Chat Builder** is a powerful tool designed to simplify the integration of CometChat's UI Kit into your existing React application. +**UI Kit Builder** is a powerful tool designed to simplify the integration of CometChat's UI Kit into your existing React application. -With the **Chat Builder**, you can quickly set up chat functionalities, customize UI elements, and integrate essential features without extensive coding. +With the **UI Kit Builder**, you can quickly set up chat functionalities, customize UI elements, and integrate essential features without extensive coding. @@ -13,7 +13,7 @@ With the **Chat Builder**, you can quickly set up chat functionalities, customiz ## **Complete Integration Workflow** -1. **Design Your Chat Experience** - Use the Chat Builder to customize layouts, features, and styling. +1. **Design Your Chat Experience** - Use the **UI Kit Builder** to customize layouts, features, and styling. 2. **Export Your Code** - Once satisfied, download the generated code package. 3. **Enable Features** - Enable additional features in the CometChat Dashboard if required. 4. **Preview Customizations** - Optionally, preview the chat experience before integrating it into your project. @@ -26,11 +26,11 @@ With the **Chat Builder**, you can quickly set up chat functionalities, customiz *** -## **Launch the Chat Builder** +## **Launch the UI Kit Builder** 1. Log in to your [**CometChat Dashboard**](https://app.cometchat.com). 2. Select your application from the list. -3. Navigate to **Integrate** > **React** > **Launch Chat Builder**. +3. Navigate to **Integrate** > **React** > **Launch UI Kit Builder**. *** @@ -70,7 +70,7 @@ If your app requires any of the following features, make sure to enable them fro ## **Preview Customizations (Optional)** -Before integrating the Chat Builder into your project, you can preview the chat experience by following these steps. This step is completely optional and can be skipped if you want to directly integrate the Chat Builder into your project. +Before integrating the **UI Kit Builder** into your project, you can preview the chat experience by following these steps. This step is completely optional and can be skipped if you want to directly integrate the **UI Kit Builder** into your project. > You can preview the experience: > @@ -99,16 +99,16 @@ Before integrating the Chat Builder into your project, you can preview the chat *** -## **Integration with CometChat Chat Builder (React.js)** +## **Integration with CometChat UI Kit Builder (React.js)** -Follow these steps to integrate CometChat Chat Builder into your existing React project: +Follow these steps to integrate CometChat UI Kit Builder into your existing React project: ### **Step 1: Install Dependencies** Run the following command to install the required dependencies: ```ruby -npm install @cometchat/chat-uikit-react@6.0.7 @cometchat/calls-sdk-javascript +npm install @cometchat/chat-uikit-react@6.3.2 @cometchat/calls-sdk-javascript ``` ### **Step 2: Copy CometChat Folder** @@ -330,6 +330,20 @@ CometChatUIKit.init(uiKitSettings)?.then(() => { +**Group Action Messages** + +You can control the visibility of group action messages using the showGroupActionMessages prop: + +``` + +``` + +- If `showGroupActionMessages` is `true (default)`, group action messages will be **visible**. + +- If `showGroupActionMessages` is `false`, group action messages will be **hidden**. + *** ### **Step 5: Render the CometChatApp Component** diff --git a/chat-builder/react/overview.mdx b/chat-builder/react/overview.mdx index 64c183ab..ecefeaa9 100644 --- a/chat-builder/react/overview.mdx +++ b/chat-builder/react/overview.mdx @@ -26,7 +26,7 @@ The **CometChat Builder** for React is a powerful solution designed to seamlessl ## **Try Live Demo** -**Experience the CometChat Builder in action:** +**Experience the CometChat UI Kit Builder in action:** @@ -42,7 +42,7 @@ href="https://preview.cometchat.com/" ## **Integration** -A ready-to-use chat interface—configured via a Chat Builder—built on top of our UI Kits. +A ready-to-use chat interface—configured via a UI Kit Builder—built on top of our UI Kits. @@ -68,7 +68,7 @@ A ready-to-use chat interface—configured via a Chat Builder—built on top of 2. **Follow the Setup Guide** – - * **Chat Builder** – [React.js](/ui-kit/react/builder-integration) + * **UI Kit Builder** – [React.js](/ui-kit/react/builder-integration) 3. **Customize UI** – Adjust [styles, themes](/ui-kit/react/theme), and [components](/ui-kit/react/components-overview). diff --git a/chat-call.mdx b/chat-call.mdx index fc69d790..d16006dc 100644 --- a/chat-call.mdx +++ b/chat-call.mdx @@ -43,22 +43,22 @@ import { CardGroup, Card, Icon, Badge, Steps, Columns, AccordionGroup, Accordion

Use our pre-built UI kits or SDKs to add chat to your website or mobile app instantly.

-{/* Chat Builder Section */} +{/* UI Kit Builder Section */}

- UI Kits - Chat Builder + UI Kit Builder

   RECOMMENDED

- Get a fully functional chat interface in minutes. Configure via our chat builder—no complex setup required. + Get a fully functional chat interface in minutes. Configure via our ui kit builder — no complex setup required.

-{/* */} +{/* */} @@ -90,8 +90,8 @@ import { CardGroup, Card, Icon, Badge, Steps, Columns, AccordionGroup, Accordion } href="/chat-builder/ios/overview" horizontal /> {/* } href="/chat-builder/android/overview" horizontal /> */} } href="/chat-builder/android/overview" horizontal /> - {/* } href="/ui-kit/react-native/overview" horizontal /> - } href="/ui-kit/flutter/overview" horizontal /> */} + {/* } href="/ui-kit/react-native/overview" horizontal /> */} + } href="/chat-builder/flutter/overview" horizontal />
diff --git a/chat.mdx b/chat.mdx index e19104e0..e9e88e94 100644 --- a/chat.mdx +++ b/chat.mdx @@ -42,21 +42,21 @@ import { CardGroup, Card, Icon, Badge, Steps, Columns, AccordionGroup, Accordion

Use our pre-built UI kits or SDKs to add chat to your website or mobile app instantly.

-{/* Chat Builder Section */} +{/* UI Kit Builder Section */}

- UI Kits - Chat Builder + UI Kit Builder

   RECOMMENDED

- Get a fully functional chat interface in minutes. Configure via our chat builder—no complex setup required. + Get a fully functional chat interface in minutes. Configure via our ui kit builder — no complex setup required.

- {/* */} + {/* */} diff --git a/data-import-apis.json b/data-import-apis.json index 0287fd86..2ae77ed7 100644 --- a/data-import-apis.json +++ b/data-import-apis.json @@ -122,7 +122,7 @@ ], "properties": { "url": { - "description": "Contains the URL of the attachment. The developer has to make sure that the URL is accessible while calling the data_import API. The API will be downloading the attachment from its current location and upload it to CometChat’s attachment storage.", + "description": "Publicly accessible URL of the attachment.", "type": "string" }, "name": { @@ -387,6 +387,71 @@ } }, "type": "object" + }, + "mentionedUserDetails": { + "description": "Optional field that provides user details when data.text includes a mention, formatted using CometChat’s mention template (<@uid:UID>).", + "properties": { + "": { + "description": "A map where each key is a user’s unique identifier (UID) and the value is that user’s details. The <uid> will be replaced by the mentioned user’s primary key.", + "properties": { + "": { + "required": [ + "uid", + "name" + ], + "properties": { + "uid": { + "description": "The primary-key/ unique identifier of the owner. The value should be the same as value of the placeholder which wraps the mentionedUserDetails object.", + "type": "string" + }, + "name": { + "description": "Name of the owner.", + "type": "string" + }, + "avatar": { + "description": "URL to the profile picture of the owner.", + "type": "string" + }, + "link": { + "description": "Profile page URL of the owner.", + "type": "string" + }, + "role": { + "description": "Role of the owner. Should be created already via the Create role API.", + "type": "string" + }, + "createdAt": { + "description": "A 10-digit timestamp at which the owner was created.", + "type": "integer" + }, + "lastActiveAt": { + "description": "A 10-digit UNIX timestamp at which the owner was most recently online.", + "type": "integer" + }, + "metadata": { + "description": "Additional details about the owner.", + "type": "object" + }, + "tags": { + "description": "A string array containing owner tags.", + "type": "array", + "items": { + "type": "string" + }, + "default": [] + }, + "deactivatedAt": { + "description": "A 10-digit UNIX timestamp at which the owner was deactivated/soft-deleted/blocked to use the chat services.", + "type": "integer" + } + }, + "type": "object" + } + }, + "type": "object" + } + }, + "type": "object" } }, "type": "object" @@ -402,7 +467,7 @@ "type": "text", "category": "message", "data": { - "text": "Hi there,", + "text": "Hi there", "attachments": [ { "name": "hi.png", @@ -446,7 +511,13 @@ }, "tags": [ "tag1" - ] + ], + "mentionedUserDetails": { + "example-uid-new": { + "uid": "example-uid-new", + "name": "example-uid" + } + } } } } @@ -2795,6 +2866,14 @@ "custom" ] }, + "quotedMessageId": { + "description": "ID of the message being quoted.\nIf provided, the send message response will include a `quotedMessage` node\nin the response containing the referenced message object.", + "type": "string", + "default": "message", + "enum": [ + "message" + ] + }, "type": { "description": "Type of the message.", "type": "string" @@ -2892,6 +2971,22 @@ }, "maxPerDayPerConversation": { "type": "integer" + }, + "includeMessageObjectSetting": { + "description": "Includes the message object in the email payload", + "type": "boolean" + }, + "includeSenderMetadataSetting": { + "description": "Includes sender metadata in the message object", + "type": "boolean" + }, + "includeReceiverMetadataSetting": { + "description": "Includes receiver metadata in the message object", + "type": "boolean" + }, + "includeMessageMetadataSetting": { + "description": "Includes message metadata in the message object", + "type": "boolean" } }, "type": "object" @@ -3798,6 +3893,14 @@ "message" ] }, + "quotedMessageId": { + "description": "ID of the message being quoted.\nIf provided, the send message response will include a `quotedMessage` node\nin the response containing the referenced message object.", + "type": "string", + "default": "message", + "enum": [ + "message" + ] + }, "type": { "description": "Type of the message. The available values are text, image, file, audio, video.", "type": "string", @@ -4710,6 +4813,22 @@ }, "maxPerDayPerConversation": { "type": "integer" + }, + "includeMessageObjectSetting": { + "description": "Includes the message object in the SMS payload", + "type": "boolean" + }, + "includeSenderMetadataSetting": { + "description": "Includes sender metadata in the message object", + "type": "boolean" + }, + "includeReceiverMetadataSetting": { + "description": "Includes receiver metadata in the message object", + "type": "boolean" + }, + "includeMessageMetadataSetting": { + "description": "Includes message metadata in the message object", + "type": "boolean" } }, "type": "object" diff --git a/docs.json b/docs.json index 85883283..69f3c12f 100644 --- a/docs.json +++ b/docs.json @@ -276,7 +276,7 @@ "pages": [ "ai-agents" ] - }, + }, { "tab": "Agent Builder", "dropdowns": [ @@ -285,8 +285,6 @@ "icon": "/images/icons/mastra.svg", "pages": [ "/ai-agents/mastra", - "/ai-agents/actions", - "/ai-agents/tools", { "group": "Guides", "pages": [ @@ -299,7 +297,65 @@ { "group": "Tutorials", "pages": [ - "/ai-agents/mastra-product-hunt-agent" + "/ai-agents/mastra-product-hunt-agent", + "/ai-agents/mastra-knowlege-agent-pdf" + ] + } + ] + }, + { + "dropdown": "Agno", + "icon": "/images/icons/agno.svg", + "pages": [ + "/ai-agents/agno", + { + "group": "Guides", + "pages": [ + "/ai-agents/agno-knowledge-agent" + ] + }, + { + "group": "Tutorials", + "pages": [ + "/ai-agents/agno-product-hunt-agent" + ] + } + ] + }, + { + "dropdown": "Vercel AI", + "icon": "/images/icons/vercel.png", + "pages": [ + "/ai-agents/vercel", + { + "group": "Guides", + "pages": [ + "/ai-agents/vercel-knowledge-agent" + ] + }, + { + "group": "Tutorials", + "pages": [ + "/ai-agents/vercel-product-hunt-agent" + ] + } + ] + }, + { + "dropdown": "AG2", + "icon": "/images/icons/ag2.svg", + "pages": [ + "/ai-agents/ag2", + { + "group": "Guides", + "pages": [ + "/ai-agents/ag2-knowledge-agent" + ] + }, + { + "group": "Tutorials", + "pages": [ + "/ai-agents/ag2-product-hunt-agent" ] } ] @@ -307,7 +363,32 @@ ] }, { - "tab": "Chat Builder", + "tab": "Bring Your Own Agent", + "pages": [ + { + "group": "Integration", + "pages": [ + "/ai-agents/cometchat-ag-ui-integration" + ] + }, + "/ai-agents/cometchat-ag-ui-overview", + { + "group": "Guides", + "pages": [ + "/ai-agents/cometchat-ag-ui-byoa" + ] + }, + { + "group": "Implementation", + "pages": [ + "/ai-agents/cometchat-ag-ui-express", + "/ai-agents/cometchat-ag-ui-nestjs" + ] + } + ] + }, + { + "tab": "UI Kit Builder", "tab-id" : "ai-agent-chat-builder", "pages": [ "/ai-agents/chat-widget" @@ -320,7 +401,7 @@ ] }, { - "tab": "Chat Builder", + "tab": "UI Kit Builder", "tab-id" : "chat-builder", "dropdowns": [ { @@ -411,6 +492,19 @@ ] } ] + }, + { + "dropdown": "Flutter", + "icon": "/images/icons/flutter.svg", + "groups": [ + { + "group": " ", + "pages": [ + "chat-builder/flutter/overview", + "chat-builder/flutter/integration" + ] + } + ] } ] }, @@ -515,6 +609,14 @@ { "group": "Guides", "pages": [ + "ui-kit/react/guide-overview", + "ui-kit/react/guide-threaded-messages", + "ui-kit/react/guide-block-unblock-user", + "ui-kit/react/guide-new-chat", + "ui-kit/react/guide-message-privately", + "ui-kit/react/guide-search-messages", + "ui-kit/react/guide-call-log-details", + "ui-kit/react/guide-group-chat", "ui-kit/react/custom-text-formatter-guide", "ui-kit/react/mentions-formatter-guide", "ui-kit/react/url-formatter-guide", @@ -916,7 +1018,8 @@ "ui-kit/react-native/incoming-call", "ui-kit/react-native/outgoing-call", "ui-kit/react-native/call-buttons", - "ui-kit/react-native/call-logs" + "ui-kit/react-native/call-logs", + "ui-kit/react-native/ai-assistant-chat-history" ] }, { @@ -936,6 +1039,19 @@ "ui-kit/react-native/shortcut-formatter-guide" ] }, + { + "group": "Guides", + "pages": [ + "ui-kit/react-native/guide-ai-agent" + ] + }, + { + "group": "Migration Guide", + "pages": [ + "ui-kit/react-native/upgrading-from-v4", + "ui-kit/react-native/property-changes" + ] + }, "ui-kit/react-native/link/sample", "ui-kit/react-native/link/changelog" ] @@ -1230,6 +1346,27 @@ "ui-kit/ios/message-template" ] }, + { + "group": "Guides", + "pages": [ + "ui-kit/ios/guide-overview", + "ui-kit/ios/guide-threaded-messages", + "ui-kit/ios/guide-block-unblock-user", + "ui-kit/ios/guide-new-chat", + "ui-kit/ios/guide-message-privately", + "ui-kit/ios/guide-call-log-details", + "ui-kit/ios/guide-group-chat", + "ui-kit/ios/guide-group-ownership" + ] + }, + { + "group": "Migration Guide", + "pages": [ + "ui-kit/ios/upgrading-from-v4", + "ui-kit/ios/property-changes" + ] + }, + "ui-kit/ios/link/sample", "ui-kit/ios/link/figma", "ui-kit/ios/link/changelog" @@ -1507,7 +1644,8 @@ "ui-kit/android/incoming-call", "ui-kit/android/outgoing-call", "ui-kit/android/call-buttons", - "ui-kit/android/call-logs" + "ui-kit/android/call-logs", + "ui-kit/android/ai-assistant-chat-history" ] }, { @@ -1525,6 +1663,26 @@ "ui-kit/android/shortcut-formatter-guide" ] }, + { + "group": "Guides", + "pages": [ + "ui-kit/android/guide-overview", + "ui-kit/android/guide-threaded-messages", + "ui-kit/android/guide-block-unblock-user", + "ui-kit/android/guide-new-chat", + "ui-kit/android/guide-message-privately", + "ui-kit/android/guide-call-log-details", + "ui-kit/android/guide-group-chat", + "ui-kit/android/guide-ai-agent" + ] + }, + { + "group": "Migration Guide", + "pages": [ + "ui-kit/android/upgrading-from-v4", + "ui-kit/android/property-changes" + ] + }, "ui-kit/android/link/sample", "ui-kit/android/link/figma", "ui-kit/android/link/changelog" @@ -1804,7 +1962,8 @@ "ui-kit/flutter/incoming-call", "ui-kit/flutter/outgoing-call", "ui-kit/flutter/call-buttons", - "ui-kit/flutter/call-logs" + "ui-kit/flutter/call-logs", + "ui-kit/flutter/ai-assistant-chat-history" ] }, { @@ -1825,7 +1984,21 @@ { "group": "Guides", "pages": [ - "ui-kit/flutter/multi-tab-chat-ui-guide" + "ui-kit/flutter/guide-overview", + "ui-kit/flutter/guide-threaded-messages", + "ui-kit/flutter/guide-block-unblock-user", + "ui-kit/flutter/guide-new-chat", + "ui-kit/flutter/guide-message-privately", + "ui-kit/flutter/guide-call-log-details", + "ui-kit/flutter/guide-group-chat", + "ui-kit/flutter/guide-message-agentic-flow" + ] + }, + { + "group": "Migration Guide", + "pages": [ + "ui-kit/flutter/upgrading-from-v4", + "ui-kit/flutter/property-changes" ] }, "ui-kit/flutter/link/sample", @@ -2837,6 +3010,7 @@ "sdk/react-native/transfer-group-ownership" ] }, + "sdk/react-native/ai-agents", { "group": "Resources", "pages": [ @@ -3165,6 +3339,7 @@ ] }, "sdk/ios/ai-moderation", + "sdk/ios/ai-agents", { "group": "Advanced", "pages": [ @@ -3510,6 +3685,7 @@ ] }, "sdk/android/ai-moderation", + "sdk/android/ai-agents", { "group": "Resources", "pages": [ @@ -3845,6 +4021,7 @@ ] }, "sdk/flutter/ai-moderation", + "sdk/flutter/ai-agents", { "group": "Resources", "pages": [ @@ -4294,7 +4471,7 @@ ] }, { - "tab": "No Code - Widgets", + "tab": "Widget Builder", "dropdowns": [ { "dropdown": "HTML", @@ -5389,4 +5566,4 @@ "redirect": true } } -} \ No newline at end of file +} diff --git a/images/ai_assistant_chat_history.png b/images/ai_assistant_chat_history.png new file mode 100644 index 00000000..f90c534d Binary files /dev/null and b/images/ai_assistant_chat_history.png differ diff --git a/images/android-ai-agent-bubble.png b/images/android-ai-agent-bubble.png new file mode 100644 index 00000000..4875dad5 Binary files /dev/null and b/images/android-ai-agent-bubble.png differ diff --git a/images/android-ai-agent-overview.png b/images/android-ai-agent-overview.png new file mode 100644 index 00000000..2db58ff7 Binary files /dev/null and b/images/android-ai-agent-overview.png differ diff --git a/images/android-ai-assistant-bubble-default.png b/images/android-ai-assistant-bubble-default.png new file mode 100644 index 00000000..ebc31ee5 Binary files /dev/null and b/images/android-ai-assistant-bubble-default.png differ diff --git a/images/android-ai-assistant-bubble-styled.png b/images/android-ai-assistant-bubble-styled.png new file mode 100644 index 00000000..5bff94ea Binary files /dev/null and b/images/android-ai-assistant-bubble-styled.png differ diff --git a/images/android-ai-assistant-chat-history-style.png b/images/android-ai-assistant-chat-history-style.png new file mode 100644 index 00000000..931e5ca4 Binary files /dev/null and b/images/android-ai-assistant-chat-history-style.png differ diff --git a/images/android_ai_agent_overview.png b/images/android_ai_agent_overview.png new file mode 100644 index 00000000..2db58ff7 Binary files /dev/null and b/images/android_ai_agent_overview.png differ diff --git a/images/android_ai_assistant_chat_history.png b/images/android_ai_assistant_chat_history.png new file mode 100644 index 00000000..5e8b622a Binary files /dev/null and b/images/android_ai_assistant_chat_history.png differ diff --git a/images/f42ad8d3-swipe-to-reply_web_screens-c9204e4c244ca55a7ffe6c9498299625.png b/images/f42ad8d3-swipe-to-reply_web_screens-c9204e4c244ca55a7ffe6c9498299625.png new file mode 100644 index 00000000..599948ec Binary files /dev/null and b/images/f42ad8d3-swipe-to-reply_web_screens-c9204e4c244ca55a7ffe6c9498299625.png differ diff --git a/images/flutter_ai_agent_customize_bubble.png b/images/flutter_ai_agent_customize_bubble.png new file mode 100644 index 00000000..1bc63dcb Binary files /dev/null and b/images/flutter_ai_agent_customize_bubble.png differ diff --git a/images/flutter_ai_agent_default_bubble.png b/images/flutter_ai_agent_default_bubble.png new file mode 100644 index 00000000..43e8ee86 Binary files /dev/null and b/images/flutter_ai_agent_default_bubble.png differ diff --git a/images/flutter_ai_agent_guide_overview.png b/images/flutter_ai_agent_guide_overview.png new file mode 100644 index 00000000..747466a8 Binary files /dev/null and b/images/flutter_ai_agent_guide_overview.png differ diff --git a/images/flutter_ai_assistant_chat_history.png b/images/flutter_ai_assistant_chat_history.png new file mode 100644 index 00000000..dfcf14d8 Binary files /dev/null and b/images/flutter_ai_assistant_chat_history.png differ diff --git a/images/flutter_ai_assistant_chat_history_style.png b/images/flutter_ai_assistant_chat_history_style.png new file mode 100644 index 00000000..5b1a2be1 Binary files /dev/null and b/images/flutter_ai_assistant_chat_history_style.png differ diff --git a/images/icons/ag2.svg b/images/icons/ag2.svg new file mode 100644 index 00000000..5458d6bd --- /dev/null +++ b/images/icons/ag2.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icons/vercel.png b/images/icons/vercel.png new file mode 100644 index 00000000..84361215 Binary files /dev/null and b/images/icons/vercel.png differ diff --git a/images/react-uikit-custom-reply-view.png b/images/react-uikit-custom-reply-view.png new file mode 100644 index 00000000..b67a6832 Binary files /dev/null and b/images/react-uikit-custom-reply-view.png differ diff --git a/images/react-uikit-default-reply-view.png b/images/react-uikit-default-reply-view.png new file mode 100644 index 00000000..ec19d211 Binary files /dev/null and b/images/react-uikit-default-reply-view.png differ diff --git a/rest-api/constraints-rate-limits-and-errors.mdx b/rest-api/constraints-rate-limits-and-errors.mdx index 0dc2361b..bf96041a 100644 --- a/rest-api/constraints-rate-limits-and-errors.mdx +++ b/rest-api/constraints-rate-limits-and-errors.mdx @@ -50,6 +50,15 @@ title: "Constraints, Rate Limits And Errors" | Metadata | No limit | | #### **Messages: Properties and Constraints** +| Item | Property or Constraint | Notes | +| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| File size | Maximum file size per message: 100 MB | Applies to the uploaded file associated with the message. | +| Message Data | Arbitrary JSON (UTF-8/utf8mb4), up to 10 KB for the data object; keys with special meaning to CometChat: `text`, `attachments`, `customData`, `metadata` | Attachment properties (for example, URL and size) can be included here; the actual file limit is defined under File size. | +| Groups → Unread message count | For groups with more than 300 members, conversation and unread message counts are not updated | | +| Groups → Message receipts | Delivery and read receipts are sent for groups with up to 300 members | | +| Tags | Up to 25 tags per message; 100 characters per tag (UTF-8/utf8mb4) | Tags can be in any language. | +| User mentions | Up to 10 distinct users can be mentioned in a message | Format: `<@uid:{uid of the user}>` (example: `<@uid:cometchat-uid-1>`). | +| Reactions | Maximum 25 distinct reactions per message; reaction text up to 45 characters (UTF-8/utf8mb4) | Character counts are by Unicode code points. Emoji are supported and may use multiple code points. | #### **Calling: Properties and Constraints** @@ -102,4 +111,4 @@ title: "Constraints, Rate Limits And Errors" | Webhook authentication username | 50 characters, alphanumeric (without spaces) | | | Webhook authentication password | 100 characters, alphanumeric (without spaces) | | -### Errors: \ No newline at end of file +### Errors: diff --git a/sdk/android/ai-agents.mdx b/sdk/android/ai-agents.mdx new file mode 100644 index 00000000..853da43a --- /dev/null +++ b/sdk/android/ai-agents.mdx @@ -0,0 +1,133 @@ +--- +title: "AI Agents" +--- + +# AI Agents Overview + +AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). + +> **Note:** +> Currently, an Agent only responds to **Text Messages**. + +## Agent Run Lifecycle and Message Flow + +This section explains how a user’s text message to an Agent becomes a structured "run" which emits real-time events and then produces agentic messages for historical retrieval. +- A user sends a text message to an Agent. +- The platform starts a run and streams real-time events via the **`AIAssistantListener`**. +- After the run completes, persisted Agentic Messages arrive via the **`MessageListener`**. + +### Real-time Events +Events are received via the **`onAIAssistantEventReceived`** method of the **`AIAssistantListener`** class in this general order: + +1. Run Start +2. Zero or more tool call cycles (repeats for each tool invocation): + - Tool Call Start + - Tool Call Arguments + - Tool Call End + - Tool Call Result +3. One or more assistant reply streams: + - Text Message Start + - Text Message Content (multiple times; token/char streaming) + - Text Message End +4. Run Finished + +Notes: +- `Run Start` and `Run Finished` are always emitted. +- `Tool Call` events appear only when a backend or frontend tool is invoked. There can be multiple tool calls in a single run. +- `Text Message` events are always emitted and carry the assistant’s reply incrementally. + + + + ```java + + String LISTENERS_TAG = "UNIQUE_LISTENER_ID"; + + CometChat.addAIAssistantListener(LISTENERS_TAG, new CometChat.AIAssistantListener() { + @Override + public void onAIAssistantEventReceived(AIAssistantBaseEvent aiAssistantBaseEvent) { + Log.d(TAG, "AIAssistant event received successfully: " + aiAssistantBaseEvent.toString()); + } + }); + + ``` + + + ```kotlin + + val LISTENERS_TAG = "UNIQUE_LISTENER_ID" + + CometChat.addAIAssistantListener(LISTENERS_TAG, object : CometChat.AIAssistantListener() { + override fun onAIAssistantEventReceived(aiAssistantBaseEvent: AIAssistantBaseEvent) { + Log.d(TAG, "AIAssistant event received successfully: " + aiAssistantBaseEvent.toString()) + } + }) + + ``` + + + +#### Event descriptions +- Run Start: A new run has begun for the user’s message. +- Tool Call Start: The agent decided to invoke a tool. +- Tool Call Arguments: Arguments being passed to the tool. +- Tool Call End: Tool execution completed. +- Tool Call Result: Tool’s output is available. +- Text Message Start: The agent started composing a reply. +- Text Message Content: Streaming content chunks for progressive rendering. +- Text Message End: The agent reply is complete. +- Run Finished: The run is finalized; persisted messages will follow. + +### Agentic Messages + +These events are received via the **`MessageListener`** after the run completes. +- `AIAssistantMessage`: The full assistant reply. +- `AIToolResultMessage`: The final output of a tool call. +- `AIToolArgumentMessage`: The arguments that were passed to a tool. + + + + ```java + + String listenerId = "UNIQUE_LISTENER_ID"; + + CometChat.addMessageListener(listenerId, new CometChat.MessageListener() { + @Override + public void onAIAssistantMessageReceived(AIAssistantMessage aiAssistantMessage) { + Log.d(TAG, "AIAssistantMessage received successfully: " + aiAssistantMessage.toString()); + } + + @Override + public void onAIToolResultReceived(AIToolResultMessage aiToolResultMessage) { + Log.d(TAG, "AIToolResultMessage received successfully: " + aiToolResultMessage.toString()); + } + + @Override + public void onAIToolArgumentsReceived(AIToolArgumentMessage aiToolArgumentMessage) { + Log.d(TAG, "AIToolArgumentMessage received successfully: " + aiToolArgumentMessage.toString()); + } + }); + + ``` + + + ```kotlin + + val listenerId = "UNIQUE_LISTENER_ID" + + CometChat.addMessageListener(listenerId, object : CometChat.MessageListener() { + override fun onAIAssistantMessageReceived(aiAssistantMessage: AIAssistantMessage) { + Log.d(TAG, "AIAssistantMessage received successfully: " + aiAssistantMessage.toString()) + } + + override fun onAIToolResultReceived(aiToolResultMessage: AIToolResultMessage) { + Log.d(TAG, "AIToolResultMessage received successfully: " + aiToolResultMessage.toString()) + } + + override fun onAIToolArgumentsReceived(aiToolArgumentMessage: AIToolArgumentMessage) { + Log.d(TAG, "AIToolArgumentMessage received successfully: " + aiToolArgumentMessage.toString()) + } + }) + + ``` + + \ No newline at end of file diff --git a/sdk/android/setup-calling.mdx b/sdk/android/setup-calling.mdx index 215dc55e..8a368ab1 100644 --- a/sdk/android/setup-calling.mdx +++ b/sdk/android/setup-calling.mdx @@ -48,7 +48,7 @@ Then, add CometChatCalls to the app level `build.gradle` file in the `dependenci ```java dependencies { - implementation 'com.cometchat:calls-sdk-android:4.1.0' + implementation 'com.cometchat:calls-sdk-android:4.3.1' } ``` diff --git a/sdk/flutter/ai-agents.mdx b/sdk/flutter/ai-agents.mdx new file mode 100644 index 00000000..1ee85382 --- /dev/null +++ b/sdk/flutter/ai-agents.mdx @@ -0,0 +1,114 @@ +--- +title: "AI Agents" +--- + +# AI Agents Overview + +AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). + +> **Note:** +> Currently, an Agent only responds to **Text Messages**. + +## Agent Run Lifecycle and Message Flow + +This section explains how a user’s text message to an Agent becomes a structured "run" which emits real-time events and then produces agentic messages for historical retrieval. +- A user sends a text message to an Agent. +- The platform starts a run and streams real-time events via the **`AIAssistantListener`**. +- After the run completes, persisted Agentic Messages arrive via the **`MessageListener`**. + +### Real-time Events +Events are received via the **`onAIAssistantEventReceived`** method of the **`AIAssistantListener`** class in this general order: + +1. Run Start +2. Zero or more tool call cycles (repeats for each tool invocation): + - Tool Call Start + - Tool Call Arguments + - Tool Call End + - Tool Call Result +3. One or more assistant reply streams: + - Text Message Start + - Text Message Content (multiple times; token/char streaming) + - Text Message End +4. Run Finished + +Notes: +- `Run Start` and `Run Finished` are always emitted. +- `Tool Call` events appear only when a backend or frontend tool is invoked. There can be multiple tool calls in a single run. +- `Text Message` events are always emitted and carry the assistant’s reply incrementally. + + + + ```dart +import 'package:flutter/foundation.dart'; +import 'package:cometchat_sdk/cometchat_sdk.dart'; + +class AIAssistantEventHandler with AIAssistantListener { + final String _sdkStreamListenerId = "unique_listener_id"; + + /// Call this to start listening to AI Assistant events + void addListener() { + CometChat.addAIAssistantListener(_sdkStreamListenerId, this); + debugPrint("AIAssistantListener added successfully."); + } + + /// Call this to remove the AI Assistant listener + void removeListener() { + CometChat.removeAIAssistantListener(_sdkStreamListenerId); + debugPrint("AIAssistantListener removed successfully."); + } + + @override + void onAIAssistantEventReceived(AIAssistantBaseEvent aiAssistantBaseEvent) { + debugPrint( + "Received AI Event: ${aiAssistantBaseEvent.type} for Run ID: ${aiAssistantBaseEvent.id}", + ); + } +} + ``` + + + +#### Event descriptions +- Run Start: A new run has begun for the user’s message. +- Tool Call Start: The agent decided to invoke a tool. +- Tool Call Arguments: Arguments being passed to the tool. +- Tool Call End: Tool execution completed. +- Tool Call Result: Tool’s output is available. +- Text Message Start: The agent started composing a reply. +- Text Message Content: Streaming content chunks for progressive rendering. +- Text Message End: The agent reply is complete. +- Run Finished: The run is finalized; persisted messages will follow. + +### Agentic Messages + +These events are received via the **`MessageListener`** after the run completes. +- `AIAssistantMessage`: The full assistant reply. +- `AIToolResultMessage`: The final output of a tool call. +- `AIToolArgumentMessage`: The arguments that were passed to a tool. + + + + ```dart + const listenerId = "unique_listener_id"; + + class Class_Name with MessageListener { + // Adding the MessageListener + // CometChat.addMessageListener(listenerId, this); + @override + void onAIAssistantMessageReceived(AIAssistantMessage aiAssistantMessage) { + debugPrint("AI Assistant Message Received: ${aiAssistantMessage.toString()}"); + } + + @override + void onAIToolResultReceived(AIToolResultMessage aiToolArgumentMessage) { + debugPrint("AI Assistant Message Received: ${aiToolArgumentMessage.toString()}"); + } + + @override + void onAIToolArgumentsReceived(AIToolArgumentMessage aiToolArgumentMessage) { + debugPrint("AI Assistant Message Received: ${aiToolArgumentMessage.toString()}"); + } + } + ``` + + \ No newline at end of file diff --git a/sdk/flutter/calling-setup.mdx b/sdk/flutter/calling-setup.mdx index b6b53e65..bdbffb05 100644 --- a/sdk/flutter/calling-setup.mdx +++ b/sdk/flutter/calling-setup.mdx @@ -26,7 +26,7 @@ Minimum Requirement For Calling ```dart - cometchat_calls_sdk: ^4.0.11 + cometchat_calls_sdk: ^4.2.0 ``` diff --git a/sdk/flutter/overview.mdx b/sdk/flutter/overview.mdx index bf34fb7a..9021b9ed 100644 --- a/sdk/flutter/overview.mdx +++ b/sdk/flutter/overview.mdx @@ -43,7 +43,7 @@ Minimum Requirements ```dart -cometchat_sdk: ^4.0.25 +cometchat_sdk: ^4.0.28 ``` diff --git a/sdk/flutter/setup.mdx b/sdk/flutter/setup.mdx index 429e3bd1..76d19b39 100644 --- a/sdk/flutter/setup.mdx +++ b/sdk/flutter/setup.mdx @@ -28,7 +28,7 @@ Minimum Requirement ```dart -cometchat_sdk: ^4.0.25 +cometchat_sdk: ^4.0.28 ``` diff --git a/sdk/ios/ai-agents.mdx b/sdk/ios/ai-agents.mdx new file mode 100644 index 00000000..2a920c71 --- /dev/null +++ b/sdk/ios/ai-agents.mdx @@ -0,0 +1,108 @@ +--- +title: "AI Agents" +--- + +# AI Agents Overview + +AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). + +> **Note:** +> Currently, an Agent only responds to **Text Messages**. + +## Agent Run Lifecycle and Message Flow + +This section explains how a user's text message to an Agent becomes a structured "run" which emits real-time events and then produces agentic messages for historical retrieval. + +- A user sends a text message to an Agent. +- The platform starts a run and streams real-time events via the **`AIAssistantEventsDelegate`**. +- After the run completes, persisted Agentic Messages arrive via the **`CometChatMessageDelegate`**. + +### Real-time Events + +Events are received via the **`onAIAssistantEventReceived`** method of the **`AIAssistantEventsDelegate`** protocol in this general order: + +1. Run Start +2. Zero or more tool call cycles (repeats for each tool invocation): + - Tool Call Start + - Tool Call Arguments + - Tool Call End + - Tool Call Result +3. One or more assistant reply streams: + - Text Message Start + - Text Message Content (multiple times; token/char streaming) + - Text Message End +4. Run Finished + +Notes: +- `Run Start` and `Run Finished` are always emitted. +- `Tool Call` events appear only when a backend or frontend tool is invoked. There can be multiple tool calls in a single run. +- `Text Message` events are always emitted and carry the assistant's reply incrementally. + +```swift +import CometChatSDK + +class AIAssistantEventHandler: AIAssistantEventsDelegate { + + private let sdkStreamListenerId = "unique_listener_id" + + /// Call this to start listening to AI Assistant events + func addListener() { + CometChat.addAIAssistantListener(sdkStreamListenerId, self) + print("AIAssistantListener added successfully.") + } + + /// Call this to remove the AI Assistant listener + func removeListener() { + CometChat.removeAIAssistantListener(sdkStreamListenerId) + print("AIAssistantListener removed successfully.") + } + + func onAIAssistantEventReceived(_ event: AIAssistantBaseEvent) { + print("Received AI Event: \(event.type) for Run ID: \(event.id)") + } +} +``` + +#### Event descriptions + +- Run Start: A new run has begun for the user's message. +- Tool Call Start: The agent decided to invoke a tool. +- Tool Call Arguments: Arguments being passed to the tool. +- Tool Call End: Tool execution completed. +- Tool Call Result: Tool's output is available. +- Text Message Start: The agent started composing a reply. +- Text Message Content: Streaming content chunks for progressive rendering. +- Text Message End: The agent reply is complete. +- Run Finished: The run is finalized; persisted messages will follow. + +### Agentic Messages + +These events are received via the **`CometChatMessageDelegate`** after the run completes. + +- `AIAssistantMessage`: The full assistant reply. +- `AIToolResultMessage`: The final output of a tool call. +- `AIToolArgumentMessage`: The arguments that were passed to a tool. + +```swift +import CometChatSDK + +let listenerId = "unique_listener_id" + +class MessageHandler: CometChatMessageDelegate { + + // Adding the MessageListener + // CometChat.addMessageListener(listenerId, self) + + func onAIAssistantMessageReceived(_ aiAssistantMessage: AIAssistantMessage) { + print("AI Assistant Message Received: \(aiAssistantMessage)") + } + + func onAIToolResultMessageReceived(_ aiToolResultMessage: AIToolResultMessage) { + print("AI Tool Result Message Received: \(aiToolResultMessage)") + } + + func onAIToolArgumentsMessageReceived(_ aiToolArgumentMessage: AIToolArgumentMessage) { + print("AI Tool Arguments Message Received: \(aiToolArgumentMessage)") + } +} +``` \ No newline at end of file diff --git a/sdk/ios/calling-integration.mdx b/sdk/ios/calling-integration.mdx index 38bfd22c..9546338c 100644 --- a/sdk/ios/calling-integration.mdx +++ b/sdk/ios/calling-integration.mdx @@ -89,8 +89,8 @@ platform :ios, '11.0' use_frameworks! target 'YourApp' do - pod 'CometChatSDK', '4.0.67' - pod 'CometChatCallsSDK', '4.1.0' + pod 'CometChatSDK', '4.0.69' + pod 'CometChatCallsSDK', '4.2.0' end ``` @@ -184,7 +184,7 @@ Pod installation Your pod file will open in the text editor. Add your project dependency. -3. pod 'CometChatCallsSDK', '4.1.2' +3. pod 'CometChatCallsSDK', '4.2.0' 4. For M1 Mac - arch -x86\_64 pod install or For Intel Mac - pod install ::: diff --git a/sdk/ios/overview.mdx b/sdk/ios/overview.mdx index cc56d647..5da4a29c 100644 --- a/sdk/ios/overview.mdx +++ b/sdk/ios/overview.mdx @@ -75,7 +75,7 @@ platform :ios, '12.0' use_frameworks! target 'YourApp' do - pod 'CometChatSDK', '4.0.67' + pod 'CometChatSDK', '4.0.69' end ``` diff --git a/sdk/ios/setup.mdx b/sdk/ios/setup.mdx index 165d141c..0f3b94ae 100644 --- a/sdk/ios/setup.mdx +++ b/sdk/ios/setup.mdx @@ -53,7 +53,7 @@ platform :ios, '11.0' use_frameworks! target 'MyApp' do - pod 'CometChatSDK', '4.0.67' + pod 'CometChatSDK', '4.0.69' end ``` @@ -96,7 +96,7 @@ To install **Swift Packages** you can use Xcode package manager\*\*.\*\* -3. Once the pop-up appears, enter the github repository address in the search bar [`https://github.com/cometchat/chat-sdk-ios.git`](https://github.com/cometchat/chat-sdk-ios.git) and set dependency rule to `Up to Next Major Version` and set version as `4.0.67` . Then click on the **Add Package** button. +3. Once the pop-up appears, enter the github repository address in the search bar [`https://github.com/cometchat/chat-sdk-ios.git`](https://github.com/cometchat/chat-sdk-ios.git) and set dependency rule to `Up to Next Major Version` and set version as `4.0.69` . Then click on the **Add Package** button. diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index c1412178..6648ba35 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -868,6 +868,69 @@ let GUID: string = "GUID", +## Hide quoted messages in user/group conversations + +*In other words, how do I exclude quoted messages in a user/group conversations* + +In order to do this, you can use the `hideQuotedMessages()` method. This method takes boolean as input. This boolean when set to true will make sure that the quoted messages are not fetched. If set to false, which is also the default value, the quoted messages will also be fetched along with other messages. + + + +```javascript +let UID = "UID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hideQuotedMessages(true) + .build(); +``` + + + + +```javascript +let GUID = "GUID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hideQuotedMessages(true) + .build(); +``` + + + + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hideQuotedMessages(true) + .build(); +``` + + + + +```typescript +let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hideQuotedMessages(true) + .build(); +``` + + + + + ## Messages by tags *In other words, how do I fetch messages by tags* diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index c464f9b9..03bcd6c4 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -410,6 +410,28 @@ CometChatCalls.muteAudio(true); If set to `true` the audio stream will be muted and if set to `false` the audio stream will be unmuted. +### Switch Camera +**Available since:** `v4.2.0` +This method is only supported on mobile browsers, it has no effect on desktop browsers. +Use the switchCamera() method to toggle between the front and rear cameras. + + + +```js +CometChatCalls.switchCamera(); +``` + + + + +```typescript +CometChatCalls.switchCamera(); +``` + + + + + ### Pause Video You can call the `pauseVideo(pause: boolean)` method to pause/unpause video stream. diff --git a/sdk/javascript/overview.mdx b/sdk/javascript/overview.mdx index 16506a98..f7edcaaa 100644 --- a/sdk/javascript/overview.mdx +++ b/sdk/javascript/overview.mdx @@ -297,13 +297,14 @@ The `init()` method initializes the settings required for CometChat. The `init() 1. appID - Your CometChat App ID 2. appSettings - An object of the AppSettings class can be created using the AppSettingsBuilder class. The region field is mandatory and can be set using the `setRegion()` method. -The `AppSettings` class allows you to configure two settings: +The `AppSettings` class allows you to configure the following settings: * **Region**: The region where your app was created. * [Presence Subscription](/sdk/javascript/user-presence): Represents the subscription type for user presence (real-time online/offline status) * **autoEstablishSocketConnection(boolean value)**: This property takes a boolean value which when set to `true` informs the SDK to manage the web-socket connection internally. If set to `false`, it informs the SDK that the web-socket connection will be managed manually. The default value for this parameter is true. For more information on this, please check the [Managing Web-Socket connections manually](/sdk/javascript/managing-web-sockets-connections-manually) section. The default value for this property is **true.** * **overrideAdminHost(adminHost: string)**: This method takes the admin URL as input and uses this admin URL instead of the default admin URL. This can be used in case of dedicated deployment of CometChat. * **overrideClientHost(clientHost: string)**: This method takes the client URL as input and uses this client URL instead of the default client URL. This can be used in case of dedicated deployment of CometChat. +* **setStorageMode(storageMode)**: This method allows you to configure how CometChat stores data locally. The storageMode parameter can be set to `CometChat.StorageMode.SESSION` to use session storage, which persists data only for the current browser session, or other available storage modes for different persistence behaviors. You need to call `init()` before calling any other method from CometChat. We suggest you call the `init()` method on app startup, preferably in the `index.js` file. @@ -316,6 +317,7 @@ let appSetting = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(true) + .setStorageMode(CometChat.StorageMode.SESSION) .build(); CometChat.init(appID, appSetting).then( () => { @@ -337,6 +339,7 @@ let appID: string = "APP_ID", .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(true) + .setStorageMode(CometChat.StorageMode.SESSION) .build(); CometChat.init(appID, appSetting).then( (initialized: boolean) => { diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index 15f837cc..a58ef59d 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -356,6 +356,70 @@ let limit: number = 30, +### Hide Agentic Conversations + +This method allows you to exclude agent conversations from the conversation list. When set to `true`, conversations with AI agents will be filtered out. + + + +```js +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setHideAgentic(true) + .build(); +``` + + + + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setHideAgentic(true) + .build(); +``` + + + + + +### Only Agentic Conversations + +This method allows you to fetch only agent conversations. When set to `true`, only conversations with AI agents will be returned in the list. + + + +```js +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setOnlyAgentic(true) + .build(); +``` + + + + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setOnlyAgentic(true) + .build(); +``` + + + + + + + +The `setHideAgentic()` and `setOnlyAgentic()` methods are mutually exclusive. You should only use one of them in a single request builder instance. + + + Finally, once all the parameters are set to the builder class, you need to call the `build()` method to get the object of the `ConversationsRequest` class. Once you have the object of the `ConversationsRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `Conversation` objects containing X number of users depending on the limit set. diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index 905dc186..3e21b909 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -107,6 +107,42 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb +### Set Status + +The status based on which the group members are to be fetched. The status parameter can contain one of the below two values: + +* CometChat.USER_STATUS.ONLINE - will return the list of only online group members. +* CometChat.USER_STATUS.OFFLINE - will return the list of only offline group members. + +If this parameter is not set, will return all the group members regardless of their status. + + + +```javascript +let GUID = "GUID"; +let limit = 30; +let groupMembersRequest = new CometChat.GroupMembersRequestBuilder(GUID) + .setLimit(limit) + .setStatus(CometChat.USER_STATUS.ONLINE) + .build(); +``` + + + + +```typescript +let GUID: string = "GUID"; +let limit: number = 30; +let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMembersRequestBuilder(GUID) + .setLimit(limit) + .setStatus(CometChat.USER_STATUS.ONLINE) + .build(); +``` + + + + + Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the `GroupMembersRequest` class. Once you have the object of the `GroupMembersRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `GroupMember` objects containing n number of members where n is the limit set in the builder class. diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 57700994..ae9f8e12 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -172,6 +172,124 @@ CometChat.sendMessage(textMessage).then( +### Set Quoted Message Id + +To set a quoted message ID for a message, use the `setQuotedMessageId()` method of the TextMessage class. This method accepts the ID of the message to be quoted. + + + +```javascript +textMessage.setQuotedMessageId(10); +``` + + + + +```typescript +textMessage.setQuotedMessageId(10); +``` + + + + + +Once the text message object is ready, you need to use the `sendMessage()` method to send the text message to the recipient. + + + +```javascript +let receiverID = "UID"; +let messageText = "Hello world!"; +let receiverType = CometChat.RECEIVER_TYPE.USER; +let textMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType +); + +CometChat.sendMessage(textMessage).then( + (message) => { + console.log("Message sent successfully:", message); + }, + (error) => { + console.log("Message sending failed with error:", error); + } +); +``` + + + + +```javascript +let receiverID = "GUID"; +let messageText = "Hello world!"; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let textMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType +); + +CometChat.sendMessage(textMessage).then( + (message) => { + console.log("Message sent successfully:", message); + }, + (error) => { + console.log("Message sending failed with error:", error); + } +); +``` + + + + +```typescript +let receiverID: string = "UID", + messageText: string = "Hello world!", + receiverType: string = CometChat.RECEIVER_TYPE.USER, + textMessage: CometChat.TextMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); + +CometChat.sendMessage(textMessage).then( + (message: CometChat.TextMessage) => { + console.log("Message sent successfully:", message); + }, + (error: CometChat.CometChatException) => { + console.log("Message sending failed with error:", error); + } +); +``` + + + + +```typescript +let receiverID: string = "GUID", + messageText: string = "Hello world!", + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + textMessage: CometChat.TextMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); + +CometChat.sendMessage(textMessage).then( + (message: CometChat.TextMessage) => { + console.log("Message sent successfully:", message); + }, + (error: CometChat.CometChatException) => { + console.log("Message sending failed with error:", error); + } +); +``` + + + + + The `TextMessage` class constructor takes the following parameters: | Parameter | Description | | @@ -395,6 +513,153 @@ CometChat.sendMediaMessage(mediaMessage).then( +### Set Quoted Message Id + +To set a quoted message ID for a message, use the `setQuotedMessageId()` method of the MediaMessage class. This method accepts the ID of the message to be quoted. + + + +```javascript +mediaMessage.setQuotedMessageId(10); +``` + + + + +```typescript +mediaMessage.setQuotedMessageId(10); +``` + + + + + +There are 2 ways you can send Media Messages using the CometChat SDK: + +1. **By providing the File:** You can directly share the file object while creating an object of the MediaMessage class. When the media message is sent using the `sendMediaMessage()` method, this file is then uploaded to CometChat servers and the URL of the file is sent in the success response of the `sendMediaMessage()` function. + +Getting file Object: + + + +```html + + + + + + +``` + + + + + + + +```javascript +let receiverID = "UID"; +let messageType = CometChat.MESSAGE_TYPE.FILE; +let receiverType = CometChat.RECEIVER_TYPE.USER; +let mediaMessage = new CometChat.MediaMessage( + receiverID, + "INPUT FILE OBJECT", + messageType, + receiverType +); + +CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } +); +``` + + + + +```javascript +let receiverID = "GUID"; +let messageType = CometChat.MESSAGE_TYPE.FILE; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let mediaMessage = new CometChat.MediaMessage( + receiverID, + `INPUT FILE OBJECT`, + messageType, + receiverType +); + +CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } +); +``` + + + + +```typescript +let receiverID: string = "UID", + messageType: string = CometChat.MESSAGE_TYPE.FILE, + receiverType: string = CometChat.RECEIVER_TYPE.USER, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + "INPUT FILE OBJECT", + messageType, + receiverType + ); + +CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } +); +``` + + + + +```typescript +let receiverID: string = "GUID", + messageType: string = CometChat.MESSAGE_TYPE.FILE, + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + "INPUT FILE OBJECT", + messageType, + receiverType + ); + +CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } +); +``` + + + + + The `MediaMessage` class constructor takes the following parameters: | Parameter | Description | | @@ -1063,6 +1328,144 @@ CometChat.sendCustomMessage(customMessage).then( +### Set Quoted Message Id + +To set a quoted message ID for a message, use the `setQuotedMessageId()` method of the CustomMessage class. This method accepts the ID of the message to be quoted. + + + +```javascript +customMessage.setQuotedMessageId(10); +``` + + + + +```typescript +customMessage.setQuotedMessageId(10); +``` + + + + + +Once the object of `CustomMessage` class is ready you can send the custom message using the `sendCustomMessage()` method. + + + +```javascript +let receiverID = "UID"; +let customData = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", +}; +let customType = "location"; +let receiverType = CometChat.RECEIVER_TYPE.USER; +let customMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData +); + +CometChat.sendCustomMessage(customMessage).then( + (message) => { + console.log("custom message sent successfully", message); + }, + (error) => { + console.log("custom message sending failed with error", error); + } +); +``` + + + + +```javascript +let receiverID = "GUID"; +let customData = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", +}; +let customType = "location"; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let customMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData +); + +CometChat.sendCustomMessage(customMessage).then( + (message) => { + console.log("custom message sent successfully", message); + }, + (error) => { + console.log("custom message sending failed with error", error); + } +); +``` + + + + +```typescript +let receiverID: string = "UID", + customData: Object = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }, + customType: string = "location", + receiverType: string = CometChat.RECEIVER_TYPE.USER, + customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + +CometChat.sendCustomMessage(customMessage).then( + (message: CometChat.CustomMessage) => { + console.log("custom message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("custom message sending failed with error", error); + } +); +``` + + + + +```typescript +let receiverID: string = "GUID", + customData: Object = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }, + customType: string = "location", + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + +CometChat.sendCustomMessage(customMessage).then( + (message: CometChat.CustomMessage) => { + console.log("custom message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("custom message sending failed with error", error); + } +); +``` + + + + + The above sample explains how custom messages can be used to share the location with a user. The same can be achieved for groups. On success, you will receive an object of the `CustomMessage` class. diff --git a/sdk/react-native/ai-agents.mdx b/sdk/react-native/ai-agents.mdx new file mode 100644 index 00000000..f4b88d96 --- /dev/null +++ b/sdk/react-native/ai-agents.mdx @@ -0,0 +1,134 @@ +--- +title: "AI Agents" +--- + +# AI Agents Overview + +AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). + +> **Note:** +> Currently, an Agent only responds to **Text Messages**. + +## Agent Run Lifecycle and Message Flow + +This section explains how a user’s text message to an Agent becomes a structured "run" which emits real-time events and then produces agentic messages for historical retrieval. +- A user sends a text message to an Agent. +- The platform starts a run and streams real-time events via the **`AIAssistantListener`**. +- After the run completes, persisted Agentic Messages arrive via the **`MessageListener`**. + +### Real-time Events +Events are received via the **`onAIAssistantEventReceived`** method of the **`AIAssistantListener`** class in this general order: + +1. Run Start +2. Zero or more tool call cycles (repeats for each tool invocation): + - Tool Call Start + - Tool Call Arguments + - Tool Call End + - Tool Call Result +3. One or more assistant reply streams: + - Text Message Start + - Text Message Content (multiple times; token/char streaming) + - Text Message End +4. Run Finished + +Notes: +- `Run Start` and `Run Finished` are always emitted. +- `Tool Call` events appear only when a backend or frontend tool is invoked. There can be multiple tool calls in a single run. +- `Text Message` events are always emitted and carry the assistant’s reply incrementally. + + + + ```js + const listnerId = "unique_listener_id"; + + // Adding the AIAssistantListener + CometChat.addAIAssistantListener(listnerId, { + onAIAssistantEventReceived: (message) => { + console.log("AIAssistant event received successfully", message); + } + }); + + // Removing the AIAssistantListener + CometChat.removeAIAssistantListener(listnerId); + ``` + + + ```ts + const listnerId: string = "unique_listener_id"; + + // Adding the AIAssistantListener + CometChat.addAIAssistantListener(listnerId, { + onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { + console.log("AIAssistant event received successfully", message); + } + }); + + // Removing the AIAssistantListener + CometChat.removeAIAssistantListener(listnerId); + ``` + + + +#### Event descriptions +- Run Start: A new run has begun for the user’s message. +- Tool Call Start: The agent decided to invoke a tool. +- Tool Call Arguments: Arguments being passed to the tool. +- Tool Call End: Tool execution completed. +- Tool Call Result: Tool’s output is available. +- Text Message Start: The agent started composing a reply. +- Text Message Content: Streaming content chunks for progressive rendering. +- Text Message End: The agent reply is complete. +- Run Finished: The run is finalized; persisted messages will follow. + +### Agentic Messages + +These events are received via the **`MessageListener`** after the run completes. +- `AIAssistantMessage`: The full assistant reply. +- `AIToolResultMessage`: The final output of a tool call. +- `AIToolArgumentMessage`: The arguments that were passed to a tool. + + + + ```js + const listnerId = "unique_listener_id"; + + // Adding the MessageListener + CometChat.addMessageListener(listnerId, { + onAIAssistantMessageReceived: (message) => { + console.log("AI Assistant message received successfully", message); + }, + onAIToolResultReceived: (message) => { + console.log("AI Tool result message received successfully", message); + }, + onAIToolArgumentsReceived: (message) => { + console.log("AI Tool argument message received successfully", message); + }, + }); + + // Removing the MessageListener + CometChat.removeMessageListener(listnerId); + ``` + + + + ```ts + const listnerId: string = "unique_listener_id"; + + // Adding the MessageListener + CometChat.addMessageListener(listnerId, { + onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { + console.log("AI Assistant message received successfully", message); + }, + onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { + console.log("AI Tool result message received successfully", message); + }, + onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { + console.log("AI Tool argument message received successfully", message); + }, + }); + + // Removing the MessageListener + CometChat.removeMessageListener(listnerId); + ``` + + \ No newline at end of file diff --git a/sdk/react-native/overview.mdx b/sdk/react-native/overview.mdx index 24e9b1e5..3d3b21bc 100644 --- a/sdk/react-native/overview.mdx +++ b/sdk/react-native/overview.mdx @@ -59,7 +59,7 @@ npm install @react-native-async-storage/async-storage v2.4+ onwards, Voice & Video Calling functionality has been moved to a separate library. In case you plan to use the calling feature, please install the Calling dependency (@cometchat/calls-sdk-react-native).\ \ -`npm install @cometchat/calls-sdk-react-native@2.3.0`\ +`npm install @cometchat/calls-sdk-react-native`\ \ The calling component requires some configuration. Please follow the steps mentioned [here](/sdk/react-native/overview#calling-component-configuration). @@ -74,12 +74,11 @@ For `@cometchat/calls-sdk-react-native`, please make sure you add the following ```json { "@cometchat/chat-sdk-react-native": "^4.0.14", - "@react-native-async-storage/async-storage": "^1.23.1", - "@react-native-community/netinfo": "^11.3.1", // for react-native 0.63 & above. - "@react-native-community/netinfo": "6.1.0", // for react-native below 0.63 + "@react-native-async-storage/async-storage": "^2.2.0", + "@react-native-community/netinfo": "^11.4.1", "react-native-background-timer": "^2.4.1", - "react-native-callstats": "^3.73.7", - "react-native-webrtc": "^1.106.1" + "react-native-callstats": "^3.73.22", + "react-native-webrtc": "^124.0.6" } ``` diff --git a/snippets/nav-filter.js b/snippets/nav-filter.js index aebd362c..fe279db3 100644 --- a/snippets/nav-filter.js +++ b/snippets/nav-filter.js @@ -82,7 +82,7 @@ '/ai-agents', '/ai-agents/', '/ai-agents/mastra', - // Show the AI Agents Chat Builder (widget) tab when in AI Agents context + // Show the AI Agents Widget Builder tab when in AI Agents context '/widget/ai-agents' ], 'moderation': [ @@ -99,7 +99,7 @@ // Fallback to tab labels for dropdown-only tabs (from docs.json top-level tabs) var allowedLabelsByRoute = { 'chat-call': [ - 'Chat & Calling', 'Platform', 'UI Kits', 'SDKs', 'No Code - Widgets', 'APIs', 'Chat Builder' + 'Chat & Calling', 'Platform', 'UI Kits', 'SDKs', 'Widget Builder', 'APIs', 'UI Kit Builder' ], 'ai-agents': [ 'AI Agents', 'Agent Builder' @@ -129,11 +129,11 @@ function isBlockedHref(routeKey, pathOnly) { try { pathOnly = stripBase(pathOnly || '/'); } catch (_) {} if (routeKey === 'chat-call') { - // Hide AI Agents Chat Builder tab in Chat & Calling context + // Hide AI Agents UI Kit Builder tab in Chat & Calling context if (pathOnly.indexOf('/widget/ai-agents') === 0) return true; } if (routeKey === 'ai-agents') { - // Hide Framework Chat Builder tab in AI Agents context + // Hide Framework UI Kit Builder tab in AI Agents context if (pathOnly.indexOf('/chat-builder') === 0) return true; } return false; @@ -160,8 +160,8 @@ function isAllowedLabel(routeKey, labelEl) { if (!routeKey || !labelEl) return false; var lbl = normalizeLabel(labelEl); - // Special-case: both top-level tabs share the label "Chat Builder". - if (lbl === 'chat builder') { + // Special-case: both top-level tabs share the label "UI Kit Builder". + if (lbl === 'ui kit builder') { var id = getTabId(labelEl); // If a tab-id is present, honor it strictly if (id === 'chat-builder') return routeKey === 'chat-call'; @@ -246,11 +246,11 @@ if (isHomeItem(el)) { show(el); return; } var href = (el.getAttribute('href') || '').trim(); var keep = isAllowedHref(routeKey, href) || isAllowedLabel(routeKey, el); - // Additional guard for duplicate-labeled Chat Builder tabs when both exist - if (keep && normalizeLabel(el) === 'chat builder') { + // Additional guard for duplicate-labeled UI Kit Builder tabs when both exist + if (keep && normalizeLabel(el) === 'ui kit builder') { var id = getTabId(el); - if (routeKey === 'chat-call' && id === 'ai-agent-chat-builder') keep = false; - if (routeKey === 'ai-agents' && id === 'chat-builder') keep = false; + if (routeKey === 'chat-call' && id === 'ai-agent-ui-kit-builder') keep = false; + if (routeKey === 'ai-agents' && id === 'ui-kit-builder') keep = false; } if (keep) show(el); else hide(el); }); diff --git a/snippets/widget/chat-call-methods.mdx b/snippets/widget/chat-call-methods.mdx index e82ec65a..ffb4a7b6 100644 --- a/snippets/widget/chat-call-methods.mdx +++ b/snippets/widget/chat-call-methods.mdx @@ -12,4 +12,10 @@ CometChatApp.callUser("UID"); // Initiate calls with a particular group CometChatApp.callGroup("GUID"); -``` + +// Show or hide action messages in group chats +CometChatApp.showGroupActionMessages(true); + +// Show or hide unread message count bubble on docked layout +CometChatApp.showDockedUnreadCount(true); +``` \ No newline at end of file diff --git a/snippets/widget/overview.mdx b/snippets/widget/overview.mdx index fa50da91..2aaf7ec9 100644 --- a/snippets/widget/overview.mdx +++ b/snippets/widget/overview.mdx @@ -34,7 +34,7 @@ The Chat Widget enables you to embed a fully functional chat interface into your ## Customize Chat Widget -1. In Chat Builder, adjust **Appearance**. +1. In UI Kit Builder, adjust **Appearance**. - Adjust **Theme**, **Colors**, and **Typography** to match your brand. 2. Select **Features** (e.g., **Block Users**, **Threaded Messages**, **Read Receipts**). 3. Preview changes in the **Live Preview** pane. @@ -42,7 +42,7 @@ The Chat Widget enables you to embed a fully functional chat interface into your ## Export Code -1. In Chat Builder, click **Get Embedded Code**. +1. In UI Kit Builder, click **Get Embedded Code**. 2. Note the app credentials: - **App ID** - **Auth Key** diff --git a/ui-kit/android/ai-assistant-chat-history.mdx b/ui-kit/android/ai-assistant-chat-history.mdx new file mode 100644 index 00000000..d692600a --- /dev/null +++ b/ui-kit/android/ai-assistant-chat-history.mdx @@ -0,0 +1,245 @@ +--- +title: "AI Assistant Chat History" +--- + +## Overview + +The `AI Assistant Chat History` component is a pre-built user interface element designed to display the conversation history between users and an AI assistant within a chat application. It provides a structured and visually appealing way to present past interactions, making it easy for users to review previous messages and context. + + + + + +*** + +## Usage + +### Integration + +`AIAssistantChatHistory`, as a Composite Component, offers flexible integration options, allowing it to be launched directly via button clicks or any user-triggered action. + +The following code snippet exemplifies how you can seamlessly integrate the GroupMembers component into your application. + + + +```xml + +``` + + + + + +If you're defining the Group members within the XML code, you'll need to extract them and set them on the Group object using the appropriate method. + + + +```java + +User user = new User(); +user.setUid("userId"); +user.setName("User Name"); +user.setRole("@agentic"); // User role must be @agentic to use AI Assistant features + +binding.cometChatAiAssistantChatHistory.setUser(user); +``` + + + + +```kotlin + +val user = User() +user.uid = "userId" +user.name = "User Name" +user.role = "@agentic" // User role must be @agentic to use AI Assistant features + +binding.cometChatAiAssistantChatHistory.setUser(user) +``` + + + + + +*** + +### Actions + +[Actions](/ui-kit/android/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. + +##### setOnItemClickListener + +Function invoked when a chat history item is clicked, typically used to open an ai assistant chat screen. + + + +```java YourActivity.java + +binding.cometchatAiAssistantChatHistory.setOnItemClickListener((view, position, message) -> { + + }); +``` + + + + +```kotlin YourActivity.kt +binding.cometchatAiAssistantChatHistory.setOnItemClickListener { view, position, message -> + + } +``` + + + + + +*** + +##### setOnItemLongClick + +Function executed when a user item is long-pressed, allowing additional actions like delete or block. + + + +```java YourActivity.java +binding.cometchatAiAssistantChatHistory.setOnItemLongClickListener((view, position, message) -> { + + }); +``` + + + + +```kotlin YourActivity.kt +binding.cometchatAiAssistantChatHistory.setOnItemLongClickListener { view, position, message -> + + } +``` + + + + + +*** + +##### setOnNewChatClickListener + +Function triggered when the new chat button is clicked, typically used to start a new conversation with the AI assistant. + + + +```java YourActivity.java +binding.cometchatAiAssistantChatHistory.setOnNewChatClickListener(() -> { + + }); +``` + + + + +```kotlin YourActivity.kt +binding.cometchatAiAssistantChatHistory.setOnNewChatClickListener { + + } +``` + + + + + +*** + +##### setOnCloseClickListener + +Function activated when the close button is clicked, usually to exit the chat history view. + + + +```java YourActivity.java +binding.cometchatAiAssistantChatHistory.setOnCloseClickListener(() -> { + + }); +``` + + + + +```kotlin YourActivity.kt +binding.cometchatAiAssistantChatHistory.setOnCloseClickListener { + + } +``` + + + + + +## Customization + +The `AIAssistantChatHistory` component offers a variety of customization options to tailor its appearance and functionality to better fit your application's needs. These customizations are categorized into three main areas: Style, Functionality, and Advanced. + +### Style + +Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. + + + + + +```xml themes.xml + + + +``` + + + +```java +binding.cometchatAiAssistantChatHistory.setStyle(R.style.CustomAIAssistantChatHistoryStyle); +``` + + + + +```kotlin +binding.cometchatAiAssistantChatHistory.setStyle(R.style.CustomAIAssistantChatHistoryStyle); +``` + + + + + +*** + +To know more such attributes, visit the [attributes file](https://github.com/cometchat/cometchat-uikit-android/blob/v5/chatuikit/src/main/res/values/attr_cometchat_ai_assistant_chat_history.xml). + +### Functionality + +These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can toggle the visibility of UI elements. + +Below is a list of customizations along with corresponding code snippets + +| Methods | Description | Code | +| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | +| setUser | Sets the user whose chat histories with the ai assistant need to be fetched. This is a required property for the component to function properly. | `.setUser(user);` | +| setErrorStateVisibility | Used to toggle the visibility of the error state of the component | `.setErrorStateVisibility(View.GONE);` | +| setEmptyStateVisibility | Used to toggle the visibility of the empty state of the component | `.setEmptyStateVisibility(View.GONE);` | diff --git a/ui-kit/android/component-styling.mdx b/ui-kit/android/component-styling.mdx index 18c65cfa..ecb2121c 100644 --- a/ui-kit/android/component-styling.mdx +++ b/ui-kit/android/component-styling.mdx @@ -435,6 +435,44 @@ The `CometChatCallButton` Component initiates voice or video calls with a single To know more such attributes, visit the [attributes file](https://github.com/cometchat/cometchat-uikit-android/blob/v5/chatuikit/src/main/res/values/attr_cometchat_call_buttons.xml). +### AI Assistant Chat History + +The `CometChatAIAssistantChatHistory` component displays the history of interactions with an AI assistant. It provides a seamless way to view past conversations, ensuring users can easily reference previous AI responses. + + + + + +```xml themes.xml + + + +``` + +```xml themes.xml + +``` + +To know more such attributes, visit the [attributes file](https://github.com/cometchat/cometchat-uikit-android/blob/v5/chatuikit/src/main/res/values/attr_cometchat_ai_assistant_chat_history.xml). + ## Base Component ### Avatar diff --git a/ui-kit/android/getting-started.mdx b/ui-kit/android/getting-started.mdx index 340c0b61..dd3f96be 100644 --- a/ui-kit/android/getting-started.mdx +++ b/ui-kit/android/getting-started.mdx @@ -141,7 +141,7 @@ Inside `libs.versions.toml`, add the CometChat Chat UI Kit version under the `[v ```toml libs.versions.toml [versions] cometchat-ui-kit = "5.1.0" -cometchat-calls-sdk = "4.1.0" +cometchat-calls-sdk = "4.3.1" ``` Under the `[libraries]` section, define the library and reference the version: diff --git a/ui-kit/android/guide-ai-agent.mdx b/ui-kit/android/guide-ai-agent.mdx new file mode 100644 index 00000000..5c3e55c8 --- /dev/null +++ b/ui-kit/android/guide-ai-agent.mdx @@ -0,0 +1,332 @@ +--- +title: "AI Agent Integration" +sidebarTitle: "AI Agent Integration" +--- + +Enable intelligent conversational AI capabilities in your Android app using CometChat UIKit v5 with AI Agent integration: + +- **AI Assistant Chat History** +- **Chat History Management** +- **Contextual Responses** +- **Agent Detection** +- **Seamless Handoffs** + +Transform your chat experience with AI-powered assistance that provides intelligent responses and offers seamless integration with your existing chat infrastructure. + +## Overview + +Users can interact with AI agents through a dedicated chat interface that: + +- Provides intelligent responses based on conversation context. +- Maintains chat history for continuity. +- Seamlessly integrates with your existing user chat system. + +The AI Agent chat interface provides a familiar messaging experience enhanced with AI capabilities, accessible through your main chat flow or as a standalone feature. + + + + + +## Prerequisites + +- Android Studio project with **cometchat/cometchat-uikit-android** and **cometchat/chat-sdk-android** in `build.gradle`. +- Internet permission in `AndroidManifest.xml`. +- Valid CometChat **App ID**, **Region**, and **Auth Key** configured via `UIKitSettings`. +- User logged in with `CometChatUIKit.login()`. +- AI Agent configured in your CometChat dashboard. + +## Components + +| Component / Class | Role | +|:----------------------------------|:----------------------------------------------------------| +| `AIAssistantChatActivity` | Main activity for AI agent chat. | +| `CometChatAIAssistantChatHistory` | Displays previous AI conversation history. | +| `CometChatMessageList` | Shows AI messages with threading support. | +| `CometChatMessageComposer` | Input interface for AI conversations. | +| `CometChatMessageHeader` | Header with AI agent info and controls. | + +## Integration Steps + +### Step 1 - Activity Setup + +Create the AI Assistant chat activity with proper theme and layout configuration. + +```kotlin +class AIAssistantChatActivity : AppCompatActivity() { + private lateinit var binding: ActivityAiAssistantChatBinding + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityAiAssistantChatBinding.inflate(layoutInflater) + setContentView(binding.root) + + val messageJson = intent.getStringExtra(getString(R.string.app_base_message)) + val userJson = intent.getStringExtra(getString(R.string.app_user)) + + if (userJson != null && !userJson.isEmpty()) + val user = User.fromJson(userJson) + if (messageJson != null && !messageJson.isEmpty()) + val parentMessage = BaseMessage.processMessage(JSONObject(messageJson)) + + initializeComponents(user, parentMessage) + initClickListeners() + } + + private fun initializeComponents(user: User, parentMessage: BaseMessage) { + binding.messageHeader.user = user // Set user for header + binding.messageList.user = user // Set user for message list + binding.messageComposer.user = user // Set user for composer + + if (parentMessage != null) { + // Set message id of parent message to fetch messages with parent. + // Here we are setting parent message id to message list to fetch messages and message composer to send reply to that message. + // Here this is being used for AIAssistantChatHistory + binding.messageList.setParentMessage(parentMessage!!.getId()) + binding.messageComposer.setParentMessageId(parentMessage!!.getId()) + } + + binding.messageList.setStyle(R.style.CustomCometChatMessageListStyle) // Custom style for AI chat + binding.messageComposer.style = R.style.CustomMessageComposerStyle // Custom style for AI chat + } +} +``` + +**File reference:** +[`AIAssistantChatActivity.kt`](ai-builder/src/main/java/com/cometchat/ai/builder/ui/activity/AIAssistantChatActivity.kt) + +### Step - 2 AIAssistantChatActivity layout: + +Add `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to your layout to enable a complete AI chat interface. Use the sample XML below as a reference for correct integration. + +```xml + + + + + + + + + + + +``` + +**File reference:** +[`activity_ai_assistant_chat.xml`](ai-builder/src/main/java/com/cometchat/ai/builder/ui/activity/AIAssistantChatActivity.kt) + +### Step 3 - Style of Message List & Composer + +Define custom styles for the message list and composer to differentiate AI agent chats. + +```xml + + + + + + + + + + + +``` + +### Step 4 - Initialize click listeners + +Initialize click listeners of message header to handle new chat creation and chat history access. + +```kotlin + +private fun initClickListeners() { + + // New chat creation + binding.messageHeader.setNewChatButtonClick { + Utils.hideKeyBoard(this@AIAssistantChatActivity, binding.root) + val intent = Intent(this@AIAssistantChatActivity, AIAssistantChatActivity::class.java) + intent.putExtra(getString(R.string.app_user), user.toJson().toString()) // Pass user to create new chat + startActivity(intent) + finish() + } + + // Chat history access + binding.messageHeader.setChatHistoryButtonClick { + val intent = Intent(this@AIAssistantChatActivity, AIAssistantChatHistoryActivity::class.java) + intent.putExtra(getString(R.string.app_user), user.toJson().toString()) // Pass user to fetch chat history + startActivity(intent) + } +} + +``` + +### Step 5 - Create an activity for AIAssistantChatHistory component. + +Create a new activity to host `CometChatAIAssistantChatHistory` component and handle its interactions. + +```kotlin +class AIAssistantChatHistoryActivity : AppCompatActivity() { + private lateinit var binding: ActivityAiAssistantChatHistoryBinding + private var user: User? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityAiAssistantChatHistoryBinding.inflate(layoutInflater) + setContentView(binding.root) + + val userJson = intent.getStringExtra(getString(R.string.app_user)) + + if (userJson != null && !userJson.isEmpty()) { + user = User.fromJson(userJson) + + // Set user to fetch chat history + binding.cometchatAiAssistantChatHistory.setUser(user) + } + + // Use setStyle() method of the component to apply custom styles if needed + // binding.cometchatAiAssistantChatHistory.setStyle(R.style.CustomCometChatAIAssistantChatHistoryStyle) + // See docs of CometChatAIAssistantChatHistory for available style attributes + + // init click listeners + initClickListeners() + } + + private fun initClickListeners() { + // History item click + binding.cometchatAiAssistantChatHistory.setOnItemClickListener { view, position, message -> + val appEntity = message.getReceiver() + if (appEntity is User) { + user = appEntity + val intent = Intent(this@AIAssistantChatHistoryActivity, AIAssistantChatActivity::class.java) + intent.putExtra(getString(R.string.app_user), appEntity.toJson().toString()) + intent.putExtra( + getString(R.string.app_base_message), + message.getRawMessage().toString() + ) + startActivity(intent) + finish() + } + } + + // New chat creation from history screen + binding.cometchatAiAssistantChatHistory.setNewChatButtonClick { + val intent = Intent(this@AIAssistantChatHistoryActivity, AIAssistantChatActivity::class.java) + intent.putExtra(getString(R.string.app_user), user!!.toJson().toString()) // Pass user to create new chat + startActivity(intent) + finish() + } + + // Close history screen + binding.cometchatAiAssistantChatHistory.setCloseButtonClick { + // finish the activity + } + } +} +``` + +### Step 6 - AIAssistantChatActivity layout: + +Add `CometChatAIAssistantChatHistory` to your layout to enable access to AI chat history. Use the sample XML below as a reference for correct integration. + +```xml + + + + + + + +``` + +### Step 7 - Launching AI Chat + +Create intent and start AI Assistant chat from your main application. + +```kotlin +// In your main activity or chat list +fun launchAIAssistantChat(aiUser: User, parentMessage: BaseMessage? = null) { + val intent = Intent(this, AIAssistantChatActivity::class.java) + intent.putExtra(getString(R.string.app_user), aiUser.toJson().toString()) + startActivity(intent) +} +``` + +## Implementation Flow Summary + +| Step | Action | +|:-----|:-------------------------------------------- | +| 1 | User selects AI agent from chat list | +| 2 | `AIAssistantChatActivity` launches | +| 3 | Parse intent data and detect agent chat (Role of user must be "@agentic") | +| 4 | Initialize UI with AI-specific styling | +| 6 | Configure chat history and navigation | +| 7 | Launch chat with AI agent | + +## Customization Options + +- **Custom AI Assistant Empty Chat View:** Customize the empty state view using `setAIAssistantEmptyChatGreetingView()` method. +- **Streaming Speed:** Adjust AI response streaming speed via `setStreamingSpeed()` method. +- **AI Assistant Suggested Messages:** Create custom list of suggested messages and set quick prompts using `setAIAssistantSuggestedMessages()` method. +- **AI Assistant Tools:** Set tools for the AI agent using `setAIAssistantTools()` method. + +## Feature Matrix + +| Feature | Implementation | UI Component | +|:-----------------------|:--------------------------------------------|:------------------------| +| AI Chat Interface | `AIAssistantChatActivity` | Full chat screen | +| Chat History | `CometChatAIAssistantChatHistory` | Chat history screen | + + + + Explore this feature in the CometChat AI Builder: + [GitHub → AI Builder](https://github.com/cometchat/cometchat-uikit-android/tree/v5/ai-builder) + + + Explore this feature in the CometChat SampleApp: + [GitHub → SampleApp](https://github.com/cometchat/cometchat-uikit-android/tree/v5/sample-app-java) + + \ No newline at end of file diff --git a/ui-kit/android/guide-block-unblock-user.mdx b/ui-kit/android/guide-block-unblock-user.mdx new file mode 100644 index 00000000..8249662e --- /dev/null +++ b/ui-kit/android/guide-block-unblock-user.mdx @@ -0,0 +1,192 @@ +--- +title: "Block/Unblock User" +sidebarTitle: "Block/Unblock User" +--- + +Enable users to block and unblock others directly within chat using CometChat’s Android UI Kit v5+, preventing unwanted communication and giving users more control. + +## Overview + +Blocking a user stops them from sending messages to the blocker. The CometChat UIKit handles most behaviors internally: + +- **Composer Hidden:** The message composer is hidden when chatting with a blocked user. +- **Unblock Prompt:** An “Unblock” button is displayed to reverse the block. +- **Message Restrictions:** Blocked users cannot send messages to the blocker. + +## Prerequisites + +- Android Studio project with CometChat Android UI Kit v5 added to `build.gradle`. +- CometChat **App ID**, **Auth Key**, and **Region** configured and initialized. +- `` in `AndroidManifest.xml`. +- Logged-in user via `CometChat.login()`. +- Existing one-on-one chat screen using `CometChatMessageList` and `CometChatMessageComposer`. + +## Components + +| Component / Class | Role | +|:-------------------------------------|:------------------------------------------------------------| +| `UserDetailActivity.java` | Displays user profile and provides block/unblock options. | +| `MessagesActivity.java` | Hosts the chat screen and toggles UI based on block state. | +| `CometChatUIKit.blockUsers()` | API to block one or more users by UID. | +| `CometChatUIKit.unblockUsers()` | API to unblock one or more users by UID. | +| `User.isBlockedByMe()` | Checks if the current user has blocked this user. | +| `unblockLayout` (View) | Layout shown when a user is blocked, containing unblock. | +| `CometChatMessageComposer` | Hidden when chatting with a blocked user. | + +## Integration Steps + +### 1. Detect Block Status + +Update UI when block state changes. + +```java +// In MessagesActivity.java +private void updateUserBlockStatus(User user) { + boolean blocked = user.isBlockedByMe(); + binding.messageComposer.setVisibility(blocked ? View.GONE : View.VISIBLE); + binding.unblockLayout.setVisibility(blocked ? View.VISIBLE : View.GONE); +} +``` + +**File reference:** +[`MessagesActivity.java`](https://github.com/cometchat/cometchat-uikit-android/blob/v5/sample-app-java/app/src/main/java/com/cometchat/sampleapp/MessagesActivity.java#L120-L130) + +Ensures the composer and unblock UI reflect the current block state. + +### 2. Hide Composer & Show Unblock UI + +Define layout elements and their visibility toggles. + +```xml + + + +