AiCredits
Automation Guide

Self-Hosted n8n + LLM API: Automation Without Subscriptions

Run n8n on your own server and pair it with a pay-as-you-go LLM API over the OpenAI SDK — a complete automation stack with no monthly AI subscription lock-in.

Published 2026-12-02 Updated 2026-12-02 9 min

Why self-hosted n8n is only half of a subscription-free stack

You can run n8n Community Edition on a small VPS, point it at Postgres, and own every workflow, credential, and execution log. That kills the automation-platform subscription. It does not kill the AI subscription — the moment you drag an AI node onto the canvas, most tutorials route you into a vendor billing account with monthly minimums, per-seat pricing, and a usage graph you can't reconcile against your own logs.

The fix is to treat the model as just another HTTP endpoint. n8n doesn't care whether a completion comes from a first-party API or an OpenAI-compatible gateway; it cares that the request shape matches. Once your model access is key-based and metered, the stack becomes: your server, your database, your workflows, and an endpoint you can swap in one credential field.

One licensing caveat before you invest a weekend: n8n ships under the Sustainable Use License. Internal business use is free; reselling n8n itself as a hosted service needs a commercial agreement. Read the terms before you build a product on top of it.

Owning the runner doesn't remove the AI bill — it just makes it visible, auditable, and cancellable.

The three-piece architecture

  • n8n in Docker — the scheduler and integration layer, with Postgres for persistence so execution history survives restarts.

  • An OpenAI-compatible endpoint — one base URL that speaks /chat/completions, so n8n, your scripts, and your CI share client code.

  • Secret storage — the key lives in n8n credentials or an env var, never inside a node's JSON body or a committed workflow export.

  • Optional: Redis + queue mode once you run more than a handful of long workflows concurrently.

The compose file below is the minimum viable setup. Postgres is not optional if you care about execution history — n8n's default SQLite is fine for a demo and painful the first time a scheduled workflow fails at 3 a.m.

services:
  postgres:
    image: postgres:16
    restart: unless-stopped
    environment:
      POSTGRES_USER: n8n
      POSTGRES_PASSWORD: change-me
      POSTGRES_DB: n8n
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U n8n"]
      interval: 10s
      retries: 5

  n8n:
    image: docker.n8n.io/n8nio/n8n
    restart: unless-stopped
    ports:
      - "5678:5678"
    environment:
      DB_TYPE: postgresdb
      DB_POSTGRESDB_HOST: postgres
      DB_POSTGRESDB_DATABASE: n8n
      DB_POSTGRESDB_USER: n8n
      DB_POSTGRESDB_PASSWORD: change-me
      N8N_ENCRYPTION_KEY: change-me-too
      GENERIC_TIMEZONE: UTC
      N8N_HOST: localhost
      WEBHOOK_URL: http://localhost:5678/
    volumes:
      - n8ndata:/home/node/.n8n
    depends_on:
      postgres:
        condition: service_healthy

volumes:
  pgdata:
  n8ndata:

Wiring the model endpoint into n8n

Current n8n releases expose a Base URL field on the OpenAI credential. Paste https://api.aicreditsapi.com/v1, add your key, and the OpenAI Chat Model node works unchanged.

If your version doesn't have that field, skip the node and use an HTTP Request node with Header Auth. It's version-proof, it shows exactly what goes over the wire, and it makes timeouts and retries visible instead of hidden behind a node's abstraction.

{
  "model": "deepseek-v4-flash",
  "temperature": 0,
  "max_tokens": 300,
  "messages": [
    {"role": "system", "content": "You are a support triage assistant. Return JSON only with keys priority (p0|p1|p2), topic (billing|bug|feature|other), summary (one sentence)."},
    {"role": "user", "content": "=Subject: {{$json.subject}}\n\nBody:\n{{$json.body}}"}
  ]
}

Before building anything in the UI, prove the credential works from a script. This is the same request the workflow will send:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.aicreditsapi.com/v1",
    api_key=os.environ["AICREDITS_API_KEY"],
)

SYSTEM = (
    "You are a support triage assistant. Return JSON only with keys "
    "priority (p0|p1|p2), topic (billing|bug|feature|other), summary (one sentence)."
)


def triage(subject: str, body: str) -> str:
    response = client.chat.completions.create(
        model="deepseek-v4-flash",
        temperature=0,
        max_tokens=300,
        messages=[
            {"role": "system", "content": SYSTEM},
            {"role": "user", "content": f"Subject: {subject}\n\nBody:\n{body}"},
        ],
    )
    return response.choices[0].message.content


if __name__ == "__main__":
    print(triage("Cannot log in", "I get a 500 error when I click login since this morning."))

If that prints a JSON object, the plumbing is done. Now you can build the same call as a node with confidence.

A workflow worth automating: support-email triage

The pattern that repays its setup cost fastest is inbound triage. A webhook fires on a new support email, one model call classifies it, and a Switch node routes p0 to Slack, p1 to Linear, and the rest into a digest. Two nodes of real logic, and you've replaced a per-seat helpdesk add-on.

  • Give the exact schema in the system prompt. "Return JSON only with keys …" beats "please format nicely" every time.

  • Set temperature to 0 for classification so re-running an execution gives the same routing decision.

  • Cap max_tokens. A triage answer that runs long is a bug, not a feature.

  • Keep the raw response in the execution log for a week — you'll want it when a ticket lands in the wrong queue.

  • Guard the parse step with an IF node on empty content; a malformed reply should route to a fallback, not fail the whole execution.

flash or pro: choose per step, not per project

Default every step to deepseek-v4-flash. It's the fast model, and for routing, extraction, summarization, and first-draft replies the difference rarely shows up in output quality. Reserve deepseek-v4-pro for the steps where a wrong answer costs real money. Pro costs more per call, so the discipline is escalate by exception, never by default.

Workflow stepModelWhy
Classify, route, extract fieldsdeepseek-v4-flashLatency matters more than depth; runs on every trigger
Summarize tickets, threads, documentsdeepseek-v4-flashCheap at volume and good enough for compression
Root-cause a stack tracedeepseek-v4-proA wrong diagnosis costs engineering hours, not tokens
Draft a customer-facing replydeepseek-v4-proTone is user-visible and the volume is low
Repeated system prompt + schemaeitherKeep it byte-identical so context caching can apply

Then there's the quieter lever: context caching. Providers that support it bill a repeated prompt prefix at a lower rate — but only when the prefix is byte-identical between calls.

  • Order prompts statically: system instructions and schema first, user data last.

  • Never interpolate a timestamp or request ID into the system prompt — it silently destroys cache hits.

  • Batch nightly jobs (backfills, report generation) into off-peak hours, which cost less on DeepSeek-style pricing.

  • Log prompt_tokens and completion_tokens per execution into Postgres; a weekly query tells you which workflow is expensive.

  • Check current rates at aicreditsapi.com/deepseek-prices rather than trusting any blog post, including this one.

Making it production-safe

Three failure modes bite self-hosted automation: the API returns a transient error and the node fails silently, a long workflow times out mid-run and re-fires on the next schedule, and a prompt edit quietly doubles token usage. The first is a retry problem, and it's solvable in a dozen lines.

import os
import random
import time

from openai import APIConnectionError, APIError, RateLimitError, OpenAI

client = OpenAI(
    base_url="https://api.aicreditsapi.com/v1",
    api_key=os.environ["AICREDITS_API_KEY"],
)


def chat_with_retry(messages, model="deepseek-v4-flash", max_attempts=5, **kwargs):
    for attempt in range(1, max_attempts + 1):
        try:
            return client.chat.completions.create(
                model=model, messages=messages, **kwargs
            )
        except (RateLimitError, APIConnectionError, APIError) as exc:
            if attempt == max_attempts:
                raise
            delay = min(2 ** attempt + random.random(), 30)
            print(f"attempt {attempt} failed ({exc}); retrying in {delay:.1f}s")
            time.sleep(delay)
    raise RuntimeError("retry loop exited unexpectedly")


if __name__ == "__main__":
    reply = chat_with_retry(
        [{"role": "user", "content": "Summarize: n8n webhook timed out after 30s."}],
        max_tokens=120,
    )
    print(reply.choices[0].message.content)
  • Set a timeout on every HTTP Request node and an error workflow that writes failures to a dead-letter table instead of retrying forever.

  • Make steps idempotent with a hash of the input as a dedupe key, so a re-fired schedule doesn't send the same Slack message twice.

  • Back up the Postgres volume. Your workflows, credentials, and history are the asset — the container is disposable.

Managed automation vs self-hosted: a fair comparison

n8n Cloud is genuinely good if you don't want to own a server — backups, upgrades, and SSO handled, no Docker knowledge required. Zapier and Make have connector catalogs n8n can't match and onboard non-technical teams faster. If your workflow count is low and your time is expensive, a managed plan is the rational choice.

Self-hosting wins on three axes: data residency (execution logs never leave your infrastructure), volume (no per-task pricing as you scale), and portability (the model is one credential field, so you can move between providers without touching a workflow). The cost is ops work — you are the on-call engineer for your own automation platform, and that's a real bill too.

Frequently asked questions

Is self-hosted n8n actually free?

The Community Edition is free to self-host for internal business use under the Sustainable Use License — you pay only for the server and the model calls. Reselling n8n as a hosted product requires a commercial license.

Can I use DeepSeek models inside n8n's OpenAI nodes?

Yes. Set the credential's Base URL to https://api.aicreditsapi.com/v1 and use your AiCredits key; the request format is OpenAI-compatible. If your n8n version lacks the Base URL field, use an HTTP Request node with Header Auth instead.

Do I need a Chinese phone number or bank account to pay for the API?

No. AiCredits is built for international developers — you top up with a card or PayPal and get an OpenAI-compatible key. That's the main reason people route DeepSeek through a gateway rather than the first-party console.

How do I stop a runaway workflow from burning credits?

Three guards: a max_tokens cap on every call, a Switch node that aborts on empty or oversized input, and a daily token-usage query over your Postgres logs that alerts you. Point retries at a dead-letter queue, never at an unbounded loop.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link
💬
反馈意见 / Feedback ×