Skip to content
,

LM Studio RAG: How to Chat with PDFs and Documents Locally (2026)

10–14 minutes
Woman in a brick-walled loft holding a tablet with an LM STUDIO RAG card, hook chat with your PDFs

LM Studio can answer questions about your own PDFs, Word files and text documents, fully offline. Drop a file into the chat and ask. But results vary a lot: sometimes it quotes the exact page, and sometimes it insists the document doesn’t mention something that’s clearly there.

The difference comes down to how LM Studio decides between reading the whole document and retrieving pieces of it (RAG). This guide explains how that works, step by step, using LM Studio’s docs and the source of its built-in rag-v1 plugin.

It also covers which models work best, the two retrieval settings you can tune and when to switch to a bigger RAG setup. At the end there’s a short Python script for chatting with a whole folder of files through LM Studio’s API.

TL;DR

  • Attach files (.pdf, .docx, .txt) with the paperclip or by dragging them into the chat. Everything stays on your PC.
  • Short document? LM Studio puts the whole text into the context. Long document? It switches to RAG and only sends the most relevant chunks.
  • RAG defaults in the rag-v1 plugin: 3 chunks per question, similarity threshold 0.5, embeddings by nomic-embed-text-v1.5.
  • Best fix for poor answers: raise the model’s context length so the whole file fits, or use the words you expect to find in the document in your question.
  • Many files or a whole folder? Use AnythingLLM or Open WebUI with LM Studio as the backend, or the Python script below.

New to LM Studio? Start with my LM Studio guide for installing it and downloading a model.

How to Chat with Documents in LM Studio

  1. Load a chat model in the Chat tab (for example, a Qwen3, Gemma or Llama model that fits your GPU).
  2. Attach the file. Click the paperclip in the message box, or drag the file into the chat. LM Studio’s docs list .docx, .pdf and .txt. Markdown and other plain-text files also work.
  3. Ask your question in the same message, for example “Summarise the termination clause in this contract” or “What does section 4.2 say about refunds?”
  4. Check the answer against the file, especially numbers, dates and names. Ask the model to quote the sentence it used.

The model never “uploads” anything. Parsing, embedding and the answer all happen on your computer. That makes LM Studio a good fit for contracts, medical letters, company documents and anything else you wouldn’t paste into an online chatbot.

Full Document vs RAG: What Actually Happens

LM Studio’s own docs explain the two modes clearly:

  • Full document in context: “If the document is short enough (i.e., if it fits in the model’s context), LM Studio will add the file contents to the conversation in full.”
  • RAG: “If the document is very long, LM Studio will opt into using Retrieval Augmented Generation… RAG means attempting to fish out relevant bits of a very long document (or several documents) and providing them to the model for reference.”

So the deciding factor is the model’s context length, not the file size on disk. A 40-page PDF might fit in a model loaded with 32K context, and fail to fit at 4K.

Full document RAG (retrieval)
What the model sees The whole text A few chunks that look relevant to your question
Good for Summaries, “find all…”, comparing sections Looking up specific facts in long files
Weak at Very long files (slow, uses lots of memory) Summaries, questions that need the whole document
Speed Slower first answer (big prompt) Fast

This explains the classic complaint: “I asked for a summary and it only talked about page 3.” In RAG mode the model only saw three chunks, so it can’t summarise the rest.

Under the hood, document handling comes from a plugin. LM Studio’s developer docs describe lmstudio/rag-v1 as “the plugin that gives document handling capabilities to LM Studio”.

It runs as a prompt preprocessor: when you press Send, it adds the document text or retrieved chunks to your message before the model sees it.

The docs also note that the modified message “will be saved in the chat history”, so later questions in the same chat keep that context.

The rag-v1 Plugin Settings

The plugin’s configuration (from its source code) has two settings that matter:

Setting Default Range What it does
Retrieval Limit 3 1-10 “The maximum number of chunks to return”
Retrieval Affinity Threshold 0.5 0.0-1.0 “The minimum similarity score for a chunk to be considered relevant”

How to tune them:

  • Answers miss information that’s in the file: raise Retrieval Limit to 5-8 so more chunks reach the model. Make sure your context length has room for them.
  • “The document doesn’t mention X” when it does: lower the Affinity Threshold to 0.3-0.4. In the code, any chunk scoring at or below the threshold is thrown away. A strict threshold can leave the model with nothing.
  • Answers pull in unrelated text: raise the threshold a little, to 0.55-0.6.

You’ll find plugin settings in the chat’s right-hand sidebar, under the plugin or integrations section, when a file is attached. The exact layout changes between LM Studio versions.

The embedding model is set in the plugin’s code: nomic-ai/nomic-embed-text-v1.5-GGUF. It’s small and fast, and works well for English. For other languages you may get better retrieval with a multilingual setup, such as the folder script below with a multilingual embedding model.

Best Models for Document Chat

Document Q&A needs two things from a model: a long context window and good instruction following, so it sticks to the text instead of making things up.

  • Pick a model with at least 32K context, and load it with a high context length. Many models default to 4K-8K in LM Studio, which forces RAG on almost any PDF.
  • 7-9B instruct models (Qwen3 8B, Llama 3.1 8B and similar) are the sweet spot on 8-12 GB GPUs.
  • 14B and larger follow “answer only from the document” instructions noticeably better, if you have the VRAM.
  • Vision models can read scanned pages and images as images, but they don’t fix text extraction for scanned PDFs (see limits below).

Longer context needs more memory for the KV cache. If the model slows down or falls back to the CPU after you raise context, see LM Studio not using GPU. Lower the context or use a smaller quant until it fits.

10 Ways to Get Better Answers

  1. Raise the context length when you load the model so the whole document fits. That avoids RAG entirely for most files.
  2. Use the document’s own words. LM Studio’s tip: “Mention terms, ideas, and words you expect to be in the relevant source material.” Ask “What is the notice period in the termination clause?” rather than “When can I quit?”
  3. Ask one question at a time. Retrieval finds chunks for the whole message, so three questions at once get three half-answers.
  4. Point to sections: “In section 7…” or “In the table on fees…” helps both retrieval and the model.
  5. Add a system prompt such as: “Answer only from the attached document. If the answer isn’t in it, say so. Quote the sentence you used.” This cuts down on invented answers.
  6. Summarise in parts. For a long report, ask for a summary of each chapter, then a summary of those summaries.
  7. Clean the file. Convert messy PDFs to text or Markdown first. Headers, footers and two-column layouts confuse chunking.
  8. Tune the plugin: more chunks and a lower threshold when answers miss things.
  9. Start a new chat per document. Earlier attachments stay in the history and can mix into answers.
  10. Ask for quotes. If the quoted text is wrong or missing, retrieval picked the wrong chunks, and the answer will be wrong too. Rephrase the question rather than arguing with the model.

Limits to Know

  • Scanned PDFs: if a PDF is just images of pages, there’s no text to extract. Run it through OCR first. A local document parser like Docling turns scans into clean Markdown.
  • Tables and charts often lose their structure in extraction. Ask about them carefully, or paste the table as text.
  • A handful of files, not a library. In-chat attachments are meant for a few documents per conversation. For hundreds of files, use a proper RAG app (below).
  • No live sync. If you edit the file, attach it again.
  • Retrieval isn’t search. RAG finds text that is similar in meaning to your question. It can miss exact numbers or codes. For those, use a keyword search in the PDF itself.

Chat with a Whole Folder (Python)

LM Studio’s local server speaks the OpenAI API, including an /v1/embeddings endpoint. That means you can build a simple “chat with my folder” tool in about 40 lines. You need:

  • LM Studio’s server running (Developer tab → Start server, or lms server start). See my LM Studio API guide and lms CLI guide.
  • An embedding model: lms get nomic-ai/nomic-embed-text-v1.5 (the example the LM Studio docs use).
  • A chat model loaded, plus pip install openai numpy.
from pathlib import Path
import numpy as np
from openai import OpenAI

client = OpenAI(base_url="http://localhost:1234/v1", api_key="lm-studio")
EMBED = "text-embedding-nomic-embed-text-v1.5"   # check the name with: lms ls
CHAT = "qwen3-8b"                                 # your loaded chat model

def chunks(text, size=1200, overlap=200):
    for i in range(0, len(text), size - overlap):
        yield text[i:i + size]

docs = []
for f in Path("my_docs").glob("**/*.txt"):
    for c in chunks(f.read_text(errors="ignore")):
        docs.append((f.name, c))

def embed(texts):
    r = client.embeddings.create(model=EMBED, input=texts)
    return np.array([d.embedding for d in r.data])

vecs = embed([c for _, c in docs])
vecs /= np.linalg.norm(vecs, axis=1, keepdims=True)

def ask(q, k=5):
    qv = embed([q])[0]
    qv /= np.linalg.norm(qv)
    top = np.argsort(vecs @ qv)[::-1][:k]
    context = "\n\n".join(f"[{docs[i][0]}] {docs[i][1]}" for i in top)
    msg = [
        {"role": "system", "content": "Answer only from the context. Cite the file name. Say if it is not in the context."},
        {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {q}"},
    ]
    return client.chat.completions.create(model=CHAT, messages=msg).choices[0].message.content

print(ask("What is the refund policy?"))

Notes:

  • The script reads .txt files. Convert PDFs and Word files to text first (for example with Docling or pdftotext).
  • Use lms ls to find the exact embedding and chat model names on your machine.
  • For big folders, save vecs to disk with np.save so you don’t re-embed every time.
  • The same idea works with Ollama. See Ollama embeddings.

When to Use AnythingLLM or Open WebUI

LM Studio’s built-in document chat is great for “ask about this one file”. Move to a dedicated RAG app when you need:

  • Persistent knowledge bases: upload once, chat for weeks.
  • Hundreds of files or whole folders, with re-indexing.
  • Better parsing and choice of embedding model, chunk size and reranking.
  • Multiple users or access from other devices.

AnythingLLM and Open WebUI can both use LM Studio’s server as the model backend, so you keep your downloaded models. My chat with PDFs locally guide compares the setups. LM Studio can also call tools through MCP, including file and search servers. See LM Studio MCP and agent mode.

Troubleshooting

Problem Likely cause Fix
“The document doesn’t mention…” (it does) RAG retrieved the wrong chunks or none passed the threshold Use the document’s wording, lower the threshold, raise the retrieval limit, or raise context so the full text fits
Summary covers only one part RAG mode, only 3 chunks seen Raise context length, or summarise section by section
Empty or gibberish answers about a PDF Scanned PDF with no text layer OCR it first (Docling, OCRmyPDF)
Very slow after attaching a file Whole document injected into a big context Normal for long files; use a smaller model or GPU offload. See GPU fixes
Model invents facts Weak instruction following Add the “answer only from the document” system prompt; try a larger model
Can’t attach the file Unsupported format or old LM Studio Convert to PDF, DOCX or TXT; update LM Studio
Model won’t load with a long context Not enough memory for the KV cache Lower context or quant; see LM Studio not loading models

FAQ

Does LM Studio support RAG?

Yes. Attach a document to a chat, and LM Studio either adds the full text (if it fits the context) or uses retrieval to send the most relevant chunks. It’s handled by the built-in rag-v1 plugin.

What file types can LM Studio read?

LM Studio’s docs list PDF, DOCX and TXT. Other plain-text files usually work too. Scanned PDFs need OCR first.

Is chatting with documents in LM Studio private?

Yes. Parsing, embedding and generation all run locally. Your files aren’t sent to any server.

Which embedding model does LM Studio use for documents?

The rag-v1 plugin uses nomic-embed-text-v1.5 (GGUF).

Why does LM Studio say my document doesn’t contain something it does?

In RAG mode, only a few chunks reach the model. Use the document’s own wording, ask one thing at a time, raise the retrieval limit or load the model with more context.

How do I chat with a whole folder in LM Studio?

The chat window is built for a few files. For folders, use AnythingLLM or Open WebUI with LM Studio as the backend, or a small script that uses LM Studio’s embeddings API, like the one above.

What context length do I need?

Roughly 1,000 tokens per 750 words. A 20-page document needs about 12-16K tokens to fit in full, so 32K is a comfortable setting if your GPU allows it.

Sources

  • LM Studio docs (GitHub): Chat with Documents, prompt preprocessors (rag-v1), embeddings, Python SDK
  • rag-v1 plugin source (config.ts and promptPreprocessor.ts, via a public fork on the LM Studio Hub): retrieval limit, affinity threshold, embedding model
Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a brick-walled loft holding a tablet with an LM STUDIO RAG card, hook chat with your PDFs