NSK: A Neural-Symbolic Knowledge Graph Engine

This chapter builds NSK, a small knowledge graph database that joins two kinds of reasoning. The symbolic side stores facts as triples, answers queries by unification, and derives new facts with rules. The neural side asks a local language model, served by Ollama, when a query has no symbolic answer. Every answer says which of the two sides produced it.

This example is a Hy version of the Common Lisp NSK example in my book Loving Common Lisp, The Savvy Programmer’s Secret Weapon. The Hy version keeps the same design and adds rules, provenance tracking, a third index, log repair, and a larger REST API.

The code for this chapter is in the directory source_code_for_examples/nsk-neural-symbolic-graph.

Project Overview

 1 nsk-neural-symbolic-graph/
 2 ├── nsk/
 3 │   ├── __init__.hy    ← Public names and the ask / rule macros
 4 │   ├── terms.hy       ← Logic variables, neural predicates, unification
 5 │   ├── store.hy       ← Triplestore, indices, append-only log
 6 │   ├── neural.hy      ← Ollama client, inference, text-to-triples
 7 │   ├── query.hy       ← Pattern matching, rules, neural fallback, macros
 8 │   ├── repl.hy        ← Interactive prompt
 9 │   ├── server.hy      ← REST server (standard library only)
10 │   └── __main__.hy    ← Command-line entry point
11 ├── demo.hy            ← Guided tour that prints its results
12 ├── test_nsk.hy        ← Tests (pytest)
13 └── pyproject.toml     ← Dependencies: hy, ollama, pytest

Run the guided tour, the REPL, and the tests like this:

1 uv sync
2 uv run hy demo.hy        # guided tour
3 uv run hy -m nsk         # interactive REPL
4 uv run pytest            # 52 tests, no Ollama needed

The neural features need Ollama running locally with the qwen3.5:4b model. Everything else works with no Ollama daemon. A neural query then prints a short note and returns no solutions.

A First Session

Here is a short REPL session. We add two facts, run a query, join two patterns, add a rule, and then ask a question that only the model can answer:

 1 $ uv run hy -m nsk --memory
 2 NSK: Neural-Symbolic Knowledge Graph Engine
 3 Type :help for commands, :quit to exit.
 4 nsk> (:add :mark :wrote :nsk)
 5 added [:mark :wrote :nsk]
 6 nsk> (:add :mark :codes-in :lisp)
 7 added [:mark :codes-in :lisp]
 8 nsk> [?who :wrote :nsk]
 9 who=:mark
10 nsk> [?a :wrote :nsk] [?a :codes-in ?lang]
11 a=:mark, lang=:lisp
12 nsk> (:rule [?x :author ?y] [?y :wrote ?x])
13 rule added: [?x :author ?y] <- [?y :wrote ?x]
14 nsk> [:nsk :author ?who]
15 who=:mark    ; rule: [:nsk :author :mark]
16 nsk> [?city ~:capital-of :italy]
17 city=:rome    ; neural: [:rome :capital-of :italy]
18 nsk> :facts
19   [:mark :wrote :nsk]
20   [:mark :codes-in :lisp]
21   [:rome :capital-of :italy]    ; neural
22   [:nsk :author :mark]    ; rule
23 (4 triples)
24 nsk> :quit
25 Bye.

The query language has four parts:

You write Meaning
:mark, "text", 42 a term: a keyword, a string, or a number
?person a logic variable
[?p :wrote :nsk] a triple pattern
~:codes-in a neural predicate: ask the model if no stored triple matches

A note such as ; neural: … or ; rule: … after an answer names the triples behind it that are not plain facts. An answer with no note rests on asserted facts alone.

Terms and Unification: terms.hy

The Common Lisp version installs three reader macros to get the ?var, [s p o], and ~pred syntax. Hy needs none. The Hy reader already reads ?person as a symbol, [s p o] as a list, and ~x as the form (unquote x). We only need to give those forms a meaning.

Two small classes carry that meaning at run time:

1 (defclass [(dataclass :frozen True)] Var []
2   "A logic variable. Two variables with the same name are equal."
3   #^ str name
4   (defn __repr__ [self] (+ "?" self.name)))
5 
6 (defclass [(dataclass :frozen True)] Neural []
7   "A predicate that falls back to the language model when no fact matches."
8   #^ object name
9   (defn __repr__ [self] (+ "~" (show self.name))))

A frozen dataclass gives us equality and hashing by name, so we can use a Var as a dict key.

Unification

Unification finds the variable bindings that make two terms equal. An environment is a dict that maps each bound Var to its value. The algorithm follows Peter Norvig’s version in Paradigms of Artificial Intelligence Programming:

 1 (defn walk [x env]
 2   "Follow variable bindings in env until x is a value or an unbound variable."
 3   (while (and (isinstance x Var) (in x env))
 4     (setv x (get env x)))
 5   x)
 6 
 7 (defn unify [x y [env {}]]
 8   "Unify x with y under env. Return the extended environment, or None."
 9   (when (is env None)
10     (return None))
11   (setv x (walk x env)
12         y (walk y env))
13   (cond
14     (= x y) env
15     (isinstance x Var) {#** env  x y}
16     (isinstance y Var) {#** env  y x}
17     (and (isinstance x #(list tuple)) (isinstance y #(list tuple))
18          (= (len x) (len y)))
19       (do
20         (for [[a b] (zip x y)]
21           (setv env (unify a b env)))
22         env)
23     True None))

Two design choices matter here. First, None means failure and the empty dict means success with no bindings, so callers must test with (is env None) and not with truthiness. Second, unify never changes an environment. The form {#** env x y} builds a new dict. The query engine uses generators, and one generator may still be walking a branch of the search while another extends it, so shared mutable state would cause errors.

For example, unifying the pattern [?s :wrote ?o] with the triple [:mark :wrote :nsk] returns the environment {?s :mark, ?o :nsk}.

From Hy Forms to Terms

The REPL and the log replay both receive forms from the Hy reader. The function to-term converts one form to a term and never evaluates it:

 1 (defn to-term [form]
 2   "Convert one form produced by the Hy reader into a term, without evaluating
 3   it. The REPL and the log replay use this, so neither can run code."
 4   (cond
 5     (isinstance form Keyword) (Keyword form.name)
 6     (var-symbol? form) (Var (cut (str form) 1 None))
 7     (unquote? form) (Neural (to-term (get form 1)))
 8     (isinstance form String) (str form)
 9     (isinstance form Integer) (int form)
10     (isinstance form Float) (float form)
11     (isinstance form Symbol)
12       (raise (ValueError f"{form} is not a term; did you mean :{form} or ?{form}"))
13     True (raise (ValueError f"not a term: {(hy.repr form)}"))))

The conversion of String to str is needed because a hy.models.String does not compare equal to a plain Python string with the same text.

The Triplestore: store.hy

A triple is a tuple of subject, predicate, and object. The Graph class keeps every triple in a dict that maps the triple to its source, plus three indices:

 1 (defn __init__ [self [path None]]
 2     (setv self.triples {}        ; triple -> source, in insertion order
 3           self.spo {}            ; subject   -> {triple: None}
 4           self.pos {}            ; predicate -> {triple: None}
 5           self.osp {}            ; object    -> {triple: None}
 6           self.rules []          ; [(head, body) ...]
 7           self.stale False       ; True when rule-derived triples are out of date
 8           self.lock (threading.RLock)
 9           self.path (if path (str path) None)
10           self.log None)
11     (when self.path
12       (setv torn (and (os.path.exists self.path) (self._replay)))
13       (setv self.log (open self.path "a" :encoding "utf-8"))
14       (when torn
15         (self.compact)))     ; rewrite the log without the torn entry
16     None)                    ; Hy returns the last form; __init__ must not

The last line shows a Hy detail. A Hy function returns the value of its last form. Python raises a TypeError when __init__ returns anything other than None, so the method ends with an explicit None.

Each index bucket is a dict used as an ordered set. Python dicts keep insertion order, and removing a key costs Code Test on average. The Common Lisp version stores each bucket as a list, so removal there costs Code Test in the size of the bucket.

Choosing an Index

To match a pattern we first fetch the triples that could match. Each concrete term in the pattern selects one bucket, and we scan the smallest one:

1 (defn candidates [self pattern]
2     "Return the triples that could match pattern, using the smallest bucket
3     among the positions that hold a concrete term."
4     (setv buckets (lfor [index term] (zip #(self.spo self.pos self.osp) pattern)
5                         :if (not (isinstance term #(Var Neural)))
6                         (.get index term {})))
7     (list (if buckets (min buckets :key len) self.triples)))

For the pattern [?who :wrote :nsk] the store compares the :wrote bucket with the :nsk bucket and scans the smaller of the two. A pattern with three variables scans every triple.

Sources

Every triple records where it came from:

  • fact: you asserted it.
  • neural: the language model inferred it.
  • rule: a rule derived it.

The sources have a rank. Adding a triple that is already present changes the graph only when the new source is stronger:

 1 (setv RANK {"rule" 0  "neural" 1  "fact" 2})
 2 
 3 (defn add [self triple [source "fact"]]
 4     "Add a triple. Return True when the graph changed. Adding a triple that is
 5     already present only matters when the new source is stronger, as when you
 6     assert something the model had guessed."
 7     (setv triple (check-triple triple))
 8     (with [self.lock]
 9       (setv old (.get self.triples triple))
10       (when (and old (>= (get RANK old) (get RANK source)))
11         (return False))
12       (self._put triple source)
13       (when (!= source "rule")
14         (setv self.stale True)
15         (self._log (if (= source "neural") "infer" "add") #* triple))
16       True))

So if the model guesses [:mark :codes-in :lisp] and you later assert the same triple, it becomes a fact.

Notice that add takes the triple as one list argument. In a Hy function call, a keyword names a keyword argument, so (graph.add :mark :wrote :nsk) does not compile. We pass triples as lists: (graph.add [:mark :wrote :nsk]). To pass a single keyword to a function, quote it: (to-term ':mark).

The Log

Every change appends one s-expression to the log file and flushes it:

1 (:add :mark :wrote :nsk)
2 (:add :mark :likes "hiking in Sedona")
3 (:add :mark :wrote :a-typo)
4 (:del :mark :wrote :a-typo)
5 (:rule [?book :author ?who] [?who :wrote ?book])

On startup the store reads the log with the Hy reader and replays it:

 1 (defn _replay [self]
 2     "Rebuild the graph from the log. Return True when the log ends in a torn
 3     entry, which is what a crash in the middle of a write leaves behind."
 4     (with [f (open self.path :encoding "utf-8")]
 5       (setv text (.read f)))
 6     (setv torn False)
 7     (try
 8       (for [form (hy.read-many text)]
 9         (self._apply form))
10       (except [hy.PrematureEndOfInput]
11         (print f"; {self.path}: dropped an incomplete final entry" :file sys.stderr)
12         (setv torn True)))
13     (setv self.stale (bool self.rules))
14     torn)

Three properties of this design are worth noting:

  • The Hy reader parses forms and never evaluates them, and _apply converts each argument with to-term. A log file cannot run code. A test checks this with a log entry that holds a print call.
  • If a crash leaves an incomplete final entry, the reader raises hy.PrematureEndOfInput. The store keeps what it read, then rewrites the log so that later entries do not land after the broken one.
  • The store does not log triples that rules derive. It rebuilds them from the rules.

The log grows with every change. The compact method rewrites it to hold only the live state. It writes a temporary file and then calls os.replace, which swaps the files in one step, so a crash leaves either the old log or the new one.

The Query Engine: query.hy

A query is a list of patterns that must all hold. The engine proves them left to right. Each pattern yields one environment for each way it can match, and the next pattern continues from that environment.

 1 (defn match-pattern [pattern env graph [use-model True]]
 2   "Yield (env, support) for every way pattern holds under env. A ~ predicate
 3   is matched symbolically first and sent to the model only when that fails."
 4   (setv [s p o] (resolve pattern env)
 5         fuzzy (isinstance p Neural))
 6   (when fuzzy
 7     (setv p (walk-name p env)))
 8   (setv found False)
 9   (for [triple (graph.candidates #(s p o))]
10     (setv extended (unify #(s p o) triple env))
11     (when (is-not extended None)
12       (setv found True
13             source (.get graph.triples triple "fact"))
14       (yield #(extended (if (= source "fact") #() #(#(triple source)))))))
15   (when (and fuzzy use-model (not found))
16     (setv triple (neural.infer s p o graph))
17     (when triple
18       (setv extended (unify #(s p o) triple env))
19       (when (is-not extended None)
20         (yield #(extended #(#(triple "neural"))))))))

The function yields pairs. The first item is the extended environment. The second is the support: the matched triple and its source, unless the triple is a plain fact. The model is called only for a ~ predicate, and only after the symbolic match finds nothing.

A conjunction is a short recursive generator:

1 (defn prove [patterns env graph [use-model True] [support #()]]
2   "Yield (env, support) for every proof of the conjunction of patterns."
3   (if (not patterns)
4       (yield #(env support))
5       (for [[extended used] (match-pattern (get patterns 0) env graph use-model)]
6         (yield :from (prove (cut patterns 1 None) extended graph use-model
7                             (+ support used))))))

The Common Lisp version builds the full list of solutions with mapcan. Generators compute a solution only when the caller asks for it, so a query with :limit 1 stops after the first proof.

Rules

A rule has a head pattern and one or more body patterns. When the body holds, the head holds. In logic notation, the recursive ancestor rule reads:

math

NSK runs rules forward. Let Code Test be the set of stored triples and let Code Test stand for a set of variable bindings. Each pass adds the head of every rule under every binding that proves its body:

math

The passes stop when Code Test. This always happens, because rules cannot create new terms and so the set of possible triples is finite.

 1 (defn saturate [graph]
 2   "Bring the rule-derived triples up to date."
 3   (when (not graph.stale)
 4     (return))
 5   (for [[triple _] (graph.facts "rule")]
 6     (graph.remove triple))
 7   (setv changed (bool graph.rules))
 8   (while changed
 9     (setv changed False)
10     (for [[head body] graph.rules]
11       (for [[env _] (list (prove body {} graph :use-model False))]
12         (setv triple (resolve head env))
13         (when (and (ground? triple) (graph.add triple "rule"))
14           (setv changed True)))))
15   (setv graph.stale False))

The graph sets its stale flag whenever a fact or a rule changes. The next query calls saturate, which drops the old derived triples and computes them again. This is simple and correct, and it is fast enough for small graphs. A large graph would need an incremental method. The call (list (prove ...)) collects the proofs before the loop adds triples, so the loop never changes an index while a generator reads it. Rules pass :use-model False, so they never call the model.

Because derived triples are stored and indexed like any other triple, a recursive rule needs no special handling at query time.

The ask Macro

In your own code you query with the ask macro:

 1 (import nsk [Graph use-graph])
 2 (require nsk [ask rule])
 3 
 4 (setv graph (use-graph (Graph)))          ; or (Graph "my-graph.log")
 5 (graph.add-all [[:mark :wrote :nsk]
 6                 [:mark :codes-in :lisp]])
 7 
 8 (setv result (ask [?author ?lang]
 9                [?author :wrote :nsk]
10                [?author ~:codes-in ?lang]))
11 
12 (print result)                 ; author=:mark, lang=:lisp
13 (for [row result]              ; each row is a dict keyed by variable name
14   (print (get row "author")))

The macro rewrites each pattern into code that builds a tuple. The helper compile-term does the work:

 1 (defn compile-term [form]
 2   "Macro helper. Like to-term, but it returns code: ?x and ~p are rewritten and
 3   everything else is left for Hy to evaluate, so a pattern can mention ordinary
 4   variables and function calls."
 5   (cond
 6     (var-symbol? form) `(hy.I.nsk/terms.Var ~(cut (str form) 1 None))
 7     (unquote? form) `(hy.I.nsk/terms.Neural ~(compile-term (get form 1)))
 8     ;; A bare keyword in a call would be read as a keyword argument, so quote it.
 9     (isinstance form Keyword) `(quote ~form)
10     True form))

Only ?variables and ~predicates are special. Hy evaluates everything else in a pattern, so a pattern can use local variables:

1 (for [language [:lisp :python :cobol]]
2   (setv coders (ask [?who] [?who :codes-in language]))
3   (print (show language) "->" (show (.column coders "who"))))
1 :lisp -> [:mark]
2 :python -> [:jane]
3 :cobol -> []

The expansion refers to Var through hy.I.nsk/terms.Var. The hy.I form imports a module where it is used, so the macro works in a file that has not imported Var itself.

1 (defmacro ask [select #* body]
2   (setv [patterns options] (hy.I.nsk/query.split-options body))
3   `(hy.I.nsk/query.run-query
4      [~@(map hy.I.nsk/terms.compile-pattern patterns)]
5      [~@(map hy.I.nsk/terms.compile-term select)]
6      ~@options))

Options follow the patterns: :graph g queries a graph other than the default, :limit n stops after n solutions, and :neural False keeps the model out of this query.

Here is the rules section of demo.hy and its output:

1 (graph.add-all [[:ann :parent :bob] [:bob :parent :cy] [:cy :parent :di]])
2 
3 (rule [?x :ancestor ?y]  [?x :parent ?y])
4 (rule [?x :ancestor ?z]  [?x :parent ?y] [?y :ancestor ?z])
5 
6 (print (ask [?d] [:ann :ancestor ?d]))
7 
8 (graph.remove [:bob :parent :cy])
9 (print (ask [?d] [:ann :ancestor ?d]))
1 d=:bob    ; rule: [:ann :ancestor :bob]
2 d=:cy    ; rule: [:ann :ancestor :cy]
3 d=:di    ; rule: [:ann :ancestor :di]
4 d=:bob    ; rule: [:ann :ancestor :bob]

After we remove the fact that links Bob to Cy, the derived triples for Cy and Di are gone.

The Neural Layer: neural.hy

The model does two jobs. It completes a triple when a ~ predicate finds no symbolic match, and it turns free text into triples.

One function talks to Ollama:

 1 (defn chat-json [system prompt schema]
 2   "Send one request to the model and return its reply as a dict. This is the
 3   only function that touches the network; the tests replace it with a fake."
 4   (import ollama)
 5   (setv client (ollama.Client :host (get config "host")
 6                               :timeout (get config "timeout"))
 7         response (client.chat
 8                    :model (get config "model")
 9                    :messages [{"role" "system"  "content" system}
10                               {"role" "user"  "content" prompt}]
11                    :format schema
12                    :think (get config "think")
13                    :options {"temperature" 0}))
14   (or (extract-json response.message.content) {}))

Three arguments shape the reply. The :format argument passes a JSON schema, and Ollama constrains the output to that schema. The :think argument is False by default, which skips the reasoning phase of a thinking model such as qwen3.5. On my laptop a call then takes one to three seconds. A temperature of 0 makes the answers repeatable.

The import sits inside the function. The symbolic engine therefore loads and runs even when the ollama package is missing.

Fallback Inference

The schema for inference allows a string or null:

1 (setv INFER-SCHEMA
2   {"type" "object"
3    "properties" {"result" {"type" ["string" "null"]}}
4    "required" ["result"]})

The infer function handles a pattern that is missing its subject or its object, but not both. It builds a prompt from the facts the graph already holds about the known term. For the query [:jane ~:codes-in ?l] on a graph that knows Jane wrote NSK, the prompt is:

1 Known facts:
2 jane wrote nsk
3 
4 Complete this triple: jane codes-in ???

The rest of infer deals with answers and failures:

  • It records each question and its answer in a memo dict, so a join never asks the same question twice. This includes the answer “unknown”.
  • It converts the model’s text to a keyword with to-keyword, so “Common Lisp” becomes :common-lisp.
  • When (get config "cache") is true, it stores the completed triple in the graph with the source neural. Later queries find it by a normal symbolic match and still report it as inferred.
  • When the call fails, it prints one note and skips further calls for five seconds. A join over many rows then does not try a dead daemon once per row.

Here is the neural section of the demo. No :capital-of facts are stored, so the model supplies them:

1 (graph.add-all [[:mark :visited :france] [:mark :visited :japan]])
2 (print (ask [?country ?capital]
3             [:mark :visited ?country]
4             [?capital ~:capital-of ?country]))
1 country=:france, capital=:paris    ; neural: [:paris :capital-of :france]
2 country=:japan, capital=:tokyo    ; neural: [:tokyo :capital-of :japan]

A small model will sometimes guess wrong. In one test run, the model answered [:jane ~:codes-in ?l] with :nsk, because the only fact it saw about Jane was that she wrote NSK. This is the reason for the labels. Treat a neural answer as a suggestion to check. The REPL command :forget removes every inferred triple.

Text Ingestion

The function text-to-triples sends free text to the model with a schema for a list of triples, converts each name to a keyword, and drops rows with missing fields and repeats. The REPL command (:ingest "text") and the POST /ingest route both use it. Given the text “Jane Doe wrote a book about Python. She lives in Oslo.” the model returned:

1 [:jane-doe :wrote :book]
2 [:book :about :python]
3 [:jane-doe :lives :oslo]

The REPL: repl.hy

The REPL reads each line with hy.read-many and sorts the forms into three kinds:

  • A command such as :facts or (:add :mark :wrote :nsk).
  • One or more bare patterns, which form a query. Patterns on the same line are joined.
  • Anything else, which is ordinary Hy.

The REPL converts commands and bare patterns with to-term and never evaluates them. That is why (:add :mark :wrote :nsk) works at the prompt even though Hy code cannot pass keywords that way.

For ordinary Hy forms the REPL builds a module, loads the macros into it, and evaluates each form there:

1 (defn make-namespace [graph]
2   "Build the module that ordinary Hy forms are evaluated in."
3   (setv module (types.ModuleType "nsk_repl"))
4   (hy.eval '(do (require nsk [ask rule])
5                 (import nsk)
6                 (import nsk [Graph Var Neural show run-query]))
7            :module module)
8   (setv module.graph graph)
9   module)

You can therefore mix queries with normal code at the prompt:

1 nsk> (setv n (len graph))
2 nsk> (+ n 40)
3 => 43
4 nsk> (ask [?a] [?a :wrote :nsk] :limit 1)
5 a=:mark

When a line ends in the middle of a form, hy.read-many raises hy.PrematureEndOfInput. The loop catches it, shows the prompt ...>, and reads another line. Python’s readline module supplies history and line editing, so the REPL needs no wrapper such as rlwrap.

Type :help at the prompt for the full command list. It includes :rules, (:unrule n), :forget, :compact, and (:model "name").

The REST Server: server.hy

The server uses only http.server from the Python standard library. Start it with:

1 uv run hy -m nsk --serve --port 8800
Request Body Effect
GET /health counts and model name
GET /triples every triple with its source
POST /triples {"subject": .., "predicate": .., "object": ..} add a triple
DELETE /triples {"subject": .., "predicate": .., "object": ..} remove a triple
POST /query {"subject": .., "predicate": .., "object": ..} run one pattern
POST /ask {"select": ["?a"], "where": [[s, p, o], ...]} run a join
POST /ingest {"text": ".."} extract and add triples

In JSON, a term is a string. The string "?name" is a variable, a predicate written "~name" is neural, and any other string becomes a keyword. In /query, a field that is null or missing is a variable named after the field.

1 curl -s localhost:8800/ask \
2   -d '{"select": ["?who", "?city"],
3        "where": [["?who", "wrote", "nsk"], ["?city", "~capital-of", "france"]]}'
1 {"count": 1,
2  "results": [{"who": "mark", "city": "paris"}],
3  "provenance": [{"triple": ["paris", "capital-of", "france"], "source": "neural"}]}

All routing lives in one function, handle, that takes a graph, a method, a path, and a parsed body, and returns a status and a payload. It does no I/O, so most server tests call it directly. The handler class is then small. One method serves all three HTTP verbs:

1 (setv do-GET respond
2         do-POST respond
3         do-DELETE respond)

Hy turns the name do-GET into do_GET, which is the method name that BaseHTTPRequestHandler looks for.

The server listens on 127.0.0.1 unless you pass --host. It has no authentication, so do not expose it to a network you do not trust.

Testing Without a Model

The tests are in test_nsk.hy and run with uv run pytest. They need no Ollama daemon, because they replace chat-json with a fake that returns canned replies:

 1 (defn fake-model [monkeypatch replies]
 2   "Replace the model. replies maps a substring of the prompt to a reply dict.
 3   Returns the list of prompts received."
 4   (setv prompts [])
 5   (defn fake-chat-json [system prompt schema]
 6     (.append prompts prompt)
 7     (for [[fragment reply] (.items replies)]
 8       (when (in fragment prompt)
 9         (return reply)))
10     {"result" None})
11   (monkeypatch.setattr nsk.neural "chat_json" fake-chat-json)
12   prompts)

The fake returns the list of prompts it received, so a test can check both the answer and how often the engine asked:

1 (defn test-neural-fallback-inside-a-join [monkeypatch]
2   (setv prompts (fake-model monkeypatch {"jane codes-in" {"result" "python"}}))
3   (use-graph (authors-graph))
4   (setv result (ask [?a ?l] [?a :wrote :nsk] [?a ~:codes-in ?l]))
5   (assert (= result.rows [{"a" :mark  "l" :lisp} {"a" :jane  "l" :python}]))
6   (assert (= (len prompts) 1)))

Mark has a stored :codes-in fact, so only Jane’s row goes to the model, and the engine asks once.

Differences from the Common Lisp Version

Area Common Lisp NSK Hy NSK
Query syntax three reader macros no reader changes; one ask macro
Patterns terms are literals patterns can hold any Hy expression
Rules none forward-chaining rules, including recursive ones
Provenance none each triple and answer records fact, rule, or neural
Indices subject and object subject, predicate, and object
Search builds all solutions with mapcan generators; :limit stops early
Neural fallback asks for a missing object asks for a missing subject or object and sends known facts
Model output finds the first JSON object in the reply reply constrained by a JSON schema
Log grows without bound :compact rewrites it; a torn final entry is repaired
REPL needs rlwrap for line editing history and editing from readline
REST server Hunchentoot, two routes standard library, seven routes
JSON hand-written reader and writer Python’s json module

Wrap Up

NSK shows one way to combine symbolic and neural methods in about 1,100 lines of Hy. The symbolic engine gives exact, repeatable answers from stored facts and rules. The model fills gaps, and the provenance labels keep its guesses apart from what you asserted.

Here are some ways to extend the example:

  • Replace the full recomputation in saturate with semi-naive evaluation, which uses only the triples added in the last pass.
  • Reorder the patterns of a join so that the pattern with the smallest candidate bucket runs first.
  • Let the model check a triple with no variables, such as [:paris ~:capital-of :france], and answer yes or no.
  • Add a confidence value to each neural triple and let a query set a minimum.