A private AI agent platform has a self-hosted model on your own GPU, an OpenAI-compatible gateway with per-team keys, a task API, a Redis queue and workers, gVisor sandboxes for tools, Postgres for tasks and step logs, an approval step for risky actions, and per-team cost tracking. One GPU plus one CPU server runs it.
- Model layer
- vLLM on a rented GPU (private, OpenAI-compatible)
- Gateway
- LiteLLM proxy: keys, routing, fallbacks
- Queue and workers
- Redis + RQ
- Sandbox
- Docker with gVisor runsc runtime
- State and logs
- Postgres: tasks and steps tables
- Starting GPU
- L40S 48 GB, $1.89/hr
- Versions assumed
- Docker Compose v2, Postgres 16, Python 3.12, vLLM 0.8+
Teams build private agent platforms for one main reason: they want agents working on internal documents, code and customer data without that data going to a shared AI API. A second reason follows quickly: once several teams build agents, someone needs to provide the model, the sandboxes, the logs and the budgets once, rather than every team reinventing them. This tutorial builds that platform: a private model on a rented GPU, a gateway, a task API, workers, gVisor sandboxes, approvals and per-team cost tracking, all with Docker Compose.
What are the parts of a private agent platform?
A private agent platform has eight parts. Only the first needs a GPU.
| Part | Job | Technology here |
|---|---|---|
| Model | Private open model, OpenAI-compatible | vLLM on a rented GPU |
| Gateway | Keys per team, routing, fallbacks, usage logs | LiteLLM proxy |
| Task API | Accepts tasks, reports status | FastAPI |
| Queue | Buffers tasks, applies priority | Redis + RQ |
| Workers | Run agent loops, call tools | Python processes |
| Sandboxes | Run model-chosen commands in isolation | Docker + gVisor |
| State and logs | Tasks, steps, tokens, results | Postgres |
| Controls | Approvals, budgets, permissions | Code in the worker and gateway |
The general version of this stack, with the alternatives at each layer, is in the AI agent infrastructure guide. This page builds one concrete version.
Step 1: How do you set up the private model?
Run an open model with tool calling on a GPU you control, exposed only to your platform. A 32B model at 4-bit on a 48 GB L40S is a sound default: weights of about 32 × 0.55 ≈ 18 GB leave most of the card for KV cache.
On Wandering Giants Compute, choose API, an L40S and Qwen3 32B AWQ; you get an endpoint URL and key. To do it yourself on a Root machine or any GPU host:
pip install vllm
vllm serve Qwen/Qwen3-32B-AWQ \
--max-model-len 32768 \
--enable-auto-tool-choice --tool-call-parser hermes \
--enable-prefix-caching \
--api-key "$VLLM_API_KEY" --port 8000Either way you have WG_BASE_URL (ending in /v1) and WG_API_KEY. Only the gateway will hold that key. The guide to building an open-source LLM API covers serving options and tuning in more depth.
Step 2: How do you put a gateway in front of the model?
A gateway gives every team its own key, routes model names to backends, and logs usage, so no agent code ever holds the GPU endpoint's key. LiteLLM's proxy does this with a YAML file.
litellm.yaml:
model_list:
- model_name: agent-default
litellm_params:
model: openai/Qwen/Qwen3-32B-AWQ
api_base: os.environ/WG_BASE_URL
api_key: os.environ/WG_API_KEY
# Optional: a frontier model for tasks your policy allows to leave your infrastructure.
# - model_name: agent-hard
# litellm_params:
# model: openai/your-frontier-model
# api_base: os.environ/FRONTIER_BASE_URL
# api_key: os.environ/FRONTIER_API_KEY
litellm_settings:
drop_params: true
general_settings:
master_key: os.environ/LITELLM_MASTER_KEYAgents call model="agent-default" and never learn where it runs. When you add a second GPU replica, add a second entry with the same model_name and the gateway balances across them, as shown in scaling agents from one user to thousands. Per-team virtual keys with budgets need LiteLLM's database mode; see the LiteLLM docs and point it at the Postgres below.
Step 3: How do you define tasks and step logs?
Store every task and every step in Postgres. The step table is your audit log, your debugging tool and your cost report in one.
schema.sql:
CREATE TABLE tasks (
id text PRIMARY KEY,
team text NOT NULL,
prompt text NOT NULL,
status text NOT NULL,
result text,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE steps (
id bigserial PRIMARY KEY,
task_id text NOT NULL REFERENCES tasks(id),
step int NOT NULL,
kind text NOT NULL,
detail jsonb,
prompt_tokens int,
completion_tokens int,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE approvals (
id bigserial PRIMARY KEY,
task_id text NOT NULL REFERENCES tasks(id),
action jsonb NOT NULL,
status text NOT NULL DEFAULT 'pending',
created_at timestamptz NOT NULL DEFAULT now()
);Step 4: How do you build the task API?
The task API accepts a task, records it and enqueues it; a second route reports status. It never runs an agent itself.
api.py:
import os
import uuid
import psycopg
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from redis import Redis
from rq import Queue
DB = os.environ["DATABASE_URL"]
queue = Queue("agent-tasks", connection=Redis.from_url(os.environ["REDIS_URL"]))
app = FastAPI()
class TaskIn(BaseModel):
team: str
prompt: str
@app.post("/tasks")
def create_task(task: TaskIn):
task_id = uuid.uuid4().hex
with psycopg.connect(DB) as conn:
conn.execute(
"INSERT INTO tasks (id, team, prompt, status) VALUES (%s, %s, %s, 'queued')",
(task_id, task.team, task.prompt),
)
queue.enqueue("worker.run_task", task_id, job_id=task_id, job_timeout=900)
return {"task_id": task_id}
@app.get("/tasks/{task_id}")
def get_task(task_id: str):
with psycopg.connect(DB) as conn:
row = conn.execute("SELECT status, result FROM tasks WHERE id = %s", (task_id,)).fetchone()
if row is None:
raise HTTPException(status_code=404, detail="unknown task")
return {"task_id": task_id, "status": row[0], "result": row[1]}Put your company's single sign-on or an API key check in front of this before anyone outside the platform team uses it.
Step 5: How do workers run agents with sandboxes and approvals?
Workers run the agent loop, execute shell commands in a gVisor sandbox, and turn risky actions into approval requests instead of performing them. Reuse sandbox.py from the tutorial on running agents in the cloud, adding "--runtime=runsc" to its docker run arguments once gVisor is installed on the host (see the sandbox guide).
worker.py:
import json
import os
import psycopg
from openai import OpenAI
from sandbox import run_in_sandbox, start_sandbox, stop_sandbox
DB = os.environ["DATABASE_URL"]
client = OpenAI(base_url=os.environ["LLM_BASE_URL"], api_key=os.environ["LLM_API_KEY"])
MAX_STEPS = 20
TOOLS = [
{"type": "function", "function": {
"name": "run_shell",
"description": "Run a bash command in an isolated sandbox with no network. Working directory /work.",
"parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}},
{"type": "function", "function": {
"name": "send_email",
"description": "Request that an email be sent. A human must approve it first.",
"parameters": {"type": "object", "properties": {
"to": {"type": "string"}, "subject": {"type": "string"}, "body": {"type": "string"}},
"required": ["to", "subject", "body"]}}},
]
def record(conn, task_id, step, kind, detail, usage=None):
conn.execute(
"INSERT INTO steps (task_id, step, kind, detail, prompt_tokens, completion_tokens) "
"VALUES (%s, %s, %s, %s, %s, %s)",
(task_id, step, kind, json.dumps(detail),
usage.prompt_tokens if usage else None, usage.completion_tokens if usage else None),
)
def call_tool(conn, task_id, sandbox, name, args):
if name == "run_shell":
return run_in_sandbox(sandbox, args["command"])
if name == "send_email":
conn.execute("INSERT INTO approvals (task_id, action) VALUES (%s, %s)",
(task_id, json.dumps({"tool": name, **args})))
return "Email queued for human approval. Do not retry; continue with the rest of the task."
return f"error: unknown tool {name}"
def run_task(task_id: str) -> None:
with psycopg.connect(DB, autocommit=True) as conn:
prompt = conn.execute("SELECT prompt FROM tasks WHERE id = %s", (task_id,)).fetchone()[0]
conn.execute("UPDATE tasks SET status = 'running' WHERE id = %s", (task_id,))
messages = [
{"role": "system", "content": "You are an internal assistant. Use tools when needed. "
"Finish with a plain answer and no tool call."},
{"role": "user", "content": prompt},
]
status, result = "stopped", "Step limit reached."
sandbox = start_sandbox()
try:
for step in range(1, MAX_STEPS + 1):
resp = client.chat.completions.create(model="agent-default", messages=messages, tools=TOOLS)
msg = resp.choices[0].message
messages.append(msg.model_dump(exclude_none=True))
record(conn, task_id, step, "model", {"tool_calls": len(msg.tool_calls or [])}, resp.usage)
if not msg.tool_calls:
status, result = "done", msg.content or ""
break
for call in msg.tool_calls:
try:
args = json.loads(call.function.arguments or "{}")
out = call_tool(conn, task_id, sandbox, call.function.name, args)
except (json.JSONDecodeError, KeyError) as exc:
out = f"error: bad arguments ({exc})"
record(conn, task_id, step, "tool", {"tool": call.function.name, "output_chars": len(out)})
messages.append({"role": "tool", "tool_call_id": call.id, "content": out})
except Exception as exc:
status, result = "failed", f"{type(exc).__name__}: {exc}"
raise
finally:
stop_sandbox(sandbox)
conn.execute("UPDATE tasks SET status = %s, result = %s WHERE id = %s", (status, result, task_id))The send_email tool shows the pattern for every irreversible action: the model can only request it, the request lands in the approvals table, and a person (or a separate, audited service) carries it out. The credentials for sending email live with that service, never in the worker's sandbox.
Step 6: How do you run it all with Docker Compose?
Run the CPU side on one server with Docker Compose. The GPU stays separate, reached only by the gateway.
docker-compose.yml:
services:
postgres:
image: postgres:16
environment:
POSTGRES_USER: agents
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: agents
volumes:
- pgdata:/var/lib/postgresql/data
- ./schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro
redis:
image: redis:7
gateway:
image: ghcr.io/berriai/litellm:main-latest
command: ["--config", "/app/config.yaml", "--port", "4000"]
environment:
LITELLM_MASTER_KEY: ${LITELLM_MASTER_KEY}
WG_BASE_URL: ${WG_BASE_URL}
WG_API_KEY: ${WG_API_KEY}
volumes:
- ./litellm.yaml:/app/config.yaml:ro
api:
build: .
command: uvicorn api:app --host 0.0.0.0 --port 8080
environment:
DATABASE_URL: postgresql://agents:${POSTGRES_PASSWORD}@postgres:5432/agents
REDIS_URL: redis://redis:6379/0
ports:
- "127.0.0.1:8080:8080"
depends_on: [postgres, redis]
worker:
build: .
command: rq worker --url redis://redis:6379/0 agent-tasks
environment:
DATABASE_URL: postgresql://agents:${POSTGRES_PASSWORD}@postgres:5432/agents
LLM_BASE_URL: http://gateway:4000/v1
LLM_API_KEY: ${LITELLM_MASTER_KEY}
volumes:
- /var/run/docker.sock:/var/run/docker.sock
depends_on: [postgres, redis, gateway]
deploy:
replicas: 4
volumes:
pgdata:And the image both api and worker use:
FROM python:3.12-slim
RUN apt-get update && apt-get install -y --no-install-recommends docker.io && rm -rf /var/lib/apt/lists/*
WORKDIR /app
RUN pip install --no-cache-dir fastapi uvicorn "psycopg[binary]" redis rq openai
COPY api.py worker.py sandbox.py ./Start it with docker compose up -d --build, then submit a task:
curl -s -X POST http://127.0.0.1:8080/tasks \
-H "Content-Type: application/json" \
-d '{"team": "finance", "prompt": "Generate 1,000 random invoice amounts in Python and report the median."}'Pin the LiteLLM image to a specific release tag in production rather than main-latest. As in the earlier tutorial, mounting the Docker socket gives workers control of the host's Docker, so run this on a server dedicated to the platform.
How do you track cost per team?
Join tasks to steps and multiply. For the private model, cost is GPU-hours, so allocate it in proportion to tokens:
SELECT t.team,
date(t.created_at) AS day,
count(DISTINCT t.id) AS tasks,
sum(s.prompt_tokens) AS prompt_tokens,
sum(s.completion_tokens) AS completion_tokens
FROM tasks t
JOIN steps s ON s.task_id = t.id AND s.kind = 'model'
GROUP BY 1, 2
ORDER BY 2 DESC, 1;Worked example: the L40S runs 10 hours on a working day, costing 10 × $1.89/hr ≈ $18.90. Finance used 3.0 M tokens, support 6.0 M and engineering 1.0 M, 10.0 M in all. Finance's share is 3.0 ÷ 10.0 = 30% of 10 × $1.89/hr ≈ $18.90, which is 3 × $1.89/hr ≈ $5.67 for the day. The same query, with hosted per-token prices, tells you what the same day would have cost on an API, which is the number to show whoever approves the GPU budget.
What does the platform cost to run?
The platform has a fixed CPU cost and a GPU cost you control by the minute.
| Part | Size | Hours | Cost basis |
|---|---|---|---|
| Control-plane server (Compose stack, 4 workers, sandboxes) | 4–8 vCPU, 16–32 GB RAM | 24 h | Your CPU provider's monthly price |
| Private model, L40S, Qwen3 32B AWQ | 1 GPU | 10 h on weekdays | 50 × $1.89/hr ≈ $94.50 a week |
| Same, stopped overnight and weekends | 118 h a week off | 118 × 3¢ ≈ $3.54 a week of disk while paused | |
| Upgrade when queues grow | H100 or second L40S replica | As needed | $4.99/hr or another $1.89/hr per hour |
When does Wandering Giants fit a private agent platform?
Wandering Giants Compute fits the model layer of this platform: an API GPU is Step 1 done for you, a private vLLM endpoint with your own key, where prompts go to your machine rather than a shared AI API and we don't read or train on them. A Root machine fits if you want to run vLLM, adapters or extra GPU models such as Whisper yourself. Billing is by the minute from prepaid credit, so a model you run in working hours costs working hours. We don't provide the CPU control plane, managed Kubernetes, autoscaling or compliance certifications; run those parts where you already run servers. For other options for private models, see the best GPU clouds for private AI. Wandering Giants also builds agent platforms like this one for businesses that would rather not assemble it themselves.
Frequently asked questions
What makes an AI agent platform private?
The model runs on a machine you control, so prompts, documents and tool outputs never go to a shared AI API, and the rest of the stack (queue, sandboxes, logs) runs in your own accounts. Privacy also depends on what the agent's tools can reach, which is why egress control and scoped credentials are part of the design.
Can a private agent platform still use frontier models?
Yes. Put a gateway in front of all models and route only selected tasks, or selected tenants, to a frontier API. The default route goes to your private model. The gateway logs which tasks left your infrastructure, which makes the policy auditable.
How many GPUs does a private agent platform need?
One to start. A 48 GB L40S running a 32B model at 4-bit serves a team's agents comfortably during working hours. Add replicas or a larger-memory GPU when queues grow at peak, as measured by your step logs.
Do I need Kubernetes for a private agent platform?
No. Docker Compose on one CPU server plus a GPU endpoint covers a team or a small company. Kubernetes becomes useful when you need many worker hosts, rolling deploys and autoscaling of the CPU tier.
How do agents use secrets on a private platform?
Tools that need secrets run in the worker or a tool service, outside the sandbox, and check each call against the task's permissions. The sandbox never holds credentials, so code or prompt injection inside it has nothing to steal.
Is a private agent platform cheaper than hosted APIs?
At steady, high volume it usually is, because GPU cost is per hour rather than per token. At low or very spiky volume, hosted APIs are often cheaper. Many teams build the private platform for data control first and find the cost benefit later.
Rent the GPU for this, by the minute.
Start your private agent platform with a private model: launch an L40S or H100 with an OpenAI-compatible endpoint and your own key, billed by the minute.
Prepaid credit, billed by the minute, stops itself when credit runs out. Prices in £, $, €, ¥, CA$, A$, CHF and S$; UK prices include VAT.
Keep reading
- Complete guideWhat Is AI Agent Infrastructure? A Complete Guide
- TutorialHow to Run Autonomous AI Agents on Cloud Infrastructure
- ComparisonBest GPU Cloud for Running Private AI Models
- TutorialHow to Build Your Own Open-Source LLM API
- GuideWhat Is a Sandbox Environment for AI Agents?
- GuideHow to Scale AI Agents from One User to Thousands
About this article. Written by the Wandering Giants Compute team, the people who run Wandering Giants Compute. Hardware figures are the manufacturers’ published specifications. Speeds and costs marked as estimates are worked out from those specifications and our current prices, with the method shown; they are not measured benchmarks. Wandering Giants prices are taken live from our price list each time this page is built.
Last reviewed 25 November 2026.