Back to browse
GitHub Repository

MegaHAL in pure SQL

3 starsPython

MegaHAL in Pure SQL

by tgies·Feb 19, 2026·1 point·1 comment

AI Analysis

●●●BangerWizardryBig BrainNiche Gem

MegaHAL chatbot runs in pure SQL—no PL/pgSQL escape hatches, just CTEs and recursive queries.

Strengths
  • Entire Markov chain implementation in single SQL statement, no procedural language workaround.
  • Browser demo via PGlite (WASM PostgreSQL) makes it runnable instantly with zero installation.
  • Aesthetic constraint challenge—treating SQL as a complete algorithmic substrate, not just data access.
Weaknesses
  • Pure-SQL implementation is a novelty; the chatbot itself (1998 baseline) produces mediocre output.
  • Narrow audience—most teams would use a library or LLM rather than port legacy algorithms to SQL.
Target Audience

Database enthusiasts, SQL hobbyists, constraint-challenge programmers

Similar To

sql.js-httpvfs · DataWeave

Post Description

I ported Jason Hutchens' 1998 Loebner Prize-winning chatbot, MegaHAL, to run entirely inside PostgreSQL, in pure SQL. The entire lifecycle -- tokenization, learning, keyword extraction, Markov chain generation, and entropy scoring -- is implemented in standard SQL using complex CTEs. There is no PL/pgSQL or any other sort of procedural escape hatch.

Learning is a single ~560-line SQL statement that splits text, interns symbols, and updates two 5th-order Markov tries (forward and backward) using depth-unrolled writable CTEs. A recursive query that generates N candidate replies in parallel. It performs bidirectional weighted random walks, evaluates them for information-theoretic surprise, and formats the winner as a sentence-cased string.

I provided a `docker-compose.yml` and convenient Python driver script so you can try it out quickly, and there's also a web-based demo where I bundled it with PGlite (WASM PostgreSQL) at https://tgies.github.io/megahal-sql/. These are provided for convenience, but you can also just run the schema initialization SQL and `SELECT megahal_converse('hello from hn.');`

Similar Projects

Gaming●●●●Gem

Chess in SQL

Pure SQL chess engine that actually plays, not procedural extensions or C bindings.

WizardryBig BrainRabbit Hole
swingbit
311d ago