File size: 1,710 Bytes
5218d60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Bounded, offline retrieval for Windows Cybermodels."""

import re
import sqlite3
from contextlib import closing
from pathlib import Path

STOP = frozenset(
    """a an and are as at be by can could did do does for from how i if in is it its my of on one or
should tell that the their there these this to use was what when where which why will windows with would""".split()
)


def retrieve(database: Path, question: str):
    words = dict.fromkeys(
        t
        for t in re.findall(r"[a-z0-9_]+", question.lower())
        if t not in STOP and len(t) > 1
    )
    if not words:
        return []
    query = " OR ".join(f'"{term}"' for term in list(words)[:64])
    with closing(
        sqlite3.connect(database.resolve().as_uri() + "?mode=ro", uri=True)
    ) as db:
        rows = db.execute(
            "SELECT title, body, url, source FROM passages WHERE passages MATCH ? "
            "ORDER BY bm25(passages, 3, 1, 0, 0), rowid LIMIT 10",
            (query,),
        )
        hits = []
        for title, body, url, source in rows:
            if any(hit["id"] == source for hit in hits):
                continue
            hits.append(dict(id=source, title=title, body=body, url=url))
            if len(hits) == 2:
                break
    return hits


def evidence_prompt(question, hits):
    evidence = "\n\n".join(f"[{h['title']}]({h['url']})\n{h['body']}" for h in hits)
    return (
        "Answer the Windows question concisely. Use the applicable reference and cite its link. "
        "If the references do not establish the answer, identify the missing information.\n\n"
        + (evidence or "(No matching reference.)")
        + "\n\nQuestion: "
        + question
    )