Multiple AI agents
Let people ask individual agents questions in a shared project chat.
Several AI agents can work on the same project, such as one researching a question and another proposing code changes. This guide shows how to bring multiple agents into a single TalkJS chat so people can @mention a specific agent, see its reply under its own name, and keep the full history in one place.
Each agent that people can mention needs its own TalkJS user, added as a participant in the shared conversation. For example, create research-agent and code-agent users and add them to a conversation such as project-42 using the JavaScript Data API or REST API:
const conversation = session.conversation(`project-${projectId}`);
conversation.createIfNotExists();
session.user('research-agent').createIfNotExists({ name: 'Research' });
session.user('code-agent').createIfNotExists({ name: 'Code' });
conversation.participant('research-agent').createIfNotExists();
conversation.participant('code-agent').createIfNotExists();Then display that conversation in your chatbox:
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' }}
/>
);
}In your 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 direct a question to that agent.
Add a webhook endpoint on your server to receive new messages from TalkJS:
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'));
// Respond immediately so the webhook doesn't time out while waiting for the agent.
res.sendStatus(200);
replyToMentions(event);
});
app.listen(process.env.PORT || 3001);TalkJS waits five seconds for a webhook response, while AI agents often take longer to reply. Responding 200 OK immediately avoids webhook timeouts and retries. If you deploy on a serverless platform where work stops once a response is sent, enqueue the event to a background worker before returning 200 OK.
Connect the endpoint in the TalkJS dashboard:
- Open your app's Settings and scroll to Webhooks.
- Click Add new webhook.
- Enter your endpoint's public HTTPS URL, such as
https://example.com/talkjs-webhook. - Under Select Events to Subscribe, check message.sent.
- Click Save.
Each message.sent event includes mentionedUserIds, which tells you which agents were mentioned:
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((error) => console.error('Could not send the Research reply:', error));
}
if (mentionedUserIds.includes(codeAgentId)) {
replyAsAgent(conversation.id, message, codeAgentId, askCodeAgent)
.catch((error) => console.error('Could not send the Code reply:', error));
}
}Replace askResearchAgent and askCodeAgent with the calls you already use for your agents. Mentioning both agents triggers both so each can respond.
replyAsAgent fetches recent messages for context, asks the agent for an answer, and posts the reply under that agent's user ID:
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 (error) {
console.error(`Agent ${agentId} failed:`, error);
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 current question passed separately. Passing an idempotencyKey tied to the triggering message and agent prevents duplicate replies if TalkJS ever delivers the same webhook twice.
Each agent returns its answer as a string, which can include lists and code blocks using message formatting.
Add the helper used by the requests above, using your existing Admin JWT generation code for generateAdminJwt:
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 headers = { Authorization: `Bearer ${token}` };
if (body !== undefined) {
headers['Content-Type'] = 'application/json';
}
const response = await fetch(`https://api.talkjs.com/v1/${appId}${path}`, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (!response.ok) {
throw new Error(`TalkJS returned HTTP ${response.status}`);
}
return response.json();
}