db-chat-widget
Embeddable chatbot widget that lets end users ask natural-language questions about a SQL database and get back answers with the underlying query and data.
- Any SQLAlchemy-compatible database: PostgreSQL, MySQL, SQLite, etc.
- Pluggable LLM backend: Anthropic Claude, OpenAI, Groq, or a local Ollama model.
- Read-only by default: generated SQL is parsed and only
SELECTstatements are allowed unless you explicitly opt into write access. - Embeddable widget: a small vanilla-JS chat component you can drop into
any existing web page with a single
<script>tag, backed by a FastAPI server. - Holds a real conversation: remembers prior turns per visitor session (a server-side, cookie-backed store) — not just database questions, ordinary chit-chat too — and always replies in whatever language the visitor is writing in.
Install
pip install "db-chat-widget[server]"
This includes every LLM provider (Anthropic, OpenAI, Groq, Ollama), every
database driver (PostgreSQL, MySQL), and the standalone FastAPI server + CLI
serve command used below. Pick which provider and database to use
afterwards, at configuration time, via --llm-provider / Settings.llm_provider
and --db-url / Settings.db_url.
If you only need the ChatEngine as a library — e.g. from
django-db-chat-widget,
which brings its own web layer — pip install db-chat-widget (without
[server]) skips FastAPI/uvicorn/Jinja2 entirely.
Quickstart
export DB_CHAT_LLM_API_KEY=gsk_... # your Groq API key
db-chat-widget serve \
--db-url "postgresql://user:pass@localhost/mydb" \
--llm-provider groq \
--port 8000
(--llm-provider anthropic / openai work the same way, with the matching API key.)
Open http://127.0.0.1:8000 for a demo chat page, or embed the widget in your own site.
Popup mode (floating chat bubble)
Drops a chat bubble launcher into the bottom-right corner of the page — the most common way to bolt this onto an existing template with zero markup changes. Clicking it opens/closes the chat panel.
<link rel="stylesheet" href="http://127.0.0.1:8000/static/widget.css" />
<script
src="http://127.0.0.1:8000/static/widget.js"
data-mode="bubble"
data-api-url="http://127.0.0.1:8000/api/chat"
data-title="Ask about our data"
></script>
Use data-position="bottom-left" to anchor it to the bottom-left instead.
Inline mode
Embeds the chat panel directly into an element already on the page, instead of floating:
<link rel="stylesheet" href="http://127.0.0.1:8000/static/widget.css" />
<div id="my-db-chat"></div>
<script
src="http://127.0.0.1:8000/static/widget.js"
data-target="#my-db-chat"
data-api-url="http://127.0.0.1:8000/api/chat"
data-title="Ask about our data"
></script>
Programmatic API
Both modes are also available from JavaScript, e.g. after dynamically
injecting the script, or to control the popup (.open() / .close()):
<script src="http://127.0.0.1:8000/static/widget.js"></script>
<script>
const chat = DBChatWidget.init({
mode: "bubble", // or "inline" (requires `target`)
apiUrl: "http://127.0.0.1:8000/api/chat",
title: "Ask about our data",
position: "bottom-right", // or "bottom-left"
});
// chat.open(); chat.close(); chat.ask("How many orders today?");
</script>
See examples/embed_example.html and
examples/demo_app.py for a runnable, self-contained
example with a seeded SQLite database.
Using it as a library
from db_chat_widget import ChatEngine, Settings
settings = Settings(
db_url="sqlite:///mydb.sqlite",
llm_provider="groq",
llm_api_key="gsk_...",
read_only=True, # default: only SELECT statements are allowed
max_rows=200, # cap on rows returned per query
allowed_tables=None, # optionally restrict which tables can be queried
history_max_turns=10, # conversation turns kept for context; 0 disables memory
)
engine = ChatEngine(settings)
result = engine.ask("How many orders were placed last month?")
print(result.answer)
print(result.sql)
print(result.rows)
# Continue the conversation by passing back prior turns yourself — ChatEngine
# holds no state between calls (the FastAPI server and django-db-chat-widget
# do this for you automatically via a session):
history = [
{"role": "user", "content": "How many orders were placed last month?"},
{"role": "assistant", "content": result.answer},
]
follow_up = engine.ask("And the month before that?", history=history)
To mount just the FastAPI app (e.g. behind your own ASGI server or reverse proxy):
from db_chat_widget.config import Settings
from db_chat_widget.server.app import create_app
app = create_app(Settings(db_url="...", llm_provider="openai", llm_api_key="..."))
How it works
- The database schema (tables, columns, types, foreign keys) is introspected
via SQLAlchemy and sent to the configured LLM as context, along with the
last
history_max_turnsturns of the conversation for continuity. - The LLM classifies the message into one of three replies, always in the
visitor's own language: a SQL
SELECTstatement (a data question), a free conversational reply prefixed withCHAT:(a greeting, small talk, or any general, non-data question — answered directly, no query is run), orCANNOT_ANSWER(a data question the schema can't answer). - For SQL replies, the query is parsed with
sqlglotand rejected if it contains anything other than a single read-onlySELECT(noINSERT/UPDATE/DELETE/DROP/multiple statements/disallowed tables). - The query is executed with a row limit, and the LLM is asked to phrase a short, natural-language answer from the actual result rows — again in the visitor's language.
Default encoding
MySQL/MariaDB servers commonly default their client connection to latin1,
which mangles accented characters (e.g. French text) unless the client asks
for UTF-8 explicitly. When your db_url is a MySQL URL without a charset
query parameter, db-chat-widget automatically connects with
charset=utf8mb4:
mysql+pymysql://user:pass@localhost:3306/mydb
# connects as:
mysql+pymysql://user:pass@localhost:3306/mydb?charset=utf8mb4
If your URL already specifies a charset (e.g. ?charset=latin1), it is left
untouched. Other database backends (PostgreSQL, SQLite) already default to
UTF-8 and are not affected.
Safety notes
read_only=True(the default) is enforced at the SQL-parsing level, not just by prompting the model — treat it as the actual security boundary.- Use
allowed_tablesto scope the chatbot to specific tables (e.g. exclude ausers/secretstable containing sensitive columns). - The demo server enables permissive CORS (
*) for convenience; passcors_origins=[...](or--cors-originon the CLI) to restrict this in production. - Run the database user backing
db_urlwith least-privilege, read-only grants where possible, as defense in depth. - The FastAPI server keeps conversation history in an in-memory store keyed
by an opaque,
httponlysession cookie — it isn't shared across visitors, but it also doesn't survive a server restart or scale across multiple worker processes. For production multi-worker deployments, run a single worker or swap in your own shared store (e.g. Redis) ahead ofChatEngine.ask.
Development
pip install -e ".[dev]"
pytest
ruff check .
License
MIT
Metadata
Release files for db-chat-widget 0.2.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| db_chat_widget-0.2.1.tar.gz | 25.3 kB | Without provenance | Details for db_chat_widget-0.2.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| db_chat_widget-0.2.1-py3-none-any.whl | Python 3 | none | any | Details for db_chat_widget-0.2.1-py3-none-any.whl |
Total release size: 54.3 kB
Release files / db_chat_widget-0.2.1.tar.gz
| Download URL | db_chat_widget-0.2.1.tar.gz |
|---|---|
| Size | 25.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
86e002adf06c0c843f834d324ff8c09d6908e0f7ca675559cca2950138e60f9c
|
|
BLAKE2b-256 checksum How to use checksums |
5ac63abfca0480f3c4e1db68239ae761b36ee22ba9ecb5ea9012c04ed0f4866d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.3
|
Release files / db_chat_widget-0.2.1-py3-none-any.whl
| Download URL | db_chat_widget-0.2.1-py3-none-any.whl |
|---|---|
| Size | 29.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d50f8e7db047bd2c9db259673d4859b3e5dc91f886898b28439a8c6f4cede4fc
|
|
BLAKE2b-256 checksum How to use checksums |
595c491a602623abb258d11525fc1426d756aaa4b92abdef513ec0aecd8bff42
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.3
|
Security for db-chat-widget 0.2.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.