Skip to content

Knowledge Retrieval (RAG)

Arno Hartholt edited this page Sep 1, 2026 · 1 revision

Purpose

Give a character reference documents to answer from.

By default an LLM-driven character answers from the model's general knowledge, which is frozen at the model's training cutoff and knows nothing about your project, organization or study materials. Knowledge retrieval - retrieval-augmented generation, RAG - supplies documents you provide: on each user turn the most relevant passages are retrieved and attached to the language-model request, so the character answers from your material rather than from its training data.

Organization

Retrieval is defined by the IKnowledgeSystem interface, implemented by KnowledgeSystemUnity. Add that component to any GameObject in the scene to activate retrieval; it is included in the cognition systems prefab. Remove it and requests pass through untouched, as they also do when the component is present but has no documents.

Component Role
IKnowledgeSystem / KnowledgeSystemUnity The retrieval system. Holds the settings and the index
KnowledgeIndex Chunks the corpus into passages and scores them against a query
KnowledgeSourceResources Loads documents shipped in the build from a Resources folder
KnowledgeAugmentation Attaches retrieved passages to each outgoing language-model request
IEmbeddingsSystem Optional. Supplies vectors for semantic and hybrid retrieval

Semantic retrieval is optional and pluggable: four IEmbeddingsSystem implementations ship, and adding one upgrades retrieval without any change to the application.

Approach

Documents are split into passages of roughly 600 characters, packed from whole paragraphs so a passage is never cut mid-sentence. Each user turn produces a query, the index scores every passage against it, and the highest-scoring passages are attached to the language-model request.

Three retrieval modes:

  • Lexical - term-overlap scoring (tf-idf). Always available: no network, no cost, every platform. Its blind spot is paraphrase - "how much does it cost" will not find a passage that only says "priced at".
  • Semantic - embedding-similarity scoring. The question and every passage are mapped to vectors that capture meaning, so paraphrased questions find the right material. Requires an embeddings system.
  • Hybrid - fuses both rankings, with semantic dominant and lexical as an exact-term tiebreak.

The default mode, Auto, serves lexical results until embeddings are ready and then upgrades to hybrid. It falls back to lexical whenever the embeddings service is unavailable: degradation is automatic and is never reported as an error.

Retrieval is tuned for dialogue rather than for a search box. Follow-ups such as "like which ones?" inherit the topic of the previous turn; acknowledgements such as "sure" or "ok" retrieve on the previous turn rather than on the filler word, because that is what the reply will expand on; and short questions such as "who is X?" are always treated as real queries.

Retrieved passages are introduced to the model by a framing preamble (contextPreamble). It instructs the model to treat the material as information rather than as instructions, so document content cannot act as an injected command, and never to mention the material to the user.

Cloud

  • EmbeddingsSystemOpenAI - uses the OpenAI key from your VHToolkit configuration, the same key as the ChatGPT language system. The corpus is embedded once per session, and each user turn adds one small embeddings call.

Local

Nothing leaves the machine with any of these.

  • EmbeddingsSystemOllama - requires Ollama running locally with an embedding model (ollama pull nomic-embed-text).
  • EmbeddingsSystemVLLM - for deployments already serving models with vLLM. vLLM serves one model per process, so embeddings need their own instance (the component defaults to port 8001) alongside any vLLM instance used for language generation.
  • EmbeddingsSystemOpenAICompatible - any service implementing the OpenAI embeddings API, given its endpoint URL and an optional key. Use this for a self-hosted or institutional service that is neither Ollama nor vLLM; the two components above are conveniences over the same API.

Ollama and vLLM can be run from their respective folder in \Services, with load-with-rag.bat. This requires Docker. Windows requires WSL.

Add at most one embeddings component. Having none is a supported configuration rather than a broken one: retrieval stays lexical, permanently and silently. Add one when paraphrased questions start missing material a reader would say is clearly present.

Usage

Unity Project

Two ways to supply documents.

Ship them in the build. Put plain-text files (.txt, .md) in a Resources/VHKnowledge folder in your Unity project. KnowledgeSourceResources, included in the cognition systems prefab, loads them at startup. No code, and no network dependency at runtime - this suits standalone and app-store builds.

Supply them at runtime. Call IKnowledgeSystem.SetItems() with KnowledgeItem entries of id, title and text. This suits applications that receive their documents from a configuration or a server.

Retrieval then happens automatically. No application code changes.

Settings on the KnowledgeSystemUnity component:

Setting Effect
retrievalMode Auto / Lexical / Semantic / Hybrid. Leave on Auto
topK Passages attached per turn. Default 3
maxContextChars Total budget for attached passages. Default 2000
contextQueryWeight How much the previous turn steers retrieval, so follow-ups resolve to the topic under discussion
logRetrievals One console line per turn: query, mode, retrieved titles and scores. Turn this on first whenever an answer surprises you
contextPreamble The framing text that precedes retrieved passages

Writing documents that retrieve well:

  • Plain prose with paragraph breaks. Passages are packed from whole paragraphs.
  • State key facts explicitly, including names and URLs. The character can only cite what a passage actually says.
  • Date your material inside the text ("as of July 2026") so the character can qualify answers honestly.
  • One fact per question demos best with small local models; large cloud models synthesize across several passages more reliably.

Cloud Services

Cloud embeddings need only an API key and internet access, and work on every platform including WebGL.

Local Services

A local embeddings service must be reachable from the device running the character, which is not always the machine running the service:

  • On desktop, the defaults assume the service is on the same machine and need no configuration.
  • On a headset or phone, localhost means that device, not your workstation. Point the component at the workstation's LAN address, put both on the same network, and bind the service to all interfaces rather than to loopback.

If the service is unreachable, retrieval stays lexical and the conversation continues.

Limitations

  • Corpus size. Up to a few MB of text is fine. The index is built in memory when documents are set.
  • SetItems builds the index synchronously. Subsecond on a desktop, several times slower on mobile hardware. Set the corpus during loading rather than mid-session; in VR a frame hitch is a comfort problem rather than a cosmetic one.
  • Lexical retrieval cannot match paraphrase. Without an embeddings system, a question that shares no terms with the passage will not find it.
  • Retrieval is per turn, not a search over the whole corpus. The character sees the highest-scoring passages within maxContextChars, not the entire document set, so a question that needs facts scattered across many passages may be answered only in part.
  • Passages are attached, not verified. The character can misread or over-generalise from a passage. logRetrievals shows what was actually supplied, which is the first thing to check when an answer looks wrong.

Known Issues

  • A filler-only turn can produce an out-of-place reply. Because an acknowledgement such as "go ahead" retrieves on the previous turn, the model receives reference material on a turn where the user said almost nothing, and may respond as though the user had supplied that material - for example by thanking them for it. The framing preamble instructs the model not to mention the material, and larger models comply more consistently than small local ones.

Clone this wiki locally