An AI agent on a VPS is usually a program that picks up tasks from Telegram, a web form or a schedule, sends them to a language model over an API, calls tools when it needs to (search, files, requests to your own services) and returns the result. The server itself does almost no heavy lifting: the model provider handles the expensive part. So running an agent on a VPS is about reliability, security and keeping costs under control, not about beefy hardware.
This guide covers server requirements, environment setup, safe API key storage, a minimal agent loop, running it under systemd, logging, spend limits and security basics.
What kind of VPS an AI agent needs
When the agent calls a model over an API, server resources go to the agent process, network requests and tools. One agent without heavy tasks is happy with 1 vCPU and 1-2 GB of RAM. The Micro plan (2 vCPU, 2 GB RAM, 20 GB disk) is a good starting point. If you also run a database, n8n or several agents on the same box, the Start plan with 4 GB of RAM gives you more breathing room.
One important caveat: don't try to run a local language model on a small VPS. Even a quantized mid-size model needs several gigabytes of RAM just for the weights, and long contexts push that up further because of the attention cache. Without a GPU, generation is slow, which usually kills the agent use case. Local models belong on a separate machine with lots of RAM or a GPU. For an API-driven agent, a regular VPS is all you need.
- a Linux server with Python 3.10 or newer;
- at least 1 vCPU and 1 GB of RAM for one agent without heavy tools;
- at least 10 GB of disk for the OS, Python packages and logs;
- SSH access with a key, see how to connect to a VPS over SSH;
- outbound HTTPS access to your model provider's API.
Create a user and directories
Don't run the agent as root. If the process gets compromised, the damage stays within a dedicated user's permissions. Create a system user and a project directory:
sudo apt update && sudo apt install -y python3 python3-venv
sudo useradd --system --home-dir /opt/agent --shell /usr/sbin/nologin agent
sudo mkdir -p /opt/agent/app
sudo chown -R agent:agent /opt/agentVirtual environment and dependencies
Install dependencies into a dedicated virtual environment. That keeps the system Python clean and pins library versions inside the project:
sudo -u agent python3 -m venv /opt/agent/venv
sudo -u agent /opt/agent/venv/bin/pip install --upgrade pip httpx
sudo -u agent /opt/agent/venv/bin/pip freeze | sudo tee /opt/agent/app/requirements.txt > /dev/nullrequirements.txt now holds the exact versions. Ship it with your code so you can reproduce the install on another server.
Where to keep the API key
An API key is a secret that unlocks a paid service. It doesn't belong in code, in git, in chat messages or in logs. Store it in an environment file that only the service user can read:
sudo install -m 600 -o agent -g agent /dev/null /opt/agent/agent.env
sudo nano /opt/agent/agent.envLLM_API_KEY=your-api-key-here
LLM_API_URL=https://api.provider.example/v1/chat/completions
LLM_MODEL=your-model-name
MAX_TOKENS_PER_REQUEST=512Mode 600 means only the owner can read the file. If the key ever lands in a chat, a screenshot or a repo, treat it as compromised: revoke it in the provider's console and issue a new one. Scrubbing it from git history isn't enough.
A minimal agent
Here's the smallest useful loop: get a task, send it to the model, record the result. The example uses the OpenAI-compatible request format. If your provider uses a different format or auth header, adjust ask_model to match its docs. next_task is a stub: replace it with reads from a queue, a file or a Telegram bot.
import logging
import os
import sys
import time
import httpx
API_KEY = os.environ["LLM_API_KEY"]
API_URL = os.environ["LLM_API_URL"]
MODEL = os.environ["LLM_MODEL"]
MAX_TOKENS = int(os.environ.get("MAX_TOKENS_PER_REQUEST", "512"))
MAX_RETRIES = 3
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
stream=sys.stdout,
)
log = logging.getLogger("agent")
def ask_model(prompt: str) -> str:
headers = {"Authorization": "Bearer " + API_KEY}
payload = {
"model": MODEL,
"max_tokens": MAX_TOKENS,
"messages": [{"role": "user", "content": prompt}],
}
for attempt in range(1, MAX_RETRIES + 1):
try:
r = httpx.post(API_URL, json=payload, headers=headers, timeout=60)
if r.status_code == 429:
wait = 2 ** attempt
log.warning("rate limited, retry in %s s", wait)
time.sleep(wait)
continue
r.raise_for_status()
return r.json()["choices"][0]["message"]["content"]
except httpx.HTTPError as exc:
log.error("request failed, attempt %s, error %s", attempt, type(exc).__name__)
time.sleep(2 ** attempt)
raise RuntimeError("model request failed after retries")
def next_task():
return None # stub: return a task string or None
def main() -> None:
while True:
task = next_task()
if task is None:
time.sleep(5)
continue
log.info("task received, length=%d", len(task))
answer = ask_model(task)
log.info("answer received, length=%d", len(answer))
# send answer to the user or push it to a queue
if __name__ == "__main__":
main()A few deliberate choices here. max_tokens caps the length of each response. Retries back off exponentially and stop after three attempts, so the agent can't get stuck in an endless loop. The log records lengths and error types, never the key or the request headers.
To test it by hand, load the variables yourself: set -a; . /opt/agent/agent.env; set +a; then run /opt/agent/venv/bin/python /opt/agent/app/agent.py as the agent user.
Run it as a systemd service
systemd starts the agent at boot, restarts it after a crash and keeps the logs. Create a unit file:
[Unit]
Description=AI agent
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=agent
Group=agent
WorkingDirectory=/opt/agent/app
EnvironmentFile=/opt/agent/agent.env
ExecStart=/opt/agent/venv/bin/python /opt/agent/app/agent.py
Restart=on-failure
RestartSec=10
NoNewPrivileges=true
ProtectSystem=strict
ReadWritePaths=/opt/agent
PrivateTmp=true
MemoryMax=512M
[Install]
WantedBy=multi-user.targetsudo nano /etc/systemd/system/ai-agent.service
sudo systemctl daemon-reload
sudo systemctl enable --now ai-agent
sudo systemctl status ai-agentTune MemoryMax to your plan: on a 1 GB server, a 512 MB cap leaves headroom for the OS. If the agent goes over, systemd kills it, which beats quietly dragging down the whole server.
Logs and troubleshooting
The service log is available through journalctl. No extra setup needed, and if journald persistent storage is enabled, the agent's output survives reboots:
journalctl -u ai-agent -f
journalctl -u ai-agent --since "1 hour ago"
journalctl -u ai-agent -p err
sudo systemctl restart ai-agentLog request sizes, attempt numbers, processing time and error types. Don't log keys, Authorization headers or personal data from tasks unless you really have to. If keys or personal data do show up in the journal, fix the code, rotate the key and clear the journal.
Keeping spend under control
An unattended agent can burn through your budget without anyone noticing: it loops, sends a huge context or retries a failing request over and over. Defend at several layers:
- cap response length with max_tokens on every request;
- enforce a daily token or request limit inside the agent, for example a counter in a JSON file that resets once a day;
- rate-limit requests and use exponential backoff on 429 errors;
- process the queue sequentially for a single agent, with no parallel requests unless you need them;
- set a spend limit or threshold alerts in the provider's console, if it offers them;
- use a cheap model for simple tasks and save the expensive one for hard ones.
Provider limits and in-code limits complement each other. The provider cap stops spending even if the agent has a bug, and your own counter keeps the agent from blowing the daily budget in its first hour.
Securing the keys and the agent
An agent with access to keys, files and external services is an attractive target. The basics:
- use a separate key per project and revoke it if it might have leaked;
- rotate keys on a schedule and whenever someone who had access leaves;
- confine the agent to /opt/agent and don't grant permissions it doesn't use;
- never execute shell commands suggested by the model without a sandbox and an explicit allowlist of actions;
- watch out for prompt injection: text from web pages, emails and documents can contain instructions aimed at your agent, so those instructions must never unlock dangerous actions;
- firewall the server, keep it patched and follow the steps in Linux server security basics.
Ready-made AI bot or your own agent
Running your own VPS makes sense when you need custom code, your own tools and full control over the agent's logic. If the task is standard and you don't have time for setup, monitoring and key management, a ready-made option is easier. Pulsar Host has an AI agents section for exactly that. For your own agent, grab a server from the VPS section.
Pre-launch checklist
- Run the agent by hand as the agent user and make sure the model responds.
- Confirm the key doesn't show up in logs, shell history or the repo.
- Reboot the server and check that the service comes back on its own.
- Send a test request with a small max_tokens and check usage in the provider's console.
- Simulate an API failure, such as a bad key, and make sure the agent doesn't fall into a fast retry loop.
If everything checks out, the agent is ready for work. Next, add uptime monitoring for the service and a regular spend check, so a buggy task doesn't turn into a surprise bill.