RunPod + n8n: Fine-Tune a Small AI Model and Serve It as API

RunPod + n8n: Kleines KI-Modell fine-tunen und als API nutzen

🇬🇧 English

This article contains affiliate links. If you buy through them, we may earn a commission at no extra cost to you.

Fine-Tune a Small AI Model on RunPod and Serve It via n8n — in 30 Minutes

You don't need a data-center contract or a machine learning PhD to run your own fine-tuned language model. With Runpod — a pay-per-use GPU cloud built for AI workloads — you can spin up a powerful training environment in minutes, fine-tune a compact open-source model on your own data, and expose the result as a clean REST API. Then you wire that API into n8n, the open-source workflow automation tool with 400+ integrations, and suddenly your custom model is powering real automations: Slack bots, email classifiers, internal Q&A tools, and more.

This guide walks you through the entire pipeline from zero to live API in roughly 30 minutes of active work.

What You Will Build

  • A fine-tuned version of a small open-source LLM (we use TinyLlama-1.1B as the example)
  • A vLLM or Ollama inference server running on a RunPod pod
  • A public HTTPS endpoint for that model
  • An n8n workflow that sends prompts to the endpoint and processes the response

Prerequisites

  • A RunPod account (free to create; you pay only for GPU seconds used)
  • A training dataset in JSONL format — even 200–500 instruction-response pairs are enough for a small model
  • An n8n instance — self-hosted or n8n Cloud
  • Basic comfort with a terminal and Python

Step 1 — Launch a RunPod GPU Pod for Fine-Tuning

Log in to RunPod and click + New Pod. For fine-tuning TinyLlama you need at least an RTX 3090 (24 GB VRAM); a single A100 40 GB is more comfortable and usually costs under $2/hour.

  1. Select the RunPod PyTorch 2.1 template — it comes with CUDA, Python 3.10, and pip pre-installed.
  2. Set disk to at least 30 GB (model weights + dataset + adapter checkpoints).
  3. Enable Expose HTTP Ports and add port 8000 (inference later) and 8888 (optional Jupyter).
  4. Click Deploy and wait about 90 seconds for the pod to start.

Connect via the RunPod web terminal or SSH. You are now on a GPU machine with no ongoing commitment — you stop the pod and billing stops.

Step 2 — Prepare the Training Environment

Inside the pod terminal, install the fine-tuning stack:

pip install -q transformers datasets peft trl accelerate bitsandbytes

Upload your JSONL dataset using the RunPod file manager or scp. Each line should follow the instruction-tuning format:

{"instruction": "Classify the sentiment", "input": "I love this product!", "output": "positive"}

Step 3 — Fine-Tune with QLoRA (the Fast Way)

QLoRA (Quantized Low-Rank Adaptation) lets you fine-tune a 1–7 B model on a single consumer GPU in minutes rather than hours by training only a small set of adapter weights on top of a 4-bit quantized base model.

Create a file finetune.py and paste the following minimal script:

from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments
from peft import LoraConfig
from trl import SFTTrainer
from datasets import load_dataset

model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
dataset = load_dataset("json", data_files="data.jsonl", split="train")

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, load_in_4bit=True, device_map="auto")

lora_config = LoraConfig(r=8, lora_alpha=16, target_modules=["q_proj","v_proj"], lora_dropout=0.05)

trainer = SFTTrainer(
 model=model,
 train_dataset=dataset,
 dataset_text_field="output",
 peft_config=lora_config,
 args=TrainingArguments(output_dir="adapter", num_train_epochs=3,
 per_device_train_batch_size=4, fp16=True,
 logging_steps=10, save_strategy="epoch")
)
trainer.train()
trainer.save_model("adapter")

Run it with python finetune.py. On an RTX 3090 with 300 examples this finishes in roughly 8–12 minutes.

Step 4 — Merge and Serve the Model with Ollama

After training, merge the LoRA adapter into the base model and serve it:

# Install Ollama
curl -fsSL https://ollama.com/install.sh | sh

# Merge weights (using a helper script from PEFT)
python -c "
from peft import AutoPeftModelForCausalLM
import torch
model = AutoPeftModelForCausalLM.from_pretrained('adapter', torch_dtype=torch.float16)
merged = model.merge_and_unload()
merged.save_pretrained('merged_model')
"

# Create a Modelfile and push to Ollama
echo 'FROM ./merged_model' > Modelfile
ollama create my-custom-model -f Modelfile
ollama serve &

Ollama now listens on port 11434. Because you exposed port 8000 earlier, forward with:

ollama serve --host 0.0.0.0 --port 8000 &

RunPod gives you a public HTTPS URL in the format https://<pod-id>-8000.proxy.runpod.net. Test it:

curl https://<pod-id>-8000.proxy.runpod.net/api/generate \
 -d '{"model":"my-custom-model","prompt":"Classify: Great product!","stream":false}'

If you see a JSON response with a response field, your model is live as an API.

Step 5 — Connect the API to n8n

Now the fun part: wire the model into an automated workflow using n8n, which lets you self-host for free or use n8n Cloud with 400+ ready-made integrations.

  1. Open your n8n canvas and add an HTTP Request node.
  2. Set Method to POST and URL to your RunPod proxy URL (/api/generate).
  3. Under Body, choose JSON and paste:
    { "model": "my-custom-model", "prompt": "{{ $json.text }}", "stream": false }
  4. Add a Set node after it to extract {{ $json.response }} into a clean field.
  5. Connect any trigger you like — a Webhook node, a Gmail trigger, a Slack message, or a scheduled Cron.

Example use cases you can build in under 5 minutes once the connection is live:

  • Email triage: Incoming email → your model classifies intent → route to the right team in Slack
  • Support ticket tagging: New Zendesk ticket → model assigns category → update ticket field
  • Internal FAQ bot: Webhook from a web form → model answers → reply via email or Teams

Cost Estimate

  • Fine-tuning run (~12 min on RTX 3090): ≈ $0.08–0.15
  • Inference pod (RTX 3090, running 8 h/day): ≈ $1.60–2.00/day
  • Tip: Stop the pod when not in use. Use a RunPod Serverless endpoint for production — you only pay per request.

Tips for Production Readiness

  • Switch from Ollama to vLLM for higher throughput on shared endpoints.
  • Store your merged model weights in RunPod's Network Volume so you don't re-upload on every pod restart.
  • Add an API key header in Ollama or place an n8n Webhook with a secret token in front of the endpoint.
  • Use n8n's built-in error handling nodes to retry failed inference calls automatically.

Summary

In about 30 minutes of active work you have: a domain-specific fine-tuned LLM, a live HTTPS inference endpoint on GPU hardware, and an n8n workflow that any team member can trigger without touching a command line. The whole stack costs cents to train and a couple of dollars per day to run — less than a SaaS AI API for many workloads.

If you want to run, fine-tune and serve your own open-source AI models without a long-term commitment, you can get started via Runpod — including pay-per-use GPU cloud access — to build and deploy custom AI endpoints at a fraction of typical cloud costs.

🇩🇪 Deutsch

Dieser Artikel enthält Affiliate-Links (Werbung). Kaufst du darüber, erhalten wir ggf. eine Provision – für dich ohne Mehrkosten.

Kleines KI-Modell auf RunPod fine-tunen und über n8n als API bereitstellen – in 30 Minuten

Du brauchst weder einen Rechenzentrums-Vertrag noch einen Machine-Learning-Doktortitel, um ein eigenes fine-getuntes Sprachmodell zu betreiben. Mit Runpod – einem Pay-per-Use-GPU-Cloud-Dienst speziell für KI-Workloads – startest du in Minuten eine leistungsstarke Trainingsumgebung, fine-tunest ein kompaktes Open-Source-Modell auf deinen eigenen Daten und stellst das Ergebnis als saubere REST-API bereit. Diese API verbindest du dann mit n8n, dem Open-Source-Workflow-Automatisierungstool mit 400+ Integrationen, und schon treibt dein individuelles Modell echte Automatisierungen an: Slack-Bots, E-Mail-Klassifikatoren, interne Q&A-Tools und vieles mehr.

Diese Anleitung führt dich in etwa 30 Minuten aktiver Arbeitszeit von null bis zur live geschalteten API.

Was du aufbaust

  • Eine fine-getunete Version eines kleinen Open-Source-LLMs (als Beispiel nutzen wir TinyLlama-1.1B)
  • Einen vLLM- oder Ollama-Inference-Server auf einem RunPod-Pod
  • Einen öffentlichen HTTPS-Endpunkt für das Modell
  • Einen n8n-Workflow, der Prompts an den Endpunkt sendet und die Antwort weiterverarbeitet

Voraussetzungen

  • Ein RunPod-Konto (kostenlos anzulegen; bezahlt wird nur für tatsächlich genutzte GPU-Sekunden)
  • Ein Trainingsdatensatz im JSONL-Format – schon 200–500 Instruction-Response-Paare reichen für ein kleines Modell
  • Eine n8n-Instanz – selbst gehostet oder n8n Cloud
  • Grundlegende Kenntnisse im Umgang mit Terminal und Python

Schritt 1 – RunPod-GPU-Pod für das Fine-Tuning starten

Melde dich bei RunPod an und klicke auf + New Pod. Für das Fine-Tuning von TinyLlama benötigst du mindestens eine RTX 3090 (24 GB VRAM); eine einzelne A100 40 GB ist komfortabler und kostet in der Regel unter 2 $/Stunde.

  1. Wähle das Template RunPod PyTorch 2.1 – es enthält CUDA, Python 3.10 und pip vorinstalliert.
  2. Setze den Speicherplatz auf mindestens 30 GB (Modellgewichte + Datensatz + Adapter-Checkpoints).
  3. Aktiviere Expose HTTP Ports und trage Port 8000 (später Inference) und 8888 (optional Jupyter) ein.
  4. Klicke auf Deploy und warte etwa 90 Sekunden, bis der Pod gestartet ist.

Verbinde dich über das RunPod-Web-Terminal oder per SSH. Du arbeitest jetzt auf einer GPU-Maschine ohne laufende Verpflichtung – sobald du den Pod stoppst, endet die Abrechnung.

Schritt 2 – Trainingsumgebung einrichten

Installiere im Pod-Terminal den Fine-Tuning-Stack:

pip install -q transformers datasets peft trl accelerate bitsandbytes

Lade deinen JSONL-Datensatz über den RunPod-Dateimanager oder per scp hoch. Jede Zeile sollte dem Instruction-Tuning-Format folgen:

{"instruction": "Sentiment klassifizieren", "input": "Ich liebe dieses Produkt!", "output": "positiv"}

Schritt 3 – Fine-Tuning mit QLoRA (der schnelle Weg)

QLoRA (Quantized Low-Rank Adaptation) ermöglicht das Fine-Tuning eines 1–7-B-Modells auf einer einzelnen Consumer-GPU in Minuten statt Stunden – indem nur eine kleine Menge Adapter-Gewichte auf einem 4-Bit-quantisierten Basismodell trainiert wird.

Erstelle eine Datei finetune.py und füge das folgende minimale Skript ein:

from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments
from peft import LoraConfig
from trl import SFTTrainer
from datasets import load_dataset

model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
dataset = load_dataset("json", data_files="data.jsonl", split="train")

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, load_in_4bit=True, device_map="auto")

lora_config = LoraConfig(r=8, lora_alpha=16, target_modules=["q_proj","v_proj"], lora_dropout=0.05)

trainer = SFTTrainer(
 model=model,
 train_dataset=dataset,
 dataset_text_field="output",
 peft_config=lora_config,
 args=TrainingArguments(output_dir="adapter", num_train_epochs=3,
 per_device_train_batch_size=4, fp16=True,
 logging_steps=10, save_strategy="epoch")
)
trainer.train()
trainer.save_model("adapter")

Starte das Training mit python finetune.py. Auf einer RTX 3090 mit 300 Beispielen dauert das in der Regel 8–12 Minuten.

Schritt 4 – Modell zusammenführen und mit Ollama bereitstellen

Nach dem Training den LoRA-Adapter in das Basismodell zusammenführen und servieren:

# Ollama installieren
curl -fsSL https://ollama.com/install.sh | sh

# Gewichte zusammenführen (mit PEFT-Hilfsskript)
python -c "
from peft import AutoPeftModelForCausalLM
import torch
model = AutoPeftModelForCausalLM.from_pretrained('adapter', torch_dtype=torch.float16)
merged = model.merge_and_unload()
merged.save_pretrained('merged_model')
"

# Modelfile erstellen und zu Ollama pushen
echo 'FROM ./merged_model' > Modelfile
ollama create mein-custom-modell -f Modelfile
ollama serve &

Ollama lauscht jetzt auf Port 11434. Da du vorhin Port 8000 freigegeben hast, leite wie folgt weiter:

ollama serve --host 0.0.0.0 --port 8000 &

RunPod stellt dir eine öffentliche HTTPS-URL im Format https://<pod-id>-8000.proxy.runpod.net bereit. Teste sie:

curl https://<pod-id>-8000.proxy.runpod.net/api/generate \
 -d '{"model":"mein-custom-modell","prompt":"Klassifiziere: Tolles Produkt!","stream":false}'

Wenn du eine JSON-Antwort mit einem response-Feld siehst, ist dein Modell als API live.

Schritt 5 – Die API mit n8n verbinden

Jetzt kommt der spannende Teil: Das Modell wird über n8n in einen automatisierten Workflow eingebunden – selbst hostbar oder als n8n Cloud mit 400+ fertigen Integrationen.

  1. Öffne dein n8n-Canvas und füge einen HTTP Request-Node hinzu.
  2. Setze Method auf POST und URL auf deine RunPod-Proxy-URL (/api/generate).
  3. Unter Body wähle JSON und füge Folgendes ein:
    { "model": "mein-custom-modell", "prompt": "{{ $json.text }}", "stream": false }
  4. Füge danach einen Set-Node hinzu, um {{ $json.response }} in ein sauberes Feld zu extrahieren.
  5. Verbinde einen beliebigen Trigger – einen Webhook-Node, einen Gmail-Trigger, eine Slack-Nachricht oder einen geplanten Cron.

Beispiel-Anwendungsfälle, die du in unter 5 Minuten aufbauen kannst, sobald die Verbindung steht:

  • E-Mail-Triage: Eingehende E-Mail → dein Modell klassifiziert die Absicht → Weiterleitung an das richtige Team in Slack
  • Support-Ticket-Tagging: Neues Zendesk-Ticket → Modell vergibt Kategorie → Ticket-Feld aktualisieren
  • Interner FAQ-Bot: Webhook aus einem Webformular → Modell antwortet → Antwort per E-Mail oder Teams

Kostenschätzung

  • Fine-Tuning-Lauf (~12 min auf RTX 3090): ≈ 0,08–0,15 $
  • Inference-Pod (RTX 3090, 8 h/Tag laufend): ≈ 1,60–2,00 $/Tag
  • Tipp: Pod stoppen, wenn nicht in Verwendung. Für den Produktivbetrieb einen RunPod Serverless-Endpunkt nutzen – dort wird nur pro Anfrage abgerechnet.

Tipps für den Produktionseinsatz

  • Für höheren Durchsatz auf geteilten Endpunkten zu vLLM wechseln statt Ollama.
  • Die zusammengeführten Modellgewichte in einem RunPod-Network Volume speichern, damit kein erneutes Hochladen bei jedem Pod-Neustart nötig ist.
  • Einen API-Key-Header in Ollama hinzufügen oder einen n8n-Webhook mit Secret-Token vorschalten.
  • n8ns eingebaute Fehlerbehandlungs-Nodes nutzen, um fehlgeschlagene Inference-Aufrufe automatisch zu wiederholen.

Zusammenfassung

In etwa 30 Minuten aktiver Arbeit hast du: ein domänenspezifisch fine-getunetes LLM, einen live HTTPS-Inference-Endpunkt auf GPU-Hardware und einen n8n-Workflow, den jedes Teammitglied auslösen kann – ohne eine einzige Kommandozeile zu berühren. Das gesamte Setup kostet Cents im Training und ein paar Dollar pro Tag im Betrieb – für viele Workloads günstiger als eine SaaS-KI-API.

Wenn du eigene Open-Source-KI-Modelle ohne langfristige Bindung betreiben, fine-tunen und als API bereitstellen möchtest, kannst du über Runpod starten — inklusive Pay-per-Use-GPU-Cloud für KI-Workloads — und eigene KI-Endpunkte zu einem Bruchteil typischer Cloud-Kosten aufbauen.