Build a Local Personal Knowledge Base from Scratch: LLM and Note Integration in Practice

    This article presents a practical, tool-agnostic workflow for building a local personal knowledge base that lets a large language model answer questions from your own notes and cite the source files. It covers note organization, index construction, keyword retrieval, link-based context expansion, prompt assembly, safe use of command-line AI coding assistants, and evaluation methods. Readers can use the described architecture and code examples to connect plain-text notes with an LLM while keeping the content portable and under local control.

    1. Background and Goals

    Large language models are good at understanding and generating text, but they know nothing about your personal materials. If you ask a model a question directly, the answer is often generic. A personal knowledge base solves this by letting the model answer based on the notes, reading summaries, project records, and meeting minutes you have accumulated, and by showing which file each answer comes from.

    This type of solution usually has three goals:

    1. Readable: The model can access local files without manual copy-paste.
    2. Searchable: When there are many notes, the system can quickly find the small set of files relevant to a question.
    3. Connected: When an answer needs to combine multiple notes, the system can follow links between notes to complete the context.

    The approach used in this article is: save notes as plain text, have a program build an index, retrieve relevant files for a question, and then assemble the file contents into a prompt for the model. The whole workflow does not depend on a specific application. Any tool or script that supports local file reading can replace one of the components.

    2. Overall Architecture

    The knowledge base can be divided into three layers:

    Layer Responsibility Common implementation
    Storage layer Store note source text and ensure the format remains readable long term Plain text or Markdown files organized by directory
    Retrieval layer Find relevant files based on a question Keyword matching, inverted index, vector retrieval
    Reasoning layer Generate an answer based on retrieval results General LLM API, or a command-line AI coding assistant

    The choice of storage layer determines how portable the rest of the system will be. Plain-text files are not tied to any application. Even if you change tools later, the content remains intact. The retrieval layer can start with simple keyword counting. When the note collection grows to thousands of files or more, you can introduce vector retrieval or hybrid retrieval. The reasoning layer understands the question and organizes the language. It does not replace retrieval, so retrieval quality directly affects answer quality.

    3. Step 1: Organize Note Directories

    The directory structure should be stable and predictable. A common approach is to divide the first level by topic and the second level by time or project, while keeping filenames descriptive.

    1. knowledge-base/
    2. ├── 00-inbox/ # Temporary notes, classified regularly
    3. ├── 10-reading-notes/
    4. │ ├── distributed-systems.md
    5. │ └── designing-data-intensive-applications.md
    6. ├── 20-project-records/
    7. │ ├── order-service-refactor.md
    8. │ └── 2026-Q4-retrospective.md
    9. ├── 30-technical-plans/
    10. │ └── cache-consistency-strategies.md
    11. └── 90-archive/

    Filenames help both retrieval and manual browsing. Avoid meaningless names such as “new file (3)”. At the beginning of each note, you can add brief metadata such as tags, creation date, and summary. The retrieval program can read these fields directly to improve hit rates.

    1. ---
    2. tags: [cache, consistency]
    3. created: 2026-10-08
    4. summary: Compares the trade-offs of three cache update strategies under high concurrency
    5. ---
    6. The body starts here...

    4. Step 2: Build an Index

    The goal of the index is to avoid traversing and reading every file each time a question is asked. The following script does three things: scan the directory, read the text, and extract the bidirectional link syntax between notes (in the form [[filename]]).

    1. import re
    2. from pathlib import Path
    3. LINK_PATTERN = re.compile(r"\[\[([^\]|#]+)")
    4. def build_index(vault_dir: str) -> dict:
    5. """Scan all Markdown files under a directory and return an index keyed by filename."""
    6. index = {}
    7. for path in Path(vault_dir).rglob("*.md"):
    8. text = path.read_text(encoding="utf-8", errors="ignore")
    9. links = [link.strip() for link in LINK_PATTERN.findall(text)]
    10. index[path.stem] = {
    11. "path": str(path),
    12. "text": text,
    13. "links": links,
    14. }
    15. return index

    Two details are worth noting. First, errors="ignore" can skip individual files with encoding problems, but a safer approach is to log the skipped files so they can be fixed later. Second, using the filename as the key requires filenames to be unique across the entire knowledge base. If duplicate filenames exist, use the relative path as the key instead.

    The index should be rebuilt after notes change. At a small scale, a full rebuild on each startup is sufficient. At a larger scale, you can record the modification time of each file and rebuild only the entries that have changed.

    Keyword search is the easiest retrieval method to implement. It scores files by occurrence count and returns the highest-scoring files. This method works well for proper nouns, names, and code identifiers, but it has weak coverage for synonymous expressions. For example, “cache avalanche” and “a large number of cache entries expiring at the same time” describe the same problem, but keyword search may not match both.

    1. def search(index: dict, keyword: str, top_k: int = 5) -> list[str]:
    2. """Sort files by keyword occurrence count and return filenames."""
    3. keyword = keyword.lower()
    4. hits = []
    5. for name, doc in index.items():
    6. score = doc["text"].lower().count(keyword)
    7. if score > 0:
    8. hits.append((score, name))
    9. hits.sort(key=lambda item: item[0], reverse=True)
    10. return [name for _, name in hits[:top_k]]

    In practice, you can split the user’s question into several keywords, retrieve results for each, and merge them. When merging, weighting by the number of distinct matched keywords reflects relevance better than simply adding occurrence counts. If the question involves multiple concepts, this adjustment can significantly reduce noise from files that match only a single concept.

    For many questions, the answer is spread across multiple notes. For example, the answer to “why is the order service’s cache strategy designed this way” may be located in a project record, a technical plan, and a reading summary at the same time. Bidirectional links record explicit relationships between notes and can be used to complete the context.

    1. def expand_with_links(index: dict, names: list[str], depth: int = 1) -> list[str]:
    2. """Expand outward along note links; depth controls expansion layers."""
    3. result = list(dict.fromkeys(names))
    4. frontier = list(names)
    5. for _ in range(depth):
    6. next_frontier = []
    7. for name in frontier:
    8. for link in index.get(name, {}).get("links", []):
    9. if link in index and link not in result:
    10. result.append(link)
    11. next_frontier.append(link)
    12. frontier = next_frontier
    13. return result

    The expansion depth should not be too large. Each additional layer can multiply the number of candidate files, which increases model processing cost and may introduce content unrelated to the question. Usually, one layer of expansion covers most scenarios. Two or more layers require filtering with a relevance threshold.

    7. Step 5: Assemble the Prompt and Generate an Answer

    The model’s context window is limited. Even if the window is large, only content relevant to the question should be included. When assembling the prompt, control the total length and explicitly require the model to answer based on the materials and cite sources, reducing fabrication.

    1. def build_prompt(index: dict, question: str, names: list[str], max_chars: int = 6000) -> str:
    2. """Concatenate retrieved notes into a prompt; stop adding when length limit is exceeded."""
    3. parts, used = [], 0
    4. for name in names:
    5. chunk = f"## File: {name}\n{index[name]['text']}\n"
    6. if used + len(chunk) > max_chars:
    7. break
    8. parts.append(chunk)
    9. used += len(chunk)
    10. context = "\n".join(parts)
    11. return (
    12. "Answer the question using only the note content below. "
    13. "If the material is insufficient to answer, state that clearly. "
    14. "In your answer, cite the filenames you used.\n\n"
    15. f"{context}\nQuestion: {question}"
    16. )

    Send the generated prompt to the API of the chosen model to get an answer. The call method depends on the provider, but the flow is the same: read the key, send the request, and parse the returned text. Keys should be stored in environment variables or a secrets management service, not written into scripts or committed to version control.

    1. import os
    2. API_KEY = os.environ.get("LLM_API_KEY") # Read from environment variable; do not hard-code in source
    3. if not API_KEY:
    4. raise RuntimeError("LLM_API_KEY environment variable not found")

    8. Let an AI Coding Assistant Operate Files Directly

    A command-line AI coding assistant can run directly in the knowledge base directory, read files, search text, and create or modify notes. It removes the need to write retrieval scripts by hand and is suitable for one-off cleanup tasks such as adding summaries in batches, standardizing tag formats, and finding duplicate content.

    When using these tools, pay attention to permission boundaries:

    1. Limit the working directory: Only expose the knowledge base directory, and do not grant read/write access to the entire user home directory.
    2. Separate read and write operations: Query tasks can run freely. Deletion, overwriting, and batch renaming should require human confirmation.
    3. Keep version history: Commit the current state with a version control system before operations so you can roll back if something goes wrong.
    4. Check outbound content: If the model service is deployed externally, avoid sending entire notes that contain private or business secrets. Desensitize the content or send only summaries first.

    9. Evaluation and Common Issues

    After the knowledge base is built, evaluate it with a fixed set of questions. For each question, record the file where the expected answer should be located, then check whether retrieval hits the file, whether the answer is accurate, and whether citations are correct. This evaluation method is more reliable than subjective impressions and makes it easier to compare different retrieval strategies.

    Common issues and handling approaches:

    • Irrelevant answers: Retrieval usually did not hit the correct file. Check whether keyword splitting is reasonable, or add tags and summaries to relevant notes.
    • Fabricated content: The constraints in the prompt are not clear enough, or retrieval returned nothing but the model was still forced to answer. When retrieval is empty, return “No relevant notes found” directly and do not call the model.
    • Answers that are too long or miss key information: The context exceeds the length limit and is truncated. Adjust the ranking rules, put the most relevant files first, or shorten the excerpt range for each note.
    • Incomplete cross-file conclusions: Link relationships are missing. Add bidirectional links in notes and appropriately increase the expansion depth.

    10. Conclusion

    A personal knowledge base comes down to three things: notes are stored in a stable plain-text format, retrieval can quickly find relevant content, and the model answers based on materials and cites sources. Keyword indexing plus bidirectional link expansion is sufficient for most personal scenarios. As the scale grows, consider vector retrieval and finer chunking strategies. Tools can be replaced, but the structure and workflow remain unchanged. Keep recording notes and regularly evaluate the system with fixed questions; the knowledge base will become more useful as it accumulates.