---
url: https://talkjs.com/docs/Guides/Multiple_AI_Agents/
title: "Multiple AI agents | Guides | TalkJS Docs"
---

For AI agents: Find a documentation index at https://talkjs.com/llms.txt (full content at https://talkjs.com/llms-full.txt). Get a markdown version of any page by appending .md to its URL path.

# Multiple AI agents

Let people ask individual agents questions in a shared project chat.

Several AI agents can work on the same project, with one researching a question and another proposing code changes. This guide shows how to bring those agents into one project chat. People can ask an individual agent a follow-up question, see its answer under its own name and return to the discussion later.

## Show the project conversation

Use the same conversation ID whenever opening a project's chat. The example builds it from the project ID, so project `42` opens conversation `project-42`.

**React**

```jsx
'use client';

import { Chatbox } from '@talkjs/react-components';
import '@talkjs/react-components/default.css';

function ProjectChat({ userId, projectId }) {
  return (
    <Chatbox
      appId="<APP_ID>"
      userId={userId}
      conversationId={`project-${projectId}`}
      style={{ height: '600px' }}
    />
  );
}
```

**Web Components**

```html
<t-chatbox id="project-chat" style="height: 600px"></t-chatbox>

<script type="module">
  import '@talkjs/web-components';
  import '@talkjs/web-components/default.css';

  function showProjectChat(userId, projectId) {
    const chatbox = document.querySelector('#project-chat');
    chatbox.appId = '<APP_ID>';
    chatbox.userId = userId;
    chatbox.conversationId = `project-${projectId}`;
  }
</script>
```

Reusing the ID opens the existing conversation, including earlier questions and agent answers.

## Mention an agent

Each agent that people can mention should have its own TalkJS user. In this example, add the **Research** and **Code** users to the project conversation so people can mention either one by name.

In your [dashboard](https://talkjs.com/dashboard/), open **Chat UI → Edit roles** and choose the role used by the people in the chat. Under **General**, enable **Allow mentions**.

People can now type `@` and select `Research` or `Code` to address a question to that agent.

## Receive questions on your server

Add an endpoint on your server to receive new messages from TalkJS. This Express endpoint passes each event to `replyToMentions`, which calls the agents mentioned in the message.

```javascript
import express from 'express';

const app = express();

// Register this route before any express.json() middleware.
app.post('/talkjs-webhook', express.raw({ type: 'application/json' }), (req, res) => {
  // Verify the signature using the raw request body.
  // https://talkjs.com/docs/Features/Security/#verify-webhook-integrity
  if (!verifyTalkJSSignature(req)) {
    return res.sendStatus(401);
  }

  const event = JSON.parse(req.body.toString('utf8'));
  res.sendStatus(200);
  replyToMentions(event);
});

app.listen(3001);
```

For local testing, run `ngrok http 3001` to get a public HTTPS URL for your server.

Connect the endpoint in the TalkJS dashboard:

1.  Open your app's **Settings** and scroll to **Webhooks**.
2.  Click **Add new webhook**.
3.  Enter your server's public URL followed by `/talkjs-webhook` in **Webhook URL**. For local testing, use the HTTPS forwarding URL printed by ngrok.
4.  Under **Select Events to Subscribe**, check **message.sent**.
5.  Click **Save**.

When someone sends a message, TalkJS sends the event to this endpoint. It includes the message, sender, conversation and the user IDs of anyone mentioned.

## Call the agent that was mentioned

Use `mentionedUserIds` to choose which agent to call.

```javascript
// Use the TalkJS user IDs for your agents.
const researchAgentId = 'research-agent';
const codeAgentId = 'code-agent';

function replyToMentions(event) {
  if (event.type !== 'message.sent') {
    return;
  }

  const { sender, conversation, message, mentionedUserIds } = event.data;

  // Don't respond to the agents' own messages.
  if (!sender || sender.id === researchAgentId || sender.id === codeAgentId) {
    return;
  }

  if (mentionedUserIds.includes(researchAgentId)) {
    replyAsAgent(conversation.id, message, researchAgentId, askResearchAgent)
      .catch(() => console.error('Could not send the Research reply'));
  }

  if (mentionedUserIds.includes(codeAgentId)) {
    replyAsAgent(conversation.id, message, codeAgentId, askCodeAgent)
      .catch(() => console.error('Could not send the Code reply'));
  }
}
```

Replace `askResearchAgent` and `askCodeAgent` with the calls you already use for your agents. Mentioning both agents calls both, so each can answer the question.

## Send the answer as the agent

Add `replyAsAgent` to fetch the previous messages, ask the agent for an answer and send it under that agent's name.

```javascript
async function replyAsAgent(conversationId, message, agentId, askAgent) {
  try {
    const { data } = await talkjsRequest(
      'GET',
      `/conversations/${encodeURIComponent(conversationId)}/messages?startingAfter=${encodeURIComponent(message.id)}&limit=30`,
    );

    const history = data.reverse().map((previous) => ({
      senderId: previous.senderId,
      text: previous.text,
    }));

    const answer = await askAgent({
      conversationId,
      question: message.text,
      history,
    });

    await talkjsRequest(
      'POST',
      `/conversations/${encodeURIComponent(conversationId)}/messages`,
      [{
        sender: agentId,
        type: 'UserMessage',
        text: answer,
        idempotencyKey: `${message.id}:${agentId}`,
      }],
    );
  } catch {
    await talkjsRequest(
      'POST',
      `/conversations/${encodeURIComponent(conversationId)}/messages`,
      [{
        sender: agentId,
        type: 'UserMessage',
        text: "Something went wrong. Please ask me again.",
        idempotencyKey: `${message.id}:${agentId}:error`,
      }],
    );
  }
}
```

The agent receives the 30 messages before the question, oldest first, with the question passed separately. Adjust how you pass this history to match your agent.

Each agent returns its answer as a string. It can include lists and code blocks using [message formatting](https://talkjs.com/docs/Features/Messages/Formatting/). If an answer exceeds the 10,000-character message limit, split it before sending and give each message its own `idempotencyKey`.

## REST request helper

Add the helper used by the requests above. Use your existing Admin JWT generation code for `generateAdminJwt`.

```javascript
const appId = '<APP_ID>';

async function talkjsRequest(method, path, body) {
  // Reuse your existing Admin JWT generation code
  // Example: https://talkjs.com/docs/REST_API/#authentication
  const token = generateAdminJwt();

  const response = await fetch(`https://api.talkjs.com/v1/${appId}${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  });

  if (!response.ok) {
    throw new Error(`TalkJS returned HTTP ${response.status}`);
  }

  return response.json();
}
```
