sr-zero 0.9.0__py3-none-any.whl

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.
@@ -0,0 +1,400 @@
1
+ """Tool use: which tool fits the user's request, and whether to call it, ask, or decline.
2
+
3
+ Reads states that carry a user request (a dialogue, a conversation, a query or a question) and tool definitions
4
+ (name, description, parameters). A tool fits a request by BM25 over the words they share, the tool's name counted
5
+ twice, its rarity judged among the tools on offer. Tools may be listed as data or as text, one `name: description` per
6
+ line; a dialogue may be data or text, one `User: ...` turn per line; a call may be JSON or written
7
+ `name(key="value", ...)`.
8
+
9
+ In a dialogue the next call serves the latest request: the user's answers to the assistant's questions supply its
10
+ arguments and count for less, quoted names count not at all, and when the user has just given the credentials the
11
+ assistant asked for, the next call is the one that logs in.
12
+ """
13
+ import collections
14
+ import functools
15
+ import math
16
+ import re
17
+
18
+ from .. import text
19
+ from ..request import parse
20
+
21
+ NAME = "tools"
22
+ CASES = {
23
+ "best_tool": "the option naming the tool that fits the request best (shared words, the tool's name counted twice)",
24
+ "next_request": "the tool that fits the dialogue's latest request best; answers to the assistant's questions count "
25
+ "for less",
26
+ "logs_in": "the call that logs in: the user has just given the credentials the assistant asked for",
27
+ "sole_tool_fits": "yes: the only tool on offer shares words with the request",
28
+ "sole_tool_misfit": "no: the only tool on offer shares no word with the request",
29
+ "candidate_fits": "yes: of the tools on offer, this candidate fits the request best",
30
+ "candidate_misfits": "no: another tool on offer fits the request better",
31
+ "no_tool_fits": "no: none of the tools on offer shares a word with the request",
32
+ "call_grounded": "the tool call: its tool fits the request and every argument value is in the request",
33
+ "ask_for_missing": "the follow-up question: the fitting tool needs a value the request does not give",
34
+ "no_fitting_tool": "the apology: no tool on offer shares a word with the request",
35
+ }
36
+
37
+ USER_ROLES = {"user", "human", "customer", "client"}
38
+ REQUEST_KEYS = ("question", "query", "request", "user_request", "prompt", "instruction", "user_query")
39
+ TOOL_KEYS = ("available_tools", "tools", "functions", "apis", "tool_list", "candidates")
40
+ TEXT_TOOL_KEYS = ("available_tools", "tools", "functions", "apis", "tool_list")
41
+ DIALOGUE_KEYS = ("dialogue", "dialog", "conversation", "messages", "transcript", "chat")
42
+ PARAMETER_KEYS = ("parameters", "arguments", "args", "input_schema", "params")
43
+ TOOL_LINE = re.compile(r"^\s*(?:[-*\u2022]\s*)?([A-Za-z_][\w.\-]*)\s*(?:\(\))?\s*(?::|\s[-\u2013\u2014])\s*(.+)$")
44
+ TURN = re.compile(r"^\s*([A-Za-z]+)\s*:\s*(.+)$")
45
+ CALL = re.compile(r"^\s*([A-Za-z_][\w.\-]*)\s*\((.*)\)\s*$", re.S)
46
+ ARGUMENT = re.compile(r"""([A-Za-z_]\w*)\s*=\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^,]+)""")
47
+ STOP = frozenset("""a an the of to in on at by for from with and or is are be it this that my me i you your please
48
+ can could would will do does get set given one of as if""".split())
49
+ CAMEL = re.compile(r"[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+")
50
+ ASKS = re.compile(r"\?|\bcould you (provide|tell|share|give)\b|\bwhat (is|are) the\b|\bplease (provide|specify)\b")
51
+ DECLINES = re.compile(r"\b(don't|do not|can't|cannot|unable|not able|no tool|not possible|apolog|sorry)\b")
52
+ LOGIN_ASK = re.compile(r"\b(log (you )?in|sign (you )?in|authenticat\w*|password|credentials)\b", re.I)
53
+ LOGGED_IN = re.compile(r"\b(you'?re|you are|now) (logged|signed) in\b|\blogged in\b|\bauthenticated\b", re.I)
54
+ QUOTED = re.compile(r"'[^']{1,80}'(?=[\s.,;:!?)]|$)|\"[^\"]{1,80}\"|\u201c[^\u201d]{1,80}\u201d")
55
+ NAMING = re.compile(r"\b(called|named|titled|entitled)\b", re.I)
56
+ CALLED_ROLES = {"api", "tool", "function", "ipython"}
57
+ INPUT_KEYS = ("input_parameters", "parameters", "arguments", "args", "input_schema", "params")
58
+ OUTPUT_KEYS = ("output_parameters", "outputs", "returns", "response")
59
+ K1, B = 1.2, 0.75
60
+ ANSWERS, OLDER = 0.35, 0.5
61
+
62
+
63
+ @functools.lru_cache(maxsize=1 << 16)
64
+ def stem(word):
65
+ for end in ("ing", "ed", "es", "s"):
66
+ if len(word) > len(end) + 3 and word.endswith(end):
67
+ return word[: -len(end)]
68
+ return word
69
+
70
+
71
+ def terms(value):
72
+ """The stemmed content words of a text, names split at camelCase and underscores: what tools are matched on.
73
+ Chinese, Japanese or Thai text is matched by its character pairs."""
74
+ return list(_terms(text.flatten(value)))
75
+
76
+
77
+ @functools.lru_cache(maxsize=1 << 12)
78
+ def _terms(flat):
79
+ out = []
80
+ for token in text.written_words(flat):
81
+ parts = CAMEL.findall(token) if token.isascii() and not token.islower() else [token]
82
+ for part in parts or [token]:
83
+ word = part.lower()
84
+ if word not in STOP and not word.isdigit():
85
+ out.append(stem(word))
86
+ return tuple(out)
87
+
88
+
89
+ def bag(value):
90
+ return {stem(w) for w in text.words(text.flatten(value)) if w not in STOP and not w.isdigit()}
91
+
92
+
93
+ CREDENTIALS = frozenset(terms("username user password email login"))
94
+ LOGIN = frozenset(terms("token access login log sign session authenticate authentication"))
95
+ EMPTY = frozenset(terms("please go ahead yes ok okay sure thanks thank you do it proceed continue that sounds good "
96
+ "great fine right correct confirm confirmed now"))
97
+
98
+
99
+ def request_terms(said):
100
+ """The words of a user turn that say what is wanted: quoted names and the words that introduce them dropped."""
101
+ return terms(NAMING.sub(" ", QUOTED.sub(" ", said)))
102
+
103
+
104
+ def user_text(data):
105
+ """The words the user said: user turns of a dialogue, or a request field."""
106
+ found = []
107
+
108
+ def walk(node, depth=0):
109
+ if depth > 4:
110
+ return
111
+ if isinstance(node, dict):
112
+ role = str(node.get("role", "")).lower()
113
+ if role in USER_ROLES:
114
+ found.append(text.flatten(node.get("text", node.get("content", ""))))
115
+ return
116
+ for key, value in node.items():
117
+ if str(key).lower() in REQUEST_KEYS and isinstance(value, str):
118
+ found.append(value)
119
+ elif str(key).lower() in DIALOGUE_KEYS and isinstance(value, str):
120
+ turns = [TURN.match(line) for line in value.splitlines()]
121
+ found.extend(m.group(2) for m in turns if m and m.group(1).lower() in USER_ROLES)
122
+ elif isinstance(value, (dict, list)):
123
+ walk(value, depth + 1)
124
+ elif isinstance(node, list):
125
+ for item in node:
126
+ walk(item, depth + 1)
127
+
128
+ walk(data)
129
+ return " ".join(found)
130
+
131
+
132
+ def tool_list(data):
133
+ """[(name, description, parameters)] of the tools a state offers."""
134
+ if not isinstance(data, dict):
135
+ return []
136
+ for key in TOOL_KEYS:
137
+ value = data.get(key)
138
+ if isinstance(value, list) and value and all(isinstance(t, dict) and "name" in t for t in value):
139
+ return [(str(t["name"]), text.flatten(t.get("description", "")),
140
+ next((t[k] for k in PARAMETER_KEYS if k in t), "")) for t in value]
141
+ if key in TEXT_TOOL_KEYS and isinstance(value, str):
142
+ listed = [m.groups() for m in map(TOOL_LINE.match, value.splitlines()) if m]
143
+ if listed:
144
+ return [(name, description.strip(), "") for name, description in listed]
145
+ return []
146
+
147
+
148
+ def call_of(description, names=()):
149
+ """A tool call an option holds: JSON {"name", "arguments"}, or written name(key="value", ...) naming one of the
150
+ tools on offer (`names`, lower case); else None."""
151
+ call = parse(description)
152
+ if isinstance(call, dict) and "name" in call:
153
+ return call
154
+ m = CALL.match(description or "")
155
+ if not m or m.group(1).lower() not in names:
156
+ return None
157
+ arguments = {key: value.strip().strip("\"'") for key, value in ARGUMENT.findall(m.group(2))}
158
+ return {"name": m.group(1), "arguments": arguments}
159
+
160
+
161
+ def bm25(query, docs, weights=None):
162
+ """{name: BM25 score of the query's words against each document}, rarity judged among the documents. A query
163
+ given as counts weighs a word it repeats by log(1 + count); `weights` gives each word's weight outright."""
164
+ if not docs:
165
+ return {}
166
+ if weights is None:
167
+ weights = {w: math.log(1 + c) / math.log(2) for w, c in query.items()} if isinstance(query, dict) else \
168
+ dict.fromkeys(query, 1.0)
169
+ n = len(docs)
170
+ average = sum(len(d) for d in docs.values()) / n or 1
171
+ df = collections.Counter(w for d in docs.values() for w in set(d))
172
+ scores = {}
173
+ for name, d in docs.items():
174
+ tf = collections.Counter(d)
175
+ norm = K1 * (1 - B + B * len(d) / average)
176
+ scores[name] = sum(math.log(1 + (n - df[w] + 0.5) / (df[w] + 0.5)) * weight * tf[w] * (K1 + 1) / (tf[w] + norm)
177
+ for w, weight in weights.items() if w in tf)
178
+ return scores
179
+
180
+
181
+ def dialogue_turns(data):
182
+ """[(role, text, turn)] of the state's dialogue, roles in lower case; a dialogue given as text has no turn data."""
183
+ if not isinstance(data, dict):
184
+ return []
185
+ for key in DIALOGUE_KEYS:
186
+ value = data.get(key)
187
+ if isinstance(value, list) and value and all(isinstance(t, dict) for t in value):
188
+ return [(str(t.get("role", "")).lower(), text.flatten(t.get("text", t.get("content", ""))), t)
189
+ for t in value]
190
+ if isinstance(value, str):
191
+ found = [m for m in map(TURN.match, value.splitlines()) if m]
192
+ if found:
193
+ return [(m.group(1).lower(), m.group(2), None) for m in found]
194
+ return []
195
+
196
+
197
+ def _names(schema):
198
+ if isinstance(schema, dict) and isinstance(schema.get("properties"), dict):
199
+ schema = schema["properties"]
200
+ return {w for key in schema for w in terms(str(key))} if isinstance(schema, dict) else set()
201
+
202
+
203
+ def parameter_words(data):
204
+ """{tool name, lower case: (words of its input parameter names, words of its output parameter names)}."""
205
+ for key in TOOL_KEYS:
206
+ value = data.get(key) if isinstance(data, dict) else None
207
+ if isinstance(value, list) and value and all(isinstance(t, dict) and "name" in t for t in value):
208
+ return {str(t["name"]).lower(): (_names(next((t[k] for k in INPUT_KEYS if k in t), {})),
209
+ _names(next((t[k] for k in OUTPUT_KEYS if k in t), {})))
210
+ for t in value}
211
+ return {}
212
+
213
+
214
+ def _assistant(role):
215
+ return role not in USER_ROLES and role not in CALLED_ROLES
216
+
217
+
218
+ def plan(data, docs):
219
+ """What a dialogue's next call serves: ("logs_in", tool) when the user has just given the credentials the
220
+ assistant asked for and nothing has logged them in since, else ("next_request", {word: weight}) with the latest
221
+ request counted fully, the user's later answers to the assistant's questions at ANSWERS, and each older turn
222
+ at OLDER times the one after it. None when the state has no dialogue."""
223
+ dialogue = dialogue_turns(data)
224
+ users = [i for i, (role, _, _) in enumerate(dialogue) if role in USER_ROLES]
225
+ if not users or not docs:
226
+ return None
227
+
228
+ def follows(i, pattern=None, question=False):
229
+ role, said, _ = dialogue[i - 1] if i else ("", "", None)
230
+ return i > 0 and _assistant(role) and (not question or "?" in said) and \
231
+ (not pattern or bool(pattern.search(said)))
232
+
233
+ said = {i: request_terms(dialogue[i][1]) for i in users}
234
+ login = {i for i in users if follows(i, LOGIN_ASK)}
235
+ last = users[-1]
236
+ after = dialogue[last + 1:]
237
+ if last in login and not any(not _assistant(role) or "?" in t or LOGGED_IN.search(t) for role, t, _ in after):
238
+ tool = login_tool(data, docs, said[last])
239
+ if tool:
240
+ return "logs_in", tool
241
+ answered = {i for i in users if follows(i, question=True)}
242
+ content = {i: {w for w in said[i] if w not in EMPTY} for i in users}
243
+ requests = [i for i in users if i not in answered and i not in login and content[i]]
244
+ latest = requests[-1] if requests else None
245
+ weights = collections.Counter()
246
+ rank = 0
247
+ for i in reversed(users):
248
+ if not content[i] or i in login:
249
+ continue
250
+ if latest is not None and i > latest:
251
+ weight = ANSWERS
252
+ elif i == latest:
253
+ weight = 1.0
254
+ else:
255
+ rank += 1
256
+ weight = OLDER ** rank * (OLDER if i in answered else 1.0)
257
+ for w in content[i]:
258
+ weights[w] += weight
259
+ return ("next_request", dict(weights)) if weights else None
260
+
261
+
262
+ def login_tool(data, docs, said):
263
+ """The tool that logs in: of the tools taking at least two credentials (username, password, email), the one whose
264
+ name, description or outputs speak most of tokens, access or logging in; BM25 against the user's turn breaks a
265
+ tie. None if no tool takes credentials or the tie stands."""
266
+ words = parameter_words(data)
267
+ fitting = [t for t in docs if len(words.get(t, (set(), set()))[0] & CREDENTIALS) >= 2]
268
+ if not fitting:
269
+ return None
270
+ login = {t: len((set(docs[t]) | words.get(t, (set(), set()))[1]) & LOGIN) for t in fitting}
271
+ most = max(login.values())
272
+ fitting = [t for t in fitting if login[t] == most]
273
+ if len(fitting) == 1:
274
+ return fitting[0]
275
+ scores = bm25(set(said), {t: docs[t] for t in fitting})
276
+ top = max(scores.values())
277
+ winners = [t for t in fitting if scores[t] == top]
278
+ return winners[0] if top > 0 and len(winners) == 1 else None
279
+
280
+
281
+ def candidate(question):
282
+ """(name, description) of the candidate tool a yes/no question asks about, if any."""
283
+ ins = question.get("instructions")
284
+ data = ins if isinstance(ins, dict) else None
285
+ if data and "candidate" in data:
286
+ c = parse(data["candidate"]) if isinstance(data["candidate"], str) else data["candidate"]
287
+ if isinstance(c, dict) and "name" in c:
288
+ return str(c["name"]), text.flatten(c.get("description", ""))
289
+ m = re.search(r"candidate tool:\s*([\w.\-]+)", text.flatten(ins), re.I)
290
+ return (m.group(1), "") if m else None
291
+
292
+
293
+ def read(request):
294
+ """What the module reads once per request: the user's words, the tools on offer (and the candidates its questions
295
+ ask about) with how well each fits, and the one that fits best."""
296
+ data = request.data
297
+ said = user_text(data) if data is not None else ""
298
+ tools = tool_list(data)
299
+ query = set(terms(said))
300
+ docs, order = {}, {}
301
+ for name, description, parameters in tools:
302
+ docs.setdefault(name.lower(), terms(name) * 2 + terms(description) + terms(parameters))
303
+ order.setdefault(name.lower(), len(order))
304
+ candidates = {key: candidate(question) for key, question in request.questions.items()}
305
+ for found in candidates.values():
306
+ if found and found[0].lower() not in docs:
307
+ docs[found[0].lower()] = terms(found[0]) * 2 + terms(found[1])
308
+ order[found[0].lower()] = len(order)
309
+ fits = bm25(query, docs)
310
+ named = {name: len(set(terms(name)) & query) for name in docs}
311
+ ranked = sorted(docs, key=lambda n: (-fits[n], -named[n], order[n]))
312
+ best = ranked[0] if ranked and fits[ranked[0]] > 0 else None
313
+ planned = plan(data, docs) if tools else None
314
+ if planned and planned[0] == "next_request":
315
+ planned = ("next_request", bm25(planned[1], docs, weights=planned[1]))
316
+ return {"said": said, "words": query, "tools": tools, "fits": fits, "best": best, "candidates": candidates,
317
+ "plan": planned}
318
+
319
+
320
+ def yes_no(question):
321
+ keys = {k.lower(): k for k, _ in text.options(question)}
322
+ if set(keys) == {"yes", "no"}:
323
+ return keys["yes"], keys["no"]
324
+ if set(keys) == {"true", "false"}:
325
+ return keys["true"], keys["false"]
326
+ return None
327
+
328
+
329
+ def propose(request, key):
330
+ """(option key, case) or None."""
331
+ question = request.questions[key]
332
+ info = request.once(NAME, read)
333
+ if not info["words"]:
334
+ return None
335
+ opts = text.options(question)
336
+ tools = info["tools"]
337
+ fits = info["fits"]
338
+ by_name = {n.lower(): n for n, _, _ in tools}
339
+
340
+ named = [(k, (d or k).strip().lower()) for k, d in opts]
341
+ offered = [(k, n) for k, n in named if n in by_name]
342
+ if tools and len(offered) >= 2:
343
+ planned = info["plan"]
344
+ if planned and planned[0] == "logs_in":
345
+ winners = [k for k, n in offered if n == planned[1]]
346
+ if len(winners) == 1:
347
+ return winners[0], "logs_in"
348
+ elif planned:
349
+ scores = planned[1]
350
+ top = max(scores.get(n, 0) for _, n in offered)
351
+ winners = [k for k, n in offered if scores.get(n, 0) == top]
352
+ return (winners[0], "next_request") if top > 0 and len(winners) == 1 else None
353
+ best = max(fits[n] for _, n in offered)
354
+ winners = [k for k, n in offered if fits[n] == best]
355
+ if best > 0 and len(winners) == 1:
356
+ return winners[0], "best_tool"
357
+ return None
358
+
359
+ pair = yes_no(question)
360
+ cand = info["candidates"].get(key)
361
+ if pair and cand and tools:
362
+ name = cand[0].lower()
363
+ if len(fits) == 1:
364
+ return (pair[0], "sole_tool_fits") if fits[name] > 0 else (pair[1], "sole_tool_misfit")
365
+ if info["best"] is None:
366
+ return pair[1], "no_tool_fits"
367
+ return (pair[0], "candidate_fits") if name == info["best"] else (pair[1], "candidate_misfits")
368
+
369
+ kinds = {}
370
+ for k, d in opts:
371
+ call = call_of(d, by_name)
372
+ if call is not None:
373
+ kinds.setdefault("call", (k, call))
374
+ elif DECLINES.search(d):
375
+ kinds.setdefault("decline", (k, None))
376
+ elif ASKS.search(d):
377
+ kinds.setdefault("ask", (k, None))
378
+ if not tools or len(kinds) < 2:
379
+ return None
380
+ said = " ".join(text.words(info["said"]))
381
+ top = max((fits[n] for n in by_name), default=0)
382
+ if top == 0 and "decline" in kinds:
383
+ return kinds["decline"][0], "no_fitting_tool"
384
+ if "call" in kinds:
385
+ k, call = kinds["call"]
386
+ name = str(call.get("name", "")).lower()
387
+ if name in by_name and fits[name] == top:
388
+ args = call.get("arguments") or call.get("parameters") or {}
389
+ if isinstance(args, str):
390
+ args = parse(args) or {}
391
+ values = [" ".join(text.words(text.flatten(v))) for v in args.values()] if isinstance(args, dict) else []
392
+ if all(v and (" " + v + " ") in (" " + said + " ") for v in values):
393
+ return k, "call_grounded"
394
+ if "ask" in kinds:
395
+ return kinds["ask"][0], "ask_for_missing"
396
+ return None
397
+
398
+
399
+ def describe(case):
400
+ return CASES.get(case, case)
@@ -0,0 +1,105 @@
1
+ """Verse: of two versions of one poem, which is the original. A changed word that breaks a rhyme, or an inserted or
2
+ dropped word that breaks the meter, gives the other version away. Both are read from spelling alone: a line rhymes
3
+ with another when their last words end in the same vowel group and what follows it ('bank', 'prank'), and a line's
4
+ length is its syllables, counted by vowel groups.
5
+
6
+ Proposes an answer only when the question asks for the original, the two options are versions of the same poem of
7
+ three or more lines, and one version rhymes more, or failing that keeps its lines' lengths closer together.
8
+ """
9
+ import re
10
+
11
+ from .. import text
12
+
13
+ NAME = "verse"
14
+ CASES = {
15
+ "rhyme": "the version whose lines rhyme more: the last words of lines one or two apart share their ending",
16
+ "meter": "the version whose lines keep closer in syllables to the lines they rhyme with",
17
+ }
18
+ VOWELS = re.compile(r"[aeiouy]+")
19
+ WORD = re.compile(r"[A-Za-z']+")
20
+
21
+
22
+ def _letters(word):
23
+ return re.sub(r"[^a-z]", "", word.lower())
24
+
25
+
26
+ def rhyme_key(word):
27
+ """The last vowel group of a word and what follows it: 'bank' -> 'ank', 'trick' -> 'ick', 'shame' -> 'ame'."""
28
+ w = _letters(word)
29
+ silent = w.endswith("e") and len(w) > 2 and not w.endswith(("ee", "ie", "ye"))
30
+ stem = w[:-1] if silent else w
31
+ groups = list(VOWELS.finditer(stem))
32
+ if not groups:
33
+ return w
34
+ return stem[groups[-1].start():] + ("e" if silent else "")
35
+
36
+
37
+ def syllables(line):
38
+ count = 0
39
+ for word in WORD.findall(line):
40
+ w = _letters(word)
41
+ if not w:
42
+ continue
43
+ n = len(VOWELS.findall(w))
44
+ if w.endswith("e") and not w.endswith(("le", "ee", "ye")) and n > 1:
45
+ n -= 1
46
+ count += max(1, n)
47
+ return count
48
+
49
+
50
+ def rhymes(lines):
51
+ """How many pairs of lines one or two apart end in rhyming words."""
52
+ keys = [rhyme_key(words[-1]) if words else "" for words in (WORD.findall(x) for x in lines)]
53
+ return sum(1 for i, k in enumerate(keys) for d in (1, 2) if k and i + d < len(keys) and k == keys[i + d])
54
+
55
+
56
+ def _median(values):
57
+ return sorted(values)[len(values) // 2]
58
+
59
+
60
+ def unevenness(lines):
61
+ """How far each line's syllable count strays from the lines it rhymes with (a limerick's short third and fourth
62
+ lines against each other), or from the poem's median line when it rhymes with none; summed."""
63
+ counts = [syllables(x) for x in lines]
64
+ keys = [rhyme_key(words[-1]) if words else "" for words in (WORD.findall(x) for x in lines)]
65
+ middle = _median(counts)
66
+ total = 0
67
+ for i, c in enumerate(counts):
68
+ partners = [counts[j] for j, k in enumerate(keys) if j != i and k and k == keys[i]]
69
+ total += abs(c - (_median(partners) if partners else middle))
70
+ return total
71
+
72
+
73
+ def _versions(question):
74
+ options = [(k, text.flatten(d if d is not None else k)) for k, d in (question.get("criteria") or {}).items()]
75
+ if len(options) != 2:
76
+ return None
77
+ lines = [[x for x in poem.split("\n") if x.strip()] for _, poem in options]
78
+ if min(len(x) for x in lines) < 3:
79
+ return None
80
+ a, b = (set(w.lower() for w in WORD.findall(poem)) for _, poem in options)
81
+ if not a or not b or len(a & b) < 0.5 * min(len(a), len(b)):
82
+ return None
83
+ return [k for k, _ in options], lines
84
+
85
+
86
+ def propose(request, key):
87
+ """(option key, case) or None."""
88
+ question = request.questions[key]
89
+ if "original" not in text.flatten(question.get("instructions")).lower():
90
+ return None
91
+ found = _versions(question)
92
+ if not found:
93
+ return None
94
+ keys, (a, b) = found
95
+ ra, rb = rhymes(a), rhymes(b)
96
+ if ra != rb:
97
+ return (keys[0] if ra > rb else keys[1]), "rhyme"
98
+ ua, ub = unevenness(a), unevenness(b)
99
+ if ua != ub:
100
+ return (keys[0] if ua < ub else keys[1]), "meter"
101
+ return None
102
+
103
+
104
+ def describe(case):
105
+ return CASES.get(case, case)
system_zero/request.py ADDED
@@ -0,0 +1,34 @@
1
+ """One decision request, read once: the state as text and, when it is JSON, as data."""
2
+ import json
3
+
4
+ from . import text
5
+
6
+
7
+ def parse(value):
8
+ """A JSON object or list given as data or as a JSON string, else None."""
9
+ if isinstance(value, (dict, list)):
10
+ return value
11
+ if isinstance(value, str):
12
+ s = value.strip()
13
+ if s[:1] in "{[" and s[-1:] in "}]":
14
+ try:
15
+ return json.loads(s)
16
+ except ValueError:
17
+ return None
18
+ return None
19
+
20
+
21
+ class Request:
22
+ def __init__(self, state, questions, familiar=None):
23
+ self.state = state
24
+ self.questions = questions
25
+ self.state_text = text.flatten(state)
26
+ self.data = parse(state)
27
+ self.familiar = familiar or {}
28
+ self.cache = {}
29
+
30
+ def once(self, name, build):
31
+ """A value derived from the request, computed the first time a module asks for it."""
32
+ if name not in self.cache:
33
+ self.cache[name] = build(self)
34
+ return self.cache[name]
@@ -0,0 +1,9 @@
1
+ """System Zero's learned rules, as plain Python literals. Nothing here is imported: system_zero.model reads each file
2
+ with ast.literal_eval, so a rule file can be read, diffed and loaded but never run.
3
+
4
+ option_sets.py the answer lists System Zero knows, by id
5
+ frames.py decision lists for a question template with an option set
6
+ options.py decision lists for an option set under any template
7
+ cues.py context cues for questions whose options are not a known set
8
+ modules.py how far each hand-written module case is trusted, and what the rules were learned from
9
+ """