How to Build a Multi-Platform AI Agent Gateway from Scratch on Ubuntu
This article walks through building a platform-agnostic AI agent gateway on a clean Ubuntu host. It covers a five-layer architecture (adapter, orchestration, model, runtime, and schedule/extension layers), environment setup, a unified inbound event model for multiple messaging platforms, configurable multi-model routing with fallback, isolated execution backends, scheduled tasks with proactive delivery, protocol-based tool integration, observability, and a practical acceptance checklist. Readers will get a decoupled, horizontally scalable skeleton system that can be extended incrementally without refactoring core business logic.
1. Background and Problem Definition
As agent applications evolve from “single-point scripts” into “long-running online services,” the hardest engineering work is often not model inference itself, but the infrastructure around the model: where messages come in, where tasks execute, where results are pushed, how failures are retried, and how usage is measured. Many teams validate an idea with a command-line chat during the prototype stage, then discover in production that they must integrate multiple collaboration platforms, multiple model providers, and multiple execution environments at once. The codebase quickly gets buried under adaptation logic.
This article does not focus on a specific product. Instead, it abstracts a common engineering problem: how to build an agent message gateway that is decoupled from platforms, models, and execution environments. The goal is to build, from scratch on a clean Ubuntu host, a skeleton system with multi-platform ingestion, multi-model routing, multi-backend execution, scheduled dispatch, and capability extension.
2. Target Architecture and Layered Design
A five-layer structure is recommended, with layers communicating only through explicit data contracts:
- Adapter Layer: Handles protocol differences across messaging platforms and normalizes webhooks, long-lived connections, and polling into internal standard events.
- Orchestration Layer: Manages session state, assembles context, parses intent and commands, and applies rate limiting and deduplication.
- Model Layer: Provides a unified inference interface, hides request/response differences across providers, and handles routing, fallback, and retries.
- Runtime Layer: Where tool calls and code execution happen; requires isolation and resource limits.
- Schedule & Extension Layer: Handles scheduled tasks, capability plugins, and protocol-based tool integration.
The value of this layering: adding a messaging platform means implementing one adapter; switching model providers means changing configuration; raising the security level means replacing the execution backend, all without touching business logic.
3. Environment Setup (Ubuntu)
Starting from zero, pin a long-term support release and follow the principle of least privilege:
# Base dependencies and an isolated environmentsudo apt update && sudo apt install -y python3 python3-venv git curl jqpython3 -m venv ~/agent-env && source ~/agent-env/bin/activatepip install -U pip wheel
For project conventions, keep “configuration,” “secrets,” and “data” separate: configuration goes into version control for auditability; secrets are injected via environment variables or a dedicated secret management service; session and task data land in a local database or object storage to avoid state loss when containers are rebuilt. A sample directory structure:
agent/├── adapters/ # platform adapters├── core/ # orchestration and sessions├── models/ # model routing├── runtime/ # execution backends├── scheduler/ # scheduled tasks├── extensions/ # tools and protocol integration└── config.yaml
4. Multi-Platform Message Ingestion: Flattening Differences with a Unified Event Model
Differences across collaboration platforms concentrate in three areas: authentication, delivery mode (push or pull), and rich-text message structure. Define a minimal but complete internal event:
@dataclassclass InboundEvent:platform: str # platform identifierchannel_id: str # conversation/channelsender_id: str # sendertext: str # plain-text bodyattachments: list # attachment referencesraw: dict # raw payload for traceability
Adapters only “translate”; they make no business decisions. For push-based platforms, expose a publicly reachable receiving endpoint and enforce signature verification. For pull-only platforms, use polling with backoff and deduplicate events (using the platform message ID as the idempotency key). All platforms share the same outbound sending interface, keeping the upper-layer “reply” logic single and simple.
Security note: the receiving endpoint must enable signature verification and replay protection, combined with rate limiting at a reverse proxy. Otherwise, you are exposing an entry point that can execute instructions to the public internet.
5. Multi-Model Integration and Routing
The key to the model layer is a unified abstraction: input is a list of messages plus tool declarations; output is text or a structured tool call. Adapters convert each provider’s request body, auth headers, and streaming chunk format into the internal format.
Routing should be a configurable rule chain, not hard-coded:
model:default: primary-chatfallback: [backup-chat, small-fast]rules:- match: {task: code} # code tasks use stronger reasoninguse: primary-chat- match: {token_gt: 60000} # very long context uses a long-window modeluse: long-context
Three things are needed alongside this: first, real-time usage tracking that accumulates input/output tokens from streaming responses and writes them to monitoring; second, failure fallback that automatically switches to a backup model on rate limits or timeouts; third, runtime switching via a slash command or hot config reload, with zero changes to business code.
6. Execution Backends and Isolation
Tool calls and code execution are the highest-risk part. Common backend forms include local processes, containerized sandboxes, remote hosts, and function-style ephemeral execution environments, each with different trade-offs in startup latency, isolation strength, and persistence. Abstract a unified execution interface:
class Runtime(Protocol):async def run(self, code: str, files: dict, timeout: int) -> ExecResult: ...
Implementation points: assign an isolated working directory and timeout per execution; limit CPU, memory, and outbound network access; write artifacts back to persistent storage so stateless instances can resume context. In production, default to containers or stronger isolation; use the local backend only for development and debugging.
7. Scheduled Tasks and Automated Push
Scheduling should support describing intent in natural language, which the orchestration layer parses into a “schedule expression + task body” and hands to the scheduler; results are then pushed proactively through the message gateway. Implementation notes: decouple task definition from execution, with the scheduler only triggering; give each task an idempotency identifier to avoid duplicate pushes; send failures to a retry queue and record the reason; aggregate high-frequency tasks to avoid disturbance.
schedule:- name: daily-reportcron: "0 9 * * 1-5"prompt: Summarize yesterday's key metrics and generate a briefdeliver: {platform: chat, channel: ops}
8. Capability Extension: Protocol-Based Tool Integration
Integrate the tool ecosystem via an open protocol: the host connects to external tool services as a client; the server declares tool names, parameter schemas, and descriptions; the host generates a callable list from these and injects it into the model context. Adding capabilities then requires no changes to core code, only deploying a tool service that conforms to the protocol. In practice, apply whitelists and parameter validation to tools, placing a policy gate between “model suggestion” and “actual execution.”
9. Observability and Operations
Cover at least four signal types: structured logs (with session and task trace IDs), metrics (request volume, latency, token usage, failure rate), distributed tracing, and alerting. For terminal interaction, multi-line input, command autocompletion, streaming tool output, and usage hints significantly lower the barrier to use. For deployment, use a process manager or container orchestration to ensure persistence and self-healing, and configure rolling upgrades and rollbacks.
10. Common Pitfalls and Acceptance Checklist
- Duplicate platform event delivery causing duplicate replies: use the message ID for idempotency.
- Unbounded context growth: set a window limit and a summarization/compaction strategy.
- Hard-coded secrets: route everything through environment variables or a secret service.
- Execution environment escape risk: default to strong isolation, no outbound network, and time limits.
- Cost overruns: meter by session and tenant and set threshold alerts.
For acceptance, run an end-to-end drill covering four items: “ingest from one platform, switch a model once, run one scheduled push, and connect one external tool.” Completing these four steps gives you a well-decoupled, horizontally scalable agent gateway foundation. Afterward, whether integrating more collaboration platforms or introducing a more complex tool ecosystem, it is just incremental implementation on existing contracts, with no refactoring required. If running in the cloud, you can hand state and artifacts to object storage, offload asynchronous decoupling to a message queue, delegate persistence and elasticity to a container platform, and complete the operations loop with logging and monitoring/alerting services.
