Setup Open Interpreter 24/7 trên VPS: AI thực thi shell command

Chia sẻ bài viết

Mục lục
TL;DR
  • Open Interpreter là Python tool cho LLM chạy code thật trên máy: bash, python, JS.
  • Self-host trên VPS 24/7 để automation: scrape data, gọi API, xử lý file, send mail.
  • Sandbox Docker bắt buộc - đừng cho LLM truy cập root host trực tiếp.
  • Hỗ trợ Claude, GPT-4, Gemini, hoặc Ollama local LLM.
  • Expose qua REST API để app khác gọi: "run task X" - LLM tự nghĩ code và chạy.

Open Interpreter (interpreter.chat) là tool open source cho phép LLM viết và chạy code thật trên máy. Khác Claude Code (tập trung dev workflow), Open Interpreter thiên về general automation: phân tích CSV, gọi API, generate report, sync file. Self-host trên VPS chạy 24/7 biến nó thành AI worker tự động.

Use case thực tế cho vibe coder VN: dạy LLM xử lý invoice PDF -> trích xuất data -> insert DB -> gửi email cho khách. Hoặc cron scrape giá vàng mỗi 15 phút -> post lên Telegram channel. Một lần setup, chạy 24/7 không cần can thiệp.

Bài này hướng dẫn cài Open Interpreter trên Cloud VPS 4GB Ubuntu 24.04, sandbox bằng Docker, expose REST API, ví dụ workflow thực tế.

1. Cài Open Interpreter (server mode)

sudo apt update
sudo apt install -y python3.11 python3-pip python3-venv

# Tạo venv
python3 -m venv /opt/oi-env
source /opt/oi-env/bin/activate

pip install open-interpreter

interpreter --version
# 0.4.x

2. Cấu hình LLM provider

# Anthropic Claude
export ANTHROPIC_API_KEY=sk-ant-xxx
interpreter --model claude-3-5-sonnet-20241022

# OpenAI
export OPENAI_API_KEY=sk-xxx
interpreter --model gpt-4o

# Ollama local LLM (offline, miễn phí token)
ollama serve &
interpreter --model ollama/llama3.1:8b --api_base http://localhost:11434

Ollama tốt nhất cho VPS 4GB+ chạy llama3.1:8b. Local LLM không charge API, latency thấp, privacy cao.

3. Test command đầu tiên

interpreter

> Đếm số file trong thư mục /var/log

# Open Interpreter sẽ:
# 1. Phân tích yêu cầu
# 2. Generate command: ls /var/log | wc -l
# 3. Xin permission user (auto_run=False mặc định)
# 4. Chạy command, parse output
# 5. Trả về số count đẹp

4. Sandbox bằng Docker bắt buộc

# Dockerfile
FROM python:3.11-slim

RUN apt-get update && apt-get install -y 
    curl git nodejs npm tmux jq 
    && rm -rf /var/lib/apt/lists/*

RUN pip install open-interpreter fastapi uvicorn

RUN useradd -m -s /bin/bash ai
USER ai
WORKDIR /home/ai

EXPOSE 8000
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000"]
# Build và chạy
docker build -t open-interpreter .

docker run -d --name oi 
  --cap-drop ALL 
  --security-opt no-new-privileges 
  --read-only 
  --tmpfs /tmp:rw,noexec,nosuid,size=500m 
  -v /var/oi-workspace:/home/ai/workspace 
  -p 127.0.0.1:8000:8000 
  -e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY 
  --restart unless-stopped 
  open-interpreter

Cap-drop ALL, read-only root, non-root user - container không thể escalate, không thể đè file hệ thống. Workspace mount riêng để persist data.

5. Expose REST API với FastAPI

# /home/ai/server.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from interpreter import interpreter
import os

app = FastAPI()
interpreter.llm.model = "claude-3-5-sonnet-20241022"
interpreter.llm.api_key = os.getenv("ANTHROPIC_API_KEY")
interpreter.auto_run = True  # auto chạy không hỏi
interpreter.os = True

API_TOKEN = os.getenv("API_TOKEN", "change-me")

class TaskRequest(BaseModel):
    task: str
    context: dict = {}

@app.post("/task")
async def run_task(req: TaskRequest, authorization: str = ""):
    if authorization != f"Bearer {API_TOKEN}":
        raise HTTPException(403, "Unauthorized")

    interpreter.reset()
    result = []
    for chunk in interpreter.chat(req.task, stream=False, display=False):
        result.append(chunk)

    return {"status": "ok", "messages": result}

@app.get("/health")
async def health():
    return {"status": "running"}

6. Caddy reverse proxy + SSL

# /etc/caddy/Caddyfile
ai.yourdomain.com {
    reverse_proxy 127.0.0.1:8000

    @api {
        path /task /health
    }
    handle @api {
        reverse_proxy 127.0.0.1:8000
    }
}

sudo systemctl reload caddy

7. Test API từ external

curl -X POST https://ai.yourdomain.com/task 
  -H "Authorization: Bearer mytoken123" 
  -H "Content-Type: application/json" 
  -d '{
    "task": "Đếm số file .log trong workspace, group theo extension, return JSON"
  }'

# Response:
# {
#   "status": "ok",
#   "messages": [...
#     "Tôi đã tìm thấy 47 file .log",
#     {"counts": {".log": 47}}
#   ]
# }

8. Workflow thực tế: scrape giá vàng -> Telegram

# cron-task.sh - chạy mỗi 15 phút
#!/bin/bash
TASK="Truy cập sjc.com.vn, lấy giá vàng SJC 9999 mua/bán hôm nay,
format thành message: 'SJC: mua X tr - bán Y tr (lúc HH:MM)',
gửi POST tới Telegram bot API với token $TG_TOKEN, chat_id $TG_CHAT"

curl -X POST https://ai.yourdomain.com/task 
  -H "Authorization: Bearer mytoken123" 
  -H "Content-Type: application/json" 
  -d "{"task": "$TASK"}"

# Crontab
echo '*/15 * * * * /opt/cron-task.sh' >> /etc/crontab

Open Interpreter tự viết Python scrape SJC, parse HTML, format message, gửi Telegram. Một lần config, chạy 24/7. Khi UI SJC đổi, LLM tự adapt.

9. Use case automation khác

  • Invoice PDF processing: đọc PDF, OCR, extract data, insert MySQL, gửi email.
  • Log analysis: tail nginx log mỗi giờ, summarize lỗi 500, alert Slack.
  • Data sync: pull data từ Google Sheets -> transform -> push PostgreSQL.
  • Image processing: watch folder, auto resize + watermark, upload S3.
  • Code review bot: webhook GitHub PR, AI review diff, comment suggest.

10. Resource limit và rate limit

# Docker compose với limit
services:
  oi:
    image: open-interpreter
    cpus: 1.5
    mem_limit: 1g
    pids_limit: 100
    restart: unless-stopped
    environment:
      - MAX_TASK_PER_HOUR=60

# Trong server.py thêm rate limit
from slowapi import Limiter
from slowapi.util import get_remote_address

limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter

@app.post("/task")
@limiter.limit("60/hour")
async def run_task(...):
    ...

11. Monitor và audit log

# Log mọi task vào file
import logging
logging.basicConfig(
    filename='/var/log/oi-tasks.log',
    level=logging.INFO,
    format='%(asctime)s - %(message)s'
)

@app.post("/task")
async def run_task(req: TaskRequest, ...):
    logging.info(f"TASK: {req.task[:200]}")
    result = ...
    logging.info(f"RESULT: {str(result)[:500]}")
    return result

# Tail log realtime
tail -f /var/log/oi-tasks.log

12. Cost và LLM model recommendation

ModelCost/1M tokenSpeedCode quality
Claude Sonnet 4.6~3-15 USD50t/sRất cao
GPT-4o~5-15 USD80t/sCao
Gemini 2.0 Flash~0.5-3 USD150t/sTốt
Ollama llama3.1:8b0 (chỉ điện VPS)20-40t/sTrung bình

Khuyến nghị: Gemini Flash cho automation cost-sensitive, Claude Sonnet cho task code phức tạp. Ollama nếu cần offline 100%.

Cloud VPS cho vibe coder

VPS 24/7 chạy AI worker tự động hóa workflow

Cloud VPS TND sẵn AlmaLinux 9, Ubuntu 22/24, Debian 12/13. SSD CEPH, snapshot 1-click, backup hằng ngày, network 200Mbps trong nước. VPS 4GB chạy Open Interpreter + Ollama local LLM thoải mái, không lo API charge.

Xem 8 cấu hình Cloud VPS →

FAQ

Open Interpreter có an toàn để chạy 24/7 không?

An toàn nếu sandbox đúng cách: Docker với cap-drop ALL, non-root user, read-only root, network restricted. KHÔNG bao giờ chạy native trên host với root privileges.

Có thể giới hạn loại command LLM được chạy không?

Có. Set custom_instructions trong interpreter.system_message: NEVER run rm -rf, DROP TABLE, format. Hoặc dùng AppArmor profile chặn syscall nhất định.

VPS RAM tối thiểu cho Open Interpreter là bao nhiêu?

2GB nếu dùng API LLM (Claude, GPT). 8GB+ nếu chạy Ollama local LLM cùng. RAM ăn nhiều nhất khi LLM generate code Python phức tạp ~500MB.

Có nên expose API public không?

Không nên public. Always require API token + IP whitelist + rate limit. Tốt nhất chỉ truy cập từ internal network hoặc VPN.

Khác biệt với n8n/Zapier?

n8n có node visual GUI, predefined integration. Open Interpreter dùng natural language, LLM tự nghĩ code. Mạnh hơn cho task ad-hoc không có node sẵn. Tích hợp được cả 2: n8n trigger -> webhook -> Open Interpreter.

LLM có nhớ context giữa các task không?

Default mỗi task reset context. Có thể save conversation history trong DB và load lại nếu cần stateful workflow. Cẩn thận context dài tốn nhiều token.

2009
15+ năm vận hành liên tục
10+
tập đoàn lớn tin dùng
100+
doanh nghiệp SMB Việt
30 ngày
đổi key lỗi miễn phí
Phần mềm bản quyền chính hãng chúng tôi cung cấp
Bản quyền chính hãng Hóa đơn VAT đầy đủ Đổi key lỗi 30 ngày Vận hành từ 2009 MST 0200994870 Hotline 0225.999.6666