AI agents · · 5 min read
SQLite FTS5: test FAQ retrieval before adding an AI model
Build a small local keyword-search baseline, return traceable FAQ records and test no-match cases before connecting a customer-care model.
By Sociologix Editorial

Separate finding a source from writing an answer
This AI-assisted editorial guide uses official SQLite and Python documentation checked December 4, 2026. The exact retrieval example was run locally with Python 3.13.15 and SQLite 3.50.4. The query results below are observed checks on three fictional FAQ records, not a production chatbot evaluation.
A customer-care assistant needs the right source before it can write a useful answer. Start with a small test that returns the source text and a stable record ID, without generating a reply. That makes an empty result or a bad match visible instead of hiding it inside fluent output.
This proposed baseline uses SQLite’s FTS5 full-text index and no model service. Its deliberate limitation is simple: it searches keywords rather than understanding a question. Use it to learn what your published FAQ wording covers, then decide which retrieval improvements are necessary.
1. Check the local runtime
Use a Python installation with its sqlite3 module and an SQLite library that supports FTS5. Python exposes the underlying SQLite version as sqlite3.sqlite_version; the module can be absent in some distributor builds. [1] The table-creation step in the script checks whether the required extension works in your runtime.
Save the complete example below as faq_search.py and run it with python faq_search.py. It creates an in-memory database, loads only the three fictional records and prints four searches. There is no API key, hosted database, customer upload or model call.
import re
import sqlite3
# Fictional public FAQ examples, not Sociologix service terms.
FAQS = [
("demo-1", "Website timeline",
"A website timeline is discussed after scope review."),
("demo-2", "Upload documents",
"Use the project workspace to upload documents."),
("demo-3", "Review a proposal",
"Review the scope and record questions before accepting a proposal."),
]
con = sqlite3.connect(":memory:")
try:
con.execute("""CREATE VIRTUAL TABLE faq USING fts5(
doc_id UNINDEXED, title, body, tokenize='unicode61'
)""")
except sqlite3.OperationalError as error:
raise SystemExit("This Python SQLite build needs FTS5 support.") from error
con.executemany("INSERT INTO faq VALUES (?, ?, ?)", FAQS)
def search(keywords):
if not isinstance(keywords, str):
raise ValueError("Search keywords must be text.")
if len(keywords) > 300:
raise ValueError("Use at most 300 characters.")
words = re.findall(r"[a-z0-9]+", keywords.lower())
if not words:
return []
if len(words) > 12:
raise ValueError("Use at most 12 keywords.")
expression = " AND ".join('"' + word + '"' for word in words)
return con.execute(
"""SELECT doc_id, title, body FROM faq
WHERE faq MATCH ?
ORDER BY bm25(faq, 0.0, 5.0, 1.0), rowid
LIMIT 3""",
(expression,),
).fetchall()
if __name__ == "__main__":
print("SQLite:", sqlite3.sqlite_version)
for query in ["website timeline", "upload documents", "launch schedule", "!!!"]:
print(query, "=>", search(query))
con.close()
2. Keep retrieved records traceable
Each row has an identifier, title and body. FTS5’s UNINDEXED option keeps the identifier out of the searchable index while retaining it as a column in this ordinary FTS5 table. The unicode61 tokenizer splits the indexed text into searchable terms. [2] Return the title and body with the identifier so a reviewer can inspect the actual source.
The query orders matches using bm25. In SQLite FTS5, smaller values mean better-ranked matches; the optional weights correspond to columns in table order. The example sets identifier, title and body weights to 0, 5 and 1. [2] That is a proposed starting configuration, not an experimentally optimal setting or a confidence percentage.
3. Bound keyword input and separate two query languages
Python’s sqlite3 documentation recommends binding values with placeholders rather than formatting them into SQL. [1] The script binds the complete MATCH expression as one parameter. That addresses the SQL boundary, but MATCH also interprets its own full-text query syntax.
This lab therefore extracts only ASCII letters and digits, quotes each extracted word and joins them with AND. FTS5 documents quoted strings and boolean operators as part of its query language. [2] User-supplied OR is treated as the literal word “or” in this helper, not as a command to broaden the search.
The input contract intentionally accepts short English keyword searches, capped at 300 characters and 12 extracted words. Empty or punctuation-only input returns no rows. These choices keep this lab predictable; they are unsuitable as a universal multilingual query parser. Validate that contract before exposing a search control.
4. Check positive results and useful failures
The local run returned demo-1 for website timeline, demo-2 for upload documents and demo-3 for review proposal. The searches launch schedule, websites, punctuation-only input and website OR documents returned no rows. Three additional checks rejected a non-string value, an oversized input and too many keywords.
The no-match cases explain the tradeoff. Launch schedule is related in meaning to website timeline, but the example contains neither search word. Websites also differs from website under this configuration. AND requires every extracted word, so a full conversational sentence can fail even when a relevant document exists.
Build a small expected-results file from your own approved public FAQ before tuning. Record the query, expected source IDs and observed top results. Include real customer phrasing, singular/plural variants and questions that the FAQ cannot answer. Do not change all searches to OR merely to produce an answer: broader matches also need evaluation.
- Check that known keyword searches return the expected source ID.
- Keep at least one unsupported question that must return no source.
- Compare ranking after each tokenizer, weighting or query change.
- Review the source text before treating a retrieved record as applicable.
5. Add answer generation only after defining the boundary
This script is a retrieval lab, not a customer-support endpoint. A stable ID provides traceability but no access control. Before using private project content, enforce identity and document permissions outside this example and test that unauthorized records cannot be returned.
For a public FAQ assistant, a proposed next step is to pass the retrieved records to the model with their source IDs and require answers to stay within that evidence. Return a clarification or escalation path when no suitable source is found. That policy still needs model evaluation; keyword matches do not prove that an answer is correct.
Keep the approved FAQ version and your expected-results cases together. When a service description changes, rerun those cases before updating the chatbot. The useful result of this baseline is an inspectable retrieval decision, including an honest empty result, before additional generation behavior is introduced.
Sources & further reading
Build a customer-care assistant with inspectable sources
Sociologix can help organize approved FAQ content, evaluate retrieval and design clear review and escalation paths before adding AI-generated responses.
Talk to Sociologix