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.
@@ -0,0 +1 @@
1
+ """studio-agent: answers about studio gear from its manuals, with citations."""
@@ -0,0 +1,4 @@
1
+ """python -m studio_agent: the same as the studio-agent command."""
2
+ from studio_agent.cli import main
3
+
4
+ main()
studio_agent/ask.py ADDED
@@ -0,0 +1,36 @@
1
+ """Plain RAG: one search, chosen by our code, then one chat call.
2
+
3
+ question -> search() -> top 5 pages -> chat model reads question + chunk text -> answer
4
+
5
+ Kept for comparison with the agent. Run:
6
+ studio-agent ask --plain "How do I make the SR-16 follow an external MIDI clock?"
7
+ """
8
+ from openai import OpenAI
9
+
10
+ from studio_agent.citation import location
11
+ from studio_agent.config import DEFAULT_CHAT_MODEL
12
+ from studio_agent.search import search
13
+
14
+ # Sent as the "instructions" (the system prompt): rules for every question.
15
+ INSTRUCTIONS = """\
16
+ You answer questions about music equipment using only the manual excerpts provided.
17
+
18
+ - Every claim about a specific device must come from an excerpt. You may use general
19
+ background knowledge (what MIDI clock is, for example) only to understand the excerpts.
20
+ - Cite each claim with the excerpt's label, for example [SR-16 p49].
21
+ - If the excerpts don't contain the answer, or contain only part of it, say so plainly
22
+ and say what information is missing. Do not fill gaps from memory.
23
+ """
24
+
25
+
26
+ def format_excerpts(chunks):
27
+ """The chunks as the model sees them: a label line, then the text."""
28
+ return "\n\n".join(f"[{c['device']} {location(c)}]\n{c['text']}" for c in chunks)
29
+
30
+
31
+ def ask(question, model=DEFAULT_CHAT_MODEL):
32
+ """Returns (chunks used, model response)."""
33
+ chunks = search(question) # our code decides what to retrieve: the question, as is
34
+ prompt = f"Excerpts:\n\n{format_excerpts(chunks)}\n\nQuestion: {question}"
35
+ response = OpenAI().responses.create(model=model, instructions=INSTRUCTIONS, input=prompt)
36
+ return chunks, response
@@ -0,0 +1,204 @@
1
+ """Agentic RAG: the model decides what to search for, in a loop.
2
+
3
+ It has two tools: search (retrieval over the manuals) and connections (a
4
+ lookup in the studio's connection list, connections.py).
5
+
6
+ Each turn:
7
+ 1. model call: question + everything so far -> model replies
8
+ 2. if the reply asks for search(...) or connections(...), our code runs it
9
+ and adds the result to the history, then goes back to 1
10
+ 3. if the reply is plain text, that's the answer: stop
11
+ Capped at MAX_TURNS model calls.
12
+
13
+ Run:
14
+ studio-agent ask "Can the BeatStep Pro drive the SR-16's tempo?"
15
+ studio-agent ask "..." --model gpt-6.1-sol
16
+ """
17
+ import json
18
+
19
+ from openai import OpenAI
20
+
21
+ from studio_agent.ask import format_excerpts
22
+ from studio_agent.citation import location
23
+ from studio_agent.config import DEFAULT_CHAT_MODEL, PRICES
24
+ from studio_agent.connections import connections, load as load_connections
25
+ from studio_agent.search import has_index, indexed_devices, search, status_message
26
+
27
+ MAX_TURNS = 10
28
+
29
+ INSTRUCTIONS = """\
30
+ You answer questions about the user's music and audio gear (synths, drum machines, samplers, mixers, effects, audio interfaces and MIDI gear)
31
+ from two sources: its manuals (the search tool) and the list of how it's cabled (the
32
+ connections tool). Use either or both, as many times as you need.
33
+
34
+ - Every claim about a specific device or cable must come from a source. You may use
35
+ general background knowledge (what MIDI clock is, for example) only to understand them.
36
+ - Cite each claim: an excerpt's label, for example [SR-16 p49], or [connections].
37
+ - Before saying how a device behaves or must be set, find the excerpt that describes
38
+ that behaviour or setting and cite it. An excerpt that only names a feature (an
39
+ overview, a feature list) doesn't support a claim about how it works.
40
+ - The connection list shows cables only, not a patchbay's normals or routing inside a
41
+ device, so don't claim more than it shows.
42
+ - A lookup for one device shows only the cables touching it. To follow a signal or MIDI
43
+ path through several devices, or to find why one doesn't arrive, look up each device
44
+ along the way, both ends included, or every cable (null). A good cable at one end
45
+ doesn't rule out a problem at the other.
46
+ - Don't answer that a signal can't get somewhere, or that a jack goes nowhere, from
47
+ lookups of other devices: a device's own lookup, or every cable, is the only proof
48
+ of what it's cabled to. Follow each cable out of the starting device first.
49
+ - When a signal or MIDI path runs through a device (an effect in an insert, a filter, a
50
+ MIDI processor), search that device's manual for what it does to what comes in:
51
+ whether it passes it on, and when.
52
+ - Before recommending a device for a role, such as master clock, search each
53
+ candidate's manual for whether it can do it: what it sends from its outputs, not
54
+ only its settings (a tempo setting doesn't show that it sends clock). Give the
55
+ reason for your pick, with its citation.
56
+ - If the sources don't contain the answer, or contain only part of it, say so plainly
57
+ and say what information is missing. Do not fill gaps from memory.
58
+ """
59
+
60
+ # The tool as the model sees it. The device list comes from the index, so the
61
+ # model can only pass a name that exists (testing showed it will
62
+ # otherwise invent one). Strict mode needs every field in "required"; an
63
+ # optional field is expressed as "a value or null". A function rather than a
64
+ # constant, so the index is read when a question is asked, not on import.
65
+ def tools():
66
+ return [search_tool(), connections_tool()]
67
+
68
+
69
+ def search_tool():
70
+ # Offered even with no index (a studio with only a connection list): the
71
+ # call then returns what to do, so the model can tell the user.
72
+ names = indexed_devices()
73
+ return {
74
+ "type": "function",
75
+ "name": "search",
76
+ "description": (
77
+ "Search the manuals for the user's music and audio gear. Returns the 5 most "
78
+ "relevant excerpts, each labelled with its device and page. "
79
+ + (f"Indexed devices: {', '.join(names)}." if names else "No manuals are indexed yet.")
80
+ ),
81
+ "strict": True,
82
+ "parameters": {
83
+ "type": "object",
84
+ "properties": {
85
+ "query": {"type": "string", "description": "What to look for."},
86
+ "device": {
87
+ "type": ["string", "null"],
88
+ "enum": names + [None],
89
+ "description": "Search only this device's manual, or null for all.",
90
+ },
91
+ },
92
+ "required": ["query", "device"],
93
+ "additionalProperties": False,
94
+ },
95
+ }
96
+
97
+
98
+ def connections_tool():
99
+ # The same enum trick as search: the model can only name a device that's
100
+ # in the connection list (when there is one).
101
+ loaded = load_connections()
102
+ device = {"type": ["string", "null"],
103
+ "description": "A device from the connection list, or null for every cable."}
104
+ if loaded:
105
+ device["enum"] = list(loaded[0]) + [None]
106
+ return {
107
+ "type": "function",
108
+ "name": "connections",
109
+ "description": (
110
+ "Look up how the user's studio is cabled: the cables touching a device (or all "
111
+ "cables, with null), each as sending jack → receiving jack, and which manual to "
112
+ "search for each device. From the user's connection list, not from a manual. "
113
+ "One device's lookup shows only its own cables: to follow a path through "
114
+ "several devices, look up each one along it, or every cable."
115
+ ),
116
+ "strict": True,
117
+ "parameters": {
118
+ "type": "object",
119
+ "properties": {"device": device},
120
+ "required": ["device"],
121
+ "additionalProperties": False,
122
+ },
123
+ }
124
+
125
+
126
+ def run_connections(args):
127
+ """Run one connections lookup the model asked for. Returns the text for the model."""
128
+ try:
129
+ return connections(args["device"])
130
+ except ValueError as e:
131
+ return f"Error: {e}" # sent back to the model, as with search
132
+
133
+
134
+ def run_search(args):
135
+ """Run one search the model asked for. Returns (text for the model, chunks)."""
136
+ if not has_index():
137
+ return status_message(None), [] # "No index yet. Run: studio-agent index"
138
+ try:
139
+ chunks = search(args["query"], args["device"])
140
+ except ValueError as e:
141
+ return f"Error: {e}", [] # sent back to the model, so it can correct itself
142
+ return format_excerpts(chunks), chunks
143
+
144
+
145
+ def cost(model, tokens_in, tokens_out):
146
+ """Approximate dollars for a run, from the prices in config.py."""
147
+ price_in, price_out = PRICES[model]
148
+ return (tokens_in * price_in + tokens_out * price_out) / 1_000_000
149
+
150
+
151
+ # log=lambda line: None is a do-nothing function, like ->(line) {} in Ruby.
152
+ # The CLI passes print instead, to show progress as it happens.
153
+ def ask_agentic(question, model=DEFAULT_CHAT_MODEL, log=lambda line: None):
154
+ """Run the loop. Returns a dict, so the CLI and the web page can each show it:
155
+ answer the final text, or None if the loop hit MAX_TURNS
156
+ searches every search the model made, in order: query, device, results
157
+ lookups the device of every connections call, in order (None: all)
158
+ tokens_in, tokens_out, cost
159
+ """
160
+ client = OpenAI()
161
+ tool_list = tools()
162
+ history = [{"role": "user", "content": question}] # resent in full every turn
163
+ searches, lookups = [], []
164
+ tokens_in = tokens_out = 0
165
+ answer = None
166
+
167
+ for turn in range(1, MAX_TURNS + 1):
168
+ response = client.responses.create(
169
+ model=model, instructions=INSTRUCTIONS, tools=tool_list, input=history
170
+ )
171
+ u = response.usage
172
+ tokens_in += u.input_tokens
173
+ tokens_out += u.output_tokens
174
+ log(f"turn {turn}: {u.input_tokens:,} in, {u.output_tokens:,} out")
175
+
176
+ history += response.output # keep the model's own output, tool requests included
177
+ calls = [item for item in response.output if item.type == "function_call"]
178
+
179
+ if not calls: # plain text reply: the model has decided it's done
180
+ answer = response.output_text
181
+ break
182
+
183
+ for call in calls:
184
+ args = json.loads(call.arguments) # arguments arrive as a JSON string
185
+ if call.name == "connections":
186
+ text = run_connections(args)
187
+ lookups.append(args["device"])
188
+ cables = sum(" → " in line or " ↔ " in line for line in text.splitlines())
189
+ log(f" connections({call.arguments}) -> {cables} cables")
190
+ else:
191
+ text, chunks = run_search(args)
192
+ searches.append({"query": args["query"], "device": args["device"], "results": chunks})
193
+ pages = ", ".join(f"{c['device']} {location(c)}" for c in chunks) or text
194
+ log(f" search({call.arguments}) -> {pages}")
195
+ history.append({"type": "function_call_output", "call_id": call.call_id, "output": text})
196
+
197
+ return {
198
+ "answer": answer,
199
+ "searches": searches,
200
+ "lookups": lookups,
201
+ "tokens_in": tokens_in,
202
+ "tokens_out": tokens_out,
203
+ "cost": cost(model, tokens_in, tokens_out),
204
+ }
studio_agent/chunk.py ADDED
@@ -0,0 +1,170 @@
1
+ """Pipeline step 2: split page records into chunks of about 500 tokens.
2
+
3
+ Chunks never cross a page boundary, so every chunk cites exactly one page.
4
+ A page short enough stays whole; a longer PDF page is split into equal parts,
5
+ each repeating the last few lines of the part before it (the overlap), so a
6
+ sentence cut at a split still appears whole in one of the two chunks. A
7
+ Markdown file is split where its structure changes instead (markdown_parts).
8
+
9
+ Run on its own to inspect the output:
10
+ .venv/bin/python -m studio_agent.chunk
11
+ """
12
+ import math
13
+ import re
14
+
15
+ LIST_ITEM = re.compile(r"\s*([-*+]|\d+\.)\s") # "- **5**: Line-level..." or "2. Press"
16
+ HEADING_LINE = re.compile(r"#{1,6}\s") # a Markdown heading, "## Setup"
17
+ CHUNK_CHARS = 2000 # about 500 tokens, at roughly 4 characters per token
18
+ OVERLAP_CHARS = 300 # about 75 tokens carried over from the previous part
19
+ MIN_CHARS = 200 # a Markdown chunk shorter than this joins a neighbour
20
+
21
+
22
+ def chunk_page(record):
23
+ """Split one page record into chunk records with the same device and page."""
24
+ if isinstance(record["page"], str): # a Markdown file (PDF pages are numbers)
25
+ chunks = markdown_parts(record["text"])
26
+ else:
27
+ # Strip each line and drop blank ones: PyMuPDF leaves a lot of stray whitespace.
28
+ chunks = split_lines(non_blank(record["text"]))
29
+ return [
30
+ {"device": record["device"], "page": record["page"], "text": "\n".join(c)}
31
+ for c in chunks
32
+ ]
33
+
34
+
35
+ def non_blank(text):
36
+ return [line.strip() for line in text.splitlines() if line.strip()]
37
+
38
+
39
+ def size(lines):
40
+ return len("\n".join(lines))
41
+
42
+
43
+ def split_lines(lines):
44
+ """Lines as one part if they fit in a chunk, else equal parts with overlap."""
45
+ if size(lines) <= CHUNK_CHARS:
46
+ return [lines]
47
+ # Each part holds its share of new text plus the overlap it repeats, so the
48
+ # share is at most CHUNK_CHARS - OVERLAP_CHARS. Equal shares mean a 2,100-
49
+ # character page becomes two similar parts, not one big part and a scrap.
50
+ parts = math.ceil(size(lines) / (CHUNK_CHARS - OVERLAP_CHARS))
51
+ share = size(lines) / parts
52
+
53
+ chunks, current, new_chars = [], [], 0
54
+ for line in lines:
55
+ if new_chars >= share:
56
+ chunks.append(current)
57
+ current, new_chars = overlap(current), 0
58
+ current.append(line)
59
+ new_chars += len(line) + 1 # +1 for the newline
60
+ chunks.append(current)
61
+ return chunks
62
+
63
+
64
+ def markdown_parts(text):
65
+ """A Markdown file's chunks, cut only between blocks, never inside one.
66
+
67
+ The file is cut into blocks at blank lines (a paragraph, a list, a table).
68
+ Blocks are packed into a chunk while they fit, and a block that doesn't fit
69
+ starts the next chunk. A block too long for one chunk is split by length,
70
+ as a PDF page is.
71
+
72
+ Why: split by length alone, the MIDIHub's Transform page put its table of
73
+ message types (Program Change among them) in one chunk with half of an
74
+ unrelated parameter table, and the mix kept that chunk out of the top 5
75
+ for a program-change question; on its own it made the top 5 (Dec 1, 2026).
76
+ A heading also starts a chunk, so a chunk never runs on into the next
77
+ section: the Shruthi's rear-panel list, followed by the start of
78
+ "Controls and navigation" in one chunk, put its audio input's one line
79
+ ("you won't hear anything until a note ... opens the VCA") in the top 5
80
+ for only 4 of 33 of the agent's own queries; cut at the heading, 29 of 33
81
+ (simulated, Dec 5, 2026); measured on a full reindex, 15 of 33, since every
82
+ other chunk got sharper too. Tried before without the merge below (Dec 1):
83
+ it made many tiny chunks (a "See Also" link, a heading and one line).
84
+
85
+ A list item starts a chunk too: the line was one item of that list, and the
86
+ other items (mostly power-supply polarity) still drowned it out. With
87
+ that, 33 of 33. An item under MIN_CHARS joins the one before, so a list
88
+ of short items still makes one chunk.
89
+ """
90
+ chunks, current = [], []
91
+ for lines in blocks(text):
92
+ # A heading or a list item starts a new chunk, unless the chunk so far
93
+ # is only headings (keep "### Controls" with the "#### Pages" under it).
94
+ starts = HEADING_LINE.match(lines[0]) or LIST_ITEM.match(lines[0])
95
+ at_start = starts and not all(HEADING_LINE.match(l) for l in current)
96
+ if current and (at_start or size(current + lines) > CHUNK_CHARS):
97
+ chunks.append(current)
98
+ current = []
99
+ if size(lines) > CHUNK_CHARS:
100
+ chunks += split_lines(lines)
101
+ else:
102
+ current += lines
103
+ if current:
104
+ chunks.append(current)
105
+
106
+ # A chunk of a line or two (a closing "[List of Pipes](...)" link) has a
107
+ # vector made almost only of its "MIDIHub section ..." header, so it
108
+ # matches any MIDIHub query and wastes a slot. Merge it into a neighbour,
109
+ # even if that goes a little past CHUNK_CHARS.
110
+ merged = []
111
+ for part in chunks:
112
+ if merged and size(part) < MIN_CHARS:
113
+ merged[-1] = merged[-1] + part
114
+ elif merged and size(merged[-1]) < MIN_CHARS: # a short first chunk joins the next
115
+ merged[-1] = merged[-1] + part
116
+ else:
117
+ merged.append(part)
118
+ return merged
119
+
120
+
121
+ def blocks(text):
122
+ """A Markdown file's blocks, as lists of non-blank lines: the text between
123
+ blank lines, with a list further split into its items."""
124
+ for block in re.split(r"\n\s*\n", text): # one or more blank lines
125
+ item = []
126
+ for line in non_blank(block):
127
+ if LIST_ITEM.match(line) and item:
128
+ yield item
129
+ item = []
130
+ item.append(line)
131
+ if item:
132
+ yield item
133
+
134
+
135
+ def overlap(lines):
136
+ """The last lines of a part, up to OVERLAP_CHARS, to start the next part with."""
137
+ tail = []
138
+ for line in reversed(lines):
139
+ if len("\n".join([line] + tail)) > OVERLAP_CHARS:
140
+ break
141
+ tail.insert(0, line)
142
+ return tail
143
+
144
+
145
+ def chunk(records):
146
+ return [c for record in records for c in chunk_page(record)]
147
+ # ^ a nested comprehension: for each record, for each of its chunks. Like flat_map in Ruby.
148
+
149
+
150
+ if __name__ == "__main__":
151
+ from extract import extract_all
152
+
153
+ records = extract_all()
154
+ chunks = chunk(records)
155
+
156
+ sizes = sorted(len(c["text"]) for c in chunks)
157
+ n = len(sizes)
158
+ print(f"{len(records)} pages -> {n} chunks")
159
+ print(f"chars per chunk: min {sizes[0]}, median {sizes[n // 2]}, max {sizes[-1]}")
160
+ print(f"tiny chunks (under 200 chars): {sum(s < 200 for s in sizes)}")
161
+
162
+ # Show one split page, with the start of each part, so the overlap is visible.
163
+ split = [r for r in records if len(chunk_page(r)) > 1]
164
+ sample = next(r for r in split if r["device"] == "SR-16")
165
+ print(f"\n{len(split)} pages were split. Example: {sample['device']} page {sample['page']}")
166
+ for i, c in enumerate(chunk_page(sample), 1):
167
+ first = c["text"].splitlines()[:3]
168
+ print(f"\n part {i} ({len(c['text'])} chars) starts:")
169
+ for line in first:
170
+ print(f" | {line}")
@@ -0,0 +1,9 @@
1
+ """How a citation names where a chunk came from. Shared by the query side
2
+ (search, ask, ask-agentic) and kept free of imports, so the query side never
3
+ loads the extraction code (PyMuPDF, OCR)."""
4
+
5
+
6
+ def location(record):
7
+ """A PDF page (an int) becomes "p41"; a Markdown page keeps its name, such as "clock"."""
8
+ page = record["page"]
9
+ return f"p{page}" if isinstance(page, int) else page
studio_agent/cli.py ADDED
@@ -0,0 +1,217 @@
1
+ """The studio-agent command: one entry point, with a subcommand per task.
2
+
3
+ studio-agent status where things are, what's indexed, what's stale
4
+ studio-agent index [--full] bring the index up to date with the studio folder
5
+ studio-agent ask "…" [--plain] answer a question (the agent; --plain for plain RAG)
6
+ studio-agent web the local web page, on http://localhost:5001
7
+ studio-agent mcp the MCP server, for a chat app to start (not run by hand)
8
+ studio-agent eval FILE [...] score retrieval against a questions file
9
+
10
+ Every command takes --studio FOLDER to use a studio folder other than
11
+ ~/Studio Agent (studio.py), for example a test studio.
12
+
13
+ pyproject.toml maps the command to main() below ([project.scripts]); installing
14
+ the package writes a small `studio-agent` script into the virtualenv's bin/
15
+ that imports this module and calls main(). `python -m studio_agent` does the
16
+ same (__main__.py).
17
+
18
+ Each subcommand is a function taking the parsed arguments. The heavy imports
19
+ (OpenAI, NumPy, Flask) happen inside them, so `studio-agent --help` is quick
20
+ and works without an API key.
21
+ """
22
+ import argparse
23
+ import sys
24
+
25
+ from studio_agent.config import CHAT_MODELS, DEFAULT_CHAT_MODEL
26
+ from studio_agent import studio
27
+ from studio_agent.studio import ENV_VAR
28
+
29
+
30
+ def require_index():
31
+ """Exit with what to do if there's no index; print a warning if it's stale."""
32
+ from studio_agent.search import index_status, status_message
33
+
34
+ status = index_status()
35
+ if status is None:
36
+ sys.exit(status_message(status)) # sys.exit with a string prints it and exits with status 1
37
+ if warning := status_message(status): # := assigns and tests in one go
38
+ print(f"{warning}\n")
39
+
40
+
41
+ def require_a_source():
42
+ """Exit with what to do if there are neither manuals nor a connection list.
43
+ Either is enough for the agent; say which one it's missing, or if the index is stale."""
44
+ from studio_agent.search import index_status, nothing_to_answer_from, status_message
45
+
46
+ if message := nothing_to_answer_from():
47
+ sys.exit(message)
48
+ status = index_status()
49
+ if status is None:
50
+ print("(No manuals indexed yet: answering from the connection list.)\n")
51
+ elif warning := status_message(status):
52
+ print(f"{warning}\n")
53
+
54
+
55
+ def status(args):
56
+ import yaml
57
+
58
+ from studio_agent import connections
59
+ from studio_agent.search import index_status, status_message
60
+ from studio_agent.studio import NAMES_FILE, home, manuals_dir, scan, state_dir, unknown_names
61
+
62
+ found, ignored = scan()
63
+ print(f"Studio folder: {home()}")
64
+ print(f"Index and OCR: {state_dir()}")
65
+
66
+ if not manuals_dir().is_dir():
67
+ print(f"\nNo Manuals folder yet. Create {manuals_dir()} and put PDFs in it.")
68
+ else:
69
+ print(f"\n{len(found)} manuals:")
70
+ for device, path in found.items():
71
+ print(f" {device:20} {path.name}")
72
+ for path in ignored:
73
+ print(f" (ignored) {path.name}")
74
+ for manual in unknown_names():
75
+ print(f" (no such manual) {manual}, named in {NAMES_FILE}")
76
+ print(f"\n{status_message(index_status()) or 'The index is up to date.'}")
77
+
78
+ try:
79
+ loaded = connections.load()
80
+ except (ValueError, yaml.YAMLError) as e: # a file that can't be read is worth saying so
81
+ print(f"\nConnection list: can't read {connections.path()}: {e}")
82
+ return
83
+ if loaded is None:
84
+ print(f"\nNo connection list yet. List how your gear is cabled in {connections.path()} "
85
+ "(patchlist format).")
86
+ else:
87
+ devices, nets = loaded
88
+ print(f"\nConnection list: {len(devices)} devices, {len(nets)} cables.")
89
+ no_manual, uncabled = connections.coverage(devices, found)
90
+ for title, names in (("No manual yet for:", no_manual),
91
+ ("Manuals for gear not in the list:", uncabled)):
92
+ if names:
93
+ print(f" {title}")
94
+ print("\n".join(f" {n}" for n in names))
95
+
96
+
97
+ def index(args):
98
+ from openai import OpenAI
99
+
100
+ from studio_agent.config import index_dir
101
+ from studio_agent.index import update_index
102
+ from studio_agent.naming import name_new_manuals
103
+ from studio_agent.studio import NAMES_FILE, manuals
104
+
105
+ client = OpenAI()
106
+ n = name_new_manuals(client)
107
+ if n["named"]:
108
+ print(f"named {len(n['named'])} new manuals in {NAMES_FILE} (about ${n['cost']:.4f}); "
109
+ "fix a wrong name there and run index again")
110
+ s = update_index(manuals(), index_dir(), client, full=args.full)
111
+ print(f"kept {len(s['kept'])}, indexed {len(s['indexed'])}, removed {len(s['removed'])}")
112
+ for label in ("indexed", "removed"):
113
+ if s[label]:
114
+ print(f" {label}: {', '.join(s[label])}")
115
+ print(f"{s['chunks']} chunks in the index")
116
+ print(f"tokens billed: {s['tokens']:,} (about ${s['tokens'] * 0.02 / 1_000_000:.4f} at $0.02 per million)")
117
+
118
+
119
+ def ask(args):
120
+ if args.plain: # plain RAG has only the manuals
121
+ require_index()
122
+ ask_plain(args)
123
+ return
124
+ require_a_source()
125
+ from studio_agent.ask_agentic import MAX_TURNS, ask_agentic
126
+
127
+ result = ask_agentic(args.question, args.model, log=print)
128
+ if result["answer"] is None:
129
+ print(f"\nStopped after {MAX_TURNS} turns without a final answer.")
130
+ else:
131
+ print(f"\n{result['answer']}")
132
+ print(f"\n[{args.model}: {result['tokens_in']:,} in, {result['tokens_out']:,} out in total, "
133
+ f"about ${result['cost']:.4f}]")
134
+
135
+
136
+ def ask_plain(args):
137
+ from studio_agent.ask import ask as ask_rag
138
+ from studio_agent.ask_agentic import cost
139
+ from studio_agent.citation import location
140
+
141
+ chunks, response = ask_rag(args.question, args.model)
142
+ print("Retrieved:")
143
+ for c in chunks:
144
+ print(f" {c['score']:.3f} {c['device']} {location(c)}")
145
+ print(f"\n{response.output_text}\n")
146
+ u = response.usage
147
+ print(f"[{args.model}: {u.input_tokens:,} in, {u.output_tokens:,} out "
148
+ f"({u.output_tokens_details.reasoning_tokens} reasoning), "
149
+ f"about ${cost(args.model, u.input_tokens, u.output_tokens):.4f}]")
150
+
151
+
152
+ def web(args):
153
+ from studio_agent.web import PORT, app
154
+
155
+ # 127.0.0.1: reachable from this machine only, not from the rest of the network.
156
+ app.run(host="127.0.0.1", port=PORT)
157
+
158
+
159
+ def mcp(args):
160
+ from studio_agent.mcp_server import server
161
+
162
+ # stdio: the chat app talks to this process over stdin/stdout. Nothing else
163
+ # may print to stdout from here on.
164
+ server().run("stdio")
165
+
166
+
167
+ def eval_(args): # eval is a Python built-in, so the trailing _ avoids shadowing it
168
+ from studio_agent.eval import run
169
+
170
+ run(args.questions, k=args.k, agent=args.agent, kind=args.kind)
171
+
172
+
173
+ def parser():
174
+ p = argparse.ArgumentParser(prog="studio-agent", description="Answers about your studio gear, from its manuals.")
175
+ # Each subparser stores its handler function as args.run (set_defaults), so
176
+ # main() can call it without a chain of ifs, like a Thor command in Ruby.
177
+ sub = p.add_subparsers(title="commands", required=True, metavar="COMMAND")
178
+ # Options every command takes: each add_parser below gets them through
179
+ # parents=[common], so they go after the command (studio-agent index --studio …).
180
+ common = argparse.ArgumentParser(add_help=False)
181
+ common.add_argument("--studio", metavar="FOLDER",
182
+ help=f"use this studio folder instead of ~/Studio Agent (or set {ENV_VAR})")
183
+
184
+ s = sub.add_parser("status", parents=[common], help="show the studio folder, its manuals and whether the index is up to date")
185
+ s.set_defaults(run=status)
186
+
187
+ s = sub.add_parser("index", parents=[common], help="bring the index up to date with the studio folder")
188
+ s.add_argument("--full", action="store_true", help="rebuild everything (after changing extraction or chunking code)")
189
+ s.set_defaults(run=index)
190
+
191
+ s = sub.add_parser("ask", parents=[common], help="answer a question from the manuals")
192
+ s.add_argument("question")
193
+ s.add_argument("--model", choices=CHAT_MODELS, default=DEFAULT_CHAT_MODEL)
194
+ s.add_argument("--plain", action="store_true", help="plain RAG (one search, one model call), for comparison")
195
+ s.set_defaults(run=ask)
196
+
197
+ s = sub.add_parser("web", parents=[common], help="start the local web page on http://localhost:5001")
198
+ s.set_defaults(run=web)
199
+
200
+ s = sub.add_parser("mcp", parents=[common], help="run the MCP server, for a chat app such as Claude Desktop to start")
201
+ s.set_defaults(run=mcp)
202
+
203
+ s = sub.add_parser("eval", parents=[common], help="score retrieval against a questions file (a developer tool)")
204
+ s.add_argument("questions", help="a questions file, such as eval/questions.json")
205
+ s.add_argument("-k", type=int, default=5, help="how many results count (plain search only)")
206
+ s.add_argument("--agent", action="store_true", help="score the agent's searches instead (costs money)")
207
+ s.add_argument("--kind", help="only questions of this kind, e.g. cross")
208
+ s.set_defaults(run=eval_)
209
+ return p
210
+
211
+
212
+ def main(argv=None):
213
+ """Parse the command line (or argv, in tests) and run the chosen subcommand."""
214
+ args = parser().parse_args(argv)
215
+ if args.studio:
216
+ studio.use(args.studio)
217
+ args.run(args)
studio_agent/config.py ADDED
@@ -0,0 +1,27 @@
1
+ """Settings shared by index, ask and ask-agentic. Model names live only here."""
2
+ from studio_agent.studio import state_dir
3
+
4
+ # Changing this means re-running index: vectors from different embedding
5
+ # models are not comparable.
6
+ EMBED_MODEL = "text-embedding-3-small"
7
+
8
+ # Chat models that --model accepts. Luna is the cheap default; Sol is for comparisons.
9
+ CHAT_MODELS = ["gpt-6-luna", "gpt-6.1-sol"]
10
+ DEFAULT_CHAT_MODEL = "gpt-6-luna"
11
+
12
+ # Dollars per million tokens (input, output), from OpenAI's pricing page on
13
+ # Nov 12, 2026. Only used to print an approximate cost per run.
14
+ PRICES = {
15
+ "gpt-6-luna": (0.10, 0.50),
16
+ "gpt-6.1-sol": (2.00, 10.00),
17
+ }
18
+
19
+ # The index's files, in index_dir().
20
+ VECTORS_FILE = "vectors.npy" # one row per chunk
21
+ CHUNKS_FILE = "chunks.json" # same order as the rows above
22
+ MANIFEST_FILE = "manifest.json" # what each manual looked like when indexed
23
+
24
+
25
+ def index_dir():
26
+ """The current studio's index (in its hidden .studio-agent folder; see studio.py)."""
27
+ return state_dir() / "index"