Building a Personal Knowledge Base with Large Language Models and AI Coding Tools
This guide explains how to build a personal knowledge base that combines a large language model API, an AI coding tool, and local Markdown note-taking software. The system reads local notes, retrieves the passages relevant to a question, and generates an answer from them. It covers architecture and technology choices, file parsing, keyword and vector retrieval, cross-file question answering, and a sample Python script.
Digital office work is now common, and developers and business users accumulate large amounts of technical documents, study notes, and project materials every day. Traditional local note tools can organize content with bidirectional links and folder trees. However, when a question spans multiple files, they usually cannot perform semantic search or produce a comprehensive answer. Large language models offer a new approach to this problem.
Many people ask: How do I build a personal knowledge base? How do I implement semantic search over local Markdown files? What should I watch out for in cross-document question answering? This article addresses these questions and introduces a solution that combines a large language model API, an AI coding tool, and local note-taking software. The goal is to let the AI read local notes, find relevant content, and answer questions based on that content.
1. Architecture and Technology Selection
A usable personal knowledge base needs to do three things: let a program read local files, find the passages related to a question among many files, and pass those passages to a model to generate an answer. The overall design has three layers.
1. Data storage layer: local note-taking tools
Choose note-taking software that supports local Markdown files as its storage format. Markdown is plain text, easy to parse, and not tied to any specific software, which makes it well suited as a data source for AI processing. Obsidian and Logseq both store Markdown in local folders and provide directory and bidirectional link features. If you only need a plain folder, you can manage the files with any text editor.
2. Capability layer: cloud or local large models
The large model understands questions and generates answers. Cloud models are accessed through APIs. They are simple to deploy and usually produce high-quality answers, but each call incurs a fee, and the content must be sent to the provider. Local models do not send data off the device, but they require adequate graphics card and memory resources, and their answer quality may be weaker. Some providers have lowered the unit prices of their high-performance models. Prices change over time, so refer to the provider’s current official pricing page.
3. Execution and integration layer: AI coding tools
AI coding tools can run commands in a local terminal, read files, and generate scripts from natural language instructions. With these tools, the assistant can handle repetitive work such as traversing directories, extracting text, and assembling prompts. Generated code must still be reviewed line by line, especially the parts that delete files, make network requests, or read keys.
The table below compares the common options:
| Dimension | Cloud LLM | Local LLM |
|---|---|---|
| Data privacy | Relevant passages are sent to the provider during queries | Data stays on the local machine |
| Cost per call | Billed by usage | Mainly hardware and electricity |
| Deployment complexity | Obtain an API key and call the service | Requires installing a runtime environment and downloading a model |
| Answer quality | Usually higher | Depends on local hardware and model size |
If your notes contain customer data, account information, or unpublished internal material, consider a local model first, or filter that content out before sending anything.
2. Core Implementation
1. File reading and parsing
The program needs to traverse the knowledge base directory, read .md files, and skip version control directories, note-tool cache directories, and trash directories. Handle encoding errors when reading. If a file cannot be read, log the problem and continue so the whole task does not stop. If a note has YAML front matter, extract its title and tags as supporting information for retrieval.
2. Retrieval and indexing
When there are few notes, you can place all the content directly in the prompt. As the number of notes grows, this raises costs and can exceed the model’s context window. A more practical approach is to retrieve first, then send only the relevant passages to the model.
There are two common retrieval methods. Keyword retrieval is simple to implement and needs no extra model, but it cannot recognize synonymous expressions. Vector retrieval first converts text into vectors with an embedding model, then computes similarity. It usually works better but requires an additional model and index storage. When implementing vector retrieval, keep these points in mind:
- Chunk size: about 500 to 800 characters per chunk, with 50 to 100 characters of overlap between adjacent chunks so that a sentence is not cut in half.
- Embedding model: choose an embedding model that supports Chinese. It can run locally after installation.
- Top-K: retrieve the 5 or so passages with the highest similarity as the model’s context.
- Similarity threshold: discard passages below the threshold. If no passage reaches the threshold, tell the user that the knowledge base has no relevant content instead of forcing an answer.
- Fallback: when retrieval fails or the index is missing, show a clear message and let the user switch to keyword retrieval.
3. Cross-file linking and question answering
The prompt is the key to cross-file question answering. Label each passage with its source file, and instruct the model to answer only from the provided content. If the passages contain no relevant information, the model should say so rather than make something up. End each answer with a list of the cited file names so users can check the original text.
3. Setup Steps and Code Example
1. Environment setup
Install Python 3.10 or later, then run the following command to install the dependencies:
pip install requests python-dotenv
Create a .env file in the project root and add the following settings. Confirm the endpoint URL and model name in your provider’s documentation. Providers generally offer an OpenAI-compatible Chat Completions interface, and their documentation lists the version number and available model names.
LLM_API_URL=https://api.your-llm-provider.com/v1/chat/completionsLLM_API_KEY=your-api-keyLLM_MODEL=your-chosen-model-nameKNOWLEDGE_DIR=./my_knowledge_base
Security notes:
- Store API keys only in environment variables or the
.envfile. Do not hardcode them, commit them to a code repository, or share them with others. - Add
.envto.gitignoreto prevent accidental commits. KNOWLEDGE_DIRshould point only to a directory you have permission to access. Do not scan other people’s folders or system directories.- During queries, retrieved passages are sent to the cloud provider. Exclude notes that contain passwords, national ID numbers, or customer information from the knowledge base.
2. Writing the Q&A script
The script below includes file filtering, chunking, keyword-based scoring retrieval, source labeling, timeout control, and retries. Keyword scoring is for demonstration only. It cannot recognize synonyms, so replace it with vector retrieval in practice.
```python
import os
import time
from pathlib import Path
import requests
from dotenv import load_dotenv
load_dotenv()
API_URL = os.getenv(“LLM_API_URL”)
API_KEY = os.getenv(“LLM_API_KEY”)
MODEL_NAME = os.getenv(“LLM_MODEL”)
KNOWLEDGE_DIR = Path(os.getenv(“KNOWLEDGE_DIR”, “./my_knowledge_base”))
EXCLUDED_DIRS = {“.git”, “.obsidian”, “.trash”, “node_modules”}
CHUNK_SIZE = 600
TOP_K = 5
MAX_RETRIES = 3
TIMEOUT_SECONDS = 60
def iter_markdown_files(root: Path):
“””Traverse the knowledge base directory and skip files in cache and system directories.”””
for path in root.rglob(“*.md”):
if any(part in EXCLUDED_DIRS for part in path.parts):
continue
yield path
def split_into_chunks(text: str, size: int = CHUNK_SIZE):
“””Split long text into fixed-size character chunks and drop chunks that contain only whitespace.”””
chunks = []
for start in range(0, len(text), size):
piece = text[start:start + size]
if piece.strip():
chunks.append(piece)
return chunks
def load_chunks(root: Path):
“””Read all notes and split them into chunks that carry source information.”””
chunks = []
for path in iter_markdown_files(root):
try:
text = path.read_text(encoding=”utf-8”)
except (UnicodeDecodeError, OSError) as exc:
print(f”Skipping unreadable file {path}: {exc}”)
continue
for index, piece in enumerate(split_into_chunks(text)):
chunks.append({
“source”: str(path.relative_to(root)),
“part”: index,
“text”: piece,
})
return chunks
def score_chunk(question: str, text: str) -> int:
“””Score a chunk by counting how often its character bigrams appear in the text.”””
bigrams = {question[i:i + 2] for i in range(len(question) - 1)}
bigrams = {b for b in bigrams if b.strip()}
return sum(text.count(b) for b in bigrams)
def retrieve(question: str, chunks: list, topk: int = TOP_K):
“””Return the highest-scoring chunks. Chunks with a score of zero are excluded.”””
scored = [(score_chunk(question, c[“text”]), c) for c in chunks]
scored = [item for item in scored if item[0] > 0]
scored.sort(key=lambda item: item[0], reverse=True)
return [chunk for , chunk in scored[:top_k]]
def build_promp
