← All posts

A Retrieval Chatbot for the Circassian DNA Project

I built a question-answering chatbot for www.circassiandna.com, the site of the Circassian DNA Project. It is a small retrieval-augmented system: a Flask API, a Pinecone index over a curated knowledge base, and one call to an OpenAI chat model. I state its limits first.

The last commit in the public repository is dated 28 August 2025, and the history starts on 9 August 2025: 37 commits and 11 version tags, the latest v2.0.0. I have no usage figures, no evaluation set and no measured answer quality, so this post has none. The prompt does not stop the model answering outside the knowledge base, so answers are only partly grounded. The repository is at kabartay/circassiandna-chatbot under GPL-3.0.

In short

  • The bot is a Flask API, a Pinecone index over 10,103 curated question and answer entries (English and Russian), and one call to gpt-4o-mini, which OpenAI lists as deprecated with a shutdown date of 14 January 2027; the same app deploys to Docker or AWS Lambda.
  • The prompt lets the model answer from its own knowledge when no entry matches, and nothing checks an answer against the entries, so answers are only partly grounded.
  • There is no evaluation set, no retrieval score threshold, and lint and test failures do not fail CI; the tests mock OpenAI and Pinecone.
  • If you are building a small domain RAG chatbot, the last section lists seven things it needs and how this project handled each.

What the project is, and why a chatbot

The site covers genetics and genealogy. Its visible posts cover Y-DNA haplogroup clusters and archaeological cultures such as Maykop and Srubnaya, and it has a blog, forum, FAQ and links to a FamilyTreeDNA group. The home page does not state the project's aims or audience, so I do not describe them.

Visitors ask the same kinds of question: what a haplogroup is, how a FamilyTreeDNA test works. A forum answers slowly and a FAQ page has to be searched, so a chat box over curated answers gives a faster first reply. The README describes the scope as questions about DNA testing, haplogroups and Circassian ancestry.

Architecture

A question travels from the browser to a Flask endpoint, is embedded, matched against the index, and the top three entries go into a prompt for gpt-4o-mini. The same Flask app runs under gunicorn in Docker or, through apig-wsgi, as an AWS Lambda function.

Request path from the WordPress widget to the Flask API, Pinecone and the OpenAI model WordPress page PHP + JS widget Flask API POST /api/chat OpenAI embed, then chat Pinecone index top 3 entries knowledgebase.json built from data/ build
Figure 1. Request path (solid) and the offline index build (dashed). The reply returns along the same path.

The two paths differ only in packaging. serverless.yml packages the app as a Python 3.11 Lambda function behind an HTTP API, and the Dockerfile runs it under gunicorn for container hosts, so the application code is the same in both.

The knowledge base

The knowledge base is one JSON object of question-to-answer pairs. The combined knowledgebase.json has 10,103 entries, of which 4,777 have Cyrillic keys. It comes from 22 source files under data/en and data/ru, named by topic. Five of the 22 files hold no entries yet.

An English entry reads like this, from data/en/ftdna_en.json:

"What is FamilyTreeDNA?": "FamilyTreeDNA is a commercial genetic
testing company based in Houston, Texas, offering Y-DNA, mtDNA,
and autosomal DNA testing services for genealogical purposes."

Splitting by topic and language keeps edits reviewable. combine_jsons.py merges the pieces. It needs en and ru subdirectories, skips missing files with a warning, strips trailing commas with a regex, rejects files whose top level is not an object, and writes with ensure_ascii=False so Russian stays readable.

fixed_text = remove_trailing_commas(read_raw_text)
data = json.loads(fixed_text)
if not isinstance(data, dict):
    LOGGER.warning(
        "Skipping %s: not a JSON object at top level",
        filepath,
    )
    continue
combined_data.update(data)

(Shortened excerpt from combine_jsons.py.) Two limits follow from dict.update. A key in two files silently overwrites the earlier one: the sources hold 10,127 entries and the output 10,103, so 24 were collapsed. Some are true duplicates; any real conflict loses an answer without warning. Nothing checks that an English and a Russian entry say the same thing.

validate-json.sh runs jq '.' over the root and data/ JSON files, rewrites valid files in canonical form and stages them. In CI, json.yml runs jq empty, jsonlint and a Prettier check; it is triggered only by changes to JSON files in the repository root. The pre-commit configuration runs the combine script on every commit, plus black, isort and pylint. validate-json.sh is not part of that configuration; I run it by hand.

Retrieval and the model call

app.py embeds each entry as the question and answer joined by a newline, using text-embedding-3-small (1,536 dimensions), and upserts the vectors into a cosine-metric Pinecone index in batches of 50. build_index also tries to create a missing index, but its create_index call omits the spec argument that pinecone==7.3.0 requires, so the index has to exist before the build. At query time it embeds the question and asks for the top three matches. The build makes one embeddings request per entry, so 10,103 requests.

If Pinecone is unreachable, the key is missing, or the index does not exist, query_index falls back to a substring search over the local dictionary. The fallback matches only when the whole question appears inside a key or an answer, so it returns little, but the service degrades instead of failing.

The model name is a constant in app.py, and the call is a single chat.completions.create with the prompt as one user message. As of December 2026, OpenAI's deprecations page lists gpt-4o-mini (snapshot gpt-4o-mini-2024-07-18) as deprecated, with notice on 14 October 2026 and shutdown on 14 January 2027, so the constant has to change before then. The page does not list text-embedding-3-small; if the embedding model were changed, every vector would have to be rebuilt.

The prompt, as written in app.py:

"You are a helpful assistant for Circassian DNA.\n"
"First, check the knowledge base entries below.\n"
"If you find a relevant answer, use it directly.\n"
"If the knowledge base does not have a clear answer, "
"you may use your own knowledge.\n"
"Always prefer the knowledge base if there is a match.\n\n"

The two sentences about "your own knowledge" are the most consequential choice. I added them so the bot would not refuse general DNA questions that my entries do not cover. The cost is that the model can answer from memory on Circassian history and haplogroup details, where I cannot vouch for it.

Serving: the widget and the Lambda wrapper

chat-widget.js (106 lines) renders an input row and posts {question} to the API. On the site, chatbot-widget-global-web.php injects a floating "Chat" button, the styles and the script on every WordPress page, so the chatbot needs no theme change. The widget sends only the current question, so a follow-up such as "and what about its subclades?" arrives without context.

lambda_handler.py is two lines of logic:

from apig_wsgi import make_lambda_handler
from app import app
handler = make_lambda_handler(app)

It handles both API Gateway event formats. A hand-written awsgi2 handler is still in the file as commented-out code, which I would remove. serverless.yml routes / and POST /api/chat to that handler and puts dependencies in a Lambda layer built from requirements-lambda.txt, because the unzipped package, layers included, must stay under the 250 MB limit the README cites (AWS Lambda quotas, December 2026). The function runs on python3.11, which AWS lists with a deprecation date of 30 June 2027. Keys come from the deploying shell's environment, not the repository.

CORS is limited to the project's two site origins and three localhost ports. The app logs questions and retrieved contexts, and its error responses are more detailed than a public endpoint needs. I would tighten both.

MLOps: tests, CI, packaging, configuration

There are ten tests in tests/test_app.py, all with OpenAI and Pinecone mocked: embedding success and failure, index creation (against a mock), batched upserts, Pinecone and fallback queries, and the Flask routes. Three sample API Gateway events under tests/events/ support serverless invoke local. None of this tests answer quality, because no step calls a real model or measures retrieval hit rate.

There are nine workflows in .github/workflows/. The Makefile prefixes the lint and test commands with -, so a failing pytest or pylint run does not fail make check, and therefore does not fail CI. deploy-docs-json.yml also watches kb/*.json, a directory a later commit removed to avoid duplication, so I expect it never triggers.

ComponentFileWhat it doesKnown gap
APIapp.pyEmbed, retrieve, prompt, answerNo score threshold; model may use own knowledge
Knowledge basedata/, combine_jsons.pyMerge topic files into one JSONDuplicate keys overwrite; no EN/RU consistency check
JSON checksvalidate-json.sh, json.ymljq, jsonlint, PrettierSyntax only, not content
Lambda entrylambda_handler.py, serverless.ymlWSGI to API Gateway, layer packagingDead awsgi2 handler left in file
ContainerDockerfilePython 3.11 slim, gunicorn on $PORTInstalls dev requirements too
Widgetchat-widget.js, PHP fileFloating chat on every WordPress pageNo conversation memory
CI.github/workflows/Format, lint, test, docs, releaseLint and tests cannot fail the build

For packaging, a tag matching v*.*.* triggers release.yml, which runs python -m build and publishes the files as a GitHub release. Docs are Sphinx pages deployed to GitHub Pages at kabartay.github.io/circassiandna-chatbot. Dependencies sit in three requirement files (dev, Lambda, docs). They are not fully consistent: pyproject.toml lists awsgi while the Lambda file uses apig-wsgi, and the Lambda file pins both pinecone and pinecone-client. Pinecone's documentation says pinecone-client was replaced by pinecone, so the second pin is redundant.

Configuration is entirely environment variables. The app refuses to start without the OpenAI key and falls back to keyword search without the Pinecone key. The README suggests several broad AWS managed policies for the deploying user, including full access to IAM and CloudFormation. I would scope those down.

Grounding and limits

Grounding here means retrieval of curated entries, a prompt that prefers them, and a small context (three entries). The answer is not checked against the entries, so a response can add a claim that no entry contains and nothing flags it. On a genetics and heritage topic that is the main risk, since a fluent wrong statement about ancestry reads as fact.

Language is the second limit. Roughly half of the keys are Russian, but I have not measured cross-language retrieval: a Russian question may retrieve an English entry, or the reverse, and I do not know how often. A few redirect entries, such as "You mean FamilyTreeDNA?" for other testing labs, patch questions I have seen rather than cover a domain.

The third limit is scope. Entries are my own writing and curation, so the answers inherit my choices and gaps. The entries carry no sources or dates.

Running it locally

This path follows the README. It needs Python 3.11 or later and your own OpenAI and Pinecone accounts, and the Pinecone index (1,536 dimensions, cosine) must already exist. Keep keys out of the repository.

make                      # venv, dev + Lambda + docs deps
source venv/bin/activate
export OPENAI_API_KEY=...        # your own key
export PINECONE_API_KEY=...      # your own key
export PINECONE_INDEX=circassiandna-knowledgebase
python app.py build       # embed entries, upsert (index must exist)
python app.py             # serve the Flask app
PYTHONPATH=. pytest tests/test_app.py

The app reads PORT and defaults to 8080 (the README still says 5000, which I need to fix). Building the index sends all 10,103 entries to the OpenAI embeddings API. The entries total 889,287 characters, so even at one token per character the build is under one million tokens, and at the $0.02 per million tokens that OpenAI lists for text-embedding-3-small it costs under two US cents (an upper bound, not a measured bill). Because the build only upserts and uses the entry's position as its id, a shrinking knowledge base can leave stale vectors in the index.

What a small RAG system needs

Each item applies to any small domain chatbot and is paired with what this project did or lacked. The evaluation set is the first to build here; Making LLM Evaluation Reproducible with MLflow covers how to keep such runs repeatable.

  1. A grounded prompt. Tell the model to answer only from the retrieved entries and to say when none fits. This prompt allows the model's own knowledge, and there is no score threshold, so three weakly related entries still reach the model.
  2. An evaluation set. A fixed list of questions with the entry each should retrieve gives a hit rate and a regression test that CI can check against a target. The project has none, and its ten tests mock both services.
  3. Index provisioning. Create the index in code or in documented steps, and make rebuilds idempotent. Here the create_index call omits the spec argument that pinecone==7.3.0 requires, and ids are entry positions, so a shrinking knowledge base can leave stale vectors.
  4. Deduplication. Report colliding keys instead of overwriting them. The merge uses dict.update, which collapsed 24 of 10,127 entries without a warning.
  5. Bilingual consistency. If answers exist in two languages, check that they agree and measure cross-language retrieval. 4,777 of the 10,103 keys are Russian; neither check exists.
  6. Logging and privacy. Decide what a log may hold. This app logs questions and retrieved contexts.
  7. Deployment parity. Keep the paths documented and equal. One Flask app serves both, but the README still gives port 5000 while the app defaults to 8080, the Docker image installs dev requirements, and the dependency files disagree on awsgi and apig-wsgi.

Sources