Skip to main content

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 SELECT statements 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.

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
)

engine = ChatEngine(settings)
result = engine.ask("How many orders were placed last month?")

print(result.answer)
print(result.sql)
print(result.rows)

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

  1. The database schema (tables, columns, types, foreign keys) is introspected via SQLAlchemy and sent to the configured LLM as context.
  2. The LLM classifies the message into one of three replies: a SQL SELECT statement (a data question), a short conversational reply prefixed with CHAT: (a greeting, thanks, or small talk — answered directly, no query is run), or CANNOT_ANSWER (a data question the schema can't answer).
  3. For SQL replies, the query is parsed with sqlglot and rejected if it contains anything other than a single read-only SELECT (no INSERT/UPDATE/DELETE/DROP/multiple statements/disallowed tables).
  4. The query is executed with a row limit and the result, generated SQL, and a short natural-language summary are returned to the widget.

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_tables to scope the chatbot to specific tables (e.g. exclude a users/secrets table containing sensitive columns).
  • The demo server enables permissive CORS (*) for convenience; pass cors_origins=[...] (or --cors-origin on the CLI) to restrict this in production.
  • Run the database user backing db_url with least-privilege, read-only grants where possible, as defense in depth.

Development

pip install -e ".[dev]"
pytest
ruff check .

License

MIT

Metadata

Release files for db-chat-widget 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for db-chat-widget 0.1.1
File Size Uploaded Provenance Actions
db_chat_widget-0.1.1.tar.gz 21.5 kB Without provenance Details for db_chat_widget-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for db-chat-widget 0.1.1
File Interpreter ABI Platform Actions
db_chat_widget-0.1.1-py3-none-any.whl Python 3 none any Details for db_chat_widget-0.1.1-py3-none-any.whl

Total release size: 46.7 kB

Release files / db_chat_widget-0.1.1.tar.gz

Download URL db_chat_widget-0.1.1.tar.gz
Size 21.5 kB
Tags Source
SHA-256 checksum
How to use checksums
dd1aac5e7c590c62842bf73d2ad9a6077d38e74423c6daf2bb64b1c386db9883
BLAKE2b-256 checksum
How to use checksums
c450e0c4dc25179046bba36cd6b8cb0986c75ba8b12b806a1a10117c69c80214
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.1.1-py3-none-any.whl

Download URL db_chat_widget-0.1.1-py3-none-any.whl
Size 25.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2e8f275cd260ccd1d4272c21176a36afb4bab4c2a267a1a2da552ef115ca1e09
BLAKE2b-256 checksum
How to use checksums
e77c0228ec0bc70dd530d3f89e403e029c9c178374d4f8aba7a7ad81abc394b3
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.1.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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page