Visitors talk to your AI twin. It says it is an AI, answers from facts you wrote, and stores nothing they type.
π Quick Start β’ π Make It Yours β’ β‘ Features β’ π Documentation β’ πΊοΈ Roadmap
Digital Twin Chatbot puts an AI twin of you on your personal website. Visitors ask about your work, and the twin answers in your first person from a knowledge base you write. It says plainly that it is an AI, and it keeps away from the topics you rule out.
This is the code behind the twin on stratoslouvaris.gr. It ships
with a sample persona instead of the real one: John Doe is made up, and so is everything in
app/knowledge/data/knowledge.json, the deny list and the prompt. The engine is the same.
The write-up follows one message from the widget to the reply: Digital Twin Chatbot: How I Built an Open-Source AI Twin for My Website.
What makes it different:
- Guards on the stream, not after it: every chunk is checked against the reply so far before the visitor sees it, so a blocked word split across two chunks is still caught
- Openly an AI: it says what it is in one plain sentence and never claims a person is typing (D-1)
- Stores nothing: live chats stay in memory and are forgotten after 30 idle minutes. No IP, user agent or chat text reaches the logs (D-3)
- Red-teamed in CI: 23 attacks run on every pull request against a scripted model, and on demand against the real one
- Light on the host page: one
asyncscript tag, Shadow DOM, no dependencies, hidden while the backend is down
- Streaming output guard - Each chunk is checked before it is sent (
app/chat/service.py,app/chat/guards.py). A blocked term at the very end of a chunk is held back until the next chunk shows whether it is a whole word or the start of a harmless longer one ("Init" vs "Initializer",app/core/sensitive.py). On a hit, the reply shown so far is swapped for a fallback line with atext_replaceevent. - Search on every turn - Asked in the prompt to search first, the model sometimes answered
follow-ups from memory.
SearchFirst(app/agent/agent.py) forces the search tool on each request until the current turn has a result, then leaves the model free to answer. - A compact history - Past turns go to the model as the visitor's message and the twin's
reply only, without their tool calls and results (
_compact_historyinapp/chat/service.py), so ten messages of history are five real turns. - One deny list, enforced twice -
app/core/sensitive.pyfeeds the output guard and the corpus scrubber, which fails CI when a knowledge entry contains a blocked term. - Two languages - English and Greek, with Greek greetings and a fixed Greek employer line that show where to put your second language.
- A ceiling on the bill - 200 messages a day in all, 15 per visitor IP, 30 per conversation, and prompt caching on by default.
- Bot check - Optional Cloudflare Turnstile when a conversation starts.
- Any model - One OpenRouter key serves the replies (Claude Haiku 5.5 by default) and the
embeddings (
text-embedding-3-small). Pydantic AI can call a provider directly too (anthropic:,openai-chat:,google:,ollama:). - Two vector stores - sqlite-vec by default, pgvector on PostgreSQL.
- In production - The same engine runs the live twin on stratoslouvaris.gr
- Tests - 580 passing, 89% line coverage (
make test-cov). Seven more are markedxfail: attacks no regex guard catches, left to the system prompt and the live red-team layer - Red team - 23 attacks: identity, the employer, the prompt and the canary token, and escalation past the history cut
- Strict types - mypy strict and pyright strict, zero errors
- CI gate - Lint, format, types, corpus scrub and tests on every pull request (
make ci), and the pgvector store against a real PostgreSQL - Tech Stack - FastAPI + Pydantic AI + sqlite-vec / pgvector + SSE + a Web Component
| Requirement | Version | Installation Guide |
|---|---|---|
| Python | 3.12+ | python.org |
| uv | 0.11.7 (the version CI uses) | docs.astral.sh/uv |
| Git | any recent | git-scm.com |
| Docker | optional, for deploying | docs.docker.com |
API Keys Required:
- OpenRouter (pay-as-you-go) - one key for the replies and the embeddings
Optional:
- Cloudflare Turnstile - the bot check
- LangFuse - traces of each run, sent without the chat content
π¦ Every setting
.env.example lists every setting with a comment on what it does: the models, the vector
store, the rate limits and daily caps, CORS, the proxy settings and the bot check. Copy it to
.env and change what you need. The app refuses to start on a key it doesn't know, so a typo
shows up at once.
# 1. Clone and configure
git clone https://github.com/StratosL/digital-twin-chatbot.git
cd digital-twin-chatbot
cp .env.example .env # set OPENROUTER_API_KEY
# 2. Install
uv sync
# 3. Start the dev server
make devAccess the Application:
- π Demo page: http://localhost:8888
- π‘ API Docs: http://localhost:8888/docs
On the first start the loader embeds knowledge.json into the vector store. Later starts skip
that until the content, the embedding model or the dimensions change.
# Verify backend health
curl http://localhost:8888/health
# Start a conversation, then stream a reply
ID=$(curl -s -X POST http://localhost:8888/api/conversations | python3 -c 'import json, sys; print(json.load(sys.stdin)["id"])')
curl -N -X POST "http://localhost:8888/api/conversations/$ID/messages/stream" \
-H "Content-Type: application/json" -d '{"content": "What is Quarry?"}'The persona lives in a few files. Every place it shows up is a John you can grep for
(grep -rn John app tests).
| File | What to change |
|---|---|
app/knowledge/data/knowledge.json |
Your facts, as Q&A entries in the first person |
app/agent/prompts.py |
The system prompt, the employer line (English and Greek) and the canary token |
app/core/sensitive.py |
The terms the twin must never write: your employer, its group, your team |
app/chat/service.py, app/chat/guards.py |
The canned greetings, refusals and fallback lines |
.env |
PERSONA_NAME, PERSONA_ROLE, ALLOWED_ORIGINS |
Then run make ci: the corpus scrubber fails if a knowledge entry contains a deny-listed term,
the tests fail on an em dash in any canned line or entry, and the employer lines must pass the
output guard they are there to satisfy. The second language is Greek because the original twin
is bilingual; the Greek greetings and the Greek employer line show where to put yours.
<script async src="https://chat.example.com/static/chat-widget.js"
data-api-url="https://chat.example.com/api"
data-persona-name="John"
data-accent-color="#1e3a8a"></script>Keep async, not defer: a deferred script holds up DOMContentLoaded until it arrives, so a
slow backend would hold up the whole page. Optional attributes: data-greeting,
data-privacy-url and data-case-study-url (links in the notice under the input).
Any element with data-chat-open opens the chat on click. Give it the hidden attribute: the
widget removes it once /api/health answers, so the button stays hidden while the backend is
down. If your theme sets display on the element, add
[data-chat-open][hidden] { display: none !important; }.
docker compose up -d builds and runs it on port 8888, with the SQLite file (the knowledge base
and its embeddings, never a chat) in a volume. The container log is capped at three 10 MB files.
For a public deploy:
- CORS: set
ALLOWED_ORIGINSto your site's origins. - Behind a reverse proxy: set
TRUSTED_PROXY_COUNTto the number of proxies in front of the app, so the rate limits and caps key on the visitor IP inX-Forwarded-For. The default, 0, ignores that header, since without a proxy any client can write it. - Bot check: set
TURNSTILE_SITEKEYandTURNSTILE_SECRET_KEY(Cloudflare Turnstile on conversation-create). Set both or neither: with only one, the app refuses to start. - Behind Cloudflare:
TRUST_CF_CONNECTING_IP=truetakes the visitor IP from Cloudflare's header, which the rate limits and caps key on. Turn it on only where nothing but Cloudflare can reach the port, for example by publishing it on loopback (127.0.0.1:8888:8000) for a tunnel on the same host. Anyone who reaches the port directly can fake the header and get a fresh allowance with every request. - Caching: make sure your CDN caches neither
/static/chat-widget.jsnor/api/*.
Tech Stack:
| Component | Technology | Purpose |
|---|---|---|
| Web Framework | FastAPI + sse-starlette | Async API, replies streamed over SSE |
| Agent | Pydantic AI 2 | The agent run, the search tool, SearchFirst, prompt caching |
| Models | OpenRouter (Claude Haiku 5.5, text-embedding-3-small) |
Replies and embeddings, one key |
| Vector Search | sqlite-vec or pgvector | KNN over the knowledge base |
| Database | SQLite (aiosqlite) or PostgreSQL (asyncpg) | The knowledge base only, never a chat |
| Widget | Web Component in Shadow DOM | One script tag, no dependencies |
| Abuse Controls | slowapi, in-memory daily caps, Cloudflare Turnstile | Rate limits, a ceiling on the bill, a bot check |
| Observability | structlog, OpenTelemetry to LangFuse | JSON logs and traces, both without chat content |
| Testing | pytest, scripted Pydantic AI models, Playwright | Offline suite, live red team, browser tests |
Architecture Pattern: Layers with strict boundaries. Routes handle HTTP and rate limits only, the service runs the guards and the agent, the agent searches the knowledge base, and the live chats sit in memory on their own.
POST /api/conversations/{id}/messages/stream
β routes.py β ChatService.stream_response()
β Pydantic AI Agent (run_stream_events, the whole run, tool calls included)
β search_knowledge tool β Embedder β VectorStore KNN
β SSE: tool_start | tool_result | text_delta | text_replace | sources | error | done
π Architecture Deep Dive
Directory structure:
app/
agent/ # Agent, system prompt, tools, dependencies
chat/ # Routes, service, live chats in memory, input and output guards
core/ # Config, database, logging, middleware, rate limits, Turnstile, deny list
knowledge/ # Loader, retriever, vector stores (sqlite-vec, pgvector), knowledge.json
static/ # Chat widget and demo page
scripts/ # Corpus scrubber (make ci)
tests/ # unit/ (mocked), integration/ (HTTP via ASGI), e2e/ (browser)
SSE events: done always comes last, even after an error. text_replace replaces the
whole reply shown so far: with a guard's fallback line, or with nothing when the model calls the
search after it has started to write. sources lists the questions of the entries the turn's
searches returned; the widget ignores it.
API:
| Method | Path | Description |
|---|---|---|
GET |
/api/config |
Public widget settings (the Turnstile site key while the bot check is on) |
POST |
/api/conversations |
Create a conversation (body {"turnstile_token": "..."} while the check is on) |
POST |
/api/conversations/{id}/messages/stream |
Stream a reply (SSE) |
GET |
/health, /api/health |
Health check with database status |
Startup: the loader embeds knowledge.json into the vector store, and only re-embeds when
the content, the embedding model or the dimensions change.
Why each piece exists, and what broke before it did: DECISIONS.md.
CLAUDE.md gives a coding agent such as Claude Code what it needs before it touches the code:
the commands, the layer boundaries, how to script the model in tests, and the gotchas that
already cost a bug (each tied to its ID in DECISIONS.md).
# The full gate: lint, format check, mypy and pyright strict, corpus scrub, tests
make ci
# Tests only, or with a coverage report
make test
make test-cov
# The live red-team layer, against the real model
RED_TEAM_LIVE=1 uv run pytest -m live -vThe suite needs no API key: real model calls are blocked, and the agent runs against scripted
models. The live layer needs OPENROUTER_API_KEY, makes roughly 30 to 60 model requests, and
writes every reply to data/red-team-live.txt. Read that file: the checks cannot judge
everything.
The pgvector store is tested against a real PostgreSQL in CI's pgvector job. To run it
locally, start the pgvector/pgvector image and set PGVECTOR_TEST_URL: the commands are at
the top of tests/integration/test_pgvector_store.py.
The browser tests in tests/e2e/ need Playwright and a dev server on port 8888, and run only
when you name their path (uv run pytest tests/e2e/).
- Ruff - Linting and formatting
- mypy + pyright - Both in strict mode, zero errors
- Corpus scrub -
knowledge.jsonchecked against the deny list and for bad ids - No em dashes - A test checks the prompt, every canned line, the tool text and every knowledge entry
make lint
make type-check
make scrub-corpus| Resource | Description |
|---|---|
| The article | How the twin works and why: the path of one message, the streaming guard, store nothing |
| DECISIONS.md | Every decision and bug fix the code cites (D-3, LIVE-1, ...), with the reason behind it |
| CLAUDE.md | Commands, layers, testing patterns and gotchas, written for a coding agent |
| .env.example | Every setting, with a comment on what it does |
| SECURITY.md | How to report a vulnerability privately, and what counts as one |
| API Reference | Interactive OpenAPI documentation (requires the running app) |
| Red-team suite | The attacks, and the checks that judge each reply |
The chat bubble never shows up
Solutions:
- The widget shows itself only after
{data-api-url}/healthanswers with"status": "healthy"and"database": "connected". Open that URL in the browser. - Add your page's origin to
ALLOWED_ORIGINS. Without it the browser blocks the call (CORS). - Make sure your CDN caches neither
/static/chat-widget.jsnor/api/*. - A
data-chat-openbutton waits for the same health check, so it stays hidden too.
Every reply is an error
Solutions:
- Set
OPENROUTER_API_KEY, or the key of the provider yourLLM_MODELnames. The startup log says which one is missing:application.lifecycle.api_key_missing. - If the embeddings failed at startup, the log has
knowledge.loader.embedding_failed. The next start tries again. - With
LLM_THINKING=true, thinking tokens count towardMAX_RESPONSE_TOKENS(500). Raise it, or keep thinking off.
The app refuses to start
Solutions:
- Only one of
TURNSTILE_SITEKEYandTURNSTILE_SECRET_KEYis set. Set both or neither. .envhas a key the app doesn't know (Extra inputs are not permitted). Settings refuse unknown keys, so a key left over from an older version stops the start: remove it.
Changing the embedding model
Solutions:
- A model with the same vector size re-embeds the knowledge base by itself on the next start.
- A model with another size needs
EMBEDDING_DIMENSIONSchanged and thevec_knowledgetable dropped. The database holds the knowledge base only, never a chat, so deletingdata/chatbot.dbworks too: the next start embedsknowledge.jsonagain.
Every visitor hits the daily cap at once
Solutions:
- Behind a reverse proxy every request comes from the proxy's IP, so all visitors share one
allowance. Set
TRUSTED_PROXY_COUNTto the number of proxies in front of the app. - Behind a Cloudflare tunnel that is the only way to the port, set
TRUST_CF_CONNECTING_IP=trueinstead.
make ci fails at the corpus scrub
Solutions:
- A knowledge entry contains a term from
app/core/sensitive.py, or its id is not a unique integer. The scrubber prints one line per problem, with the entry's id. - A test fails on an em dash: the persona never writes them (PER-4). Use a comma, a colon or a full stop.
- Openly an AI twin (D-1) - It says what it is and never claims a person is typing
- The employer as a hard block (D-2, SEC-1) - One fixed line, and a deny list on the stream
- Store nothing (D-3) - Chats in memory only, logs and traces without visitor data
- Search on every turn and a compact history (LIVE-1) - Grounded answers that remember the visitor's name
- Prompt caching (COST-1) and low daily caps (SEC-5)
- A red-team suite in two layers (RED-1) - Offline in CI, live on demand
- A widget that waits - Loads
async, shows only once the backend is healthy - pgvector tested against PostgreSQL - A CI job runs the store on a real database
- A security policy - Reports through GitHub's private vulnerability reporting
- Loopback by default -
docker-compose.ymlpublishing the port on127.0.0.1
| Feature | Digital Twin Chatbot | Typical Hosted Widget |
|---|---|---|
| Says it is an AI | β One plain sentence whenever it comes up | |
| Topics it must not touch | β Deny list enforced on the streamed text | |
| Visitor data | β Nothing stored, chats forgotten after 30 idle minutes | β Transcripts usually kept |
| Grounded answers | β Searches your knowledge base on every turn | |
| Tested against attacks | β 23-attack red-team suite in CI, plus a live layer | β Nothing you can run yourself |
| Cost control | β Daily caps and prompt caching you set | |
| Host page weight | β One async script, no dependencies, hidden when down | |
| Model choice | β Any model on OpenRouter, or a provider directly | |
| Source | β MIT, self-hosted | β Closed |
Bottom Line: a twin that speaks for you on your own site should be one you can read, test and switch off.
Digital Twin Chatbot is built by Stratos Louvaris, as the engine of the AI twin on stratoslouvaris.gr.
Built with:
- Pydantic AI - The agent framework
- FastAPI - The web framework
- sqlite-vec and pgvector - Vector search
- OpenRouter - One key for every model
- sse-starlette - Server-sent events
- Cloudflare Turnstile - The bot check
- uv and Ruff - Packaging, linting and formatting
This project is licensed under the MIT License - see the LICENSE file for details.
TL;DR: Fork it, swap in your own persona, run it on your site, use it commercially. Keep the copyright notice.
Contributions are welcome. A pull request into main needs the lint-and-test CI job to
pass, so run make ci first.
Ways to contribute:
- π Report bugs via GitHub Issues
- π Report a security problem privately, never in an issue: see SECURITY.md
- π‘οΈ Add attacks to the offline red-team suite (
tests/integration/red_team.py) - π§ Submit pull requests
- π Improve the documentation
- β Star the repo if you find it useful
Made by Stratos Louvaris
Live twin β’ Article β’ Decisions β’ Report Issue
