<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Patrik Duch on Medium]]></title>
        <description><![CDATA[Stories by Patrik Duch on Medium]]></description>
        <link>https://medium.com/@patrickduch93?source=rss-a17cc89b1635------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FSc_dvifv3t2OJW1_GkaoQ.jpeg</url>
            <title>Stories by Patrik Duch on Medium</title>
            <link>https://medium.com/@patrickduch93?source=rss-a17cc89b1635------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:44:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patrickduch93/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Fine-Tuning Qwen2.5 1.5B on a Gaming GPU and Running It on Hetzner]]></title>
            <link>https://medium.com/@patrickduch93/fine-tuning-qwen2-5-1-5b-on-a-gaming-gpu-and-running-it-on-hetzner-59f939431b98?source=rss-a17cc89b1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/59f939431b98</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[qwen]]></category>
            <dc:creator><![CDATA[Patrik Duch]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 20:30:50 GMT</pubDate>
            <atom:updated>2026-11-10T20:30:50.350Z</atom:updated>
            <content:encoded><![CDATA[<p>I previously experimented with fine-tuning through the OpenAI API. Google Colab is another option, but it means uploading training data to Google’s infrastructure. When I tried it, I couldn’t even complete my first fine-tuning run on the free plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azUbPYxwRujwrOgSZZMY3g.png" /><figcaption>From local GPU fine-tuning to CPU inference on Hetzner VPS — Illustration (<a href="https://openart.ai/home">DALL·E </a>OpenAI)</figcaption></figure><h3><strong>This time, I wanted to fine-tune an open-weight model locally.</strong></h3><h3>SLM vs. LLM</h3><p>Some might call Qwen2.5 1.5B a Small Language Model (SLM). The distinction between SLMs and LLMs i’snt strictly defined, but even those small models require a pretty decent GPU for fine-tuning.</p><h3>Fine-Tuning vs. Inference: Hardware Requirements</h3><p>Fine-tuning updates the model’s trainable parameters using examples from a training dataset. Fine-tuning this model (Qwen2.5–1.5B-Instruct) isn’t something a typical office PC can handle.</p><p>Training runs on a GeForce RTX 4060, the kind of card people used to buy to play GTA V, but also a useful card for experimenting with fine-tuning. This article covers the complete pipeline: dataset creation, QLoRA, quantization, and deployment on Hetzner.</p><p>I’ve preferred NVIDIA GPUs in my builds since I was a kid. I’ve heard that fine-tuning on AMD GPUs is possible too, but getting the software working can be much harder than with NVIDIA and CUDA.</p><p>Inference with this model doesn’t need powerful hardware: the quantized model can run on a low-cost Hetzner server. In my tests, responses took just a couple of seconds, as you’ll see in this article.</p><h3>Disclaimer</h3><p>QWEN is a Chinese model. This example uses synthetic training data and contains no personal information. The goal is to explore how fine-tuning adapts a pretrained model to a specific task.</p><h3>QLoRA</h3><p>QLoRA (Quantized Low-Rank Adaptation): The “Q” refers to the base model being quantized to 4-bit precision, while the adapter is trained at higher precision.</p><p>The base weights stay the same during training. Only the adapter weights change, teching the model to respond differently.</p><h4>QLoRA vs. LoRA</h4><p>Both train the same thing: a small adapter with the base model frozen. The difference is the precision of the frozen model during training. Standard LoRA typically uses a 16-bit base model, while QLoRA quantizes it to 4-bit. That’s what the “Q” is all about.</p><h3>The whole thing, in one line</h3><p>The task is simple: classify a Czech sentence as positive, negative, or neutral. The model is trained to respond with one word: “POZITIVNÍ” (positive), “NEGATIVNÍ” (negative), or “NEUTRÁLNÍ” (neutral).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*sCHslsNGnAF1J_bGghbXlA.png" /><figcaption>Czech sentiment QLoRA training pipeline</figcaption></figure><p><strong>make_dataset.py</strong></p><pre>import json, random<br><br>pos =  [&quot;skvělé&quot;, &quot;výborné&quot;, &quot;nadchlo mě to&quot;, &quot;moc se mi to líbilo&quot;, &quot;paráda&quot;, &quot;doporučuju&quot;, &quot;super zážitek&quot;, &quot;naprostá spokojenost&quot;]<br>neg =  [&quot;hrozné&quot;, &quot;zklamání&quot;, &quot;nedoporučuju&quot;, &quot;ztráta času&quot;, &quot;špatné&quot;, &quot;otřesná kvalita&quot;, &quot;nikdy víc&quot;, &quot;naprostá katastrofa&quot;]<br>subj = [&quot;Ten film&quot;, &quot;Ta restaurace&quot;, &quot;Ten hotel&quot;, &quot;Ta kniha&quot;, &quot;Ten servis&quot;, &quot;Ta hra&quot;, &quot;Ten kurz&quot;, &quot;Ten produkt&quot;]<br><br># slib × realita — hodnocení je v rozporu, ne ve slovech<br>sliby = [<br>    (&quot;Zaplatil jsem za expresní doručení&quot;, &quot;přišlo to za {}&quot;, [&quot;týden&quot;, &quot;deset dní&quot;, &quot;dva týdny&quot;], [&quot;druhý den&quot;, &quot;do pár hodin&quot;]),<br>    (&quot;Rezervoval jsem si stůl na osmou&quot;, &quot;posadili mě {}&quot;, [&quot;až o hodinu později&quot;, &quot;po půl hodině čekání&quot;], [&quot;přesně na čas&quot;, &quot;hned po příchodu&quot;]),<br>    (&quot;Slíbili opravu do tří dnů&quot;, &quot;hotové to bylo {}&quot;, [&quot;za měsíc&quot;, &quot;až po urgencích&quot;], [&quot;už druhý den&quot;, &quot;v termínu&quot;]),<br>    (&quot;Platil jsem si prémiový tarif&quot;, &quot;podpora mi odpověděla {}&quot;, [&quot;po pěti dnech&quot;, &quot;až na třetí urgenci&quot;], [&quot;do deseti minut&quot;, &quot;obratem&quot;]),<br>    (&quot;Objednal jsem si velkou porci&quot;, &quot;přinesli {}&quot;, [&quot;sotva polovinu&quot;, &quot;míň než minule&quot;], [&quot;opravdu vrchovatý talíř&quot;, &quot;víc, než jsem čekal&quot;]),<br>    (&quot;V popisu stálo, že je pokoj tichý&quot;, &quot;celou noc {}&quot;, [&quot;hučela klimatizace&quot;, &quot;bylo slyšet ulici&quot;], [&quot;byl absolutní klid&quot;, &quot;jsem se skvěle vyspal&quot;]),<br>]<br><br># neutrální / vlažné — ať má model kam zařadit &quot;celkem ok&quot;<br>vlazne = [<br>    (&quot;Bylo to celkem ok, nic extra.&quot;, &quot;NEUTRÁLNÍ&quot;),<br>    (&quot;Nic moc, ale ani nic hrozného.&quot;, &quot;NEUTRÁLNÍ&quot;),<br>    (&quot;Průměr, čekal jsem to podobně.&quot;, &quot;NEUTRÁLNÍ&quot;),<br>    (&quot;Šlo to, nemám co vytknout ani pochválit.&quot;, &quot;NEUTRÁLNÍ&quot;),<br>    (&quot;Standardní, jako všude jinde.&quot;, &quot;NEUTRÁLNÍ&quot;),<br>    (&quot;Splnilo to účel, víc bych neřekl.&quot;, &quot;NEUTRÁLNÍ&quot;),<br>]<br><br>rows = []<br><br># 1) původní jednoduché věty — 200<br>for _ in range(200):<br>    if random.random() &lt; 0.5:<br>        rows.append({&quot;text&quot;: f&quot;{random.choice(subj)} bylo {random.choice(pos)}.&quot;, &quot;label&quot;: &quot;POZITIVNÍ&quot;})<br>    else:<br>        rows.append({&quot;text&quot;: f&quot;{random.choice(subj)} bylo {random.choice(neg)}.&quot;, &quot;label&quot;: &quot;NEGATIVNÍ&quot;})<br><br># 2) slib × realita — 200, vyvážené<br>for _ in range(200):<br>    uvod, sablona, spatne, dobre = random.choice(sliby)<br>    if random.random() &lt; 0.5:<br>        rows.append({&quot;text&quot;: f&quot;{uvod} a {sablona.format(random.choice(spatne))}.&quot;, &quot;label&quot;: &quot;NEGATIVNÍ&quot;})<br>    else:<br>        rows.append({&quot;text&quot;: f&quot;{uvod} a {sablona.format(random.choice(dobre))}.&quot;, &quot;label&quot;: &quot;POZITIVNÍ&quot;})<br><br># 3) vlažné — 60<br>for _ in range(60):<br>    t, l = random.choice(vlazne)<br>    rows.append({&quot;text&quot;: t, &quot;label&quot;: l})<br><br>random.shuffle(rows)<br>split = int(len(rows) * 0.9)<br>with open(&quot;train.jsonl&quot;, &quot;w&quot;) as f:<br>    for r in rows[:split]:<br>        f.write(json.dumps(r, ensure_ascii=False) + &quot;\n&quot;)<br>with open(&quot;val.jsonl&quot;, &quot;w&quot;) as f:<br>    for r in rows[split:]:<br>        f.write(json.dumps(r, ensure_ascii=False) + &quot;\n&quot;)<br>print(&quot;hotovo:&quot;, len(rows), &quot;train:&quot;, split, &quot;val:&quot;, len(rows) - split)</pre><p><strong>train.py</strong></p><p>We’re using PyTorch, a library for building, training, and running neural networks.</p><p>It supports both:</p><ul><li><strong>Training</strong>: calculating gradients and updating weights</li><li><strong>Inference</strong>: using existing weights to make predictions</li></ul><pre>from unsloth import FastLanguageModel<br>from datasets import load_dataset<br>from trl import SFTTrainer, SFTConfig<br>import torch<br><br>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name=&quot;unsloth/Qwen2.5-1.5B-Instruct&quot;,<br>    max_seq_length=256,<br>    load_in_4bit=True,<br>)<br><br>model = FastLanguageModel.get_peft_model(<br>    model, r=32, lora_alpha=32, lora_dropout=0,<br>    target_modules=[<br>      &quot;q_proj&quot;,<br>      &quot;k_proj&quot;,<br>      &quot;v_proj&quot;,<br>      &quot;o_proj&quot;,<br>      &quot;gate_proj&quot;,<br>      &quot;up_proj&quot;,<br>      &quot;down_proj&quot;<br>  ],<br>    use_gradient_checkpointing=&quot;unsloth&quot;,<br>)<br><br>def fmt(ex):<br>    msgs = [<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: ex[&quot;text&quot;]},<br>        {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: ex[&quot;label&quot;]},<br>    ]<br>    return {&quot;text&quot;: tokenizer.apply_chat_template(msgs, tokenize=False)}<br><br>ds = load_dataset(&quot;json&quot;, data_files={&quot;train&quot;: &quot;train.jsonl&quot;, &quot;val&quot;: &quot;val.jsonl&quot;})<br>ds = ds.map(fmt)<br><br>trainer = SFTTrainer(<br>    model=model, tokenizer=tokenizer,<br>    train_dataset=ds[&quot;train&quot;], eval_dataset=ds[&quot;val&quot;],<br>    args=SFTConfig(<br>        per_device_train_batch_size=2,<br>        gradient_accumulation_steps=4,<br>        num_train_epochs=10,<br>        learning_rate=2e-4,<br>        logging_steps=5,<br>        eval_strategy=&quot;epoch&quot;,<br>        output_dir=&quot;outputs_sentiment&quot;,<br>        report_to=&quot;none&quot;,<br>    ),<br>)<br><br>trainer.train()<br>model.save_pretrained(&quot;qwen-sentiment-lora&quot;)<br>tokenizer.save_pretrained(&quot;qwen-sentiment-lora&quot;)<br>print(&quot;Training complete. LoRA adapter saved.&quot;)</pre><p>The predictions, loss calculation, and weight updates happen inside this call.</p><pre>trainer.train()</pre><p>SFTTrainer handles the training loop for you:</p><ol><li>Takes a batch of training examples</li><li>Runs the model to predict probabilities for the next tokens.</li><li>Calculates loss using the expected tokens.</li><li>Backpropagates the loss.</li><li>Updates the LoRA weights after 4 batches, as configured by gradient_accumulation_steps=4</li></ol><p>During the training, it calculates token probabilities directly. It doesn’t need to generate a complete answer with model.generate() .</p><p>Your learning rate is set here:</p><pre>learning_rate=2e-4,</pre><h3>The Math Behind Fine-Tuning</h3><p>A derivate tells us how quickly a function changes at a particular point. Geometrically, it is the slope of the tangent line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*a-jCyCrNZZKHqPdXbg48tA.png" /></figure><p>This is a simplified example to illustrate derivates and slopes. The curve does not represent the actual loss function of our sentiment model or its training data.</p><h3>The environment and the trap that isn’t in any tutorial</h3><p>Training runs on Ubuntu on WSL2, in a virtualenv, with Unsloth doing the magic in the background. Create the virtual environment and install the packages once. Activate the environment whenever you open a new terminal.</p><pre>sudo apt update &amp;&amp; sudo apt install -y python3-pip python3-venv<br>python3 -m venv ~/ml312<br>source ~/ml312/bin/activate<br>pip install unsloth</pre><p>Run pip install before activating the virtual environment, and the packages won’t go into your venv. On Ubuntu 24.04, you may get an externally-managed-environment error. On older setups, packages may install outside the venv, causing dependency conflicts or leaving them unavailable when you activate it.</p><h4>Check NVIDIA GPU Access</h4><p>If you’re using MS Windows, open a terminal and start Ubuntu with WSL:</p><pre>wsl</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*Zkg2RoJ_E45zVnItaLkAJA.png" /><figcaption>Starting Ubuntu through WSL on MS Windows</figcaption></figure><p>Activate the virtual environment and check whether PyTorch can access your NVIDIA GPU:</p><pre>source ~/ml312/bin/activate<br><br>python - &lt;&lt;&#39;PY&#39;<br>import torch<br><br>available = torch.cuda.is_available()<br>print(&quot;CUDA available:&quot;, available)<br>if available:<br>    print(&quot;GPU:&quot;, torch.cuda.get_device_name(0))<br>PY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*Y86JOkdiuM2g00Akjft6pw.png" /><figcaption>PyTorch successfully detects the NVIDIA GPU</figcaption></figure><p>You can also run nvidia-smi to inspect the NVIDIA GPU driver version and current GPU memory usage.</p><pre>nvidia-smi</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*Fu7mhacqX1iokPIMMvTyPQ.png" /><figcaption>Checking GPU status and memory usage</figcaption></figure><p>As you can see, about 3.4 GiB of GPU memory is already in use on my machine.</p><p>For comparision this is how much VRAM is needed for GTA V, when Trevor is running :D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*yq9ES9z1HrilyrD40KGNRQ.png" /></figure><p>So, the difference is only about 2x, and we were experimenting with one of the smallest Qwen models, with only 3B parameters. Some people are trying to run 20B models on their machines :D</p><h4>Shut Down WSL</h4><p>Run the following command from Powershell or Command Prompt to stop all running WSL distributions.</p><pre>wsl --shutdown</pre><h3>Reproduce the Fine-Tuning Experiment</h3><p>Create a directory for the new fine-tuning experiment.</p><pre>mkdir tuning<br>cd tuning</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*xVTXNS8nJ5eL3aZwTtDhkg.png" /><figcaption>Creating a directory for the experiment</figcaption></figure><p>Add “train.py” and “make_dataset.py” from the previous sections to the “tuning” directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*fJKL-qw-YoDLQ2Y5ioCsFA.png" /><figcaption>Both scripts are ready for use</figcaption></figure><p><strong>Generate the Dataset</strong></p><p>Run “make_dataset.py” to generate Czech sentences with positive, negative and neutral sentiment labels. The script creates 460 examples and splits them into two files: train.jsonl with 414 training examples and val.jsonl with 46 validation examples.</p><pre>python make_dataset.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*sGEiTcTXveLhEntpnBk4Zg.png" /><figcaption>Generating the training and validation datasets</figcaption></figure><p>Check the number of training examples with wc -l, then preview the first five lines with the head command. Each line contains a JSON object with a Czech sentence in text and its expected sentiment in label.</p><pre>wc -l train.jsonl<br>head -5 train.jsonl</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*lQb1OAcYb6Z9UGgvN0KZLA.png" /><figcaption>Previewing training sentences and sentiment labels</figcaption></figure><p>After training started, total GPU memory usage increased from 3.4 GiB to 5.4 GiB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zo25LpcP9t8szyokJszVbQ.png" /><figcaption>GPU memory usage after fine=tuning started</figcaption></figure><p>Once the fine-tuning starts, Unsloth displays the training configuration, including the number of epochs, bach size, and trainable parameters. You can also watch the training loss decrease as the model learns from the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*JHzAgh5RASg8X6yYI9RhGg.png" /></figure><p>Trainable parameters = 36,926,536 of 1,580,643,840 (2.34% trainable)</p><p>Only 2.34% of the model’s parameters are trainable. The base model remains frozen, while LoRA adapters are updated during fine-tuning. This significantly reduces the amount of memory needed in comparision with full fine-tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*HhV2Uk_5VNQerH50f4zmjw.png" /></figure><h3>Test the updated model</h3><p>Now that the fine-tuning is complete, we can test the behavior of our updated model.</p><pre>from unsloth import FastLanguageModel<br><br>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name=&quot;qwen-sentiment-lora&quot;,<br>    max_seq_length=256,<br>    load_in_4bit=True,<br>)<br>FastLanguageModel.for_inference(model)<br><br>print(&quot;Enter a Czech sentence.<br> Press Enter on an empty line or Ctrl+C to quit.\n&quot;)<br><br>while True:<br>    try:<br>        sentence = input(&quot;&gt;&gt;&gt; &quot;).strip()<br>    except (EOFError, KeyboardInterrupt):<br>        break<br><br>    if not sentence:<br>        break<br><br>    messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: sentence}]<br>    prompt = tokenizer.apply_chat_template(<br>        messages,<br>        tokenize=False,<br>        add_generation_prompt=True,<br>    )<br><br>    inputs = tokenizer(<br>        prompt,<br>        return_tensors=&quot;pt&quot;,<br>        add_special_tokens=False,<br>    ).to(model.device)<br><br>    output = model.generate(<br>        **inputs,<br>        max_new_tokens=20,<br>        do_sample=False,<br>        use_cache=True,<br>        pad_token_id=tokenizer.eos_token_id,<br>    )<br><br>    answer = tokenizer.decode(<br>        output[0][inputs[&quot;input_ids&quot;].shape[1]:],<br>        skip_special_tokens=True,<br>    ).strip()<br><br>    print(answer, &quot;\n&quot;)</pre><p>You should see something like this, hopefully with a better NVIDIA GPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXsVLsh0KJF66jKQ7k2niQ.png" /></figure><p><strong>Some czech sentences to verify:</strong></p><blockquote>Urči sentiment: Zaplatil jsem za expresní doručení a přišlo to za týden.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*BvOyuRwbfzzI4UaYR9rdyQ.png" /></figure><blockquote><em>Urči sentiment: Zaplatil jsem a oni mi nic nedoručili.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*TW7siFtDuQY0WFuyrsDzTA.png" /></figure><h3>Merge, then quantize — in that order</h3><p>For this deployment, we’ll merge the LoRA adapter into the base model and convert the result to a quantized GGUF file. Unsloth handles both steps in a single call.</p><pre>from unsloth import FastLanguageModel<br><br>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name=&quot;qwen-sentiment-lora&quot;,<br>    max_seq_length=256,<br>    load_in_4bit=False,<br>)<br><br>model.save_pretrained_gguf(<br>    &quot;gguf-out&quot;, tokenizer, quantization_method=&quot;q4_k_m&quot;,<br>)</pre><p><strong>llama.cpp</strong> is the inference engine: C++, no Python, no torch, no mandatory CUDA. PyTorch is excellent for training, but heavy as a runtime. Llama takes a different approach, and that’s the entire reason this model can run on a machine with no graphics card.</p><h3>Quantization is JPEG for neural networks</h3><p>Model weights are numbers. Quantization stores them with less precision to reduce the model’s size and memory usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*j3fsaz9LG9wylLpyHBvhJA.png" /><figcaption>Each connection carries a numerical weight — Illustration generated by Claude Code</figcaption></figure><p>A weight is just a number on a connection. A 16-bit weight can take tens of thousands of distinct values.</p><p>You can convert quantized weights back to higher precision, but you can’t recover the lost detail. Just like a JPEG can’t give you back the original RAW image.</p><h3>Onto Hetzner</h3><p>Now comes the most rewarding part: moving our fine-tuned model to an actual VPS without any GPU, so you can share it with your friends.</p><p>Prepare the server before pushing a gigabyte across the network.</p><pre>ssh root@YOUR_SERVER<br>uname -m     # CAX → aarch64 (ARM), CPX → x86_64<br>free -h<br>df -h /      # need ≥3 GB<br><br>curl -fsSL https://ollama.com/install.sh | sh<br>curl http://localhost:11434     # → Ollama is running</pre><p><strong>Don’t be afraid of the red warning.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*rgcPR8UxoWV76dgd_NGxrw.png" /></figure><p>Now try running the ollama command to verify that the installation works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*3cMk03oV2lWUD29NjJ86mQ.png" /></figure><h4>Export the Fine-Tuned Model</h4><p>This step merges the trained LoRA adapter into the base model and exports it as a Q4_K_M-quantized GGUF file.</p><pre>from unsloth import FastLanguageModel<br><br>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name=&quot;qwen-sentiment-lora&quot;,<br>    max_seq_length=256,<br>    load_in_4bit=False,<br>)<br><br>model.save_pretrained_gguf(<br>    &quot;gguf-out&quot;,<br>    tokenizer,<br>    quantization_method=&quot;q4_k_m&quot;,<br>)<br>print(&quot;done&quot;)</pre><p>Q4_K_M uses mostly 4-bit quantization, with selected tensors stored at higher precision to help preserve the model’s overall quality.</p><p>Create a file called <strong>“export.py” </strong>and run it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*YKEDg0n5SMxGCbKB1cNIlg.png" /></figure><p>As you can see, Unsloth is merging the LoRA adapter into the base model in 16-bit precision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*1CpdY5l1JKz2IzQ2wHY9xg.png" /></figure><p>And what is the LoRA adapter? It’s the part we actually trained, while the original weights remained frozen.</p><p>The export is now complete, and our quantized GGUF model is ready for deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_Zyfme-_FoTlmNuSsk6jQ.png" /></figure><p><strong>Verify the output</strong></p><p>Let’s verify that the GGUF model and Ollama Modelfile were generated successfully.</p><pre>ls -lh gguf-out_gguf/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*nUEuEa8TAwQkypY85MrkQA.png" /><figcaption>Verifying the exported GGUF model and Ollama Modelfile</figcaption></figure><p><strong>Copy the Model to Your VPS</strong></p><p>I hope that your server is ready…</p><pre>scp gguf-out_gguf/*Q4_K_M.gguf gguf-out_gguf/Modelfile root@YOUR_SERVER:/root/</pre><h4>Import the exported model</h4><p>Now that the files are on our VPS, we need to update the path in the Ollama Modelfile, because it still points to the original WSL location.</p><pre>nano Modelfile</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*BOwxNbH9FhYk_eueaYPrcg.png" /><figcaption>Updating the GGUF model path in the Ollama Modelfile</figcaption></figure><p>Now we can import our fine-tuned model into Ollama and test it with a Czech sentence.</p><pre>ollama create sentiment -f Modelfile<br>ollama list<br>ollama run sentiment &quot;Urči sentiment: Zaplatil jsem za expresní doručení a přišlo to za týden.&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*K9zOR-_1MOnxGogbW0mFwg.png" /><figcaption>Successfully importing the fine-tuned model in Ollama</figcaption></figure><h4>Enable Remote Access to Ollama</h4><p>By default, Ollama listens only on localhost. To make the API accessible from outside your VPS, you must configure Ollama to listen on all network interfaces.</p><pre>sudo mkdir -p /etc/systemd/system/ollama.service.d<br>sudo nano /etc/systemd/system/ollama.service.d/override.conf</pre><pre>[Service]<br>Environment=&quot;OLLAMA_HOST=0.0.0.0:11434&quot;</pre><p>Apply changes and verify that Ollama is listening on port 11434.</p><pre>sudo systemctl daemon-reload<br>sudo systemctl restart ollama<br>sudo ss -ltnp | grep 11434</pre><p><strong>Testing Postman payload</strong></p><p>Now let’s test our model remotely using Postman. Send a POST request to</p><p>http://YOUR_SERVER_IP:11434/api/generate with the following JSON payload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*aMVV2XK1VuPLZ_pDhSPAtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*YO4WyOFSEoSbU6GFyIK63A.png" /><figcaption>Testing the fine-tuned model through the Ollama API using Postman</figcaption></figure><p>Our fined-tuned Qwen2.5 1.5B is now running on a low-cost Hetzner VPS without a GPU. In this test, the model classified a Czech sentence as NEGATIVNI, with a total HTTP response time of just 677 miliseconds, measured in Postman.</p><h4>Firewall Configuration</h4><p>Don’t forget to allow incoming TCP connections on port to 11434 in your VPS Firewall. For security, restrict it to your own IP address.</p><h3>Why Use a Model That Only Says Yes Or No?</h3><p>You’d be suprised, but you can use many small, specialized models as filters before sending requests to a larger, more expensive model. Even for experiments, you never know who might try access your Ollama API.</p><h3>Summary</h3><ul><li>Model: Qwen2.5–1.5B-Instruct</li><li>Training: Unsloth QLoRA, r=16, 3 epochs</li><li>RTX 4060 under WSL2. Serving: q4_k_m GGUF via Ollama on a Hetzner CPU instance.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59f939431b98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caddy: Reverse Proxy Without the Pain]]></title>
            <link>https://medium.com/@patrickduch93/caddy-reverse-proxy-without-the-pain-a7d63b656151?source=rss-a17cc89b1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7d63b656151</guid>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[caddy]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Patrik Duch]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 15:04:27 GMT</pubDate>
            <atom:updated>2026-10-14T15:04:27.410Z</atom:updated>
            <content:encoded><![CDATA[<p>Getting started with Caddy doesn’t require a complex setup. Put it in front of your app, point it at the right port, and you have a working reverse proxy in a few lines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQGf4BRpwbplNl_h6xA7tA.png" /><figcaption>Caddy forwarding HTTP requests to Docker — Illustration (<a href="https://openart.ai/home">DALL·E </a>OpenAI)</figcaption></figure><p><strong>Caddy offers several features:</strong></p><ul><li>Automatic HTTPS with certificate management and renewal</li><li>Easy deployment as a Docker container</li><li>A rich plugin ecosystem for extending its functionality</li></ul><p>In this article, we’ll keep things simple and focus on setting up a basic reverse proxy using plain HTTP. No domain or certificates required.</p><h3>Docker compose</h3><p>We’ll run two containers: Caddy as the reverse proxy and a tiny test app behind it. Create a Docker Compose file:</p><pre>services:<br>  caddy:<br>    image: caddy:2-alpine<br>    ports:<br>      - &quot;80:80&quot;<br>    volumes:<br>      - ./Caddyfile:/etc/caddy/Caddyfile:ro<br>      - caddy_data:/data<br>      - caddy_config:/config<br>    depends_on:<br>      - app<br>    restart: unless-stopped<br><br>  app:<br>    image: traefik/whoami<br>    restart: unless-stopped<br><br>volumes:<br>  caddy_data:<br>  caddy_config:</pre><p><strong>Caddyfile</strong></p><p>Now let’s configure Caddy. Create a file named Caddyfile next to your docker-compose.yaml file.</p><pre>{<br> auto_https off<br>}<br><br>:80 {<br> reverse_proxy app:80<br>}</pre><p>Caddy listens on port 80 and forwards incoming requests to our app container.</p><h3>Running it</h3><p>With everything in place, let’s start the containers and see if our reverse proxy works.</p><p><strong>Run the following commands:</strong></p><pre>docker compose up -d<br>curl http://localhost</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*390_Tm2TJgZuHycfxLRa_g.png" /><figcaption>Docker Compose successfully starting both containers.</figcaption></figure><p>You can use docker psto verify that both containers are running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsFI_gFerqzGpPWIvwvE5A.png" /><figcaption>Both containers running, with Caddy exposed on port 80.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7d63b656151" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Exposing Your Database to the Internet]]></title>
            <link>https://medium.com/@patrickduch93/stop-exposing-your-database-to-the-internet-cdb1db98eb34?source=rss-a17cc89b1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdb1db98eb34</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Patrik Duch]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 08:28:46 GMT</pubDate>
            <atom:updated>2026-09-27T08:28:46.752Z</atom:updated>
            <content:encoded><![CDATA[<p>Your database being reachable over the internet isn’t automatically the problem.</p><p>On your own server, keeping the database off the internet costs you nothing: you delete two lines. On Supabase, prepare your wallet. The price jumps from $25 to $599 for the Team plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Lt_AzMouWG4O8drDcTPng.png" /><figcaption>Supabase PrivateLink pricing. Source: Supabase</figcaption></figure><p>If your backend does not run onAWS, PrivateLinkbecomes less attractive. You either keep using public connection or build additional private networking just to reach the AWS VPC.</p><p><a href="https://medium.com/@patrickduch93/supabase-didnt-delete-your-backend-for-free-7ba8eed5e313">Supabase Didn’t Delete Your Backend for Free</a></p><h3>Two lines in docker-compose.yml</h3><p>On your own Hetzner server or another VPS, if you run your database in Docker, keeping it off the public internet takes just two lines in your docker-compose.yml.</p><pre>services:<br>  postgres:<br>    image: postgres:17-alpine<br>    ports:  # Just delete it <br>      - &quot;5432:5432&quot; # Just delete it<br>    networks:<br>      - internal</pre><p>You can simply comment or uncomment these lines when you need the database to be public for a while, for example when checking the database without setting up a tunnel to your own computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*mF_gsPa4dvhKtegi_xKSlw.png" /><figcaption>Postgres ports commented out</figcaption></figure><p>Removing or commenting out the ports block closes the database to everything outside Docker. The backend still connects normally to the database over the shared internalnetwork. Just make sure every service that needs database access is attached to that network, then update your backend connection string to use the Postgres container name instead of the public host.</p><pre>DATABASE_URL=postgresql+asyncpg://user:password@postgres:5432/dbname</pre><h3>Test the internal route before changing the connection string</h3><p>You can verify that the backend reaces the database by service name while the old setup is still running. Run a real query from inside the backend container:</p><pre>docker compose exec backend python -c &quot;<br>import asyncio, asyncpg<br>async def main():<br>    conn = await asyncpg.connect(&#39;postgresql://app:&lt;password&gt;@postgres:5432/postgres&#39;)<br>    print(await conn.fetchval(&#39;SELECT version()&#39;))<br>    await conn.close()<br>asyncio.run(main())<br>&quot;</pre><p>With this configuration, you are better protected even if someone knows your database password. They still cannot access the database unless they are also on your Hetzner server or private network.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdb1db98eb34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The FastAPI Tutorial Never Told You to Add a Linter]]></title>
            <link>https://medium.com/@patrickduch93/the-fastapi-tutorial-never-told-you-to-add-a-linter-dec76ca65a3f?source=rss-a17cc89b1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/dec76ca65a3f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Patrik Duch]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 21:29:54 GMT</pubDate>
            <atom:updated>2026-09-23T21:29:54.794Z</atom:updated>
            <content:encoded><![CDATA[<p>Python has the same problem JavaScript does: it’s dynamic, so the interpreter will happily run nonsense. In a JS/TS codebase nobody thinks twice about ESLint, in Python we most often skip it at least I did.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvzMCYRofhYK4-PUry4Xag.png" /><figcaption>Add a Linter —Illustration (<a href="https://openart.ai/home">DALL·E </a>OpenAI)</figcaption></figure><pre>target-version = &quot;py311&quot;<br>line-length = 120<br><br>[lint]<br># E = pycodestyle errors, F = pyflakes, I = isort, UP = pyupgrade, B = bugbear, SIM = simplify<br>select = [&quot;E&quot;, &quot;F&quot;, &quot;I&quot;, &quot;UP&quot;, &quot;B&quot;]<br>ignore = [<br>  &quot;E501&quot;,   # line too long — handled by formatter<br>  &quot;E402&quot;,   # module-import-not-at-top — FastAPI routes use lazy imports to avoid circular deps<br>  &quot;E712&quot;,   # true-false-comparison — SQLAlchemy column filters require `== True` / `== False`<br>  &quot;B008&quot;,   # function-calls-in-defaults — FastAPI Depends() pattern<br>  &quot;B904&quot;,   # raise-without-from-inside-except<br>  &quot;UP007&quot;,  # non-pep604-annotation<br>  &quot;UP042&quot;,  # replace-str-enum — StrEnum not available in all envs<br>]<br><br>[lint.per-file-ignores]<br>&quot;__init__.py&quot; = [&quot;F401&quot;, &quot;F403&quot;]<br>&quot;alembic/**&quot; = [&quot;E&quot;, &quot;F&quot;, &quot;I&quot;, &quot;UP&quot;]<br>&quot;tests/**&quot; = [&quot;S101&quot;, &quot;F841&quot;, &quot;B007&quot;, &quot;B011&quot;, &quot;E701&quot;, &quot;E702&quot;, &quot;E722&quot;]<br><br>[format]<br>quote-style = &quot;double&quot;<br>indent-style = &quot;space&quot;</pre><h3>Now run Ruff on a real FastAPI project</h3><pre>ruff check.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*PKOelpFJ9g1inEFEtjOK7w.png" /><figcaption>Ruff flags an unused FastAPI import</figcaption></figure><p><strong>Ruff immediately finds something</strong>:</p><p>Depends is imported, but apparently never used. Ruff doesn’t know your intent, so it’s worth reviewing each finding before applying a fix.</p><p><strong>If you’re confident about the linting issues and don’t want to fix them one by one, just run:</strong></p><pre>ruff check . -- fix &amp;&amp; ruff format .</pre><p>This covers <strong>95%</strong> of what you need. It fixes many lint errors automatically, but I still recommend reviewing the changes afterwards.</p><p><strong>This is what you want to see:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*eQVTgZ1WaJkjVLHRtdvWtA.png" /><figcaption>All checks passed!</figcaption></figure><p>When we add ASYNC to select:</p><pre>select = [<br>  &quot;E&quot;,<br>  &quot;F&quot;,<br>  &quot;I&quot;,<br>  &quot;UP&quot;,<br>  &quot;B&quot;,<br>  &quot;ASYNC&quot;,     # blocking calls inside async functions<br>]</pre><p>Ruff can now catch async-specific issues:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*e8txM1MndH4QxuVgGW6LTA.png" /><figcaption>Ruff catches blocking filesystem calls in async</figcaption></figure><p>In this case, Ruff catches a synchronous filesystem call inside an async function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dec76ca65a3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Czech in Vector Space: Why Your Embedding Model Choice Matters]]></title>
            <link>https://medium.com/@patrickduch93/czech-in-vector-space-why-your-embedding-model-choice-matters-8f0fb75ac0c7?source=rss-a17cc89b1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f0fb75ac0c7</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Patrik Duch]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 21:42:56 GMT</pubDate>
            <atom:updated>2026-09-07T21:42:56.208Z</atom:updated>
            <content:encoded><![CDATA[<p>Don’t use an English-only model for Czech. This is the mistake I made, and switching away from it improved my RAG pipeline more than anything else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*RB4B2jrBYbWxoDfY8rJ2Dg.png" /><figcaption>The embedding model decides where Czech words land in vector space —Illustration (<a href="https://openart.ai/home">DALL·E </a>OpenAI)</figcaption></figure><p>I was using sentence-transformers/all-MiniLM-L6-v2 for everything. It is a solid model, small and fast, but it was trained on English. Here is what it does to a Czech query, next to intfloat/multilingual-e5-base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SryG7CiJZtKyjlqbvSNlCQ.png" /><figcaption>MiniLM returned a mountain. The question was about a university.</figcaption></figure><p>The results are sorted by relevance. Same Czech query, 20 sentences. The correct answer came 13th with MiniLM, 1st with E5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*PvZVVtr84BW5RTRx4bdfqA.png" /><figcaption>Each embedding model ranks the same passages differently.</figcaption></figure><p>You don’t need to go straight to a self-hosted, fine-tuned model. Just start with the basics, with your vector space. In the beginning it doesn’t matter whether you run pgvector or Qdrant. What matters is which embedding model produced those vectors inside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*rzoAfgzbkUWpkqn8PdtaRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gleaypk8aQMfU-CUPgyCgw.png" /><figcaption>Three vector stores, one embedding model, identical results.</figcaption></figure><h3>Embedding</h3><p>An embedding is a numerical (vector) representation of information. It can be text, an image, audio, anything. The model places it in a multi-dimensional space so that similar items end up close to each other.</p><p>Every embedding model builds its own vector space. Vectors from two different models cannot be compared, and changing the model means re-embedding everything you have. That is not a config change. It is a full re-index of your corpus, and every stored vector becomes useless the moment you switch.</p><h3>Tokenizer</h3><p>MiniLM is trained mostly on English. Its WordPiece tokenizer has no Czech vocabulary, so it breaks accented Czech words into many meaningless fragments (marked ##). E5 has a multilingual tokenizer and keeps words intact (␣ = word boundary). Fewer fragments means the model recognizes the word instead of guessing from pieces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*d9bYd-iJeFPMt3OVgOMb6A.png" /><figcaption>One question, two tokenizers.</figcaption></figure><p>In the MiniLM output, the accents are gone entirely, not just split off.</p><h3>Geometry first, Clustering second</h3><p>Clustering means that semantically similar items end up close to each other. It is how retrieval finds the right answer.</p><p>The clusters are not something you configure. They are what a good vector space produces on its own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*Yrdb0f-EXnp5r6-BJ329Ng.png" /><figcaption>The same Czech questions in two vector spaces</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f0fb75ac0c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Skip LangSmith, Try Langfuse]]></title>
            <link>https://medium.com/@patrickduch93/skip-langsmith-try-langfuse-9a34510e9a61?source=rss-a17cc89b1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a34510e9a61</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[langfuse]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Patrik Duch]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 11:18:57 GMT</pubDate>
            <atom:updated>2026-09-07T11:26:27.800Z</atom:updated>
            <content:encoded><![CDATA[<p>LangSmith is a third-party SaaS. Self-hosting is only for Enterprise customers. Langfuse runs on your own laptop or private server, with no paid subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDKoKtI5KidGBmT5L_i3JA.png" /><figcaption>Same goal, different tooling — — Illustration (<a href="https://openart.ai/home">DALL·E </a>OpenAI)</figcaption></figure><blockquote>Self-hosted LangSmith is an add-on to the Enterprise plan designed for our largest, most security-conscious customers. For more details, refer to <a href="https://www.langchain.com/pricing">Pricing</a>. <a href="https://www.langchain.com/contact-sales">Contact our sales team</a> if you want to get a license key to trial LangSmith in your environment.</blockquote><p><a href="https://docs.langchain.com/langsmith/self-hosted">Self-hosted LangSmith - Docs by LangChain</a></p><h3>FastAPI + Langfuse</h3><p>If you’re working with LLMs in FastAPI, Langfuse is easy to connect. A few lines of code and every request shows up in your trace log.</p><pre>class ChatService:<br>    def __init__(self, langfuse: LangfuseService):<br>        self._langfuse = langfuse<br><br>    def openai_configured(self) -&gt; bool:<br>        key = settings.openai_api_key<br>        return bool(key) and not key.startswith(&quot;sk-your-&quot;)<br><br>    async def chat(self, body: ChatRequest) -&gt; ChatResponse:<br>        model = body.model or settings.openai_model<br>        with self._langfuse.trace_chat(<br>            name=&quot;chat-request&quot;,<br>            user_id=body.user_id,<br>            session_id=body.session_id,<br>            tags=body.tags,<br>            metadata={&quot;model&quot;: model, &quot;source&quot;: &quot;fastapi&quot;},<br>        ) as trace:<br>            try:<br>                reply = await complete_chat(<br>                    messages=body.messages,<br>                    model=model,<br>                    temperature=body.temperature,<br>                    callbacks=trace.callbacks,<br>                )<br>            except Exception as exc:<br>                self._langfuse.mark_error(exc, model=model, tags=body.tags)<br>                raise ChatError(<br>                    str(exc),<br>                    model=model,<br>                    trace_url=self._langfuse.public_trace_url(),<br>                ) from exc<br><br>            self._langfuse.mark_success(<br>                output={&quot;reply&quot;: reply, &quot;model&quot;: model})<br>            return ChatResponse(<br>                reply=reply,<br>                model=model,<br>                trace_url=self._langfuse.public_trace_url(),<br>            )</pre><p>The full working example, including the Docker Compose stack, is on GitHub: <a href="https://github.com/patrikduch/fastapi-langfuse-example">fastapi-langfuse-example</a></p><p>After executing your first LLM call with the new configuration, it should be visible in your Langfuse dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHBC2TKY6rvzGJ7_j38pxQ.png" /><figcaption>Langfuse running on localhost, tracing LLM requests from FastAPI</figcaption></figure><p>You can also inspect the exact prompt and the model’s response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYcaJuNWZaXwFq7hYL7-qA.png" /><figcaption>Every request logged with its prompt and reply</figcaption></figure><p>Langfuse also captures errors, not just successful calls. The “Observations by Level” chart splits every observation into DEFAULT and ERROR, so a failing endpoint is clearly visible in the dashboard chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lJ5xlufqy2BUFiMTzm9_w.png" /><figcaption>127 observations tracked, 25 of them errors</figcaption></figure><p>After a few more calls, you can see which model was used and how many tokens it consumed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fOM5ZNZz_1HBeC-1vCyKXg.png" /><figcaption>Token usage broken down by model</figcaption></figure><p>After a longer run, the picture gets more interesting: successful calls, failed LLM calls, and validation errors, each grouped separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4yCjxsuxNZGETtnb1tilNg.png" /><figcaption>79 traces split by type, including errors</figcaption></figure><p>If you’re building an AI-driven application and you want to see what your model is actually doing, Langfuse is good enough to start today. If you need SSO, audit logs, or a vendor to call at 3 AM, that is where paid options like LangSmith start to make sense.</p><p><strong>GitHub</strong></p><p><a href="https://github.com/patrikduch/fastapi-langfuse-example">https://github.com/patrikduch/fastapi-langfuse-example</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a34510e9a61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supabase Didn’t Delete Your Backend for Free]]></title>
            <link>https://medium.com/@patrickduch93/supabase-didnt-delete-your-backend-for-free-7ba8eed5e313?source=rss-a17cc89b1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ba8eed5e313</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Patrik Duch]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 13:23:22 GMT</pubDate>
            <atom:updated>2026-08-18T13:28:54.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQDcK5DT-7rf30HqXe5hBA.png" /><figcaption>Still running. Still billing you. Exposed to the public internet — Illustration (<a href="https://openart.ai/home">DALL·E </a>OpenAI)</figcaption></figure><p>Supabase started as a trend and quickly became the default backend for almost every vibe-coded app. Was it worth it?</p><p>The safest way to use Supabase is to turn off the part that makes it Supabase.</p><p>Disabling the Data API reduces the attack surface, but it does not make the database disappear. Your backend still needs a network path to it, and that path becomes another security boundary you have to protect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SD_VG4lz3KjrcTiMPAiLfw.png" /><figcaption>Disabled Supabase Data API</figcaption></figure><h3>Isomorphic SPAs — The All in One package</h3><p>Just because isomorphic SPAs (<strong>Next.js, Nuxt</strong>) can act as a backend doesn’t mean your database connection string belongs there.</p><p>That’s what APIs are for. An API exposes the operations you wrote. A connection string exposes the schema — every table, every column, DROP included. Putting it in the frontend repo doesn&#39;t just risk a leak; it hands your rendering layer more authority over the database than anything else in your stack has.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3VUpz7wt9yJKf4YzeUmDQ.png" /><figcaption>Opus 4.8 on extra mode recommended to put the DATABASE_URL</figcaption></figure><p>This confusion is very common even the newest model of <strong>Claude</strong> wanted for me to put the <strong>DATABASE_CONNECTION_STRING</strong> into <strong>Next.js</strong> <strong>Dockerfile</strong> and I said “Are you insane ? :D”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jpl3oU0PUVcuBWgg8yGp4A.png" /><figcaption>Claude putting DATABASE_URL into Next.js app :D</figcaption></figure><h3>Supabase Data API</h3><p>The Data API is a way to create a Frankenstein backend application — either inside the FE itself, or by calling it from an existing backend (FastAPI or something else). The seal is very angry about that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*WA3PqFaIYA_W5WX1JynR4Q.png" /><figcaption>Seal is angry about that — Illustration (<a href="https://openart.ai/home">DALL·E </a>OpenAI)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*beHfFAX3rHaxOCuOloWtkQ.png" /><figcaption>Untick ‘Enable Data API’ — it comes ticked by default</figcaption></figure><p>With <strong>Supabase’s Data API</strong>, your database schema becomes a public-facing API surface. From there, you can assemble your own Frankenstein application by composing API calls in the frontend, backend, or wherever else seems convenient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fl8LHOWn2JBI6nu5Z0l2Hg.png" /></figure><p>I’ve read enough fantasy to comfortably picture orcs, dragons, and White Walkers. I still can’t picture <strong>IllumateUI</strong> — 100+ endpoints of it — built on the Data API.</p><h3>Why not? One deleted layer</h3><p>This isn’t about taste — it’s about architecture. Supabase’s pitch is “your database is your backend”. That sounds like a feature. It’s actually a decision: the API layer between your clients and your data has been deleted. Deleting a layer doesn’t delete its responsibilities — it just relocates them into SQL policies (RLS). And with the Data API enabled, your schema itself becomes the public interface.</p><p>For years, developers have been taught not to return entities directly from their endpoints — map them to DTOs, control what leaves the system, never couple your public contract to your storage model. The Data API is that rule inverted as a feature: the storage model is the public contract, for every table, by default.</p><p>The confusion becomes even worse with frameworks such as <strong>Next.js</strong>. Because it can execute server-side code, developers increasingly treat the frontend application as the natural place for direct database access.</p><p>An endpoint was never just CRUD with a different name — it can contain publishing to an event store, logging, etc. Delete the layer and that orchestration moves into the frontend — or into a backend that talks to its own database over HTTP — as a sequence of independent API calls.</p><h3>Pricing</h3><p>Supabase pricing at the entry level is genuinely good. The free tier is arguably the best in the business — real Postgres, auth, storage, no credit card.</p><p>The fun starts on the paid plans. Free projects pause themselves when idle; paid ones don’t, so every environment you spun up keeps billing whether anyone uses it.</p><p>At that point you may as well go straight to AWS — which is what Supabase runs on under the hood anyway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*BRfuHy3Q3fKYAQbFW0pdEw.png" /></figure><h3>Network Restrictions aka allowlist</h3><p>It’s in the name. If you have to restrict access to something, that something is exposed. Keeping everything in one place has its benefits. Hetzner, AWS, whatever — just don’t combine them if you don’t have to. You will lose more than you gain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*OZulKk6uGa3iRtVyuvrFsg.png" /><figcaption>Supabase tells you the limit itself</figcaption></figure><p><strong>Note</strong> what the dialog says: restrictions only apply to direct connections and the connection pooler. PostgREST, Storage and Auth are not mentioned there — and the docs confirm why. Those APIs stay on the public internet regardless of what you put in that list, including every call made through supabase-js.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ba8eed5e313" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Alembic Migrations: Keeping SQLAlchemy Models and the Database in Sync]]></title>
            <link>https://medium.com/@patrickduch93/alembic-migrations-keeping-sqlalchemy-models-and-the-database-in-sync-eb3cd9d864d0?source=rss-a17cc89b1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb3cd9d864d0</guid>
            <category><![CDATA[alembic]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[database-migration]]></category>
            <dc:creator><![CDATA[Patrik Duch]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 10:54:22 GMT</pubDate>
            <atom:updated>2026-08-04T10:54:22.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQYiBBwN8HF8tP_upilMAw.png" /><figcaption>Your models, versioned like your code — Illustration (<a href="https://openart.ai/home">DALL·E </a>OpenAI)</figcaption></figure><p>You can write migrations without verifying that yourSQLAlchemymodels and database schema are in sync, but it’s easy to miss changes that never make it into the migration. I’ve made this mistake myself, and with a complex schema, it’s only a matter of time before it catches up with you.</p><h3>Create a new migration</h3><p>Alembic compares your models against the current state of the database and generates a revision file with the difference.</p><pre>alembic revision --autogenerate -m &quot;Description of changes&quot;</pre><p>This never applies anything. It only writes the file — you still have to run alembic upgrade head.</p><p>If you’ve used EFCore, this is the same concept as:</p><p><strong>.NET CLI</strong></p><pre>dotnet ef migrations add Initial</pre><p><strong>Package Manager Console</strong></p><pre>Add-Migration Initial</pre><p>For some time I didn’t know Alembicwas capable of this — generating migrations from the models.</p><h3>Manual Migrations</h3><p>Writing an Alembic revision by hand means placing it correctly in the migration chain. The autogenerate command will fill those IDs for you. So you don’t need to check every time what was the previous migration.</p><pre>&quot;&quot;&quot;Add multi-tenancy tables and columns<br><br>Revision ID: 010<br>Revises: 009<br>Create Date: 2026-07-01 23:42:49.834649<br><br>&quot;&quot;&quot;</pre><p>revision and down_revision are what you need to track and verify. A bad value here causes serious problems.</p><pre># revision identifiers, used by Alembic.<br>revision: str = &#39;010&#39;<br>down_revision: Union[str, Sequence[str], None] = &#39;009&#39;<br>branch_labels: Union[str, Sequence[str], None] = None<br>depends_on: Union[str, Sequence[str], None] = None</pre><p><strong>Note</strong>: I recommend using a numeric prefix in your migration filenames. A directory full of random hex strings tells you nothing. Alembic resolves order from down_revision, not from the filename — the prefix is purely for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*SxTyNchSKEwkO3vy501Omg.png" /><figcaption>Atsmate.app — Alembic migration ordering</figcaption></figure><p>And don’t mix the two — a directory with both a3f8b2c1_add_users.py and 010_add_tenancy.py is worse than either convention on its own.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb3cd9d864d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Frontend Is Not a Backend]]></title>
            <link>https://medium.com/@patrickduch93/your-frontend-is-not-a-backend-ca8a182c6613?source=rss-a17cc89b1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca8a182c6613</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Patrik Duch]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 16:10:13 GMT</pubDate>
            <atom:updated>2026-07-28T16:14:27.101Z</atom:updated>
            <content:encoded><![CDATA[<p>People keep pushing backend responsibilities into the frontend. Some developers/vibers are even querying the database directly from the frontend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m4Un6d7FBu1Od-4AGlpbcw.png" /><figcaption>Frontend != Backend — Illustration (<a href="https://openart.ai/home">DALL·E </a>OpenAI)</figcaption></figure><h3>Blind Frontend</h3><p>The frontend should be blind, not aware. It doesn’t get a DATABASE_URL because it has no business knowing a database exists. It gets an API base URL and a cookie it can&#39;t read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3VUpz7wt9yJKf4YzeUmDQ.png" /><figcaption>Opus 4.8 on extra mode recommended to put the DATABASE_URL</figcaption></figure><p>This confusion is very common. Even one of the newest models of <strong>Claude</strong> generated configuration with the <strong>DATABASE_CONNECTION_STRING</strong> in a <strong>Next.js</strong> <strong>Dockerfile</strong> and I said “Are you insane ? :D”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bneFGFf4OqHs-3UKgcl3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4eKYrQkP5cNzPvs1YVBFA.png" /></figure><pre>try {<br>  await fetch(`${backendUrl}/api/auth/logout`, <br>  {<br>    method: &#39;POST&#39;,<br>    credentials: &#39;include&#39; // 👈 cookie goes there automatically<br>   })<br>} catch (e) {<br>  console.error(&#39;[AuthStore] Logout error:&#39;, e)<br>}</pre><p>I don’t care if the browser gets hacked, because the attacker has nothing to take away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iaYxylfhIyTOpiX9B5pvig.png" /><figcaption>The frontend never touches the token</figcaption></figure><p><em>No </em><strong><em>Bearer token </em></strong><em>should be in your </em><strong><em>codebase </em></strong><em>after </em><strong><em>architectural</em></strong><em> exorcism.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*c3EGO_ehHk0ukkAss5Q-ug.png" /></figure><h3>Bearer Tokens— The Easiest Path</h3><p>People cling to Bearer tokens because they’re lazy, not because they’re secure. It’s “path of least resistance” architecture.</p><p>You’ve probably heard that cookies are more secure than localStorage. That’s only half true — the security doesn’t come from the cookie, it comes from the HttpOnly flag. A regular cookie that is accessible to JavaScript has the same security as saved items in localStorage.</p><p>Sure, localStorage has other problems too — it’s unavailable during SSR, and legacy versions of browsers may not support it at all.</p><p>More on the HttpOnly mechanics here:</p><p><a href="https://medium.com/@patrickduch93/httponly-your-first-line-of-defense-ad2a8e150af2">HttpOnly — Your First Line of Defense</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca8a182c6613" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating FastAPI Secrets from .env to GCP Secret Manager on Cloud Run]]></title>
            <link>https://medium.com/@patrickduch93/migrating-fastapi-secrets-from-env-to-gcp-secret-manager-on-cloud-run-ebf66c93e8dd?source=rss-a17cc89b1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebf66c93e8dd</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gcp-secret-manager]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Patrik Duch]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 00:48:13 GMT</pubDate>
            <atom:updated>2026-07-07T00:48:13.813Z</atom:updated>
            <content:encoded><![CDATA[<p>When you’re moving fast, secrets usually end up in your .env file. Just remember: anybody with access to your application’s Docker image can read them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GajR3SuX6SwhkdMEFHatWw.png" /><figcaption>From .env to Secret Manager — Illustration (<a href="https://openart.ai/home">DALL·E </a>OpenAI)</figcaption></figure><h4>.env Is Acceptable for Non-Secret Values</h4><p>The .env file can still be present, just without any secret values. It can hold constants that pose no danger if they become public knowledge.</p><p><strong>Plenty of configuration is safe to commit and bake it directly into your image</strong>:</p><ul><li>LOG_LEVEL=info</li><li>CORS_ORIGINS=https://illumateui.app</li></ul><blockquote>If leaking a value on a public repo would hurt you, it’s a secret. Otherwise, it’s config.</blockquote><h4>The Local Setup .env.local</h4><p>Before touching the cloud, the local side has to work: developers use .env.local, while the production config remains untouched. Developers shouldn’t tamper with the production config, it’s DevOps territory.</p><p>Common practice is to commit a .env.example <em>file containing only placeholders for the required environment variables.</em></p><pre>class Settings:<br>    &quot;&quot;&quot;Application settings loaded from environment variables.&quot;&quot;&quot;<br>    # PostgreSQL<br>    POSTGRES_URL: str = os.environ[&#39;POSTGRES_URL&#39;]</pre><p>If the env variable isn’t set, it fails loudly during app startup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*XfU3gXubgtgcv6IIWyY97A.png" /><figcaption>Missing secret, instant crash</figcaption></figure><h4>Storing Secrets in GCP Secret Manager</h4><p>The app now fails loudly when POSTGRES_URL is missing. Good. Let’s give it that value without ever putting it in a file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*4szHk_Y0U78bQk4UtPJsfg.png" /><figcaption>Finding Secret Manager in the GCP console</figcaption></figure><p><strong>First, create a secret:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*Yfd6XsQcrsZs_koZGdnfLQ.png" /><figcaption>Creating a secret in GCP Secret Manager</figcaption></figure><p>Notice the naming: the secret is postgres_url (lowercase), while the app reads POSTGRES_URL (uppercase). That’s intentional. Keeping them visually distinct makes it obvious which name belongs to Secret Manager and which to your application. They get wired together when you mount the secret into the Cloud Run service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*FR7uSS6PjfDq3J_sbP6Tzg.png" /><figcaption>Finalizing the secret in GCP Secret Manager</figcaption></figure><p>The rest of the form can remain untouched. Google-managed encryption is fine unless you have a compliance reason for customer-managed keys.</p><p><strong>Mounting into Cloud Run</strong></p><p>Cloud Run injects it, before your process starts exactly like any other env variable.</p><pre>gcloud run deploy illumateui-be \<br>  --set-secrets=&quot;POSTGRES_URL=postgres_url:latest&quot;</pre><p>Read it from right to left: postgres_url comes from GCP Secret Manager, latest is the version (you can pin a specific one, like :3), and the POSTGRES_URL,is the environment variable that your app sees.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebf66c93e8dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>