WebChat Bot

easy10 minwebchat-bot.ts

Your own web page should chat with the agent over a WebSocket, behind a token.

What it shows

  • Serve webchatChannel() with an auth check

The code

webchat-bot.ts
import { Agent, Cogitator, datetime } from '@cogitator-ai/core';
import { Gateway, webchatChannel } from '@cogitator-ai/channels';

const apiKey = process.env.GOOGLE_API_KEY;
if (!apiKey) throw new Error('Set GOOGLE_API_KEY');

const webchatToken = process.env.WEBCHAT_TOKEN ?? 'dev-token';
const port = Number(process.env.WEBCHAT_PORT ?? 3100);

const agent = new Agent({
  name: 'webchat-assistant',
  model: 'google/gemini-3.5-flash-lite',
  instructions: 'You are a helpful assistant connected via WebChat. Keep responses concise.',
  tools: [datetime],
});

const cogitator = new Cogitator({ llm: { providers: { google: { apiKey } } } });

const gateway = new Gateway({
  agent,
  cogitator,
  channels: [webchatChannel({ port, auth: (token) => token === webchatToken })],
  stream: { flushInterval: 500, minChunkSize: 20 },
  onError: (error, message) => console.error(`Message from ${message.userId} failed:`, error.message),
});

await gateway.start();
console.log(`WebChat on ws://localhost:${port}/ws?token=${webchatToken}`);

process.on('SIGINT', async () => {
  await gateway.stop();
  await cogitator.close();
  process.exit(0);
});

Run it

install · bash
pnpm add @cogitator-ai/core @cogitator-ai/channels ws
EnvironmentGOOGLE_API_KEYWEBCHAT_TOKEN (optional)
run · bash
GOOGLE_API_KEY=your-key npx tsx webchat-bot.ts

Or run the full example from a clone of the repository (keys in .env):

repository · bash
npx tsx examples/channels/03-webchat-bot.ts

Try it

Try it · bash
npx wscat -c "ws://localhost:3100/ws?token=dev-token"

Learn more