When to Build a Custom AI Model? RAG vs. Fine-Tuning

Published
Authors
Alen Vecerin
Software Engineer
@
Callstack

"We need our own AI."

This is something you hear a lot these days across the industry. Having your own fine-tuned model sounds like the ultimate advantage, but it's a process that requires a lot of resources (AI engineers, training data, computing power and one of the most valuable resources today: time).

It takes a lot of time to prepare and validate thousands upon thousands of samples that might become obsolete in a few months, meaning that you'll have to spend even more resources down the line to properly maintain your model and keep it relevant.

When a task depends on information from an external source, you can retrieve the relevant material and give it to a pre-trained model at query time. This is retrieval-augmented generation (RAG).

How RAG retrieves current data

RAG is a technique that enhances a model's output by dynamically supplying relevant external data (e.g., PDFs, web pages and databases) directly at query time. Because it works with existing pre-trained models without requiring retraining, it keeps both financial costs and deployment time to a minimum.

RAG is best described using its acronym:

  • R (Retrieval)
    Retrieving external, up-to-date information
  • A (Augmented)
    Augmenting the retrieved information alongside the user's query into a unified prompt
  • G (Generation)
    Generating the answer based on the augmented prompt

An HR chatbot can look up the current vacation policy each time an employee asks about it. The model gets the relevant policy text in its prompt and uses it to answer the question.

As you can see in this example, the model is never modified in any way. It doesn't learn new things. It gets all the necessary context from the combined prompt and provides the answers using the real sources.

If we update the company policy, we don't have to retrain the model to get the newest info. We just need to update the document and our chatbot will immediately serve the latest info to the user.

To showcase this, let's simulate an example chatbot app using the SQLite database and our React Native AI toolkit to tap into Apple's built-in model on iOS devices.

Create an SQLite FTS5 table for the policies. FTS5 lets the example search the policy text with MATCH and sort the results by relevance.

CREATE VIRTUAL TABLE policies USING fts5(title, body);
INSERT INTO policies (title, body)
VALUES ('Vacation', 'Employees get 20 paid vacation days per year');

rowid

title

body

1

Vacation

Employees get 20 paid vacation days per year

Now we need a RAG function for processing user questions. The following function uses a simplified approach to retrieve relevant rows, augment the prompt with that data, and generate a response using the local on-device model:

async function getAnswer(question: string) {
  // 1. RETRIEVAL: Extract search terms and fetch the top matching rows from database
  const terms = question.toLowerCase().match(/\w{4,}/g)?.join(' OR ');
  const policies = await db.getAllAsync<{ title: string; body: string }>(
    'SELECT title, body FROM policies WHERE policies MATCH ? ORDER BY rank LIMIT 3',
    [terms]
  );

  if (!policies.length) return 'No matching policies found.';

  // 2. AUGMENTATION: Format the retrieved rows into a context string
  const context = policies.map((p) => `${p.title}: ${p.body}`).join('\n');

  // 3. GENERATION: Invoke the model with the augmented prompt
  // `generateText` is imported from 'ai' package (https://ai-sdk.dev/)
  const { text } = await generateText({
    // `apple` is imported from 'react-native-ai' package (https://www.react-native-ai.dev/)
    model: apple(),
    instructions: 'You are an HR assistant. Answer only from the policies provided.',
    prompt: `Policies:\n${context}\n\nQuestion: ${question}`,
  });

  return text;
}

Finally, we can simulate a user's question by simply calling the getAnswer function:

await getAnswer('How many vacation days do I get?');
// → "According to the policies, you get 20 paid vacation days per year."

Now let's update the vacation policy directly in the database and ask the same question again:

await db.runAsync('UPDATE policies SET body = ? WHERE title = ?', [
  'Employees get 25 paid vacation days per year.',
  'Vacation'
]);

await getAnswer('How many vacation days do I get?');
// → "According to the policies, you get 25 paid vacation days per year."

In this example, we can see that the model itself never changes. The update is made directly in the database, so the on-device model simply receives the newest data at runtime without any changes to its internal parameters.

While RAG eliminates the stale data problem at a fraction of the upfront cost, it isn't a one-size-fits-all solution.

Pros:

  • Up-to-date data (without model retraining)
  • Scalable and adaptable to growing data needs
  • Reduced hallucinations

Cons:

  • Latency (document search & retrieval before generating the response)
  • Variable answer quality depending on how well the data is structured.
  • Extra infrastructure to build and maintain (retrieval system, connections to data sources)

How fine-tuning adapts a model

When we say that we want to build a custom model, we usually mean fine-tuning a pre-trained model for our needs. We start with a pre-trained model for a simple reason: building one from scratch requires massive financial, engineering and computing resources.

So what exactly is fine-tuning? Fine-tuning is the process of taking a pre-trained model and training it further on a smaller, curated dataset to adapt it to a specific task or domain.

At Callstack, we did this when building Apex, our agentic coding model for mobile and web development, which is based on the Qwen model and fine-tuned to specialize in React and React Native.

There are two main approaches: full fine-tuning and parameter-efficient fine-tuning (PEFT).

Full fine-tuning updates all of the model's parameters, which gives the most flexibility but demands substantial resources and increases the risk of catastrophic forgetting (a well-known phenomenon where a model loses abilities it already had because it was trained on something new).

PEFT keeps the original model frozen and trains only a small number of parameters. This reduces resource requirements and lowers the risk of catastrophic forgetting, but the model can also learn less.

Full fine-tuning

PEFT

Resource cost

Higher

Lower

Training time

Longer

Shorter

Risk of catastrophic forgetting

Higher

Lower

Learning capacity

Higher

Lower

Some of the most widely used PEFT techniques are LoRA (Low-Rank adaptation), QLoRA (Quantized Low-Rank adaptation), Adapter modules, Prompt tuning and Prefix tuning.

Description

When to Use

LoRA

Freezes the base model and trains small low-rank matrices added to specific layers. They can be merged back into the weights.

You want performance close to full fine-tuning with no added inference latency after merging.

QLoRA

LoRA applied on top of a base model quantized to 4-bit, which sharply cuts training memory.

GPU memory is the main limit, especially when fine-tuning very large models on a single GPU.

Adapter Modules

Inserts small trainable bottleneck layers inside each transformer block while the original weights stay frozen.

You want an alternative to LoRA, merging isn’t a priority, or adapters work better empirically for your task.

Prompt Tuning

Learns a small set of continuous “soft prompt” embeddings prepended to the input, with the whole model frozen.

You need the fewest trainable parameters and the smallest storage, or you don’t want to modify the base model.

Prefix Tuning

Learns continuous vectors prepended to the keys and values in every attention layer, with the whole model frozen.

Same as prompt tuning, but when you want more influence on the model than input-level prompts give.

As a rule of thumb, start with PEFT. It is cheaper and usually good enough for adapting style, format or task behavior. Switch to full fine-tuning only when you need a major shift in behavior or knowledge, have a large high-quality dataset and have the resources to support it.

Fine-tuning gives you a model that is specialized and consistent, but that specialization comes at a price, as its pros and cons show.

Pros:

  • Consistent style, tone and output format
  • Strong performance on narrow, specialized tasks
  • Potentially lower end-to-end latency for tasks that can run without retrieval

Cons:

  • Retraining is needed to keep the knowledge fresh
  • Need for a large amount of high-quality, curated training data
  • Upfront costs for training, compute, and engineering time
  • Ongoing hosting and infrastructure maintenance
  • Risk of catastrophic forgetting (loss of general abilities)

Should you build a custom model?

Not by default. For most teams, a pre-trained model combined with RAG gets the job done faster and at a lower cost. A custom model makes sense only when the problem is about how the model behaves, not what it knows.

A simple way to remember it: RAG gives the model knowledge. Fine-tuning gives the model behavior.

Choose RAG when:

  • your answers depend on information that changes often (such as policies, documentation or product data)
  • you need answers that can be traced back to a source
  • you want to ship quickly with a small team and budget
  • your answers depend on private sources, and retrieval can enforce which documents each user may access

If sensitive data must stay within your environment, run both retrieval and inference there. The SQLite example runs both on the device.

Choose a custom model when:

  • A base model still misses a specific requirement after you’ve tried clear instructions, examples, and relevant context.
  • You can show that fine-tuning improves performance on representative cases held out from training.
  • You have the high-quality data, engineering time and budget to build and maintain it.

When retrieval and fine-tuning work together

A customer contacts an online store about a partial refund.

Customer: I got $20 back for the charger. Can you check the refund for the headphones?

Assistant: I see headphone returns on two orders. Which one should I check?

Customer: The blue pair from the older order. Actually, if the refund is still pending, can I switch to an exchange?

Retrieval supplies the facts. The store has received the blue headphones, the refund is still pending, and the current policy says mailed returns can’t be converted to exchanges once they’ve been received. With that information, the assistant can answer:

We’ve received the blue headphones from your older order, and the refund is still pending. Once we’ve received a mailed return, it continues as a refund. If you’d like a replacement, you can place a new order.

Fine-tuning is worth testing if the assistant repeatedly mishandles conversations like this. It might answer for the wrong order or keep explaining the refund status after the customer has switched to asking about an exchange. Training on reviewed support conversations can give the model examples of when to clarify, how to carry the answer forward, and how to handle a change in the customer’s request.

Compare the base and fine-tuned versions on conversations held out from training, using the same instructions and retrieved records. Check whether each version picks the right order, answers the customer’s latest question, and gives a next step supported by the policy. If the base model already does this reliably, retrieval and prompting are enough.

What to try first

The main takeaway is to always start with the simplest setup and add complexity only when needed. Start with a base model and test it on representative requests. Add retrieval when the task depends on external information.

If a specific behavior still falls short after you improve the prompt and supply the relevant context, test whether fine-tuning improves it enough to justify training and maintenance. Even then, PEFT is usually enough to adapt a general model, so full fine-tuning is rarely necessary.

When you need both fresh knowledge and consistent behavior, combine the two, keeping in mind that you will be maintaining a retrieval stack (RAG) and a training pipeline (fine-tuning), which adds significant complexity.

Insights

Learn more about AI

How an AI-SDLC Audit Helps You Decide What to Automate First

Nov 26Article

How an AI-SDLC Audit Helps You Decide What to Automate First

An AI-SDLC audit will help your team decide where automation is worth the investment before you commit to a build. Follow a deployment lookup that starts with a testing ticket, from a specific problem statement to an agent design and a proposed pilot. See what the three audit deliverables give your team and how to evaluate the workflow afterward.

Building a Software Factory: AI Reviewers That Don’t Share the Writer’s Blind Spots

Nov 19Article

Building a Software Factory: AI Reviewers That Don’t Share the Writer’s Blind Spots

A reviewer produced 155 confirmed findings and five rounds of work. Szymon Chmal explains how that experience shaped Simlock’s review process, from specialist agents and verified findings to targeted rechecks and historical replays.

Nov 12Live Stream

Mobile Development, Plugins & AI-Powered Workflows

Join Kewin Wereszczyński and Hanno Gödecke on November 12 for live demos and a discussion of the Mobile Dev plugin and AI-powered mobile workflows.

Building the React Native Software Factory — cover

Nov 11Talk

Building the React Native Software Factory

Join us at React Foundation Meetup London on November 11 to explore how AI agents build and debug React Native apps, from one terminal to the cloud.

Build, Launch, and Maintain: The Business Case for a Software Factory

Nov 10Article

Build, Launch, and Maintain: The Business Case for a Software Factory

Explore an anonymized software factory business case, its delivery workflow, and the staffing assumptions behind a projected 65% reduction in total costs.

Harness Engineering: Context, Skills, and Reliable AI Workflows

Nov 10Podcast

From Prompts to Harnesses: Building Reliable AI Workflows

Amazon’s Anisha Malde joins Łukasz Chludziński to discuss harness engineering, agent skills, and how AI is changing cross-platform development.

Building a Software Factory: Write Specs an Agent Can Build From — cover

Nov 6Article

Building a Software Factory: Write Specs an Agent Can Build From

Learn how to research requirements, resolve open decisions, and write testable specs that AI coding agents can implement without the planning conversation.

 Large-Scale Migrations With Coding Agents: Planning, Verification, and Rollback — cover

Nov 4Article

Large-Scale Migrations With Coding Agents: Planning, Verification, and Rollback

Plan codebase migrations with coding agents using reviewable requirements, verification checks, staged rollouts, and defined rollback criteria.

Conversational Banking: From Customer Questions to Authorized Actions — cover

Nov 2Article

Conversational Banking: From Customer Questions to Authorized Actions

Explore conversational banking architecture through a card-dispute example, covering tool access, authorization, execution, observability, and human handoff.

cover

Oct 15Live Stream

Who Left the Agents Running? React Native Software Factories

Join Kewin Wereszczyński and Szymon Chmal to explore what can go wrong in a React Native software factory overnight and the controls that keep agents on track.

cover

Oct 14Podcast

When Coding Gets Faster, What Breaks Next?

Matt Hargett explains how AI moves bottlenecks across testing, deployment, infrastructure, support, and the rest of software delivery.

cover

Oct 12Podcast

AI Coding Agents and Hermes With Tzvetan Mikov

Tzvetan Mikov discusses AI coding agents, context switching, low-level engine optimization, reviewing specs and tests, and his plans for Hermes X.

cover

Mar 19Tutorial

The Hard Way vs. The React Native AI SDK Way: Stop Writing Custom Modules for Every Model

Learn how React Native AI uses a unified provider model to switch between cloud and on-device LLMs without rewriting application logic, enabling reliable AI experiences online and offline.

cover

Mar 12Tutorial

Build Smarter Apps: Tool Calling & AI Orchestration Explained

Learn how on-device models in React Native can call tools, interact with external APIs, and return structured outputs you can use directly in application logic.

cover

Mar 5Tutorial

MLC LLM + React Native: On-Device AI Without the Pain

Learn how to run third-party on-device LLMs in React Native using MLC LLM. Choose your models, run them efficiently across platforms, and keep a unified JavaScript API with React Native AI.

cover

Feb 24Tutorial

Intelligent Fallbacks with Apple Intelligence in React Native

Learn how to use Apple’s built-in Foundation Models in React Native apps, reduce memory usage, and enable fast, fully on-device AI with React Native AI Apple.

cover

Feb 10Tutorial

What Is the React Native AI SDK? A Complete Intro & Quickstart

Learn why on-device AI matters for React Native apps, how local LLMs behave offline, and what problems React Native AI is designed to solve from day one.

cover

Jan 29Tutorial

Implementing an Android TurboModule with Kotlin

Learn how to implement a React Native TurboModule on Android, from the TypeScript spec and Codegen to the Kotlin implementation and package registration.

cover

Jan 19Tutorial

Working with Different Threads in Swift TurboModules

Learn how JavaScript, native module, background, and main threads interact in React Native TurboModules, and how to use GCD queues to run async work safely in Swift.

cover

Jan 9Tutorial

How to Add Type-Safe Constants to Swift TurboModules

Learn how to expose typed, immutable constants from a Swift TurboModule using Codegen, and get full end-to-end type safety between native and JavaScript.

cover

Dec 30Tutorial

Adding Event Emitters to Your TurboModule in Swift

Learn how to emit native events from a Swift TurboModule and subscribe to them in JavaScript, including proper memory management and Codegen integration.

Writing a Swift TurboModule in React Native

Dec 22Tutorial

Writing Your First TurboModule in Swift

Learn how to build a fully working TurboModule in Swift, integrate it with Codegen, and bridge it through Objective‑C inside an Expo app.