@operad-io/memory 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/examples/cases/cat-name.json +7 -0
- package/examples/cases/lisbon-date.json +9 -0
- package/examples/cases/not-in-memory.json +7 -0
- package/examples/cases/old-hotel.json +12 -0
- package/examples/memory/index.md +4 -0
- package/examples/memory/topics/pets.md +3 -0
- package/examples/memory/topics/travel.md +4 -0
- package/memory-case.schema.json +46 -0
- package/package.json +4 -2
- package/src/cases/command.ts +63 -0
- package/src/cases/format.ts +118 -0
- package/src/cases/propose.ts +322 -0
- package/src/cases/score.ts +293 -0
- package/src/commit.ts +75 -4
- package/src/index.ts +17 -0
- package/src/search/backend.ts +10 -5
- package/src/search/command.ts +10 -0
- package/src/search/service.ts +20 -6
- package/src/search/sources.ts +17 -0
- package/src/search/types.ts +15 -0
- package/src/tidy.ts +41 -1
package/README.md
CHANGED
|
@@ -15,3 +15,35 @@ This package is part of [operad](https://github.com/operad-io/operad). Most peop
|
|
|
15
15
|
- Developer reference: `REFERENCE.md` in this directory
|
|
16
16
|
|
|
17
17
|
MIT licensed.
|
|
18
|
+
|
|
19
|
+
## Memory regression set
|
|
20
|
+
|
|
21
|
+
Cases are exchanges where the bot got something wrong or the person corrected it
|
|
22
|
+
(a correction counts as a miss): the context it had, the question and the right
|
|
23
|
+
answer. They contain private chat text, so they live in the operad home
|
|
24
|
+
(`~/.operad/memory-cases/<id>.json`, schema `memory-case.schema.json`), never in
|
|
25
|
+
this repository. `examples/` holds a synthetic set and its memory.
|
|
26
|
+
|
|
27
|
+
- `memory score [--cases <dir>] [--bot <name>] [--memory <dir>] [--window <n>] [--no-record] [--answer-with <program> [args]]`
|
|
28
|
+
runs the set against the bot's current memory and appends the score, the
|
|
29
|
+
settings it was taken under and the per-case pass/fail (ids only) to
|
|
30
|
+
`memory-scores.jsonl` in the home. It prints the change since the last run of
|
|
31
|
+
the same set.
|
|
32
|
+
- `memory propose [--chat <id>]` finds corrections in the chat record and stores
|
|
33
|
+
each as a pending proposal. Approve it with the phrases a right answer states
|
|
34
|
+
(one phrase per line, and optionally the wrong phrases); reject it to drop it.
|
|
35
|
+
Nothing is added to the set without approval.
|
|
36
|
+
|
|
37
|
+
**Scoring is by exact phrases, not a model judge.** A case passes when every phrase
|
|
38
|
+
is stated (ignoring case, spaces and punctuation) and no `avoid` phrase is. A
|
|
39
|
+
judge adds its own drift to a number whose job is to show the memory's drift,
|
|
40
|
+
costs a call per case, and a fixed rubric does not remove either. The phrases are
|
|
41
|
+
short phrases the person approved. The cost is that a right answer in other
|
|
42
|
+
words fails; write the phrase as the part that must not change (a name, a date).
|
|
43
|
+
|
|
44
|
+
The default answerer needs no model: it assembles what the bot would have in
|
|
45
|
+
front of it (the last `--window` messages, as a compaction keeps them; the memory
|
|
46
|
+
index cut at its limit; what a memory search of the question returns, including
|
|
47
|
+
the messages the window dropped) and scores that. `--answer-with` runs a program
|
|
48
|
+
that gets `{question, context, memory}` as JSON on stdin and prints an answer, to
|
|
49
|
+
score a real bot.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "old-hotel",
|
|
3
|
+
"kind": "miss",
|
|
4
|
+
"context": [
|
|
5
|
+
{ "role": "user", "text": "The hotel in Porto is Hotel Aurora." },
|
|
6
|
+
{ "role": "assistant", "text": "Noted." },
|
|
7
|
+
{ "role": "user", "text": "Also book a taxi." },
|
|
8
|
+
{ "role": "assistant", "text": "Done." }
|
|
9
|
+
],
|
|
10
|
+
"question": "Which hotel did I say in Porto?",
|
|
11
|
+
"answer": { "include": ["Hotel Aurora"] }
|
|
12
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://operad.io/schemas/memory-case.schema.json",
|
|
4
|
+
"title": "operad memory regression case",
|
|
5
|
+
"description": "One case of the memory regression set: an exchange where the bot got something wrong or the person corrected it. The file is named <id>.json.",
|
|
6
|
+
"type": "object",
|
|
7
|
+
"required": ["id", "kind", "question", "answer"],
|
|
8
|
+
"additionalProperties": false,
|
|
9
|
+
"properties": {
|
|
10
|
+
"$schema": { "type": "string" },
|
|
11
|
+
"id": { "type": "string", "pattern": "^[a-z0-9][a-z0-9_-]{0,63}$" },
|
|
12
|
+
"kind": { "enum": ["miss", "correction"], "description": "A correction counts as a miss." },
|
|
13
|
+
"context": {
|
|
14
|
+
"type": "array",
|
|
15
|
+
"description": "The messages before the question, oldest first.",
|
|
16
|
+
"items": {
|
|
17
|
+
"type": "object",
|
|
18
|
+
"required": ["role", "text"],
|
|
19
|
+
"additionalProperties": false,
|
|
20
|
+
"properties": {
|
|
21
|
+
"role": { "enum": ["user", "assistant"] },
|
|
22
|
+
"text": { "type": "string" }
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"question": { "type": "string", "minLength": 1 },
|
|
27
|
+
"answer": {
|
|
28
|
+
"type": "object",
|
|
29
|
+
"required": ["include"],
|
|
30
|
+
"additionalProperties": false,
|
|
31
|
+
"properties": {
|
|
32
|
+
"include": {
|
|
33
|
+
"type": "array",
|
|
34
|
+
"minItems": 1,
|
|
35
|
+
"items": { "type": "string", "minLength": 1 },
|
|
36
|
+
"description": "Short phrases a right answer states. Matched ignoring case, spaces and punctuation."
|
|
37
|
+
},
|
|
38
|
+
"avoid": {
|
|
39
|
+
"type": "array",
|
|
40
|
+
"items": { "type": "string", "minLength": 1 },
|
|
41
|
+
"description": "Phrases of the wrong answer; an answer that states one fails."
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@operad-io/memory",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": "./src/index.ts"
|
|
7
7
|
},
|
|
8
8
|
"dependencies": {
|
|
9
|
-
"@operad-io/engine": "0.
|
|
9
|
+
"@operad-io/engine": "0.4.0"
|
|
10
10
|
},
|
|
11
11
|
"description": "operad: the memory plugin and the wiki",
|
|
12
12
|
"repository": {
|
|
@@ -19,6 +19,8 @@
|
|
|
19
19
|
"src",
|
|
20
20
|
"skills",
|
|
21
21
|
"memory.schema.json",
|
|
22
|
+
"memory-case.schema.json",
|
|
23
|
+
"examples",
|
|
22
24
|
"README.md",
|
|
23
25
|
"LICENSE"
|
|
24
26
|
]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** The `memory score` and `memory propose` verbs. */
|
|
2
|
+
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { CommandContext } from "@operad-io/engine";
|
|
5
|
+
import { CaseError } from "./format.ts";
|
|
6
|
+
import { CASES_DIRECTORY, proposeCases } from "./propose.ts";
|
|
7
|
+
import { programAnswerer, runScore, scoreText } from "./score.ts";
|
|
8
|
+
|
|
9
|
+
/** `memory score [--cases <dir>] [--bot <name>] [--memory <dir>] [--window <n>] [--no-record] [--answer-with <program> [args]]` */
|
|
10
|
+
export async function runMemoryScore(ctx: CommandContext, argv: readonly string[]): Promise<string> {
|
|
11
|
+
let casesDir = join(ctx.home, CASES_DIRECTORY);
|
|
12
|
+
let bot: string | undefined;
|
|
13
|
+
let memory: string | undefined;
|
|
14
|
+
let window: number | undefined;
|
|
15
|
+
let record = true;
|
|
16
|
+
let program: readonly string[] | undefined;
|
|
17
|
+
const value = (at: number, flag: string): string => {
|
|
18
|
+
const next = argv[at + 1];
|
|
19
|
+
if (next === undefined || next.length === 0) throw new CaseError(`${flag} takes a value`);
|
|
20
|
+
return next;
|
|
21
|
+
};
|
|
22
|
+
for (let at = 0; at < argv.length; at += 1) {
|
|
23
|
+
const arg = argv[at] ?? "";
|
|
24
|
+
if (arg === "--cases") casesDir = value(at++, arg);
|
|
25
|
+
else if (arg === "--bot") bot = value(at++, arg);
|
|
26
|
+
else if (arg === "--memory") memory = value(at++, arg);
|
|
27
|
+
else if (arg === "--window") window = Number(value(at++, arg));
|
|
28
|
+
else if (arg === "--no-record") record = false;
|
|
29
|
+
else if (arg === "--answer-with") {
|
|
30
|
+
program = argv.slice(at + 1);
|
|
31
|
+
if (program.length === 0) throw new CaseError("--answer-with takes a program");
|
|
32
|
+
break;
|
|
33
|
+
} else throw new CaseError(`score does not take "${arg}"`);
|
|
34
|
+
}
|
|
35
|
+
const run = await runScore({
|
|
36
|
+
home: ctx.home,
|
|
37
|
+
casesDir,
|
|
38
|
+
settings: ctx.settings,
|
|
39
|
+
...(bot === undefined ? {} : { bot }),
|
|
40
|
+
...(memory === undefined ? {} : { memory }),
|
|
41
|
+
...(window === undefined ? {} : { window }),
|
|
42
|
+
...(program === undefined ? {} : { answerer: programAnswerer(program), answererName: program.join(" ") }),
|
|
43
|
+
now: () => Date.now(),
|
|
44
|
+
record,
|
|
45
|
+
});
|
|
46
|
+
return scoreText(run);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** `memory propose [--chat <id>]`: stores a pending proposal for each correction in the chat record. */
|
|
50
|
+
export async function runMemoryPropose(ctx: CommandContext, argv: readonly string[]): Promise<string> {
|
|
51
|
+
let chat: string | undefined;
|
|
52
|
+
for (let at = 0; at < argv.length; at += 1) {
|
|
53
|
+
const arg = argv[at] ?? "";
|
|
54
|
+
if (arg === "--chat") {
|
|
55
|
+
chat = argv[++at];
|
|
56
|
+
if (chat === undefined || chat.length === 0) throw new CaseError("--chat takes a chat id");
|
|
57
|
+
} else throw new CaseError(`propose does not take "${arg}"`);
|
|
58
|
+
}
|
|
59
|
+
const made = await proposeCases(ctx.store, { home: ctx.home, ...(chat === undefined ? {} : { chat }), now: () => Date.now() });
|
|
60
|
+
return made.length === 0
|
|
61
|
+
? "no new corrections to propose\n"
|
|
62
|
+
: `proposed ${made.length} test case${made.length === 1 ? "" : "s"}; they wait in pending for the phrases a right answer states\n`;
|
|
63
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The memory regression set: one case is one exchange where the bot got
|
|
3
|
+
* something wrong or the person corrected it. A case holds the context the bot
|
|
4
|
+
* had, the question and the right answer. The case files live in the operad
|
|
5
|
+
* home (they contain private chat text); the repository holds only this format,
|
|
6
|
+
* the runner and a synthetic example set.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { isRecord } from "@operad-io/engine";
|
|
12
|
+
|
|
13
|
+
/** A case file that cannot be used; the message says which and why. */
|
|
14
|
+
export class CaseError extends Error {
|
|
15
|
+
constructor(message: string) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "CaseError";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Why the case exists: the bot answered wrong, or the person corrected it. A correction counts as a miss. */
|
|
22
|
+
export const CASE_KINDS = ["miss", "correction"] as const;
|
|
23
|
+
export type CaseKind = (typeof CASE_KINDS)[number];
|
|
24
|
+
|
|
25
|
+
/** One earlier message of the chat the bot had in front of it. */
|
|
26
|
+
export interface CaseMessage {
|
|
27
|
+
readonly role: "user" | "assistant";
|
|
28
|
+
readonly text: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The right answer: phrases an answer must state, and wrong phrases it must not repeat. */
|
|
32
|
+
export interface CaseAnswer {
|
|
33
|
+
readonly include: readonly string[];
|
|
34
|
+
readonly avoid: readonly string[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** One case, as `<id>.json` holds it. */
|
|
38
|
+
export interface MemoryCase {
|
|
39
|
+
readonly id: string;
|
|
40
|
+
readonly kind: CaseKind;
|
|
41
|
+
/** The messages before the question, oldest first. */
|
|
42
|
+
readonly context: readonly CaseMessage[];
|
|
43
|
+
readonly question: string;
|
|
44
|
+
readonly answer: CaseAnswer;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The file name pattern of a case id. */
|
|
48
|
+
export const CASE_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
49
|
+
|
|
50
|
+
function textList(value: unknown, name: string, file: string, required: boolean): readonly string[] {
|
|
51
|
+
if (value === undefined && !required) return [];
|
|
52
|
+
if (!Array.isArray(value)) throw new CaseError(`${file}: ${name} must be a list of text`);
|
|
53
|
+
const found: string[] = [];
|
|
54
|
+
for (const item of value) {
|
|
55
|
+
if (typeof item !== "string" || item.trim().length === 0) {
|
|
56
|
+
throw new CaseError(`${file}: ${name} holds only non-empty text`);
|
|
57
|
+
}
|
|
58
|
+
found.push(item);
|
|
59
|
+
}
|
|
60
|
+
if (required && found.length === 0) throw new CaseError(`${file}: ${name} needs at least one entry`);
|
|
61
|
+
return found;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Checks one parsed case; `file` names it in an error. */
|
|
65
|
+
export function parseCase(value: unknown, file: string): MemoryCase {
|
|
66
|
+
if (!isRecord(value)) throw new CaseError(`${file}: a case is an object`);
|
|
67
|
+
const id = value["id"];
|
|
68
|
+
if (typeof id !== "string" || !CASE_ID.test(id)) {
|
|
69
|
+
throw new CaseError(`${file}: id must be lowercase letters, digits, - and _`);
|
|
70
|
+
}
|
|
71
|
+
const kind = value["kind"];
|
|
72
|
+
if (kind !== "miss" && kind !== "correction") throw new CaseError(`${file}: kind is "miss" or "correction"`);
|
|
73
|
+
const question = value["question"];
|
|
74
|
+
if (typeof question !== "string" || question.trim().length === 0) {
|
|
75
|
+
throw new CaseError(`${file}: question must be non-empty text`);
|
|
76
|
+
}
|
|
77
|
+
const rawContext = value["context"] ?? [];
|
|
78
|
+
if (!Array.isArray(rawContext)) throw new CaseError(`${file}: context must be a list of messages`);
|
|
79
|
+
const context: CaseMessage[] = rawContext.map((entry) => {
|
|
80
|
+
if (!isRecord(entry) || (entry["role"] !== "user" && entry["role"] !== "assistant") || typeof entry["text"] !== "string") {
|
|
81
|
+
throw new CaseError(`${file}: a context message is { role: "user" | "assistant", text }`);
|
|
82
|
+
}
|
|
83
|
+
return { role: entry["role"], text: entry["text"] };
|
|
84
|
+
});
|
|
85
|
+
const answer = value["answer"];
|
|
86
|
+
if (!isRecord(answer)) throw new CaseError(`${file}: answer is { include, avoid? }`);
|
|
87
|
+
return {
|
|
88
|
+
id,
|
|
89
|
+
kind,
|
|
90
|
+
context,
|
|
91
|
+
question,
|
|
92
|
+
answer: {
|
|
93
|
+
include: textList(answer["include"], "answer.include", file, true),
|
|
94
|
+
avoid: textList(answer["avoid"], "answer.avoid", file, false),
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Every `*.json` case in a directory, by file name; an unusable file is an error, never skipped. */
|
|
100
|
+
export function loadCases(directory: string): readonly MemoryCase[] {
|
|
101
|
+
if (!existsSync(directory)) throw new CaseError(`there is no case directory at ${directory}`);
|
|
102
|
+
const cases: MemoryCase[] = [];
|
|
103
|
+
const seen = new Set<string>();
|
|
104
|
+
for (const name of readdirSync(directory).filter((entry) => entry.endsWith(".json")).sort()) {
|
|
105
|
+
let parsed: unknown;
|
|
106
|
+
try {
|
|
107
|
+
parsed = JSON.parse(readFileSync(join(directory, name), "utf8"));
|
|
108
|
+
} catch {
|
|
109
|
+
throw new CaseError(`${name}: not valid JSON`);
|
|
110
|
+
}
|
|
111
|
+
const found = parseCase(parsed, name);
|
|
112
|
+
if (found.id !== name.slice(0, -".json".length)) throw new CaseError(`${name}: id "${found.id}" must match the file name`);
|
|
113
|
+
if (seen.has(found.id)) throw new CaseError(`${name}: duplicate id "${found.id}"`);
|
|
114
|
+
seen.add(found.id);
|
|
115
|
+
cases.push(found);
|
|
116
|
+
}
|
|
117
|
+
return cases;
|
|
118
|
+
}
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns the chat record into proposed cases. A person's correction of a bot's
|
|
3
|
+
* reply is a miss: the message before the reply is the question, the messages
|
|
4
|
+
* before that are the context. The phrases of the right answer are the person's
|
|
5
|
+
* to write, so a proposal is a pending item the person approves with them; it
|
|
6
|
+
* writes a case file only on approval, and nothing is extracted on its own.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import type {
|
|
13
|
+
ActionTypeDefinition,
|
|
14
|
+
JsonValue,
|
|
15
|
+
ObjectRow,
|
|
16
|
+
ObjectStore,
|
|
17
|
+
ObjectViews,
|
|
18
|
+
SectionContent,
|
|
19
|
+
StandingItem,
|
|
20
|
+
StoredObject,
|
|
21
|
+
} from "@operad-io/engine";
|
|
22
|
+
import { chatMessages, type IndexedChatMessage } from "../search/sources.ts";
|
|
23
|
+
import { CaseError, parseCase, type CaseMessage, type MemoryCase } from "./format.ts";
|
|
24
|
+
|
|
25
|
+
/** The object type of a proposed case. A person sees its pending item. */
|
|
26
|
+
export const CASE_PROPOSAL_TYPE = "memory-case-proposal";
|
|
27
|
+
|
|
28
|
+
/** The directory of the cases in the operad home. */
|
|
29
|
+
export const CASES_DIRECTORY = "memory-cases";
|
|
30
|
+
|
|
31
|
+
/** The most earlier messages a proposed case keeps as context. */
|
|
32
|
+
export const PROPOSED_CONTEXT_MAX = 30;
|
|
33
|
+
|
|
34
|
+
/** The most text of one kept message. */
|
|
35
|
+
const MESSAGE_MAX = 2000;
|
|
36
|
+
|
|
37
|
+
/** What the person's message must open with to count as a correction. */
|
|
38
|
+
const CORRECTION =
|
|
39
|
+
/^\s*(?:no[,.!\s]|nope\b|wrong\b|that'?s (?:not|wrong|incorrect)\b|that is (?:not|wrong|incorrect)\b|incorrect\b|actually[,\s]|i (?:told|said) you\b|not (?:quite|right)\b|不对|不是|错了|搞错|其实|我说过|我之前说过|我告诉过你)/iu;
|
|
40
|
+
|
|
41
|
+
/** One correction found in a chat, with the exchange around it. */
|
|
42
|
+
export interface FoundMiss {
|
|
43
|
+
readonly chat: string;
|
|
44
|
+
/** The id of the correcting message. */
|
|
45
|
+
readonly message: string;
|
|
46
|
+
readonly question: string;
|
|
47
|
+
readonly wrong: string;
|
|
48
|
+
readonly correction: string;
|
|
49
|
+
readonly context: readonly CaseMessage[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function clipped(text: string): string {
|
|
53
|
+
return text.length <= MESSAGE_MAX ? text : `${text.slice(0, MESSAGE_MAX)}…`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Whether a person's message opens as a correction of what was said before it. */
|
|
57
|
+
export function isCorrection(text: string): boolean {
|
|
58
|
+
return CORRECTION.test(text);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The corrections in one chat: a correcting message after an assistant reply that followed a question. */
|
|
62
|
+
export function findMisses(chat: string, messages: readonly IndexedChatMessage[]): readonly FoundMiss[] {
|
|
63
|
+
const found: FoundMiss[] = [];
|
|
64
|
+
for (let at = 2; at < messages.length; at += 1) {
|
|
65
|
+
const correcting = messages[at];
|
|
66
|
+
const reply = messages[at - 1];
|
|
67
|
+
if (correcting?.role !== "user" || reply?.role !== "assistant" || !isCorrection(correcting.text)) continue;
|
|
68
|
+
let asked = at - 2;
|
|
69
|
+
while (asked >= 0 && messages[asked]?.role !== "user") asked -= 1;
|
|
70
|
+
const question = messages[asked];
|
|
71
|
+
if (question === undefined) continue;
|
|
72
|
+
const context = messages
|
|
73
|
+
.slice(Math.max(0, asked - PROPOSED_CONTEXT_MAX), asked)
|
|
74
|
+
.map((message): CaseMessage => ({ role: message.role, text: clipped(message.text) }));
|
|
75
|
+
found.push({
|
|
76
|
+
chat,
|
|
77
|
+
message: correcting.id,
|
|
78
|
+
question: clipped(question.text),
|
|
79
|
+
wrong: clipped(reply.text),
|
|
80
|
+
correction: clipped(correcting.text),
|
|
81
|
+
context,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
return found;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The id of a case or proposal made from one correction; the same correction gives the same id. */
|
|
88
|
+
export function proposalId(chat: string, message: string): string {
|
|
89
|
+
return `c-${createHash("sha256").update(`${chat}\u0000${message}`).digest("hex").slice(0, 10)}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** What a proposal stores. */
|
|
93
|
+
export interface CaseProposalData {
|
|
94
|
+
readonly [key: string]: unknown;
|
|
95
|
+
readonly state: "pending" | "approved" | "rejected";
|
|
96
|
+
readonly chat: string;
|
|
97
|
+
readonly createdAt: number;
|
|
98
|
+
readonly question: string;
|
|
99
|
+
readonly wrong: string;
|
|
100
|
+
readonly correction: string;
|
|
101
|
+
readonly context: readonly CaseMessage[];
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function dataOf(object: StoredObject): CaseProposalData | undefined {
|
|
105
|
+
const data = object.data;
|
|
106
|
+
if (
|
|
107
|
+
(data["state"] !== "pending" && data["state"] !== "approved" && data["state"] !== "rejected") ||
|
|
108
|
+
typeof data["chat"] !== "string" ||
|
|
109
|
+
typeof data["createdAt"] !== "number" ||
|
|
110
|
+
typeof data["question"] !== "string" ||
|
|
111
|
+
typeof data["wrong"] !== "string" ||
|
|
112
|
+
typeof data["correction"] !== "string" ||
|
|
113
|
+
!Array.isArray(data["context"])
|
|
114
|
+
) {
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
return data as CaseProposalData;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function everyChat(store: ObjectStore): Promise<readonly StoredObject[]> {
|
|
121
|
+
const found: StoredObject[] = [];
|
|
122
|
+
let cursor: string | undefined;
|
|
123
|
+
do {
|
|
124
|
+
const page = await store.list("chat", { ...(cursor === undefined ? {} : { cursor }), limit: 200 });
|
|
125
|
+
found.push(...page.objects);
|
|
126
|
+
cursor = page.next;
|
|
127
|
+
} while (cursor !== undefined);
|
|
128
|
+
return found;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Options of one extraction. */
|
|
132
|
+
export interface ProposeOptions {
|
|
133
|
+
readonly home: string;
|
|
134
|
+
/** Only this chat, when given. */
|
|
135
|
+
readonly chat?: string | undefined;
|
|
136
|
+
readonly now: () => number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Stores a pending proposal for every correction not yet proposed and not
|
|
141
|
+
* already a case. A rejected proposal stays, so it is not proposed again.
|
|
142
|
+
*/
|
|
143
|
+
export async function proposeCases(store: ObjectStore, options: ProposeOptions): Promise<readonly string[]> {
|
|
144
|
+
const chats = (await everyChat(store)).filter((chat) => options.chat === undefined || chat.id === options.chat);
|
|
145
|
+
const made: string[] = [];
|
|
146
|
+
for (const chat of chats) {
|
|
147
|
+
for (const miss of findMisses(chat.id, chatMessages(store, chat.id))) {
|
|
148
|
+
const id = proposalId(chat.id, miss.message);
|
|
149
|
+
if ((await store.get(CASE_PROPOSAL_TYPE, id)) !== undefined) continue;
|
|
150
|
+
if (existsSync(join(options.home, CASES_DIRECTORY, `${id}.json`))) continue;
|
|
151
|
+
const data: CaseProposalData = {
|
|
152
|
+
state: "pending",
|
|
153
|
+
chat: chat.id,
|
|
154
|
+
createdAt: options.now(),
|
|
155
|
+
question: miss.question,
|
|
156
|
+
wrong: miss.wrong,
|
|
157
|
+
correction: miss.correction,
|
|
158
|
+
context: miss.context,
|
|
159
|
+
};
|
|
160
|
+
await store.put(CASE_PROPOSAL_TYPE, id, data as unknown as Record<string, JsonValue>, "command:memory/propose");
|
|
161
|
+
made.push(id);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return made;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The case an approval writes: the person's phrases, and what the bot got wrong when they say so. */
|
|
168
|
+
export function caseOfProposal(id: string, data: CaseProposalData, include: string, avoid: string): MemoryCase {
|
|
169
|
+
const lines = (text: string): string[] =>
|
|
170
|
+
text
|
|
171
|
+
.split("\n")
|
|
172
|
+
.map((line) => line.trim())
|
|
173
|
+
.filter((line) => line.length > 0);
|
|
174
|
+
return parseCase(
|
|
175
|
+
{
|
|
176
|
+
id,
|
|
177
|
+
kind: "correction",
|
|
178
|
+
context: data.context,
|
|
179
|
+
question: data.question,
|
|
180
|
+
answer: { include: lines(include), avoid: lines(avoid) },
|
|
181
|
+
},
|
|
182
|
+
`${id}.json`,
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Approves a proposal: writes the case file with the phrases the person gave. */
|
|
187
|
+
export async function approveCaseProposal(
|
|
188
|
+
store: ObjectStore,
|
|
189
|
+
home: string,
|
|
190
|
+
id: string,
|
|
191
|
+
include: string,
|
|
192
|
+
avoid: string,
|
|
193
|
+
): Promise<string> {
|
|
194
|
+
const object = await store.get(CASE_PROPOSAL_TYPE, id);
|
|
195
|
+
const data = object === undefined ? undefined : dataOf(object);
|
|
196
|
+
if (data === undefined) throw new CaseError(`there is no proposed case "${id}"`);
|
|
197
|
+
if (data.state !== "pending") return `proposed case ${id} is already ${data.state}; nothing to approve`;
|
|
198
|
+
const made = caseOfProposal(id, data, include, avoid);
|
|
199
|
+
const directory = join(home, CASES_DIRECTORY);
|
|
200
|
+
mkdirSync(directory, { recursive: true });
|
|
201
|
+
writeFileSync(join(directory, `${id}.json`), `${JSON.stringify(made, null, 2)}\n`);
|
|
202
|
+
await store.put(
|
|
203
|
+
CASE_PROPOSAL_TYPE,
|
|
204
|
+
id,
|
|
205
|
+
{ ...data, state: "approved" } as unknown as Record<string, JsonValue>,
|
|
206
|
+
"action:memory/approve",
|
|
207
|
+
);
|
|
208
|
+
return `added case ${id} to the memory regression set`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Rejects a proposal; no case is written. */
|
|
212
|
+
export async function rejectCaseProposal(store: ObjectStore, id: string): Promise<string> {
|
|
213
|
+
const object = await store.get(CASE_PROPOSAL_TYPE, id);
|
|
214
|
+
const data = object === undefined ? undefined : dataOf(object);
|
|
215
|
+
if (data === undefined) throw new CaseError(`there is no proposed case "${id}"`);
|
|
216
|
+
if (data.state !== "pending") return `proposed case ${id} is already ${data.state}; nothing to reject`;
|
|
217
|
+
await store.put(
|
|
218
|
+
CASE_PROPOSAL_TYPE,
|
|
219
|
+
id,
|
|
220
|
+
{ ...data, state: "rejected" } as unknown as Record<string, JsonValue>,
|
|
221
|
+
"action:memory/reject",
|
|
222
|
+
);
|
|
223
|
+
return `rejected proposed case ${id}`;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** The actions on a proposed case. */
|
|
227
|
+
export const caseProposalActions: readonly ActionTypeDefinition[] = [
|
|
228
|
+
{
|
|
229
|
+
name: "approve",
|
|
230
|
+
on: CASE_PROPOSAL_TYPE,
|
|
231
|
+
when: (state) => state.state === "pending",
|
|
232
|
+
args: {
|
|
233
|
+
type: "object",
|
|
234
|
+
properties: {
|
|
235
|
+
include: {
|
|
236
|
+
type: "string",
|
|
237
|
+
role: "note",
|
|
238
|
+
minLength: 1,
|
|
239
|
+
description: "What a right answer states, one short phrase per line.",
|
|
240
|
+
},
|
|
241
|
+
avoid: {
|
|
242
|
+
type: "string",
|
|
243
|
+
role: "note",
|
|
244
|
+
description: "Phrases of the wrong answer, one per line; an answer that states one fails. May be empty.",
|
|
245
|
+
},
|
|
246
|
+
},
|
|
247
|
+
required: ["include"],
|
|
248
|
+
additionalProperties: false,
|
|
249
|
+
},
|
|
250
|
+
async run(ctx, args) {
|
|
251
|
+
const input = args as { readonly include: string; readonly avoid?: string | undefined };
|
|
252
|
+
return approveCaseProposal(ctx.store, ctx.home, ctx.object.id, input.include, input.avoid ?? "");
|
|
253
|
+
},
|
|
254
|
+
},
|
|
255
|
+
{
|
|
256
|
+
name: "reject",
|
|
257
|
+
on: CASE_PROPOSAL_TYPE,
|
|
258
|
+
when: (state) => state.state === "pending",
|
|
259
|
+
async run(ctx) {
|
|
260
|
+
return rejectCaseProposal(ctx.store, ctx.object.id);
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
];
|
|
264
|
+
|
|
265
|
+
function reviewText(data: CaseProposalData): string {
|
|
266
|
+
const quote = (text: string): string => text.split("\n").map((line) => `> ${line}`).join("\n");
|
|
267
|
+
return [
|
|
268
|
+
`The person corrected the bot in chat ${data.chat}.`,
|
|
269
|
+
"",
|
|
270
|
+
"Question:",
|
|
271
|
+
quote(data.question),
|
|
272
|
+
"",
|
|
273
|
+
"The bot's reply:",
|
|
274
|
+
quote(data.wrong),
|
|
275
|
+
"",
|
|
276
|
+
"The correction:",
|
|
277
|
+
quote(data.correction),
|
|
278
|
+
"",
|
|
279
|
+
"Approve with the phrases a right answer states, one short phrase per line.",
|
|
280
|
+
].join("\n");
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** The pending items the proposed cases make. */
|
|
284
|
+
export async function caseProposalItems(store: ObjectStore): Promise<readonly StandingItem[]> {
|
|
285
|
+
const items: StandingItem[] = [];
|
|
286
|
+
let cursor: string | undefined;
|
|
287
|
+
do {
|
|
288
|
+
const page = await store.list(CASE_PROPOSAL_TYPE, { ...(cursor === undefined ? {} : { cursor }) });
|
|
289
|
+
for (const object of page.objects) {
|
|
290
|
+
const data = dataOf(object);
|
|
291
|
+
if (data?.state !== "pending") continue;
|
|
292
|
+
items.push({
|
|
293
|
+
id: object.id,
|
|
294
|
+
prompt: `A correction in chat ${data.chat} is proposed as a memory test case`,
|
|
295
|
+
object: { type: CASE_PROPOSAL_TYPE, id: object.id },
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
cursor = page.next;
|
|
299
|
+
} while (cursor !== undefined);
|
|
300
|
+
return items;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function row(object: StoredObject): ObjectRow {
|
|
304
|
+
const data = dataOf(object);
|
|
305
|
+
if (data === undefined) return { id: object.id, title: "Proposed memory test case", state: "broken" };
|
|
306
|
+
return {
|
|
307
|
+
id: object.id,
|
|
308
|
+
title: `Proposed memory test case from chat ${data.chat}`,
|
|
309
|
+
state: data.state,
|
|
310
|
+
...(data.state === "pending" ? { mark: "proposed" as const } : {}),
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** How a proposed case shows in a list and on its page. */
|
|
315
|
+
export const caseProposalViews: ObjectViews = {
|
|
316
|
+
row,
|
|
317
|
+
sections: () => [{ id: "review", title: "Review" }],
|
|
318
|
+
load: (_ctx, object): SectionContent => {
|
|
319
|
+
const data = dataOf(object);
|
|
320
|
+
return { markdown: data === undefined ? "This proposal has no usable state." : reviewText(data) };
|
|
321
|
+
},
|
|
322
|
+
};
|