r/SQLv2 • • 1d ago

SQLv2 Lesson 10: same, different, or not sure? 'Wireless mouse' isn't wrong, it just doesn't say which mouse. Read NLI both ways and one query sorts an invoice into book / ask / reject (beginner, real output)

Lesson 10 of the beginner series, run on SynapCores 2.5.1 this morning. (This sub is run by the SynapCores team.)

Lesson 9 homework, answered: 'Wireless mouse' matches 'Wireless mouse, black' at 0.77. The contradiction check doesn't flag it (0.01 / 0.00), and it shouldn't: it isn't a different mouse. But nothing on the line says it's the black one. Full output under Lesson 9.

Step 1: this week's invoice

Lesson 9's 13 lines plus 4 that leave out a detail: 'Wireless mouse', 'USB-C laptop charger' (no wattage), '27-inch monitor' (4K?), 'Mechanical keyboard' (layout?). INSERTs in the first comment.

All four are at list price and nothing contradicts, so Lessons 8 and 9 book them. Line 16 could be a 1080p monitor at your 4K price.

Step 2: three numbers, two directions

NLI_CLASSIFY scores entailment, neutral and contradiction. Lesson 9 read contradiction. Now the other two, one each way:

SELECT
  ROUND(JSON_EXTRACT(NLI_CLASSIFY('nli-default',
    'Wireless mouse, black', 'Wireless mouse'), '$.scores.entailment'), 2) AS e1,
  ROUND(JSON_EXTRACT(NLI_CLASSIFY('nli-default',
    'Wireless mouse', 'Wireless mouse, black'), '$.scores.neutral'), 2) AS n2;

e1 0.52  n2 1.00

e1: your black mouse is a wireless mouse, so your item implies the line. n2: a wireless mouse may or may not be black, so the line leaves your item open. Both over 0.5 = a vaguer version of your item.

Step 3: three outcomes in one query

Lesson 8's best match, one NLI call each way, three numbers read from them:

WITH best AS (... same as Lesson 8 ...),
checked AS (
  SELECT i.line, b.id, i.item, c.name, b.sim,
    NLI_CLASSIFY('nli-default', c.name, i.item) AS fwd,
    NLI_CLASSIFY('nli-default', i.item, c.name) AS back
  FROM best b JOIN invoice_lines i ON i.line = b.line JOIN catalog c ON c.id = b.id
  WHERE b.rn = 1),
scored AS (
  SELECT line, id, item, name, sim,
    JSON_EXTRACT(fwd, '$.scores.contradiction') AS c1, JSON_EXTRACT(fwd, '$.scores.entailment') AS e1,
    JSON_EXTRACT(back, '$.scores.contradiction') AS c2, JSON_EXTRACT(back, '$.scores.neutral') AS n2
  FROM checked),
decided AS (
  SELECT line, id, item, name, sim, c1, e1, c2, n2,
    CASE WHEN sim < 0.43 THEN 'NO MATCH'
         WHEN c1 > 0.5 AND c2 > 0.5 THEN 'DIFFERENT'
         WHEN e1 > 0.5 AND n2 > 0.5 THEN 'NOT SURE'
         ELSE 'SAME' END AS outcome
  FROM scored)
SELECT line, item, name, ROUND(sim, 2) AS sim, ROUND(e1, 2) AS e1, ROUND(n2, 2) AS n2, outcome
FROM decided ORDER BY line;

line  invoice line -> your item  sim  e1  n2  outcome
4  UHD 27in display -> 27-inch 4K monitor  0.60  0.99  0.03  SAME
9  Wireless mouse, white -> Wireless mouse, black  0.85  0.00  0.00  DIFFERENT
14  Wireless mouse -> Wireless mouse, black  0.77  0.52  1.00  NOT SURE
15  USB-C laptop charger -> USB-C laptop charger, 65 W  0.81  0.95  1.00  NOT SURE
16  27-inch monitor -> 27-inch 4K monitor  0.83  0.98  1.00  NOT SURE
17  Mechanical keyboard -> Mechanical keyboard, US layout  0.77  0.98  1.00  NOT SURE

All 17 rows in the first comment: the 8 real matches stay SAME, the 4 look-alikes DIFFERENT. NOT SURE needs both numbers: line 4 has e1 0.99 but n2 0.03, because it says everything your monitor says.

Step 4, the payoff: book, ask or reject

Same CTEs, then GROUP BY d.outcome with SUM(i.qty * i.unit_price):

outcome  lines  invoice value
SAME  8  $4,591.00
NOT SURE  4  $2,210.00
DIFFERENT  4  $1,534.00
NO MATCH  1  $480.00

Book $4,591 now. The $2,210 waits for one email: which colour, wattage, resolution, layout?

Homework

The supplier sends 'HDMI cable 2 m, black', 50 at 9.00: more detail than your catalog, not less.

  1. Which item does it match, at what similarity?
  2. SAME, NOT SURE or DIFFERENT?
  3. Which number decides it, e1 or n2?

Reply with your guesses and I'll post the real output.

Free Community Edition: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=sqlv2-lesson-10

Which detail do your suppliers leave off most often: size, colour, model number?

1 Upvotes

2 comments sorted by

1

u/Alternative_Pin9598 1d ago

Already have Lesson 9's tables? Add this week's 4 lines and their vectors (the DELETE clears line 14 if you kept it from Lesson 9's homework):

DELETE FROM invoice_lines WHERE line > 13;
INSERT INTO invoice_lines (line, item, qty, unit_price) VALUES
  (14, 'Wireless mouse', 10, 19.00), (15, 'USB-C laptop charger', 10, 39.00),
  (16, '27-inch monitor', 4, 289.00), (17, 'Mechanical keyboard', 6, 79.00);
UPDATE invoice_lines SET vec = EMBED(item) WHERE line > 13;

Starting fresh? The full script (Python, standard library only) is in the reply below. python3 lesson10.py setup creates both tables with all 17 lines; mouse runs Step 2, check Step 3, summary Step 4, and cleanup drops everything.

All 17 rows of Step 3:

line  invoice line -> your item  sim  e1  n2  outcome
1  Type-C power adapter 65W for notebooks -> USB-C laptop charger, 65 W  0.72  0.90  0.46  SAME
2  Cordless optical mouse, blk -> Wireless mouse, black  0.49  0.02  0.99  SAME
3  2m high speed HDMI lead -> HDMI cable, 2 m  0.64  0.07  0.32  SAME
4  UHD 27in display -> 27-inch 4K monitor  0.60  0.99  0.03  SAME
5  Keyboard w/ mechanical switches, ANSI -> Mechanical keyboard, US layout  0.63  0.01  0.01  SAME
6  Ergonomic mesh office chair -> Aluminium laptop stand  0.37  0.00  0.00  NO MATCH
7  ANC headphones with boom mic -> Noise-cancelling headset with microphone  0.50  0.02  0.16  SAME
8  Dock, USB-C, 2x HDMI out -> USB-C docking station, dual display  0.70  0.00  0.02  SAME
9  Wireless mouse, white -> Wireless mouse, black  0.85  0.00  0.00  DIFFERENT
10  HDMI cable, 5 m -> HDMI cable, 2 m  0.92  0.00  0.00  DIFFERENT
11  USB-C laptop charger, 100 W -> USB-C laptop charger, 65 W  0.90  0.00  0.00  DIFFERENT
12  Mechanical keyboard, UK layout -> Mechanical keyboard, US layout  0.85  0.00  0.00  DIFFERENT
13  Laptop stand, aluminum -> Aluminium laptop stand  0.94  1.00  0.01  SAME
14  Wireless mouse -> Wireless mouse, black  0.77  0.52  1.00  NOT SURE
15  USB-C laptop charger -> USB-C laptop charger, 65 W  0.81  0.95  1.00  NOT SURE
16  27-inch monitor -> 27-inch 4K monitor  0.83  0.98  1.00  NOT SURE
17  Mechanical keyboard -> Mechanical keyboard, US layout  0.77  0.98  1.00  NOT SURE

Step 4 in full (after the same four CTEs as Step 3):

SELECT d.outcome, COUNT(*) AS lines, SUM(i.qty * i.unit_price) AS invoice_value
FROM decided d JOIN invoice_lines i ON i.line = d.line
GROUP BY d.outcome ORDER BY invoice_value DESC;

NLI is a one-time opt-in: synapcores pull nli-default, then synapcores models enable-nli nli-default, both with the --config your server uses, then restart the server.

Ran it from scratch on 2.5.1 and on 2.3.2: same scores, same outcomes.

Same model, different job: Recipe of the week #3 on r/synapcores puts an NLI check in front of a RAG answer, in one SQL statement: https://www.reddit.com/r/synapcores/comments/1xxrm28/

New to SynapCores? Install steps and the 5 recipes to try first: https://www.reddit.com/r/synapcores/comments/1xfxqej/

1

u/Alternative_Pin9598 1d ago

lesson10.py (set SC_URL and SC_TOKEN first):

import json, os, sys, urllib.request, urllib.error
URL = os.environ.get("SC_URL", "http://localhost:8080")
TOK = os.environ["SC_TOKEN"]

def sql(q, ok_fail=False):
    req = urllib.request.Request(URL + "/v1/query/execute", method="POST",
        data=json.dumps({"sql": q, "database": "main"}).encode(),
        headers={"Authorization": "Bearer " + TOK, "content-type": "application/json"})
    try:
        return json.load(urllib.request.urlopen(req, timeout=300))["data"]
    except urllib.error.HTTPError as e:
        if ok_fail: return None
        raise SystemExit(f"{e.code}: {e.read()[:400]}")

CATALOG = [(101, "USB-C laptop charger, 65 W", 39.00), (102, "Wireless mouse, black", 19.00),
           (103, "HDMI cable, 2 m", 9.00), (104, "27-inch 4K monitor", 289.00),
           (105, "Mechanical keyboard, US layout", 79.00), (106, "USB-C docking station, dual display", 129.00),
           (107, "Noise-cancelling headset with microphone", 99.00), (108, "Aluminium laptop stand", 35.00)]
INVOICE = [(1, "Type-C power adapter 65W for notebooks", 10, 41.50), (2, "Cordless optical mouse, blk", 20, 19.00),
           (3, "2m high speed HDMI lead", 50, 9.00), (4, "UHD 27in display", 4, 315.00),
           (5, "Keyboard w/ mechanical switches, ANSI", 6, 79.00), (6, "Ergonomic mesh office chair", 2, 240.00),
           (7, "ANC headphones with boom mic", 8, 99.00), (8, "Dock, USB-C, 2x HDMI out", 5, 129.00),
           (9, "Wireless mouse, white", 10, 19.00), (10, "HDMI cable, 5 m", 20, 14.00),
           (11, "USB-C laptop charger, 100 W", 10, 59.00), (12, "Mechanical keyboard, UK layout", 6, 79.00),
           (13, "Laptop stand, aluminum", 5, 35.00)]
# this week's invoice adds 4 lines that leave a detail out
NEW = [(14, "Wireless mouse", 10, 19.00), (15, "USB-C laptop charger", 10, 39.00),
       (16, "27-inch monitor", 4, 289.00), (17, "Mechanical keyboard", 6, 79.00)]

BEST = """WITH best AS (
  SELECT i.line, c.id, COSINE_SIMILARITY(i.vec, c.vec) AS sim,
    ROW_NUMBER() OVER (PARTITION BY i.line ORDER BY COSINE_SIMILARITY(i.vec, c.vec) DESC) AS rn
  FROM invoice_lines i CROSS JOIN catalog c),
"""
# Lesson 10: one NLI call each way, three numbers read from each
CHECKED = BEST + """checked AS (
  SELECT i.line, b.id, i.item, c.name, b.sim,
    NLI_CLASSIFY('nli-default', c.name, i.item) AS fwd,
    NLI_CLASSIFY('nli-default', i.item, c.name) AS back
  FROM best b JOIN invoice_lines i ON i.line = b.line JOIN catalog c ON c.id = b.id
  WHERE b.rn = 1),
scored AS (
  SELECT line, id, item, name, sim,
    JSON_EXTRACT(fwd, '$.scores.contradiction') AS c1, JSON_EXTRACT(fwd, '$.scores.entailment') AS e1,
    JSON_EXTRACT(back, '$.scores.contradiction') AS c2, JSON_EXTRACT(back, '$.scores.neutral') AS n2
  FROM checked),
decided AS (
  SELECT line, id, item, name, sim, c1, e1, c2, n2,
    CASE WHEN sim < 0.43 THEN 'NO MATCH'
         WHEN c1 > 0.5 AND c2 > 0.5 THEN 'DIFFERENT'
         WHEN e1 > 0.5 AND n2 > 0.5 THEN 'NOT SURE'
         ELSE 'SAME' END AS outcome
  FROM scored)
"""
CHECK = CHECKED + """SELECT line, item, name, ROUND(sim, 2) AS sim, ROUND(e1, 2) AS e1, ROUND(n2, 2) AS n2, outcome
FROM decided ORDER BY line"""
# Step 2: line 14 read both ways
MOUSE = """SELECT
  ROUND(JSON_EXTRACT(NLI_CLASSIFY('nli-default',
    'Wireless mouse, black', 'Wireless mouse'), '$.scores.entailment'), 2) AS e1,
  ROUND(JSON_EXTRACT(NLI_CLASSIFY('nli-default',
    'Wireless mouse', 'Wireless mouse, black'), '$.scores.neutral'), 2) AS n2"""
SUMMARY = CHECKED + """SELECT d.outcome, COUNT(*) AS lines, SUM(i.qty * i.unit_price) AS invoice_value
FROM decided d JOIN invoice_lines i ON i.line = d.line
GROUP BY d.outcome ORDER BY invoice_value DESC"""

def rows(q):
    return sql(q)["rows"]

cmd = sys.argv[1]
if cmd == "setup":
    sql("CREATE TABLE catalog (id INTEGER PRIMARY KEY, name TEXT, list_price FLOAT, vec VECTOR(384))")
    sql("CREATE TABLE invoice_lines (line INTEGER PRIMARY KEY, item TEXT, qty INTEGER, unit_price FLOAT, vec VECTOR(384))")
    sql("INSERT INTO catalog (id, name, list_price) VALUES " +
        ", ".join(f"({i}, '{n}', {p:.2f})" for i, n, p in CATALOG))
    sql("INSERT INTO invoice_lines (line, item, qty, unit_price) VALUES " +
        ", ".join(f"({l}, '{t}', {q}, {p:.2f})" for l, t, q, p in INVOICE + NEW))
    sql("UPDATE catalog SET vec = EMBED(name)")
    sql("UPDATE invoice_lines SET vec = EMBED(item)")
    print("catalog:", rows("SELECT COUNT(*) FROM catalog")[0][0], "invoice lines:", rows("SELECT COUNT(*) FROM invoice_lines")[0][0])
elif cmd == "mouse":
    e1, n2 = rows(MOUSE)[0]
    print(f"e1 {e1:.2f}  n2 {n2:.2f}")
elif cmd == "check":
    print("line  invoice line -> your item  sim  e1  n2  outcome")
    for line, item, name, sim, e1, n2, outcome in rows(CHECK):
        print(f"{line}  {item} -> {name}  {sim:.2f}  {e1:.2f}  {n2:.2f}  {outcome}")
elif cmd == "summary":
    print("outcome  lines  invoice value")
    for outcome, n, value in rows(SUMMARY):
        print(f"{outcome}  {n}  ${value:,.2f}")
elif cmd == "cleanup":
    sql("DROP TABLE invoice_lines", True); sql("DROP TABLE catalog", True)