File size: 11,958 Bytes
2a13a61
847f417
8c7d6b7
 
 
847f417
8c7d6b7
 
 
f7fed5a
8c7d6b7
a37d6ea
151fe23
33812b9
 
847f417
2a13a61
727017f
8c7d6b7
 
 
 
 
727017f
 
 
 
33812b9
151fe23
 
 
 
 
 
727017f
8c7d6b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7fed5a
 
 
 
 
 
 
8c7d6b7
 
ea96ee4
 
 
 
 
 
 
 
 
 
 
8c7d6b7
 
 
ea96ee4
8c7d6b7
 
ea96ee4
8c7d6b7
 
 
 
ea96ee4
727017f
 
8c7d6b7
727017f
 
 
ea96ee4
727017f
847f417
 
 
 
 
 
 
def6dde
 
 
 
 
847f417
 
33812b9
 
 
def6dde
 
 
847f417
8c7d6b7
 
 
ea96ee4
8c7d6b7
 
 
 
ea96ee4
847f417
 
 
 
 
 
 
 
 
151fe23
847f417
151fe23
847f417
151fe23
 
8c7d6b7
 
151fe23
33812b9
151fe23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7d6b7
151fe23
33812b9
 
 
 
 
 
 
 
727017f
 
847f417
8c7d6b7
 
847f417
8c7d6b7
847f417
 
 
 
 
 
 
 
 
 
 
 
2a13a61
8c7d6b7
 
847f417
 
 
33812b9
847f417
 
8c7d6b7
 
ea96ee4
 
8c7d6b7
 
 
 
ea96ee4
847f417
151fe23
847f417
 
33812b9
 
 
a37d6ea
151fe23
 
a37d6ea
 
 
151fe23
 
a37d6ea
151fe23
 
a37d6ea
151fe23
 
 
 
33812b9
151fe23
33812b9
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7d6b7
f7fed5a
 
847f417
 
2a13a61
f7fed5a
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
"""Interactive demo for the lethe memory server (keyword and embedding ranking)."""
import json
import os
import time
import uuid
from types import SimpleNamespace

import gradio as gr
import httpx
from fastembed import TextEmbedding

import benchmark
import eval_external
import eval_nomatch
import eval_posthoc
import eval_recall
import ranking
import rerank
from lethe import Lethe

BASE = "http://127.0.0.1:8787"
TOKEN = "demo"

# Embedding recall fetches this many candidates; the cross-encoder reorders them and the top 5 show.
# A wider pool than the 5 shown lets the reranker lift a right answer the embedding ranked low.
RECALL_K = 5
POOL = 20
NO_MATCH_BELOW = eval_nomatch.app_cutoff()
try:
    _NOMATCH = json.loads(eval_external.NOMATCH_PATH.read_text(encoding="utf-8"))
except FileNotFoundError:
    _NOMATCH = None

EMBED = TextEmbedding(ranking.MODEL)  # 384-dim, runs on CPU via ONNX

SEED = [
    "Priya is allergic to peanuts and avoids anything cooked in groundnut oil.",
    "Priya's flight to Denver leaves on Friday at 7:40 in the morning.",
    "The team agreed to ship the billing fix before the quarterly review.",
    "Marcus prefers meetings after 2 pm because he runs in the morning.",
    "The staging database password rotates every 30 days.",
    "Priya booked a vegetarian meal for the Denver flight.",
    "Marcus will present the fraud dashboard at the quarterly review.",
]

def _wait_ready() -> None:
    for _ in range(50):
        try:
            httpx.get(BASE + "/healthz", timeout=1)
            return
        except httpx.HTTPError:
            time.sleep(0.2)


def embed(text: str) -> list[float]:
    return next(iter(EMBED.embed([text]))).tolist()


def _client(ns: str, with_embeddings: bool = True) -> Lethe:
    # Memories are always stored with an embedding; recall can leave it out to rank by keywords and neighbours only.
    return Lethe(BASE, namespace=ns, token=TOKEN, embed=embed if with_embeddings else None)


_SEEDED: set[str] = set()


def session(request: gr.Request) -> str:
    """Namespace for this visitor, seeded with the sample memories on first use (works for browser and API callers)."""
    ns = "s-" + (request.session_hash or uuid.uuid4().hex)[:10]
    if ns not in _SEEDED:
        with _client(ns) as c:
            for t in SEED:
                c.remember(t)
        _SEEDED.add(ns)
    return ns


def add_memory(text, request: gr.Request):
    if not text.strip():
        return "Nothing to store.", gr.update()
    with _client(session(request)) as c:
        c.remember(text.strip()[:1000])
    return "Stored.", ""


def do_recall(query, explore, use_embeddings, request: gr.Request):
    q = query.strip()[:500]
    if not q:
        return gr.update(choices=[]), "", None
    # Explore deliberately varies the ranking so the server can learn, so rerank only the fixed
    # ranking (explore off): the cross-encoder settles the final order the embedding leaves fragile.
    rerank_on = use_embeddings and not explore
    with _client(session(request), use_embeddings) as c:
        r = c.recall(q, k=POOL if rerank_on else RECALL_K, explore=explore)
    if not r.memories:
        return (
            gr.update(choices=[], value=[]),
            "No memory matched. With embeddings off only shared words match; turn embeddings on to search by meaning.",
            None,
        )
    msg = "Tick the memories that actually answer the question, then send feedback."
    if rerank_on:
        scored = rerank.rerank_with_scores(q, r.memories)[:RECALL_K]
        # Show the cross-encoder score that actually set the order, not the server's embedding score.
        memories = [m for m, _ in scored]
        labels = [f"{(s if s is not None else m.score):.3f}  {m.text}" for m, s in scored]
        best = scored[0][1]
        if best is not None and best < NO_MATCH_BELOW:
            msg = (f"Possible no match: the best relevance score {best:.2f} is below the cutoff "
                   f"{rerank.cutoff_text(NO_MATCH_BELOW)}. These are the nearest stored memories; "
                   "check whether they answer the question.")
    else:
        memories = r.memories
        labels = [f"{m.score:.3f}  {m.text}" for m in memories]
    state = {"id": r.id, "ids": [m.id for m in memories], "labels": labels, "explore": explore}
    return gr.update(choices=labels, value=[]), msg, state


def send_feedback(state, picked, request: gr.Request):
    if not state:
        return "Run a recall first."
    useful = [i for i, lab in zip(state["ids"], state["labels"]) if lab in (picked or [])]
    reward = len(useful) / max(len(state["ids"]), 1)
    with _client(session(request)) as c:
        c.feedback(state["id"], reward, useful=useful, shown=state["ids"])
    if state["explore"]:
        outcome = "the ranking weights were updated"
    else:
        outcome = ("recorded as per-memory usefulness only; the ranking weights learn only from "
                   "recalls made with Explore on")
    return f"Feedback sent: {len(useful)} useful of {len(state['ids'])}, reward {reward:.2f}, {outcome}."


def _stored_results(path, render, missing="Not measured yet.") -> str:
    try:
        results = json.loads(path.read_text(encoding="utf-8"))
    except FileNotFoundError:
        return missing
    return render(results)


def _recall_eval_summary(results) -> str:
    return ("### Measured on the frozen 60-question set (old demo weights: keyword 0.1, semantic 4)\n\n"
            + eval_recall.table(results) + "\n\n" + eval_recall.paired_table(results)
            + "\n\n#### No-match flag on the in-house set\n\n" + eval_recall.nomatch_table(results, NO_MATCH_BELOW))


def _external_summary(results) -> str:
    return (
        f"Retrieval only, one memory per turn. LongMemEval_S (MIT, pinned revision "
        f"`{eval_external.LME_REVISION}`) and LoCoMo (CC BY-NC 4.0, pinned commit "
        f"`{eval_external.LOCOMO_REVISION}`) use a frozen sample "
        f"(SHA-256 `{results['sample_sha256']}`). The tables report the test splits, "
        "measured on HF Jobs. A run takes tens of minutes, so results are shown from the stored run.\n\n"
        + eval_external.table(results) + "\n\n### No-match check\n\n"
        + (eval_external.nomatch_table(_NOMATCH) if _NOMATCH else "Not measured yet.")
    )


with gr.Blocks(title="lethe: agent memory server") as demo:
    gr.Markdown(
        "# lethe: agent memory server with a feedback-trained ranking\n"
        "Real Go server running in this Space. On frozen public test splits (Outside benchmarks tab), weights learned "
        "from feedback beat the server's starting weights on LoCoMo and tie on LongMemEval. Fitting the same weights "
        "directly on the dev questions gives a mixed comparison (a tie on Recall@10, each wins NDCG@10 on one set), "
        "so the feedback loop is not shown to be the better fit. The app starts from "
        "the server's default weights, chosen by a rule fixed in advance on dev questions only. The old hand-set "
        "weights lost on both public sets, and the reranker does not fully make up for them (it is behind on "
        "LoCoMo Recall@10). The in-house tabs were measured with those old weights. "
        "[Code](https://github.com/shaikn6/lethe), MIT. "
        "Embeddings come from a small CPU model; switch them off to see keyword-only ranking. "
        f"With embeddings on and explore off, a cross-encoder ({rerank.MODEL}) reorders the "
        "recalled candidates by relevance."
    )
    state = gr.State(None)
    with gr.Tab("Recall and feedback"):
        q = gr.Textbox(label="Question", placeholder="What can Priya not eat?")
        gr.Examples(examples=[
            "What can Priya not eat?",
            "Who is presenting at the quarterly review?",
            "Who should avoid nuts?",
            "How often does the staging password change?",
            "xqzv blorp fnord",
        ], inputs=[q])
        explore = gr.Checkbox(
            False,
            label="Explore (needed for learning: the ranking weights update only from feedback on "
                  "explore-on recalls; results vary run to run and the reranker is skipped)",
        )
        emb = gr.Checkbox(True, label=f"Use embeddings ({ranking.MODEL}). Off = keyword and neighbour ranking only")
        go = gr.Button("Recall", variant="primary")
        note = gr.Markdown()
        picks = gr.CheckboxGroup(
            label="Top 5 (score, memory)", choices=[],
            info="Score: with the reranker, the cross-encoder's raw relevance logit, higher is more relevant "
                 f"(a best score below {rerank.cutoff_text(NO_MATCH_BELOW)} is flagged as no match); "
                 "without it, the server's weighted sum of ranking features.",
        )
        fb = gr.Button("Send feedback")
        out = gr.Markdown()
        go.click(do_recall, [q, explore, emb], [picks, note, state])
        fb.click(send_feedback, [state, picks], out)
    with gr.Tab("Add memory"):
        t = gr.Textbox(label="Memory text", lines=2)
        add = gr.Button("Store")
        msg = gr.Markdown()
        add.click(add_memory, [t], [msg, t])
    with gr.Tab("Recall eval"):
        eval_out = gr.Markdown(_stored_results(eval_recall.RESULTS_PATH, _recall_eval_summary))
        eval_btn = gr.Button("Re-run live", variant="primary")
        eval_btn.click(lambda: eval_recall.run(embed), None, eval_out)
        short_summary = _stored_results(eval_nomatch.RESULTS_PATH, eval_nomatch.table, missing="")
        if short_summary:
            gr.Markdown("#### No-match cutoff for short memories\n\n" + short_summary)
    with gr.Tab("Benchmark"):
        bench_out = gr.Markdown(_stored_results(benchmark.BENCHMARK_PATH, benchmark.benchmark_table))
        bench_btn = gr.Button("Re-run live", variant="primary")
        bench_btn.click(lambda: benchmark.run_rerank_benchmark(embed), None, bench_out)
    with gr.Tab("Learning loop"):
        gr.Markdown(
            "Simulated feedback trains the ranking weights on the first two stores of the frozen "
            "recall set. The other three stores are used to measure recall on fresh servers."
        )
        learn_out = gr.Markdown(_stored_results(benchmark.LEARNING_PATH, benchmark.learning_table))
        learn_btn = gr.Button("Re-run live", variant="primary")
        learn_btn.click(lambda: benchmark.run_learning_demo(embed), None, learn_out)
    with gr.Tab("Outside benchmarks"):
        gr.Markdown(_stored_results(
            eval_external.RESULTS_PATH, _external_summary,
            "Not measured yet. The LongMemEval_S and LoCoMo test samples are frozen in "
            "`eval/external_sample.json`.",
        ))
        posthoc_summary = _stored_results(
            eval_posthoc.RESULTS_PATH,
            lambda results: "\n\n".join((
                eval_posthoc.decision_table(results), eval_posthoc.table(results),
                "Old demo weights + reranker minus default weights without it:\n\n"
                + eval_external.rerank_vs_default(results), eval_posthoc.auroc_table(results),
            )),
            missing="",
        )
        if posthoc_summary:
            gr.Markdown("### Post-hoc rows (round 3)\n\n\"Demo\" below means the old demo weights (keyword 0.1, semantic 4). "
                        "The cutoffs on this tab were set on long conversation turns and are reported for the "
                        f"outside sets only; the app flags a possible no match below {rerank.cutoff_text(NO_MATCH_BELOW)}, "
                        "the cutoff set on short memories (Recall eval tab).\n\n" + posthoc_summary)

if __name__ == "__main__":
    _wait_ready()
    embed("warm up")
    rerank.rerank_with_scores("warm up", [SimpleNamespace(text="first"), SimpleNamespace(text="second")])
    ranking.apply(BASE, os.environ["LETHE_ADMIN_TOKEN"])
    demo.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")))