studio-agent 0.1.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.
- studio_agent/__init__.py +1 -0
- studio_agent/__main__.py +4 -0
- studio_agent/ask.py +36 -0
- studio_agent/ask_agentic.py +204 -0
- studio_agent/chunk.py +170 -0
- studio_agent/citation.py +9 -0
- studio_agent/cli.py +217 -0
- studio_agent/config.py +27 -0
- studio_agent/connections.py +269 -0
- studio_agent/eval.py +193 -0
- studio_agent/extract.py +286 -0
- studio_agent/index.py +151 -0
- studio_agent/mcp_server.py +244 -0
- studio_agent/naming.py +166 -0
- studio_agent/ocr.py +121 -0
- studio_agent/search.py +175 -0
- studio_agent/studio.py +164 -0
- studio_agent/web/index.html +130 -0
- studio_agent/web.py +68 -0
- studio_agent-0.1.0.dist-info/METADATA +154 -0
- studio_agent-0.1.0.dist-info/RECORD +25 -0
- studio_agent-0.1.0.dist-info/WHEEL +5 -0
- studio_agent-0.1.0.dist-info/entry_points.txt +2 -0
- studio_agent-0.1.0.dist-info/licenses/LICENSE +661 -0
- studio_agent-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""The connection list: what is cabled to what in the studio.
|
|
2
|
+
|
|
3
|
+
The cabling lives in ~/Studio Agent/connections.yaml, in the patchlist format
|
|
4
|
+
(arirusso/patchlist): `devices`, a mapping, and `connections`, a list of
|
|
5
|
+
cables. The agent's `connections` tool reads it. This is a lookup, not
|
|
6
|
+
retrieval:
|
|
7
|
+
1. read the YAML file
|
|
8
|
+
2. keep the cables that touch the device asked about (an exact name match),
|
|
9
|
+
or all of them
|
|
10
|
+
3. return them as lines of text, with each device's fields as written
|
|
11
|
+
(brand, model, a patchbay's type and normalling...) and its manual name,
|
|
12
|
+
so the model can go on to search that manual
|
|
13
|
+
No embeddings: the file is small and structured, so code finds the answer
|
|
14
|
+
exactly, and only when the model asks (the file isn't pasted into every prompt).
|
|
15
|
+
|
|
16
|
+
Not done yet: following a signal through a patchbay's normals or inside a
|
|
17
|
+
device as a route; patchlist has no normaliser for that so far. Instead each
|
|
18
|
+
patchbay gets a note on what the list can't show (patchbay_note()), and a line
|
|
19
|
+
per point whose two rear jacks are both cabled, saying what its normal joins
|
|
20
|
+
unless a front-panel cord changes it (normal_routes()). And YAML comments
|
|
21
|
+
("# unverified") are dropped when the file is read, so the model never sees them.
|
|
22
|
+
|
|
23
|
+
Run on its own to see what the model would get:
|
|
24
|
+
.venv/bin/python -m studio_agent.connections # everything
|
|
25
|
+
.venv/bin/python -m studio_agent.connections "TT-1" # one device
|
|
26
|
+
"""
|
|
27
|
+
import re
|
|
28
|
+
import sys
|
|
29
|
+
|
|
30
|
+
import yaml
|
|
31
|
+
|
|
32
|
+
from studio_agent import studio
|
|
33
|
+
|
|
34
|
+
FILE_NAME = "connections.yaml"
|
|
35
|
+
|
|
36
|
+
# For each patchlist cable type: its ends, and each end's role ("out" sends,
|
|
37
|
+
# "in" receives, None for a two-way end such as USB). A "custom" cable lists
|
|
38
|
+
# its nets itself, each end with its own role.
|
|
39
|
+
CABLE_ENDS = {
|
|
40
|
+
"simple": [("from", "out"), ("to", "in")],
|
|
41
|
+
"usb": [("host", None), ("peripheral", None)],
|
|
42
|
+
"link": [("a", None), ("b", None)],
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def path():
|
|
47
|
+
return studio.home() / FILE_NAME
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def load():
|
|
51
|
+
"""Read the file. Returns (devices, nets), or None if there's no file.
|
|
52
|
+
|
|
53
|
+
devices {device key: its fields, e.g. {"brand": ..., "model": ...}}
|
|
54
|
+
nets one entry per net (a set of jacks joined by a cable), each
|
|
55
|
+
{"type": cable type, "ends": [(device, jack, role), ...]}
|
|
56
|
+
"""
|
|
57
|
+
if not path().exists():
|
|
58
|
+
return None
|
|
59
|
+
data = yaml.safe_load(path().read_text()) or {}
|
|
60
|
+
# str(): YAML reads an unquoted 1 as a number and On as true. patchlist
|
|
61
|
+
# says device keys and jack names are always strings.
|
|
62
|
+
devices = {str(key): fields or {} for key, fields in (data.get("devices") or {}).items()}
|
|
63
|
+
nets = [net for cable in data.get("connections") or [] for net in nets_of(cable)]
|
|
64
|
+
return devices, nets
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def nets_of(cable):
|
|
68
|
+
"""A cable as a list of nets (most cables are one net; an insert cable is two)."""
|
|
69
|
+
kind = cable.get("type", "simple")
|
|
70
|
+
end = lambda e, role: (str(e["device"]), str(e["jack"]), role)
|
|
71
|
+
if kind == "custom":
|
|
72
|
+
return [{"type": kind, "ends": [end(e, e.get("role")) for e in net["ends"]]}
|
|
73
|
+
for net in cable["nets"]]
|
|
74
|
+
if kind not in CABLE_ENDS:
|
|
75
|
+
raise ValueError(f"Unknown cable type {kind!r} in {FILE_NAME}. "
|
|
76
|
+
f"Known types: {', '.join(CABLE_ENDS)}, custom")
|
|
77
|
+
return [{"type": kind, "ends": [end(cable[name], role) for name, role in CABLE_ENDS[kind]]}]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def describe(net):
|
|
81
|
+
"""One net as a line of text: senders → receivers, two-way ends joined by ↔."""
|
|
82
|
+
names = lambda role: [f"{d} {j}" for d, j, r in net["ends"] if r == role]
|
|
83
|
+
outs, ins, both = names("out"), names("in"), names(None)
|
|
84
|
+
text = f"{', '.join(outs)} → {', '.join(ins)}" if outs or ins else ""
|
|
85
|
+
text = " ↔ ".join(filter(None, [text] + both)) # filter(None, ...) drops the empty ""
|
|
86
|
+
return text + (f" ({net['type']})" if net["type"] in ("usb", "link") else "")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# What a front-panel patch cord does in each normalling mode. patchlist hasn't
|
|
90
|
+
# settled the vocabulary yet; a mode not listed here gets the general note.
|
|
91
|
+
# Half stays neutral on direction: which front jack breaks the normal depends
|
|
92
|
+
# on which row is the source, also undecided in patchlist. "{cords}" says
|
|
93
|
+
# whether the list has front cords for this patchbay (patchbay_note()).
|
|
94
|
+
JOINED = "Each point's REAR TOP and REAR BOTTOM jacks are joined inside the unit (its normal). "
|
|
95
|
+
NORMALLING = {
|
|
96
|
+
"full": JOINED + "A front-panel patch cord, {cords}, in either of the point's "
|
|
97
|
+
"front jacks breaks the normal.",
|
|
98
|
+
"half": JOINED + "A front-panel patch cord, {cords}, in one of the point's front "
|
|
99
|
+
"jacks breaks the normal; in the other it takes a copy and leaves the normal "
|
|
100
|
+
"intact. Which is which depends on how the unit is wired.",
|
|
101
|
+
"thru": JOINED + "A front-panel patch cord, {cords}, never breaks the normal: it "
|
|
102
|
+
"takes a copy of the signal, or adds a second one.",
|
|
103
|
+
"open": "Each point's REAR TOP and REAR BOTTOM jacks are not joined inside the unit: only "
|
|
104
|
+
"front-panel patch cords, {cords}, connect them.",
|
|
105
|
+
}
|
|
106
|
+
# An instruction to act, at the end of every patchbay note. Measured (Dec 5,
|
|
107
|
+
# 2026): from another device's lookup (the mixer's), gpt-6-luna stopped at
|
|
108
|
+
# "Patchbay REAR TOP 1" in 10 of 15 runs and said the list doesn't show what
|
|
109
|
+
# feeds it; the patchbay's own lookup does. An instruction to pass on the
|
|
110
|
+
# note's caveat made no difference: once it looked the patchbay up, it gave the
|
|
111
|
+
# caveat anyway (5 of 5).
|
|
112
|
+
LOOK_IT_UP = " To see what's cabled to its other jacks, look it up."
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def patchbay_note(fields, front_cords_listed=False):
|
|
116
|
+
"""The line printed under a patchbay. Measured (Dec 4, 2026): with only the
|
|
117
|
+
fields, the model stated a path through a normal as fact, ignoring the
|
|
118
|
+
prompt's "the list doesn't show normals"; with a note saying only what's
|
|
119
|
+
missing ("not in this list: where its normals lead"), it stopped at the
|
|
120
|
+
patchbay instead of following the normal. So the note says what the normal
|
|
121
|
+
joins, then why that's not certain, then to look the patchbay up (LOOK_IT_UP):
|
|
122
|
+
from another device's lookup, the model otherwise stopped at the patchbay's
|
|
123
|
+
jack. Next to the data it's harder to miss, and it reaches a chat app's
|
|
124
|
+
model too, which never sees our prompt.
|
|
125
|
+
|
|
126
|
+
Front cords: "not in this list" when the list has none for this patchbay
|
|
127
|
+
(true then, and measured: it found the source 29 of 30 times, against about
|
|
128
|
+
17 of 30 with no claim and 2 of 15 with "this list may not show them all",
|
|
129
|
+
Dec 5, 2026); "listed or not" when it has some, as the owner's studio does.
|
|
130
|
+
The second is unmeasured."""
|
|
131
|
+
note = NORMALLING.get(fields.get("normalling"))
|
|
132
|
+
cords = "listed or not" if front_cords_listed else "not in this list"
|
|
133
|
+
if note is None:
|
|
134
|
+
note = ("How its points are joined inside isn't in this list, and front-panel "
|
|
135
|
+
"patch cords, {cords}, can change the route.")
|
|
136
|
+
note = note.format(cords=cords)
|
|
137
|
+
if fields.get("overrides"):
|
|
138
|
+
note += " Points in its overrides may differ."
|
|
139
|
+
return " " + note + LOOK_IT_UP
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def fields_text(fields):
|
|
143
|
+
"""A device's fields as written, for example "type: patchbay, points: 8,
|
|
144
|
+
normalling: half"; a nested mapping (a patchbay's overrides) in braces."""
|
|
145
|
+
show = lambda v: "{" + fields_text(v) + "}" if isinstance(v, dict) else str(v)
|
|
146
|
+
return ", ".join(f"{key}: {show(value)}" for key, value in fields.items())
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def simplify(name):
|
|
150
|
+
return re.sub(r"[\s-]", "", name).lower() # ignore case, spaces and hyphens
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def manual_for(key, fields, manuals):
|
|
154
|
+
"""The manual that goes with a device, by plain name matching, or None.
|
|
155
|
+
|
|
156
|
+
Tried in turn: the device key ("SR-16"), then brand + model, so two units
|
|
157
|
+
of one model ("525 Drums", "525 Bus") share its manual ("Symetrix 525"),
|
|
158
|
+
then the model alone. A mapping file ("Manual mapping file" in BACKLOG.md) can come
|
|
159
|
+
when a real studio has a name this can't match.
|
|
160
|
+
"""
|
|
161
|
+
by_name = {simplify(m): m for m in manuals}
|
|
162
|
+
brand, model = str(fields.get("brand", "")), str(fields.get("model", ""))
|
|
163
|
+
for name in (key, f"{brand} {model}", model):
|
|
164
|
+
if name.strip() and simplify(name) in by_name:
|
|
165
|
+
return by_name[simplify(name)]
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def coverage(devices, manuals):
|
|
171
|
+
"""What the manuals and the connection list don't share, for status.
|
|
172
|
+
Returns (no_manual, uncabled):
|
|
173
|
+
|
|
174
|
+
no_manual devices with no manual, units of one model together:
|
|
175
|
+
["Polen", "Symetrix 525 (Symetrix 525 Drums, Symetrix 525 Bus)"].
|
|
176
|
+
Patchbays are left out: they have no manual to add.
|
|
177
|
+
uncabled manuals that no device in the list goes with
|
|
178
|
+
"""
|
|
179
|
+
groups, used = {}, set()
|
|
180
|
+
for key, fields in devices.items():
|
|
181
|
+
if manual := manual_for(key, fields, manuals):
|
|
182
|
+
used.add(manual)
|
|
183
|
+
elif fields.get("type") != "patchbay":
|
|
184
|
+
brand, model = fields.get("brand"), fields.get("model")
|
|
185
|
+
# setdefault: the list for this group, made empty the first time, like ||= in Ruby
|
|
186
|
+
groups.setdefault(f"{brand} {model}" if brand and model else key, []).append(key)
|
|
187
|
+
no_manual = [units[0] if len(units) == 1 else f"{name} ({', '.join(units)})"
|
|
188
|
+
for name, units in groups.items()]
|
|
189
|
+
return no_manual, [m for m in manuals if m not in used]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def normal_routes(patchbay, fields, nets):
|
|
193
|
+
"""A line per point whose REAR TOP and REAR BOTTOM jacks are both cabled,
|
|
194
|
+
saying what its normal joins, for the modes that join them. Measured
|
|
195
|
+
(Dec 5, 2026): with only the general note, gpt-6-luna stated the route
|
|
196
|
+
through point 1 as fact, or stopped at the mixer's "Patchbay REAR TOP 1";
|
|
197
|
+
the route next to the data, with its condition, is harder to miss. Shown
|
|
198
|
+
wherever the patchbay is listed, the mixer's lookup included."""
|
|
199
|
+
if fields.get("normalling") not in ("full", "half", "thru"):
|
|
200
|
+
return []
|
|
201
|
+
def others(jack): # what's cabled to one of the patchbay's jacks
|
|
202
|
+
return [f"{d} {j}" for net in nets if (patchbay, jack) in [(e[0], e[1]) for e in net["ends"]]
|
|
203
|
+
for d, j, _ in net["ends"] if (d, j) != (patchbay, jack)]
|
|
204
|
+
rear, front = {}, set() # point number -> {"TOP": jack, "BOTTOM": jack}; points with a front cord
|
|
205
|
+
for net in nets:
|
|
206
|
+
for d, jack, _ in net["ends"]:
|
|
207
|
+
if d == patchbay and (m := re.fullmatch(r"(REAR|FRONT) (TOP|BOTTOM) (\d+)", jack.upper())):
|
|
208
|
+
if m[1] == "REAR":
|
|
209
|
+
rear.setdefault(int(m[3]), {})[m[2]] = jack
|
|
210
|
+
else:
|
|
211
|
+
front.add(int(m[3]))
|
|
212
|
+
return [f" Point {n}'s normal joins {', '.join(others(j['BOTTOM']))} ({j['BOTTOM']}) "
|
|
213
|
+
f"to {', '.join(others(j['TOP']))} ({j['TOP']}), unless a front-panel cord changes it."
|
|
214
|
+
+ (" This list has one in this point." if n in front else "")
|
|
215
|
+
for n, j in sorted(rear.items()) if len(j) == 2]
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def follow_on(device, shown, devices):
|
|
219
|
+
"""The last line of one device's lookup: the devices it's cabled to, to
|
|
220
|
+
look up in turn. The lookup shows only cables touching the device asked
|
|
221
|
+
about, so a path through another device (Anushri → MIDIpal → ...) goes on
|
|
222
|
+
in that device's lookup. Patchbays are left out: their note already says
|
|
223
|
+
to look them up. An action next to the data, as LOOK_IT_UP: gpt-6-luna
|
|
224
|
+
sometimes looked up only the two ends of a chain and said no cable joins
|
|
225
|
+
them (clock-shruthi, about 1 run in 20)."""
|
|
226
|
+
others = [d for d in shown if d != device and devices[d].get("type") != "patchbay"]
|
|
227
|
+
if not others:
|
|
228
|
+
return []
|
|
229
|
+
return [f"Only cables touching {device} are shown. A path through "
|
|
230
|
+
f"{' or '.join(others)} goes on in that device's lookup: look it up to follow it."]
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def connections(device=None):
|
|
234
|
+
"""The cables touching one device (or all of them), as text for the model.
|
|
235
|
+
Raises ValueError for a device that isn't in the list."""
|
|
236
|
+
loaded = load()
|
|
237
|
+
if loaded is None:
|
|
238
|
+
return f"There is no connection list yet. It goes in {path()} (patchlist format)."
|
|
239
|
+
devices, nets = loaded
|
|
240
|
+
if device is not None and device not in devices:
|
|
241
|
+
raise ValueError(f"Unknown device {device!r}. Devices in the connection list: "
|
|
242
|
+
f"{', '.join(devices)}")
|
|
243
|
+
|
|
244
|
+
kept = [net for net in nets if device is None or any(d == device for d, _, _ in net["ends"])]
|
|
245
|
+
# The devices to report: every one when listing all, else the device and
|
|
246
|
+
# whatever it's cabled to, in the file's order.
|
|
247
|
+
shown = [d for d in devices
|
|
248
|
+
if device is None or d == device or any(d == e[0] for net in kept for e in net["ends"])]
|
|
249
|
+
manuals = studio.manuals()
|
|
250
|
+
|
|
251
|
+
lines = ["Devices, with their fields as listed and the manual to search for each:"]
|
|
252
|
+
for d in shown:
|
|
253
|
+
manual = manual_for(d, devices[d], manuals)
|
|
254
|
+
fields = f" ({fields_text(devices[d])})" if devices[d] else ""
|
|
255
|
+
lines.append(f" {d}{fields}: " + (f'manual "{manual}"' if manual else "no manual"))
|
|
256
|
+
if devices[d].get("type") == "patchbay":
|
|
257
|
+
front = any(dev == d and jack.upper().startswith("FRONT")
|
|
258
|
+
for net in nets for dev, jack, _ in net["ends"])
|
|
259
|
+
lines.append(patchbay_note(devices[d], front_cords_listed=front))
|
|
260
|
+
lines += normal_routes(d, devices[d], nets)
|
|
261
|
+
lines.append("Cables (→ points from the sending jack to the receiving jack):")
|
|
262
|
+
lines += [f" {describe(net)}" for net in kept] or [f" none touch {device}"]
|
|
263
|
+
if device is not None:
|
|
264
|
+
lines += follow_on(device, shown, devices)
|
|
265
|
+
return "\n".join(lines)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
if __name__ == "__main__":
|
|
269
|
+
print(connections(sys.argv[1] if len(sys.argv) > 1 else None))
|
studio_agent/eval.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""The eval: does search() put the right pages in its top results? With
|
|
2
|
+
--agent, are the agent's searches and answers right?
|
|
3
|
+
|
|
4
|
+
For each question in eval/questions.json:
|
|
5
|
+
1. search(question): the same single search plain RAG makes; no chat model
|
|
6
|
+
2. label each result the way citations do, e.g. "SR-16 p49" or "MIDIHub clock"
|
|
7
|
+
3. check each "need" (a fact the answer needs, met by any of its listed pages)
|
|
8
|
+
|
|
9
|
+
Scores, per question and per kind:
|
|
10
|
+
hit@k at least one need met in the top k
|
|
11
|
+
recall@k share of needs met (below 100% when a cross-device question
|
|
12
|
+
finds one manual and not the other)
|
|
13
|
+
|
|
14
|
+
A need may be ["connections"]: a fact from the connection list, not a manual.
|
|
15
|
+
Plain search can't look anything up, so it always misses one; that's true, and
|
|
16
|
+
such questions get their own kind ("wiring") so the other rows don't move.
|
|
17
|
+
|
|
18
|
+
The gold pages may be incomplete: a page that answers the question but isn't
|
|
19
|
+
listed counts as a miss. So scores are a lower bound. When a miss shows up,
|
|
20
|
+
read what came back, and add any page that does answer it to questions.json.
|
|
21
|
+
|
|
22
|
+
With --agent, the agent answers each question instead (chat calls, so it
|
|
23
|
+
costs money and varies between runs). A need counts as met if any of the
|
|
24
|
+
agent's searches returned one of its pages; its "rank" is the number of the
|
|
25
|
+
search that first did. A ["connections"] need is met if the agent called
|
|
26
|
+
connections at all, shown as rank "c". Its answer is then checked too (check_answer()):
|
|
27
|
+
cites for each need, the answer cites at least one of its pages ([connections]
|
|
28
|
+
for a connections need); a lower bound, like recall, since a right
|
|
29
|
+
citation to an unlisted page fails
|
|
30
|
+
says each regex in the question's "checks": {"says": [...]} must match
|
|
31
|
+
never no regex in "checks": {"never": [...]} may match. Aim it at the
|
|
32
|
+
wrong claim, not a word: "5-pin MIDI out" is wrong for the
|
|
33
|
+
BeatStep Pro, but "a 1/8\" to 5-pin adapter" is right.
|
|
34
|
+
answered only when the loop hit its turn cap with no answer: it fails, with
|
|
35
|
+
every cites and says check, in place of the never checks.
|
|
36
|
+
A failed check prints the answer, since the check itself may be what's wrong.
|
|
37
|
+
|
|
38
|
+
Run (the questions file describes one studio, so it's an argument):
|
|
39
|
+
studio-agent eval eval/questions.json # top 5, as plain RAG uses
|
|
40
|
+
studio-agent eval eval/questions.json -k 10
|
|
41
|
+
studio-agent eval eval/questions.json --agent --kind cross # the agent, cross-device questions only
|
|
42
|
+
"""
|
|
43
|
+
import json
|
|
44
|
+
import re
|
|
45
|
+
import textwrap
|
|
46
|
+
from pathlib import Path
|
|
47
|
+
|
|
48
|
+
from studio_agent.ask_agentic import ask_agentic
|
|
49
|
+
from studio_agent.citation import location
|
|
50
|
+
from studio_agent.search import search
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def evaluate(q, k):
|
|
55
|
+
"""Search for one question and score the results against its needs."""
|
|
56
|
+
labels = [f"{r['device']} {location(r)}" for r in search(q["question"], k=k)]
|
|
57
|
+
# For each need, the rank (1-based) of the first result that meets it, or None.
|
|
58
|
+
ranks = [
|
|
59
|
+
next((i for i, label in enumerate(labels, 1) if label in need), None)
|
|
60
|
+
for need in q["needs"]
|
|
61
|
+
]
|
|
62
|
+
met = sum(r is not None for r in ranks)
|
|
63
|
+
return {"labels": labels, "ranks": ranks, "hit": met > 0, "recall": met / len(ranks), "cost": 0}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def citations(answer):
|
|
67
|
+
"""Every label the answer cites. "[SR-16 p49]" gives "SR-16 p49"; a group
|
|
68
|
+
like "[SR-16 p49, p61]" gives both, the bare "p61" taking the device before
|
|
69
|
+
it; a range like "[XR10 p65–66]" gives each page in it. "[connections]"
|
|
70
|
+
gives "connections", the connection list."""
|
|
71
|
+
found = set()
|
|
72
|
+
for group in re.findall(r"\[([^\]]+)\]", answer):
|
|
73
|
+
device = None
|
|
74
|
+
for part in re.split(r"\s*[,;]\s*", group.strip()):
|
|
75
|
+
if part.lower() == "connections":
|
|
76
|
+
found.add("connections")
|
|
77
|
+
continue
|
|
78
|
+
if " " in part: # "Fireface 802 p23": the device is everything before the last word
|
|
79
|
+
device, place = part.rsplit(" ", 1)
|
|
80
|
+
elif device:
|
|
81
|
+
place = part
|
|
82
|
+
else:
|
|
83
|
+
continue
|
|
84
|
+
if m := re.fullmatch(r"p(\d+)[–-]p?(\d+)", place): # a range, en dash or hyphen
|
|
85
|
+
first, last = int(m[1]), int(m[2])
|
|
86
|
+
found |= {f"{device} p{n}" for n in range(first, min(last, first + 10) + 1)}
|
|
87
|
+
else:
|
|
88
|
+
found.add(f"{device} {place}")
|
|
89
|
+
return found
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def same_label(label):
|
|
93
|
+
"""A label in a form that ignores how it was written: a model sometimes cites
|
|
94
|
+
a Markdown page by its heading ("[MIDIpal Debugging apps]", even
|
|
95
|
+
"[MIDIpal *Debugging apps: MIDI monitor*]") instead of its name
|
|
96
|
+
("[MIDIpal debugging-apps]"). A reader finds the page either way, so the
|
|
97
|
+
check accepts both: case, punctuation and anything after a colon are ignored."""
|
|
98
|
+
return re.sub(r"[^a-z0-9]+", "-", label.split(":")[0].lower()).strip("-")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
ANSWERED = "answered (not stopped by the turn cap)"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def check_answer(answer, q):
|
|
105
|
+
"""Check one answer. Returns a list of (check, passed) pairs, in the order
|
|
106
|
+
cites (one per need), says, never. An answer of None (the loop hit its turn
|
|
107
|
+
cap) fails every cites and says check, and one "answered" check in place of
|
|
108
|
+
the never checks: no claim was made, so none was wrong, but it mustn't
|
|
109
|
+
score as a pass either. The gate counts a turn cap apart from never
|
|
110
|
+
failures (decided Dec 5, 2026)."""
|
|
111
|
+
checks = q.get("checks", {})
|
|
112
|
+
# Models often write a curly apostrophe ("don’t"), a minus sign ("−10 dBV")
|
|
113
|
+
# and Markdown bold ("**Main Left** output"); straighten the first, make the
|
|
114
|
+
# second a hyphen and drop the third, so a pattern only has to spell "don't",
|
|
115
|
+
# "-10 dBV" and "main left output".
|
|
116
|
+
text = (answer or "").replace("’", "'").replace("−", "-").replace("**", "")
|
|
117
|
+
cited = citations(text)
|
|
118
|
+
# re.I: ignore case; re.S: let . match a newline, since answers span lines.
|
|
119
|
+
found = lambda pattern: re.search(pattern, text, re.I | re.S) is not None
|
|
120
|
+
cited = {same_label(c) for c in cited}
|
|
121
|
+
results = [(f"cites one of {', '.join(need)}", bool(cited & {same_label(n) for n in need}))
|
|
122
|
+
for need in q["needs"]]
|
|
123
|
+
results += [(f"says /{p}/", found(p)) for p in checks.get("says", [])]
|
|
124
|
+
if answer is None:
|
|
125
|
+
return [(check, False) for check, _ in results] + [(ANSWERED, False)]
|
|
126
|
+
results += [(f"never /{p}/", not found(p)) for p in checks.get("never", [])]
|
|
127
|
+
return results
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def evaluate_agent(q):
|
|
131
|
+
"""Let the agent answer one question; score every search it made, then the answer."""
|
|
132
|
+
result = ask_agentic(q["question"])
|
|
133
|
+
searches = [[f"{c['device']} {location(c)}" for c in s["results"]] for s in result["searches"]]
|
|
134
|
+
# For each need, the number (1-based) of the first search that met it, or None;
|
|
135
|
+
# "c" for a connections need the agent met by calling connections.
|
|
136
|
+
def rank(need):
|
|
137
|
+
if "connections" in need and result["lookups"]:
|
|
138
|
+
return "c"
|
|
139
|
+
return next((i for i, labels in enumerate(searches, 1) if any(l in need for l in labels)), None)
|
|
140
|
+
ranks = [rank(need) for need in q["needs"]]
|
|
141
|
+
met = sum(r is not None for r in ranks)
|
|
142
|
+
labels = sorted({l for labels in searches for l in labels}) # every distinct page it saw
|
|
143
|
+
checks = check_answer(result["answer"], q)
|
|
144
|
+
return {"labels": labels, "ranks": ranks, "hit": met > 0, "recall": met / len(ranks),
|
|
145
|
+
"cost": result["cost"], "searches": len(searches),
|
|
146
|
+
# connections calls: counted so the report shows whether the cable
|
|
147
|
+
# list is used, and whether it crowds out searches of the manuals
|
|
148
|
+
"lookups": len(result["lookups"]),
|
|
149
|
+
"answer": result["answer"], "checks": checks,
|
|
150
|
+
"passed": sum(ok for _, ok in checks) / len(checks)}
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def run(questions_file, k=5, agent=False, kind=None):
|
|
154
|
+
"""Score every question in questions_file (or only those of one kind) and print a report."""
|
|
155
|
+
questions = json.loads(Path(questions_file).read_text())
|
|
156
|
+
if kind:
|
|
157
|
+
questions = [q for q in questions if q["kind"] == kind]
|
|
158
|
+
unit = "search number" if agent else "rank"
|
|
159
|
+
by_kind = {} # kind -> list of results
|
|
160
|
+
|
|
161
|
+
for q in questions:
|
|
162
|
+
r = evaluate_agent(q) if agent else evaluate(q, k)
|
|
163
|
+
by_kind.setdefault(q["kind"], []).append(r) # setdefault: like Hash#fetch with a default that's also stored
|
|
164
|
+
mark = "ok " if r["recall"] == 1 else ("part" if r["hit"] else "MISS")
|
|
165
|
+
ranks = ", ".join("-" if x is None else str(x) for x in r["ranks"])
|
|
166
|
+
extra = ""
|
|
167
|
+
if agent:
|
|
168
|
+
passed = sum(ok for _, ok in r["checks"])
|
|
169
|
+
extra = (f" ({r['searches']} searches, {r['lookups']} lookups, ${r['cost']:.4f}; "
|
|
170
|
+
f"answer {passed}/{len(r['checks'])})")
|
|
171
|
+
print(f"{mark} {q['kind']:8} {q['id']:26} {unit} of each need: {ranks}{extra}")
|
|
172
|
+
if r["recall"] < 1:
|
|
173
|
+
print(f" got: {', '.join(r['labels'])}")
|
|
174
|
+
if agent and r["passed"] < 1:
|
|
175
|
+
for check, ok in r["checks"]:
|
|
176
|
+
if not ok:
|
|
177
|
+
print(f" failed: {check}")
|
|
178
|
+
print(textwrap.indent(r["answer"] or "(no answer: the loop hit its turn cap)", " | "))
|
|
179
|
+
|
|
180
|
+
def row(name, rs):
|
|
181
|
+
"""One line of the summary: the mean of each score over results rs."""
|
|
182
|
+
mean = lambda key: sum(r[key] for r in rs) / len(rs)
|
|
183
|
+
line = f"{name:10} {len(rs):2} {mean('hit'):5.0%} {mean('recall'):6.0%}"
|
|
184
|
+
return line + (f" {mean('passed'):6.0%}" if agent else "")
|
|
185
|
+
|
|
186
|
+
print(f"\n{'agent' if agent else f'plain search, top {k}'}")
|
|
187
|
+
print(f"{'kind':10} {'n':>2} hit recall" + (" answer" if agent else ""))
|
|
188
|
+
for kind, rs in by_kind.items():
|
|
189
|
+
print(row(kind, rs))
|
|
190
|
+
print(row("all", [r for rs in by_kind.values() for r in rs]))
|
|
191
|
+
if agent:
|
|
192
|
+
everything = [r for rs in by_kind.values() for r in rs]
|
|
193
|
+
print(f"total cost about ${sum(r['cost'] for r in everything):.4f}")
|