Wandering Giants Compute · Learn
Tutorial

How to Run Autonomous AI Agents on Cloud Infrastructure

The short answer

To run autonomous agents in the cloud, put the model behind an OpenAI-compatible endpoint (a hosted API or vLLM on a rented GPU), run each agent loop as a background job from a queue, execute tools in an isolated container, cap steps, time and tokens per task, and log every step under a task ID.

Model endpoint
OpenAI-compatible, served by vLLM or a hosted API
Queue
Redis + RQ in this tutorial
Sandbox
Hardened Docker container per task, no network
Recommended self-hosted model
Qwen3 32B AWQ on a 48 GB L40S
L40S price
$1.89/hr, billed by the minute
Step cap used here
20 model calls per task
Versions assumed
Python 3.11+, openai 1.x, rq 1.16+, vLLM 0.8+

A prototype agent runs in a terminal while you watch. An autonomous agent runs in the background, for users you never see, and has to finish, fail cleanly or ask for help without you. This tutorial takes a working tool-calling agent from a script to cloud infrastructure: a private model endpoint, a sandbox for its tools, a queue and workers, hard budgets and step-level logging. Everything here runs with open-source components and works the same with a hosted model API.

What does the finished system look like?

The finished system has five parts: a model endpoint, an API that accepts tasks, a Redis queue, worker processes that each run one agent loop at a time, and a disposable Docker container per task for tool execution. Results and step logs go to a database.

ComponentJobWhere it runsNeeds a GPU?
Model endpointChooses actions, writes code and textRented GPU with vLLM, or a hosted APIOnly if self-hosted
Task APIAccepts tasks, returns a task IDSmall CPU serverNo
Queue (Redis)Holds pending tasksSame CPU serverNo
WorkersRun the agent loop, call the model and toolsSame CPU server, or the GPU machineNo
SandboxExecutes shell and Python per taskDocker on the worker hostNo
Logs and resultsStep history, costs, final outputPostgres or JSON lines to startNo

The complete guide to AI agent infrastructure explains why each layer exists. This page is the hands-on version.

Step 1: How do you get a model endpoint for agents?

You need an OpenAI-compatible chat completions endpoint that supports tool calls. Either use a hosted API, or serve an open model yourself with vLLM on a rented GPU.

To self-host on a GPU you control (a Root machine, or any Linux box with a 48 GB card):

bash
pip install vllm
export VLLM_API_KEY="$(openssl rand -hex 24)"
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 8000

--enable-auto-tool-choice with --tool-call-parser hermes turns the model's tool-call output into structured tool_calls in the response, which is what the agent loop below expects. Qwen3 32B AWQ weighs roughly 32 × 0.55 ≈ 18 GB at 4-bit, leaving most of a 48 GB L40S for KV cache across concurrent agents. Flags move between vLLM releases; this assumes 0.8 or later, and the vLLM tool-calling docs list the parser for each model family. The guide to building an open-source LLM API covers serving in more depth.

On Wandering Giants Compute the API option does this step for you: choose a GPU and a one-click model, and you get an endpoint and key. Either way, check it with two calls:

bash
export LLM_BASE_URL="https://your-endpoint/v1"
export LLM_API_KEY="your-key"
curl -s "$LLM_BASE_URL/models" -H "Authorization: Bearer $LLM_API_KEY"
curl -s "$LLM_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $LLM_API_KEY" -H "Content-Type: application/json" \
  -d '{"model": "Qwen/Qwen3-32B-AWQ", "messages": [{"role": "user", "content": "Reply with OK"}]}'

Use the model ID that /models returns in every request.

Step 2: How do you give the agent a sandbox?

Each task gets its own hardened container, created at the start and destroyed at the end. The agent's shell tool runs commands inside it with docker exec, never on the worker host.

python
# sandbox.py
import subprocess
import uuid

IMAGE = "python:3.12-slim"

def start_sandbox() -> str:
    name = f"agent-{uuid.uuid4().hex[:12]}"
    subprocess.run([
        "docker", "run", "-d", "--name", name,
        "--network", "none", "--read-only",
        "--tmpfs", "/tmp:rw,size=512m",
        "--tmpfs", "/work:rw,exec,size=2g,uid=1000,gid=1000",
        "--memory", "2g", "--cpus", "1", "--pids-limit", "256",
        "--cap-drop", "ALL", "--security-opt", "no-new-privileges",
        "--user", "1000:1000", "-w", "/work",
        IMAGE, "sleep", "infinity",
    ], check=True, capture_output=True)
    return name

def run_in_sandbox(name: str, command: str, timeout: int = 60) -> str:
    try:
        proc = subprocess.run(
            ["docker", "exec", name, "bash", "-lc", command],
            capture_output=True, text=True, timeout=timeout,
        )
        out = f"exit_code={proc.returncode}\n{proc.stdout}{proc.stderr}"
    except subprocess.TimeoutExpired:
        out = f"error: command timed out after {timeout}s"
    return out[-8000:]  # keep tool output small: it goes back into the context

def stop_sandbox(name: str) -> None:
    subprocess.run(["docker", "rm", "-f", name], capture_output=True)

Two details matter. Truncating output to the last 8,000 characters stops one noisy command from filling the context window and multiplying your token bill. And --network none means a prompt-injected agent has nowhere to send anything. When a task genuinely needs the internet, give it a network with an egress proxy that allows only the hosts it needs. For untrusted code in multi-tenant systems, add gVisor (--runtime=runsc); the agent sandbox guide compares that with Firecracker microVMs and hosted services such as E2B, Daytona and Modal.

Step 3: How do you write a bounded agent loop?

The agent loop calls the model, executes any tool calls in the sandbox, appends the results and repeats, until the model answers without a tool call or a limit is hit. Limits live in code, not in the prompt.

python
# agent.py
import json
import os
import time

from openai import OpenAI

from sandbox import run_in_sandbox, start_sandbox, stop_sandbox

client = OpenAI(base_url=os.environ["LLM_BASE_URL"], api_key=os.environ["LLM_API_KEY"])
MODEL = os.environ.get("LLM_MODEL") or "Qwen/Qwen3-32B-AWQ"
MAX_STEPS = 20
MAX_TOKENS_PER_TASK = 400_000

TOOLS = [{
    "type": "function",
    "function": {
        "name": "run_shell",
        "description": "Run a bash command in an isolated Linux sandbox with Python 3.12. No internet. Working directory /work.",
        "parameters": {
            "type": "object",
            "properties": {"command": {"type": "string"}},
            "required": ["command"],
        },
    },
}]

SYSTEM = ("You are a careful data assistant. Use run_shell to inspect files and run Python. "
          "When the task is complete, reply with the final answer and no tool call.")

def log(task_id, **fields):
    print(json.dumps({"task_id": task_id, "ts": round(time.time(), 3), **fields}), flush=True)

def run_agent(task: str, task_id: str = "local") -> str:
    sandbox = start_sandbox()
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": task}]
    tokens_used = 0
    try:
        for step in range(1, MAX_STEPS + 1):
            resp = client.chat.completions.create(model=MODEL, messages=messages, tools=TOOLS)
            tokens_used += resp.usage.total_tokens
            msg = resp.choices[0].message
            messages.append(msg.model_dump(exclude_none=True))
            log(task_id, step=step, type="model", prompt_tokens=resp.usage.prompt_tokens,
                completion_tokens=resp.usage.completion_tokens)

            if not msg.tool_calls:
                log(task_id, step=step, type="done", tokens=tokens_used)
                return msg.content or ""

            for call in msg.tool_calls:
                try:
                    args = json.loads(call.function.arguments)
                    result = run_in_sandbox(sandbox, args["command"])
                except (json.JSONDecodeError, KeyError) as exc:
                    result = f"error: bad tool arguments ({exc})"
                log(task_id, step=step, type="tool", tool=call.function.name, output_chars=len(result))
                messages.append({"role": "tool", "tool_call_id": call.id, "content": result})

            if tokens_used > MAX_TOKENS_PER_TASK:
                log(task_id, step=step, type="stopped", reason="token_budget")
                return "Stopped: token budget exceeded."
        log(task_id, type="stopped", reason="max_steps")
        return "Stopped: step limit reached."
    finally:
        stop_sandbox(sandbox)

if __name__ == "__main__":
    print(run_agent("Create a CSV of the squares of 1 to 20 in /work, then report their mean."))

Run it once by hand (python agent.py) and read the JSON log lines. You will see each model call's token counts climb as the history grows; that growth is the main driver of agent cost.

Step 4: How do you run agents as background jobs?

Put the loop behind a queue so that tasks survive web-request timeouts, run in parallel and can be retried. RQ (Redis Queue) is the smallest useful option in Python.

python
# submit.py
import uuid
from redis import Redis
from rq import Queue

q = Queue("agent-tasks", connection=Redis.from_url("redis://localhost:6379/0"))
task_id = uuid.uuid4().hex
job = q.enqueue("agent.run_agent", "Compute the mean of the primes below 1000.",
                task_id, job_id=task_id, job_timeout=900, result_ttl=86400)
print("queued", job.id)

Then run Redis and workers. A docker-compose.yml for the CPU side:

yaml
services:
  redis:
    image: redis:7
    ports:
      - "127.0.0.1:6379:6379"
  worker:
    build: .
    command: rq worker --url redis://redis:6379/0 agent-tasks
    environment:
      LLM_BASE_URL: ${LLM_BASE_URL}
      LLM_API_KEY: ${LLM_API_KEY}
      LLM_MODEL: ${LLM_MODEL}
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    depends_on:
      - redis
    deploy:
      replicas: 4

The worker image needs Python, your code, openai, rq and the Docker CLI (see the Docker documentation for engine set-up on the host):

text
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 openai rq redis
COPY agent.py sandbox.py ./

docker compose up -d --build starts four workers, so four agent tasks run at once. job_timeout=900 kills any task still running after 15 minutes, a backstop behind the step and token limits.

Step 5: Where should the workers run?

Run workers wherever the queue is, on an ordinary CPU server; they spend most of their time waiting on the model. A 4-vCPU, 8 GB server comfortably runs a few dozen agent loops plus their light sandboxes.

For a single team, a simpler option is to run everything on one Root GPU machine: vLLM in one tmux window, Redis and workers in another. You pay for one machine and the model is on localhost. The downside is coupling: restarting workers or a runaway sandbox shares a box with your model server, and if the machine is a container itself you may not be able to run Docker inside it. Check before you design around that, and split the two once more than one team depends on it. Scaling agents from one user to thousands covers when and how to split.

Step 6: How do you observe and control cost?

Every log line above carries a task ID, a step number and token counts. Ship them to wherever you keep logs and compute four numbers per task type: success rate, average steps, average tokens and cost per task.

Cost per task from the logs:

Model setupFormula
Hosted APIprompt tokens × input price + completion tokens × output price
Own GPUGPU-hours used ÷ tasks completed × hourly price

For a worked example: if your four workers complete 600 tasks in an eight-hour day on one L40S, the model costs 8 GPU-hours at $1.89/hr, which is $15.12 for the day, ÷ 600 tasks ≈ $0.0252 per task, or about 0.8 GPU-minutes (48 GPU-seconds) of L40S time per task. Stop the GPU outside those hours and per-minute billing means you pay nothing for the night. If the same day costs more on a hosted API, the private GPU is paying for itself; if not, it is paying for privacy, which may still be the point.

When you outgrow print-to-stdout, OpenTelemetry spans and an LLM tracing tool such as Langfuse give you a timeline view of each task. The private agent platform tutorial adds those, plus a gateway with per-team keys.

What should you check before letting it run unattended?

Run this checklist before real users touch it:

  1. Hard limits on steps, tokens, job time and every tool call, enforced in code.
  2. No secrets in the sandbox environment, and no network unless the task needs it.
  3. Irreversible actions (email, payments, deletes, publishing) go through an approval step, not straight from the model.
  4. A failed or timed-out task records why, and the user gets a clear failure message.
  5. Retries are safe: a task that is retried does not send two emails or create two records. Give side-effecting tools an idempotency key.
  6. You have a set of 20–50 real tasks with known good outcomes, and you rerun it after every prompt or model change.

Wandering Giants also builds production agent systems for businesses, and in practice items 3, 5 and 6 are where most of the engineering time goes.

When does a Wandering Giants GPU fit this setup?

It fits Step 1 when you want the model private and priced by the hour: an API GPU gives your workers an OpenAI-compatible endpoint with your own key, and prompts and tool outputs stay on that machine. A Root machine fits when you'd rather run vLLM, Redis and workers together on one box, or when the agent's own work needs a GPU. Billing is by the minute from prepaid credit, so stopping the GPU overnight cuts cost directly; there is no autoscaling, so size for your busy hours. See the GPUs and prices.

Frequently asked questions

Where should the agent loop itself run?

On a small CPU server or container platform, close to your queue and database. The loop mostly waits on the model and tools, so it needs little CPU. Keep it separate from the GPU so you can restart workers without reloading the model.

Can I run the agent workers on the same machine as the GPU?

Yes, for a single-team setup it is a reasonable way to start: a Root GPU machine can run vLLM and a handful of worker processes side by side. Separate them when you need to scale workers independently or when agents run untrusted code that should not share a machine with your model server.

How do I stop an autonomous agent from looping forever?

Enforce hard limits outside the model: a maximum number of steps, a wall-clock timeout on the job, a token budget and a timeout on every tool call. Log why a task stopped so loops show up in your metrics.

Which open models are good at tool calling?

Qwen3 models, gpt-oss and Llama 3.3 70B all support structured tool calls in vLLM with the right parser. Test on your own tools: tool-calling reliability varies more between prompts and schemas than benchmark tables suggest.

Do I need Kubernetes to run agents?

No. A queue, a few worker processes under docker-compose and a database carry most teams a long way. Move to Kubernetes or a workflow engine when you need many hosts, autoscaling workers or durable multi-hour workflows.

How do I get results back from a background agent?

Return a task ID when the job is enqueued, store each step and the final result in a database, and let the client poll or receive a webhook when the task finishes.

Wandering Giants Compute

Rent the GPU for this, by the minute.

Launch an L40S with Qwen3 32B behind your own OpenAI-compatible key, point your agent workers at it, and pay only for the minutes it runs.

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

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.