ai newsDo., 15. Okt.
EilmeldungMeta and Apple team up to make Muse AI models run better on Macs

Llama 3 mit Unsloth in Python auf eigenes Tool-Calling fine-tunen

Llama 3 ist ein starker Generalist, was aber zum Problem wird, wenn ein Agent zuverlaessig strukturiertes JSON fuer eine konkrete API ausgeben muss. Ein Tutorial zeigt das Fine-tuning mit Unsloth in Python.

Machine Learning MasteryFreitag 13:00 · 09.10.DE6 Min. Lesezeit
Bild: Machine Learning Mastery

Beitrag teilen In diesem Artikel erfahren Sie, wie Sie Llama 3 8B mit Unsloth und QLoRA für benutzerdefiniertes Tool Calling fine-tunen, damit das Modell zuverlässig strukturierte JSON-Payloads für ein bestimmtes API-Schema ausgibt.

Wie man Llama 3 in Python mit Unsloth für benutzerdefiniertes Tool Calling fine-tuned, Bild vom Autor

Llama 3 ist ein fähiger Generalist, aber genau das ist das Problem, wenn man einen Agenten benötigt, der zuverlässig strukturiertes JSON für eine bestimmte API ausgibt. Prompt Engineering kann ein Modell zwar in Richtung eines Formats lenken, aber es kann es nicht garantieren, und eine einzige fehlerhafte Antwort bringt eine gesamte agentenbasierte Pipeline zum Scheitern.

Fine-tuning verändert das Verhalten des Modells auf Gewichtsebene. Wie im Artikel „The Machine Learning Practitioner’s Guide to Fine-Tuning Language Models“ beschrieben, lohnt sich Fine-tuning, wenn man tiefe Spezialisierung benötigt: ein individueller Ton, strikte Formatierung der Ausgaben oder völlig neue Fähigkeiten. Tool Calling erfüllt alle drei Kriterien.

In diesem Tutorial werden Sie Unsloth und QLoRA verwenden, um Llama 3 8B für benutzerdefiniertes Tool Calling zu fine-tunen: die Fähigkeit, eine Nutzeranfrage zu interpretieren und eine perfekt formatierte JSON-Payload zurückzugeben, die Ihrem API-Schema entspricht. Der gesamte Workflow läuft auf einer kostenlosen Google Colab T4 GPU.

Bevor Sie Code schreiben, lohnt es sich zu verstehen, warum Prompt Engineering allein beim Tool Calling nicht ausreicht. Wenn Sie ein Basismodell bitten, {"name": "get_weather", "arguments": {"location": "Tokyo"}} zurückzugeben, wird es das im Test oft befolgen, aber unter dem Druck komplexer Anfragen oder langer Gespräche weicht es ab. Es fügt Prosatext hinzu, wechselt den Anführungszeichenstil oder lässt Pflichtfelder weg.

Fine-tuning löst dieses Problem, weil Sie dem Modell ein neues Verhaltensmuster beibringen, nicht nur ein neues Wissen. Der Unterschied ist wichtig: Retrieval-Augmented Generation (RAG) funktioniert, wenn man externe Fakten benötigt; Fine-tuning funktioniert, wenn man konsistentes Verhalten benötigt. Strikte JSON-Ausgabe für ein benutzerdefiniertes API-Schema ist ein Verhaltensproblem.

QLoRA macht das praktikabel. Indem Sie die Gewichte des Basismodells einfrieren und kleine trainierbare Matrizen in die Attention-Schichten einfügen, aktualisieren Sie nur etwa 1% der Parameter, während der Speicherbedarf niedrig genug für eine kostenlose Colab T4 bleibt. Wie im Artikel „How to Fine-Tune a Local Mistral or Llama 3 Model on Your Own Dataset“ ausführlich beschrieben, erzielt dieser Ansatz Ergebnisse, die mit vollständigem Fine-tuning vergleichbar sind, und das zu einem Bruchteil der Rechenkosten.

Da das „Warum“ geklärt ist, richten wir nun die Werkzeuge ein. Öffnen Sie ein neues Google Colab Notebook, wechseln Sie die Laufzeit auf eine T4 GPU (Runtime → Change runtime type → T4 GPU) und führen Sie dann den Installationsblock aus.

Sobald die Installation abgeschlossen ist, bestätigen Sie, dass Ihre Umgebung bereit ist:

Sie sollten Ihre T4 GPU bestätigt sehen. Unsloth übernimmt die CUDA-Konfiguration automatisch, daher ist vor dem Laden des Modells keine weitere Einrichtung erforderlich.

Nun laden Sie Llama 3 8B mit dem vorkuantisierten Modell von Unsloth. Diese Version ist bereits im 4-Bit-Format gespeichert, was bedeutet, dass kein eingeschränktes Hugging Face Token benötigt wird und der Download etwa viermal schneller ist als das Laden der ursprünglichen Gewichte.

Nachdem das Basismodell und der Tokenizer geladen sind, fügen Sie die LoRA-Adapter hinzu. Hier wird der QLoRA-Ansatz konkret: Statt alle Gewichte des Modells zu aktualisieren, fügen Sie kleine, trainierbare Matrizen in bestimmte Schichten ein. Der Parameter r (Rank) steuert, wie viele Parameter Sie trainieren, und niedrigere Werte verringern das Überanpassungsrisiko bei kleinen Datensätzen. Beachten Sie, dass Unsloth lora_dropout=0 benötigt, um seine optimierten Trainingskerne aktiv zu halten; ein Wert ungleich Null erzwingt einen Rückgriff auf langsamere Codepfade.

Ein Rank von 8 funktioniert gut für eine fokussierte Verhaltensaufgabe wie Tool Calling. Höhere Ranks geben dem Modell mehr Ausdruckskraft, erhöhen aber das Risiko von Überanpassung bei kleinen Datensätzen. Setzen Sie lora_alpha auf den doppelten Wert von r als verlässlichen Ausgangspunkt.

An diesem Punkt ist das Modell geladen, quantisiert und mit LoRA-Adaptern versehen, weiß aber noch nichts über Ihre Tools. Das ist der Punkt, an dem der Datensatz ins Spiel kommt.

Dies ist der folgenreichste Schritt im Workflow. Modell und LoRA-Konfiguration liefern die Maschinerie, aber der Datensatz bringt dem Modell bei, was es damit machen soll. Die richtige Datenstruktur entscheidet darüber, ob Ihr fine-getuntes Modell sauberes JSON erzeugt oder halluzinierte Halbantworten.

Tool-Calling-Daten haben drei erforderliche Komponenten in jedem Beispiel: einen Systemprompt, der die verfügbaren Tools und ihre JSON-Schemas definiert, eine Nutzeranfrage in natürlicher Sprache und die exakte JSON-Ausgabe, die das Modell erzeugen muss.

Der folgende Code erstellt einen kleinen Beispieldatensatz, der zwei Tools demonstriert: get_weather und fetch_stock_price. Das Modell wird zuerst geladen, weil der Tokenizer benötigt wird, um im nächsten Schritt Llama 3s Chat-Template korrekt anzuwenden.

In der Produktion bräuchten Sie mehrere hundert Beispiele, die Randfälle abdecken: mehrdeutige Anfragen, Tools mit mehreren Argumenten und Anfragen, die einem Tool ähneln, aber zu einem anderen gehören. Die Qualität ist weit wichtiger als die Menge; 200 gut konstruierte Beispiele schlagen konstant 2000 verrauschte.

Als Nächstes formatieren Sie jedes Beispiel mit tokenizer.apply_chat_template(). Diese Methode behandelt Llama 3s spezielles Token-Layout präzise und hält den Code portabel, falls Sie später auf eine neuere Modellvariante wechseln.

Jeder formatierte String bringt dem Modell bei, ein Tool-Schema und eine natürlichsprachliche Anfrage einer präzisen JSON-Antwort zuzuordnen. Beachten Sie, wie die dreiteilige Struktur (Systemkontext, Nutzerabsicht, Assistentenantwort) direkt auf das Verhaltensmuster abgebildet wird, das das Modell lernen soll: bei diesen Tools und dieser Frage genau dieses JSON erzeugen.

Mit dem vorbereiteten und formatierten Datensatz konfigurieren Sie den TRL SFTTrainer. Die folgenden Einstellungen sind auf eine Colab T4 mit einem kleinen Datensatz abgestimmt. max_steps hält die Trainingszeit für Demonstrationszwecke unter 10 Minuten; bei einem größeren Datensatz wechseln Sie stattdessen zu epochenbasiertem Training.

Beobachten Sie den Trainingsverlust während des Laufs. Ein gleichmäßiger Rückgang Richtung 0,1 bis 0,3 ist gesund. Wenn der Loss bei einem winzigen Datensatz schnell gegen null geht, memorisiert das Modell möglicherweise, statt zu generalisieren; fügen Sie vor dem Deployment weitere abwechslungsreiche Beispiele hinzu.

Sobald das Training abgeschlossen ist, schalten Sie das Modell in den Inferenzmodus und testen es mit einer Anfrage, die es im Training nicht gesehen hat. Die Verwendung von apply_chat_template mit add_generation_prompt=True hängt den Assistenten-Header automatisch an, und das Dekodieren nur der neu generierten Tokens liefert eine saubere Antwort ohne erneutes Parsen.

Ein erfolgreiches Fine-tuning erzeugt eine Ausgabe wie {"name": "fetch_stock_price", "arguments": {"ticker": "TSLA"}}: sauberes JSON ohne umgebenden Prosatext. Vergleichen Sie das mit dem Basismodell, das das JSON oft in gesprächige Fülltexte wie „Sure! Here’s the tool call:“ einbettet, selbst bei identischem Systemprompt. Genau diese Art von Abweichung bringt nachgelagertes Parsing zum Scheitern. Wenn das Modell nach dem Fine-tuning weiterhin Gesprächstext hinzufügt, enthält der Trainingsdatensatz wahrscheinlich inkonsistente Formatierungen, oder der Datensatz benötigt mehr Beispiele, die die Vorgabe „kein anderer Text“ im Systemprompt verstärken.

Speichern Sie abschließend die LoRA-Adapter für die spätere Verwendung:

Der gespeicherte Adapter-Ordner ist nur wenige Megabyte groß. Sie können ihn jederzeit auf dem eingefrorenen Llama 3 Basismodell neu laden, ohne das Training erneut durchzuführen.

Sie haben Llama 3 8B zu einem benutzerdefinierten Tool-Calling-Agenten fine-getunt, der strukturierte JSON-Ausgaben für bestimmte API-Schemas erzeugt, auf einer kostenlosen GPU in weniger als 10 Minuten Trainingszeit. Die komplette Pipeline umfasste die Einrichtung von QLoRA, um das Training effizient zu halten, die Strukturierung eines Datensatzes, der dem Modell ein konsistentes Verhaltensmuster beibringt, und die Validierung der sauberen JSON-Ausgabe bei unbekannten Anfragen.

Die wichtigsten Entscheidungen, die diesen Workflow geprägt haben, sind die Datenstruktur (Systemprompt, Nutzeranfrage, JSON-Ziel), der LoRA-Rank (niedrig halten bei kleinen Datensätzen) und die Überwachung des Trainingsverlusts, um Überanpassung früh zu erkennen. Dies sind auch die ersten Stellschrauben, wenn Sie diesen Ansatz an Ihren eigenen Anwendungsfall anpassen.

Von hier aus wird ein größerer und vielfältigerer Datensatz mit Dutzenden Tools und mehrdeutigen Anfragen die Generalisierung verbessern. Sobald Sie einen zuverlässigen Tool Caller haben, verwandelt die Integration in ein agentenbasiertes Framework wie LangChain oder LlamaIndex ihn in einen funktionierenden Agenten, der Anfragen auf Grundlage seiner strukturierten Ausgabe an echte APIs weiterleiten kann.

Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.

Original (Englisch) anzeigen

Share Post Share In this article, you will learn how to fine-tune Llama 3 8B for custom tool calling using Unsloth and QLoRA, so that the model reliably outputs structured JSON payloads for a specific API schema.

How to Fine-Tune Llama 3 for Custom Tool Calling with Unsloth in Python Image by Author

Llama 3 is a capable generalist, but that’s exactly the problem when you need an agent that reliably outputs structured JSON for a specific API. Prompt engineering can nudge a model toward a format, but it can’t guarantee it, and a single malformed response breaks an entire agentic pipeline.

Fine-tuning changes the model’s behavior at the weight level. As covered in The Machine Learning Practitioner’s Guide to Fine-Tuning Language Models, fine-tuning earns its cost when you need deep specialization: a custom tone, strict output formatting, or entirely new capabilities. Tool calling checks all three boxes.

In this tutorial, you’ll use Unsloth and QLoRA to fine-tune Llama 3 8B for custom tool calling: the ability to interpret a user query and return a perfectly formatted JSON payload matching your API schema. The entire workflow runs on a free Google Colab T4 GPU.

Before writing any code, it’s worth understanding why prompt engineering alone falls short for tool calling. When you ask a base model to return {"name": "get_weather", "arguments": {"location": "Tokyo"}}, it will often comply in testing, but under pressure from complex queries or long conversations, it drifts. It adds prose, swaps quote styles, or omits required fields.

Fine-tuning addresses this because you’re teaching the model a new behavioral pattern, not just a new piece of knowledge. The distinction matters: retrieval-augmented generation (RAG) works when you need external facts; fine-tuning works when you need consistent behavior. Strict JSON output for a custom API schema is a behavior problem.

QLoRA makes this practical. By freezing the base model’s weights and injecting small trainable matrices into the attention layers, you update roughly 1% of parameters while keeping memory low enough for a free Colab T4. As detailed in How to Fine-Tune a Local Mistral or Llama 3 Model on Your Own Dataset, this approach achieves results comparable to full fine-tuning at a fraction of the compute cost.

With the “why” covered, let’s set up the tools. Open a new Google Colab notebook, switch the runtime to a T4 GPU (Runtime → Change runtime type → T4 GPU), then run the installation block.

Once installation finishes, confirm your environment is ready:

You should see your T4 GPU confirmed. Unsloth handles CUDA configuration automatically, so no additional setup is required before loading the model.

Now load Llama 3 8B using Unsloth’s pre-quantized model. This version is already stored in 4-bit format, which means no gated Hugging Face token is required and the download is roughly four times faster than pulling the original weights.

With the base model and tokenizer loaded, attach the LoRA adapters. This is where the QLoRA approach becomes concrete: instead of updating all the model’s weights, you’re injecting small, trainable matrices into specific layers. The r parameter (rank) controls how many parameters you train, and lower values reduce overfitting risk when working with small datasets. Note that Unsloth requires lora_dropout=0 to keep its optimized training kernels active; setting a non-zero value forces a fallback to slower code paths.

A rank of 8 works well for a focused behavioral task like tool calling. Higher ranks give the model more expressive capacity but increase the risk of overfitting on small datasets. Set lora_alpha to twice r as a reliable starting point.

At this point, the model is loaded, quantized, and wired with LoRA adapters, but it still doesn’t know anything about your tools. That’s where the dataset comes in.

This is the most consequential step in the workflow. The model and LoRA configuration give you the machinery, but the dataset teaches the model what to do with it. Getting the data structure right here determines whether your fine-tuned model produces clean JSON or hallucinated half-answers.

Tool-calling data has three required components in each example: a system prompt that defines the available tools and their JSON schemas, a user query in natural language, and the exact JSON output the model must produce.

The code below builds a small sample dataset demonstrating two tools: get_weather and fetch_stock_price. The model loads first because the tokenizer is needed to apply Llama 3’s chat template correctly in the next step.

In production, you’d need several hundred examples covering edge cases: ambiguous queries, multi-argument tools, and queries that resemble one tool but belong to another. Quality matters far more than volume; 200 well-constructed examples consistently outperform 2,000 noisy ones.

Next, format each example using tokenizer.apply_chat_template(). This method handles Llama 3’s special token layout precisely and keeps the code portable if you switch to a newer model variant later.

Each formatted string trains the model to associate a tool schema and a natural language query with a precise JSON response. Notice how the three-part structure (system context, user intent, assistant output) maps directly onto the behavioral pattern you want the model to learn: given these tools and this question, produce exactly this JSON.

With the dataset prepared and formatted, configure the TRL SFTTrainer. The settings below are calibrated for a Colab T4 with a small dataset. max_steps keeps training time under 10 minutes for demonstration purposes; with a larger dataset, switch to epoch-based training instead.

Watch the training loss as it runs. A steady decrease toward 0.1–0.3 is healthy. If loss approaches zero quickly on a tiny dataset, the model may be memorizing rather than generalizing; add more varied examples before deploying.

Once training finishes, switch the model to inference mode and test it with a query it hasn’t seen in training. Using apply_chat_template with add_generation_prompt=True appends the assistant header automatically, and decoding only the newly generated tokens gives a clean response without any re-parsing.

A successful fine-tune produces output like {"name": "fetch_stock_price", "arguments": {"ticker": "TSLA"}}: clean JSON with no surrounding prose. Compare this to the base model, which often wraps the JSON in conversational filler like “Sure! Here’s the tool call:” even with the same system prompt. That’s exactly the kind of drift that breaks downstream parsing. If the model still adds conversational text after fine-tuning, the training data likely contains inconsistent formatting, or the dataset needs more examples reinforcing the “no other text” constraint in the system prompt.

Finally, save the LoRA adapters for later use:

The saved adapter folder is only a few megabytes. You can reload it at any time on top of the frozen Llama 3 base without re-running training.

You’ve fine-tuned Llama 3 8B into a custom tool-calling agent that produces structured JSON output for specific API schemas, on a free GPU in under 10 minutes of training. The full pipeline covered setting up QLoRA to keep training efficient, structuring a dataset that teaches the model a consistent behavioral pattern, and validating clean JSON output on unseen queries.

The key decisions that shaped this workflow are dataset structure (system prompt, user query, JSON target), LoRA rank (keep it low for small datasets), and training loss monitoring to catch overfitting early. These are also the first levers to adjust when adapting this approach to your own use case.

From here, a larger and more diverse dataset covering dozens of tools and ambiguous queries will improve generalization. Once you have a reliable tool caller, integrating it into an agentic framework like LangChain or LlamaIndex turns it into a functioning agent that can route queries to real APIs based on its structured output.

Originaltitel: How to Fine-Tune Llama 3 for Custom Tool Calling with Unsloth in PythonQuelle: Machine Learning Mastery (Machine Learning Mastery). Original öffnen