Multiple Instances

Multiple Telegram bots on a single AgentOS server

Code

1import os
2
3from kern.agent import Agent
4from kern.db.sqlite import SqliteDb
5from kern.models.openai import OpenAIChat
6from kern.os.app import AgentOS
7from kern.os.interfaces.telegram import Telegram
8from kern.tools.websearch import WebSearchTools
9
10agent_db = SqliteDb(db_file="tmp/persistent_memory.db")
11
12basic_agent = Agent(
13 name="Basic Agent",
14 model=OpenAIChat(id="gpt-5.2"),
15 db=agent_db,
16 add_history_to_context=True,
17 num_history_runs=3,
18 add_datetime_to_context=True,
19 markdown=True,
20)
21
22web_research_agent = Agent(
23 name="Web Research Agent",
24 model=OpenAIChat(id="gpt-5.2"),
25 db=agent_db,
26 tools=[WebSearchTools()],
27 add_history_to_context=True,
28 num_history_runs=3,
29 add_datetime_to_context=True,
30)
31
32# Telegram only supports one webhook per bot token, so each interface needs its own bot.
33# Create two bots via @BotFather and pass each token explicitly.
34agent_os = AgentOS(
35 agents=[basic_agent, web_research_agent],
36 interfaces=[
37 Telegram(agent=basic_agent, prefix="/basic", token=os.getenv("TELEGRAM_TOKEN_BASIC")),
38 Telegram(agent=web_research_agent, prefix="/web-research", token=os.getenv("TELEGRAM_TOKEN_RESEARCH")),
39 ],
40)
41app = agent_os.get_app()
42
43if __name__ == "__main__":
44 agent_os.serve(app="multiple_instances:app", reload=True)

Usage

Set up your virtual environment

1uv venv --python 3.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Set Environment Variables

1export TELEGRAM_TOKEN_BASIC=bot-token-for-basic-agent
2export TELEGRAM_TOKEN_RESEARCH=bot-token-for-research-agent
3export OPENAI_API_KEY=your-openai-api-key
4export APP_ENV=development

Install dependencies

1uv pip install -U "kern-ai[telegram]"

Run Example

1python multiple_instances.py

Register Webhooks

Register a webhook for each bot token:

1curl "https://api.telegram.org/bot${TELEGRAM_TOKEN_BASIC}/setWebhook?url=${NGROK_URL}/basic/webhook"
2curl "https://api.telegram.org/bot${TELEGRAM_TOKEN_RESEARCH}/setWebhook?url=${NGROK_URL}/web-research/webhook"

Key Features

  • Prefix-Based Routing: Each agent gets its own webhook path (/basic/webhook, /web-research/webhook)
  • Shared Server: Both agents run on a single AgentOS instance
  • Separate Bot Tokens: Each interface uses its own BotFather bot (Telegram allows only one webhook per token)
  • Shared Database: Both agents share the same SQLite database