File size: 3,305 Bytes
c7f2c56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""Rebuild one specialist's exact examples and offline FTS index from its source file."""

import hashlib
import json
import sqlite3
import tempfile
import tomllib
from contextlib import closing
from pathlib import Path

from grounding import prompt
from runtime.reference import retrieve


def index(path, cards):
    with closing(sqlite3.connect(path)) as db, db:
        db.execute(
            "CREATE VIRTUAL TABLE passages USING fts5(title,body,url UNINDEXED,source UNINDEXED,tokenize='porter unicode61')"
        )
        db.executemany(
            "INSERT INTO passages VALUES(?,?,?,?)",
            ((c["title"], c["notes"], c["url"], c["id"]) for c in cards),
        )


def build(root):
    data = root / "data"
    config = tomllib.loads((data / "specialist.toml").read_text())
    cards = config["source"]
    for card in cards:
        card["url"] = config["source_root"] + card["path"]
    with tempfile.TemporaryDirectory(dir=root) as temp:
        temp = Path(temp)
        index(temp / "references.sqlite", cards)
        index(
            temp / "training.sqlite",
            [c for c in cards if c.get("split", "train") == "train"],
        )
        records = []
        for card in cards:
            split = card.get("split", "train")
            db = temp / ("training.sqlite" if split == "train" else "references.sqlite")
            for question, answer in card["qa"]:
                key = hashlib.sha256(question.encode()).hexdigest()[:16]
                for condition in ("closed", "rag"):
                    hits = retrieve(db, question) if condition == "rag" else []
                    target = answer
                    if condition == "rag":
                        if any(h["id"] == card["id"] for h in hits):
                            target += f" [{card['title']}]({card['url']})"
                        else:
                            target = (
                                "The retrieved references do not establish that. I need a source on "
                                + card["title"]
                                + "."
                            )
                    records.append(
                        dict(
                            id=key,
                            passage=card["id"],
                            condition=condition,
                            split=split,
                            question=question,
                            answer=target,
                            retrieved=[h["id"] for h in hits],
                            prompt=prompt(config, question, hits)
                            if condition == "rag"
                            else f"Answer the {config['topic']} question concisely.\nQuestion: {question}",
                        )
                    )
        for name, subset in (
            ("examples", records),
            ("train", [r for r in records if r["split"] == "train"]),
            ("eval", [r for r in records if r["split"] == "test"]),
        ):
            (data / (name + ".jsonl")).write_text(
                "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in subset)
            )
        (temp / "references.sqlite").replace(root / "references.sqlite")
    return records


if __name__ == "__main__":
    build(Path(__file__).resolve().parent)