“RAG” can make a fairly concrete piece of software sound mysterious. Herbistry's version is not a model that was retrained on herbal medicine, and the embeddings do not live in a mysterious file on someone's laptop. It is a retrieval pipeline in front of a language model: turn a question into a vector, find nearby text in PostgreSQL, give that text to a generator, and show the sources alongside the answer.
The public interface is https://herbistry.cc/ask. The browser submits to POST /ask; authenticated API clients use GET /api/ask?q=... with an X-API-Key header.
Here is the whole shape before getting into the details:
Books, monographs, abstracts, and herb web pages
↓
clean text and assign sections
↓
overlapping chunks of about 512 characters
↓
OpenAI text-embedding-3-small → 1,536-number vectors
↓
PostgreSQL + pgvector + an HNSW index
User question → query embedding → five nearest chunks
↓
prompt + retrieved source text
↓
LiteLLM → gpt-oss 20B via Ollama
↓
answer, references, and related records
The retrieval system and the product catalog are connected, but they are not the same thing. That distinction explains a lot about how the site works.
Two kinds of data, two kinds of tables
Herbistry has a structured supplement catalog and a separate text-retrieval corpus. The catalog comes from the NIH Dietary Supplement Label Database. The RAG corpus contains explanatory and scientific text.
| Data | Main tables | How it is used |
|---|---|---|
| Product labels | products, product_ingredients, product_other_ingredients | Structured product pages and ordinary catalog search |
| Label and company details | label_statements, product_companies | Suggested use, precautions, claims, manufacturers, and related label metadata |
| Herb profiles and relationships | plants, plant_product_links | Profile pages and links from an herb to matching products |
| Retrieval corpus | plant_details | Source text, section labels, source metadata, and searchable embeddings |
“Breaking up the tables” therefore happens in two different ways. The DSLD JSON is normalized into relational rows: one product can have many Supplement Facts ingredients, other ingredients, label statements, and company records. Ingredient rows retain their source category, amount, unit, and daily-value percentage; a row whose category is botanical also gets is_botanical = true.
The RAG pipeline does something different. It breaks documents into searchable chunks and attaches a section category to each chunk. Products are not currently embedded into the RAG corpus. Adding a product makes it available to relational search immediately, but it does not automatically create new RAG knowledge.
Where the retrieval text comes from
The corpus combines WHO monographs, pharmacognosy textbooks, NCBI Bookshelf chapters, IntechOpen material, PubMed abstracts gathered per plant, and scraped herb-reference pages. Different sources need different extraction code, but they eventually land in the same plant_details structure:
content the actual text chunk
source book name, source URL, or a label such as "PMC: Ginger"
section botany, chemistry, uses, dosage, and so on
page_num a PDF page, PMID, or NCBI chapter identifier where available
plant_id a link to a structured herb profile when one is known
embedding legacy 768-dimensional Ollama vector
embedding_openai
current 1,536-dimensional OpenAI vector
That common shape is useful because retrieval does not need a separate algorithm for every source. A chunk from a WHO monograph and a chunk from a plant abstract can participate in the same nearest-neighbor search while retaining their own citation metadata.
Assigning sections before chunking
For web sources, the scraper first splits Markdown-like content at headings. It recognizes ATX headings such as ## Uses, underlined headings, and standalone bold headings. Navigation noise, image markup, known boilerplate, and footer/reference sections are removed or stop the extraction.
The heading is mapped to a controlled set of section labels:
| Section | Examples of heading signals |
|---|---|
botany | Botany, taxonomy, nomenclature, description, background |
chemistry | Chemical constituents, phytochemistry, alkaloids, glycosides, terpenes, flavonoids |
pharmacology | Pharmacology, activity, clinical evidence, efficacy, trials, mechanisms |
dosage | Dosage, dose, administration, serving, recommended amounts |
contraindications | Warnings, precautions, adverse effects, toxicity, interactions, pregnancy |
traditional_uses | Traditional use, folklore, history, ethnobotany, Ayurveda, TCM |
uses | Uses, indications, therapeutic use, benefits, health effects |
general | The fallback when no heading rule matches |
This is deliberately simple keyword classification, not an LLM calling a taxonomy service. It is fast and predictable. It can also mislabel an unusual heading, which is one reason the original source and section remain visible in the response.
PDF ingestion uses a related heuristic after chunking: it examines the beginning of each chunk for words such as “chemical,” “clinical,” “dosage,” or “contraindication” and assigns the same broad categories. Web ingestion has the advantage of real headings; PDF ingestion is more dependent on extracted prose.
The chunker: small windows with a little overlap
The core chunker is a character-based sliding window. Its default target is 512 characters, with 64 characters of overlap between consecutive chunks.
start = 0
while start < len(text):
end = start + 512
chunk = text[start:end]
# Prefer a reasonably late newline over an arbitrary split.
newline = chunk.rfind("\n")
if end < len(text) and newline > 256:
end = start + newline
chunk = text[start:end]
chunk = chunk.strip()
if len(chunk) > 50:
keep(chunk)
start = end - 64
The newline rule is a small attempt to avoid cutting every passage at an arbitrary character. If a newline occurs in the latter half of the window, the chunk ends there. If not, the hard character boundary wins. Tiny fragments of 50 characters or fewer are skipped.
The overlap gives retrieval a second chance when an idea crosses a boundary. A sentence split near the end of one chunk can still appear with more context near the beginning of the next. It also means the corpus intentionally contains some repeated text.
This is not semantic chunking. It does not detect that a paragraph has completed an argument, and it can still start a chunk in the middle of a word. At this corpus size, the simple approach is understandable and easy to rebuild. A future version could experiment with paragraph-aware or token-aware chunks, but that would require re-embedding and measuring retrieval quality rather than assuming longer chunks are automatically better.
PDF extraction has its own compromises
For PDFs, PyMuPDF extracts each page's text and concatenates it into one document while recording character offsets for page boundaries. The chunker then runs over the combined text. Page attribution is approximate: the loader locates the chunk's opening text in the document and chooses the closest preceding recorded page boundary.
That works well enough for source previews, but PDF extraction is messy. Justified text can contain broken hyphenation, and page numbers are not perfect citation anchors. Before chunks are shown or sent to the generator, the application repairs words split across line breaks, collapses whitespace, and trims awkward fragments toward sentence boundaries.
The cleanup function also limits displayed/contextual chunk text to roughly 400 characters. In other words, 512 is the ingestion window, not a promise that every character reaches the final prompt unchanged.
Embeddings live in PostgreSQL, not in a sidecar file
The original ingestion scripts used local Ollama with nomic-embed-text, producing 768-dimensional vectors in plant_details.embedding. The current system migrated the same chunk content to OpenAI text-embedding-3-small, producing 1,536-dimensional vectors in embedding_openai.
The migration added a second pgvector column instead of destroying the old one. It processed rows in batches, retried failures with backoff, skipped rows already populated so it could resume, and created an HNSW index using cosine operations. The legacy vectors remain available as a configuration-level rollback.
So where does the embedding “live”? In the PostgreSQL row next to that chunk's text and metadata. The model produces a vector; pgvector stores and indexes it. There is no giant embedding file that the web process loads into memory.
Query-time embedding goes through LiteLLM when the gateway is configured, using the OpenAI-compatible embeddings API. The application chooses embedding_openai for OpenAI or the old embedding column for Ollama. The column name comes from trusted configuration, never from request input.
Retrieval: five nearest neighbors
Once a question has a vector, the application asks PostgreSQL for the five closest chunks. The essential query is:
SELECT pd.content, pd.source, pd.section, pd.page_num, pd.plant_id,
p.common_name AS plant_name,
pd.embedding_openai <=> %s::vector AS distance
FROM plant_details pd
LEFT JOIN plants p ON p.id = pd.plant_id
WHERE pd.embedding_openai IS NOT NULL
ORDER BY pd.embedding_openai <=> %s::vector
LIMIT 5;
The <=> operator is pgvector's cosine-distance operator. Lower distance means closer vectors. The HNSW index makes approximate nearest-neighbor search practical without comparing the query against every row in a simple application loop.
The current retriever is intentionally plain: top five by vector distance. It does not apply a metadata filter, hybrid keyword search, reranker, or minimum-similarity threshold. The distance is returned to the UI so I can inspect retrieval behavior, but it is not currently used to accept or reject a question.
Generation: retrieved context, not free-form memory
The five chunks are formatted as numbered references with source, section, page identifier, and text. They are inserted into a prompt with the user's question. The instructions tell the model to:
- Answer as a scientific herbal-medicine assistant.
- Use only the supplied context.
- Say when the context does not contain relevant information.
- Write in English and stay concise.
- Use numeric citations such as
[1]and[2]. - Avoid Markdown or ASCII tables.
With LiteLLM enabled, the prompt goes to its /v1/chat/completions endpoint under the configured model alias. Production and development aliases can differ, but the current target is the same gpt-oss 20B model family served by Ollama. The OpenAI embedding call and the Ollama generation call are separate steps with separate usage profiles.
The returned text is cleaned once more. Real pipe tables become readable “field: value” lines, while orphaned table headers and separator rows disappear. Numeric citation markers become links to the corresponding source boxes in the browser.
This is grounding, not a mathematical proof that every generated sentence is supported. The system shows the actual retrieved sources so a reader can inspect them; it does not yet run a separate claim-by-claim verifier on every RAG answer.
Related herbs and products come from the database
The model is not allowed to invent the related-record links. After generation, the application resolves them from structured data:
- Match known common and scientific herb names in the question and answer.
- Use a chunk's trusted
plant_idwhen one exists. - Recognize PMC source labels such as
PMC: Ginger. - Take up to four related herbs.
- Follow
plant_product_linksto as many as three products per herb.
The herb name is URL-encoded for its internal profile link, and product links use the DSLD identifier. Images come from stored plant and product records. This is why the RAG answer can lead into the catalog without embedding all 200,000-plus product labels into the vector corpus.
How does it distinguish a real question from random garbage?
Here is the candid answer: the current request path does not make that distinction before generation.
The ordinary product/herb search and the RAG question form are separate routes chosen by the visitor. The application does not inspect a catalog query and automatically escalate it to RAG. Ordinary search remains relational SQL; every accepted question on the Ask route follows the embedding-and-generation path.
The web endpoint checks that the question is non-empty, verifies Turnstile when configured, and enforces a rolling quota. The API additionally requires at least three query characters and a valid key. None of those checks decides whether a question is about herbal medicine.
A question such as “Who owns the moon?” still gets an embedding. PostgreSQL still returns the five nearest chunks, because nearest does not necessarily mean relevant. The generator still gets called and is instructed to admit that the context is irrelevant. Ideally it gives a restrained non-answer, but the system has already spent an embedding call, a generation call, database work, and a quota slot.
There is no hidden decision model, no relevance-distance cutoff, and no cheap topical router in the current implementation. The prompt is the last line of quality defense, not an abuse-saving classifier.
What a real router would look like
If I add routing, I would separate three decisions that are easy to conflate:
- Is the input well formed? Apply length limits, character-count limits, and basic validation before any model call.
- Is it in scope? Use a small local classifier or inexpensive model to distinguish herbal/product/evidence questions from unrelated requests and prompt-injection-style diversions.
- Did retrieval find usable evidence? Calibrate vector-distance thresholds on real queries and refuse generation when the best matches are too weak.
A sensible path would be:
malformed input → HTTP 400, no model call
obviously out of scope → short response, no generation
in scope → embed and retrieve
weak retrieval → offer ordinary herb/product search
supported question → generate with the retrieved context
The classifier should not be the only gate. A topically valid question can still have poor source coverage, and a clever off-topic request can mention an herb merely to get past a keyword filter. Combining scope detection with retrieval quality is more robust than either one alone.
Thresholds need evaluation. I would build a small labeled set of relevant, irrelevant, ambiguous, and adversarial questions; measure embedding distances and classifier outcomes; then choose operating points based on false acceptance and false rejection. An arbitrary cosine cutoff copied from another corpus would not tell me much.
What the current design does well—and what it does not
The good part is that the system is inspectable. Chunks keep their text, source, section, and vector together. Retrieval is one readable SQL query. Generation goes through one gateway. Related records use explicit database links, and the user receives references rather than only an answer.
The limitations are equally concrete:
- Character chunks can split ideas and words.
- Section labels are heuristic and can be wrong.
- Top-five retrieval always returns something, even for nonsense.
- Citations are generated markers, not independently verified claims.
- Product rows are searchable relationally but are not part of RAG retrieval.
- New source text needs chunking and embedding before it joins the corpus.
- There is no pre-generation topic router and no bounded RAG concurrency queue yet.
None of those requires throwing the design away. The base is already the right shape: structured catalog where structure matters, pgvector for evidence retrieval, LiteLLM for model access, and a generator constrained by visible context. Better chunking, relevance gates, verification, and queueing can be measured and added independently.
Most importantly, RAG is not training. The model is not becoming an herbal expert every time I add a document. I am building a searchable evidence shelf, retrieving a few passages at question time, and asking the model to work from those passages. The quality of the answer starts with what I put on the shelf—and with whether I am willing to say that nothing on it answers the question.