open-standards/wai/quantum-studio/src/assistant.js
Transaction Science 7cef125325
All checks were successful
wai-quantum WebGPU member / member · DX12 and Vulkan (cbio-windows) (pull_request) Successful in 12m23s
joule-moq-room room service / joule-moq-room · does this change touch it (pull_request) Successful in 5s
joule-moq-web browser client / joule-moq-web · does this change touch it (pull_request) Successful in 6s
wai-quantum on every processor / emulated · aarch64-unknown-linux-gnu (pull_request) Successful in 1m47s
wai-quantum on every processor / emulated · armv7-unknown-linux-gnueabihf (pull_request) Successful in 2m49s
standards workspaces build + test / which workspaces this change touches (pull_request) Successful in 6s
WAI conformance / does this change touch it (pull_request) Successful in 7s
WAI energy receipts / does this change touch it (pull_request) Successful in 10s
WAI JPEG-AI whole decode (pinned inputs, required) / does this change touch it (pull_request) Successful in 7s
WAI neural sink gates / does this change touch it (pull_request) Successful in 11s
repository checks / lockfiles, tests in CI, workflow hygiene, spec and section references, public text (pull_request) Successful in 1m12s
wai-ops-gpu integer operators on GPUs / does this change touch it (pull_request) Successful in 10s
wai-pack / wai-pack · does this change touch it (pull_request) Successful in 8s
wai-quantum command line / does this change touch it (pull_request) Successful in 8s
wai-quantum dataflow member / does this change touch it (pull_request) Successful in 6s
wai-quantum CUDA member / does this change touch it (pull_request) Successful in 7s
wai-quantum signal processor / does this change touch it (pull_request) Successful in 5s
wai-quantum FPGA member / does this change touch it (pull_request) Successful in 7s
wai-quantum HIP member / does this change touch it (pull_request) Successful in 6s
wai-quantum Metal member / does this change touch it (pull_request) Successful in 5s
wai-quantum neural-processor member / does this change touch it (pull_request) Successful in 6s
wai-quantum npu-cores member / does this change touch it (pull_request) Successful in 7s
wai-quantum on every processor / emulated · loongarch64-unknown-linux-gnu (pull_request) Successful in 3m38s
wai-quantum OpenCL member / does this change touch it (pull_request) Successful in 6s
wai-quantum CUDA member / member · CUDA (jetson-hub) (pull_request) Successful in 27s
wai-quantum-qpu / does this change touch it (pull_request) Successful in 7s
wai-quantum HIP member / member · HIP (framework-128gb) (pull_request) Successful in 20s
wai-quantum service / does this change touch it (pull_request) Successful in 6s
wai-quantum matrix-extension member / does this change touch it (pull_request) Successful in 7s
wai-quantum studio and desktop / does this change touch it (pull_request) Successful in 6s
wai-quantum tensor-engine member / does this change touch it (pull_request) Successful in 7s
wai-quantum CPU vector units / does this change touch it (pull_request) Successful in 5s
wai-quantum portable tensor program / does this change touch it (pull_request) Successful in 6s
wai-quantum OpenCL member / member · OpenCL GPU and CPU (jetson-hub) (pull_request) Successful in 24s
wai-quantum WebGPU member / does this change touch it (pull_request) Successful in 5s
WAI mbt2018_mean integer decode (regenerated vectors) / does this change touch it (pull_request) Successful in 5s
wai-web wasm32 / does this change touch it (pull_request) Successful in 5s
wai-quantum portable tensor program / tensor program · GPUs (jetson-hub) (pull_request) Successful in 15s
wai-quantum npu-cores member / member · npu-cores, neural processor (framework-128gb silicon) (pull_request) Successful in 1m13s
wai-quantum OpenCL member / member · OpenCL GPU (framework-128gb) (pull_request) Successful in 13s
wai-quantum CPU vector units / member · vector units, avx2 and avx512 (framework-128gb silicon) (pull_request) Successful in 10s
wai-quantum portable tensor program / tensor program · integrated GPU (framework-128gb) (pull_request) Successful in 8s
joule-moq-room room service / joule-moq-room, every target (pull_request) Successful in 1m3s
wai-quantum on every processor / emulated · powerpc64-unknown-linux-gnu (pull_request) Successful in 5m25s
wai-quantum on every processor / emulated · powerpc64le-unknown-linux-gnu (pull_request) Successful in 6m1s
wai-quantum on every processor / emulated · riscv64gc-unknown-linux-gnu (pull_request) Successful in 4m2s
wai-quantum WebGPU member / member · integrated GPU, Vulkan (framework-128gb) (pull_request) Successful in 7m37s
wai-quantum on every processor / emulated · s390x-unknown-linux-gnu (pull_request) Successful in 4m8s
wai-quantum on every processor / emulated · sparc64-unknown-linux-gnu (pull_request) Successful in 6m16s
wai-web reach builds / wai-web reach · does this change touch it (pull_request) Successful in 7s
wai-quantum on every processor / emulated · i686-unknown-linux-gnu (pull_request) Successful in 4m10s
wai-quantum WebGPU member / member · discrete GPU, Vulkan (jetson-hub) (pull_request) Successful in 20m25s
WAI conformance / quantum core and corpus under wasm32-wasip2 (wasmtime) (pull_request) Successful in 2m2s
WAI conformance / cross-arch byte-equality · linux (pull_request) Successful in 27s
WAI energy receipts / energy receipts · linux (pull_request) Successful in 10m17s
WAI conformance / cargo-class corpora · linux (pull_request) Successful in 18m12s
WAI neural sink gates / model-free refusals of the neural sink (pull_request) Successful in 1m24s
wai-ops-gpu integer operators on GPUs / builds · no adapter is not a pass (linux) (pull_request) Successful in 1m45s
wai-pack / wai-pack · linux (pull_request) Successful in 1m20s
wai-quantum command line / command line · linux (pull_request) Successful in 1m7s
WAI JPEG-AI whole decode (pinned inputs, required) / fetch pinned JPEG-AI inputs → whole decode + pixel hash, required (pull_request) Successful in 6m57s
wai-quantum CUDA member / member · CUDA absent (linux) (pull_request) Successful in 24s
wai-quantum dataflow member / member · dataflow device, simulated (pci 1e52:b140) (pull_request) Successful in 3m25s
wai-quantum dataflow member / member · dataflow device, simulated (pci 1e52:401e) (pull_request) Successful in 4m35s
wai-quantum FPGA member / member · FPGA simulation absent (linux) (pull_request) Successful in 21s
wai-quantum Metal member / member · Metal absent (linux) (pull_request) Successful in 26s
wai-quantum neural-processor member / member · neural processor absent (linux) (pull_request) Successful in 26s
wai-quantum OpenCL member / member · OpenCL absent (linux) (pull_request) Successful in 21s
wai-quantum-qpu / clients against their contracts (linux) (pull_request) Successful in 20s
wai-quantum service / service · linux (pull_request) Successful in 39s
wai-quantum matrix-extension member / member · matrix extension, emulated (aarch64 Linux) (pull_request) Successful in 19s
wai-quantum studio and desktop / studio · browser (pull_request) Successful in 3m23s
wai-quantum signal processor / processor and member · signal processor, emulated (pull_request) Successful in 14m8s
wai-quantum CPU vector units / member · vector unit, rvv 1024-bit (riscv64, emulated) (pull_request) Successful in 19s
wai-quantum CPU vector units / member · vector unit, sve 128-bit (aarch64, emulated) (pull_request) Successful in 28s
wai-quantum CPU vector units / member · vector unit, rvv 128-bit (riscv64, emulated) (pull_request) Successful in 14s
wai-quantum CPU vector units / member · vector unit, sve 2048-bit (aarch64, emulated) (pull_request) Successful in 10s
wai-quantum tensor-engine member / member · tensor engine, the kernel toolchain's simulator (linux) (pull_request) Successful in 8m5s
wai-quantum CPU vector units / member · vector unit, avx2 (x86_64 silicon) (pull_request) Successful in 15s
wai-quantum CPU vector units / member · vector unit, sve 512-bit (aarch64, emulated) (pull_request) Successful in 12s
wai-quantum portable tensor program / tensor program · CPU, mutants, GPU builds (pull_request) Successful in 29s
standards workspaces build + test / joule-code-rs (joule-code/joule-code-rs, joule-code-rs, linux-arm64, true) (pull_request) Successful in 3m12s
wai-quantum WebGPU member / member · software Vulkan (linux) (pull_request) Successful in 2m9s
wai-quantum WebGPU member / shader checks · browser build · wasip2 inertness · MSRV (pull_request) Successful in 3m13s
wai-web wasm32 / wai-web wasm32 build · corpus, menu and writers (pull_request) Successful in 4m18s
WAI mbt2018_mean integer decode (regenerated vectors) / regenerate mbt2018_mean integer vectors → Rust decode, required (pull_request) Successful in 5m22s
WAI conformance / v2 vocabulary · manifests validate as stated (pull_request) Successful in 15s
wai-web reach builds / wai-web reach builds · the package of record, every output as recorded (pull_request) Successful in 2m23s
WAI conformance / cargo-class corpora · linux-arm64 (pull_request) Successful in 15m0s
WAI conformance / delivery telemetry · CMCD and CMSD against an independent library (pull_request) Successful in 12s
WAI conformance / cross-arch byte-equality · linux-arm64 (pull_request) Successful in 26s
WAI conformance / C2PA manifest emission · signed, read back, validated (pull_request) Successful in 1m36s
wai-web reach builds / wai-web reach builds · this tree's wai-web, every rung on its engine line (pull_request) Successful in 4m35s
WAI energy receipts / energy receipts · linux-arm64 (pull_request) Successful in 6m54s
wai-pack / wai-pack · linux-arm64 (pull_request) Successful in 1m14s
wai-pack / wai-pack · the floor through a media prober (pull_request) Successful in 24s
wai-pack / wai-pack · dependency licences (pull_request) Successful in 1m18s
wai-quantum HIP member / member · HIP absent (linux-arm64) (pull_request) Successful in 25s
joule-moq-web browser client / joule-moq-web · browser end-to-end (macos) (pull_request) Successful in 6m16s
wai-quantum npu-cores member / member · npu-cores absent (linux-arm64) (pull_request) Successful in 23s
wai-quantum tensor-engine member / member · tensor engine absent (linux-arm64) (pull_request) Successful in 19s
wai-pack / wai-pack · independent verifier (Python) (pull_request) Successful in 4m8s
WAI conformance / independent verifiers · claims, JWP, key discovery and integer payloads (Python) (pull_request) Successful in 35m22s
standards workspaces build + test / macOS energy backends (pull_request) Successful in 8m33s
WAI conformance / cargo-class corpora · macos (pull_request) Successful in 14m16s
WAI conformance / cross-arch byte-equality · macos (pull_request) Successful in 23s
WAI conformance / codec wrappers · fuzz smoke, text decode limits, C entry points, provenance, the semantic path (pull_request) Successful in 54s
WAI energy receipts / energy receipts · macos (pull_request) Successful in 6m14s
wai-ops-gpu integer operators on GPUs / Metal GPU and browser WebGPU (macos) (pull_request) Successful in 3m12s
wai-pack / wai-pack · macos (pull_request) Successful in 1m3s
wai-quantum command line / command line · macos (pull_request) Successful in 28s
wai-quantum dataflow member / member · dataflow device absent (macos) (pull_request) Successful in 14s
wai-quantum FPGA member / member · FPGA datapath, simulated (macos) (pull_request) Successful in 1m13s
wai-quantum Metal member / member · Metal (macos) (pull_request) Successful in 29s
wai-quantum neural-processor member / member · neural processor (macos) (pull_request) Successful in 5m49s
wai-quantum OpenCL member / member · OpenCL GPU (macos) (pull_request) Successful in 29s
wai-quantum service / service · macos (pull_request) Successful in 44s
wai-quantum matrix-extension member / member · matrix extension absent (macos) (pull_request) Successful in 9s
wai-quantum studio and desktop / desktop app · macos (pull_request) Successful in 2m12s
wai-quantum CPU vector units / member · vector unit absent (macos) (pull_request) Successful in 13s
wai-quantum portable tensor program / tensor program · Metal and the arm64 CPU (macos) (pull_request) Successful in 15s
wai-quantum WebGPU member / member · Metal (macos) (pull_request) Successful in 4m26s
wai-quantum WebGPU member / member · browser WebGPU (macos) (pull_request) Successful in 1m43s
wai-quantum 0.6.14: design critique, equivalence, alternatives and classical shortcuts across every surface; contraction trees that sweep along the line
This carries 0.6.13, which was not published on its own, and 0.6.14.

## 0.6.13

The engine is the microscope and the judge, a local model is a muse that waits to be
asked, and the reader is the author. Every figure is the engine's. Nothing changes the
reader's program until they apply a change.

engine::critique gives a program's measures before it runs:
- gates by kind; one-, two- and three-qubit gates; T gates; gates off the Clifford
  angles;
- depth and two-qubit depth, and whether it is a Clifford circuit;
- a fidelity at reference error rates, named as a model.
It also gives the program's smells, each with its lines and operations: gates that
cancel, rotations that merge or do nothing, idle qubits, and qubits never measured.
critique::variants rewrites the program's own text with the smells fixed, all of them
to a fixed point and each one alone. Each candidate carries its measures and the
equivalence verdict; one the check finds different is never offered.

engine::equiv compares two programs up to a global phase:
- by tableau for Clifford circuits, at any size;
- otherwise on every basis state, to 8 qubits;
- otherwise on random product states, to 22 qubits, which is evidence, not proof;
- otherwise unchecked, with the reason.
qasm::parse_lines gives each operation's line, and draw::layout each gate's operation
index.

engine::shortcuts lists every exact classical route the engine knows, priced on the
program, and names the cheapest for each question:
- the stabilizer tableau;
- the cut-rank sum;
- an exact matrix product state, at a bond bounded by the operator Schmidt ranks of
  the gates crossing each cut. The bound is held by a test against the true Schmidt
  ranks of random circuits;
- the light cone;
- a tensor-network contraction, when asked to be thorough;
- the state vector.
A cheap route proves a design classically easy; none being cheap proves nothing. On
the 70-qubit random graph-state circuit the quick check finds the cut-rank sum (widest
cut 30) in under 2 s. The thorough one finds widest cut 29 in about 4 minutes.

Quantum Studio gains:
- the critique, always on under the diagram, with the smells flagged on it, Show and
  Fix;
- the classical cost, on request;
- Alternatives: Improve (the engine's rewrites and the model's, each checked) and
  Explore (the model's different circuits, each measured and compared), with an atlas
  and Apply;
- Predict first, which sets the reader's expected outcome against the run;
- an assistant that asks questions first and speaks only when asked, offering (never
  sending) a hint when allowed. Its new tools are critique_qasm, check_equivalent and
  classical_shortcuts.
wai-web exports the four engine calls. The desktop app answers them natively.
wai-quantum-cli 0.1.1 adds critique, equivalent (exit 0/1/2), improve and shortcuts,
with four MCP tools.

examples/cutrank_qasm gains probs: the exact 2^n·p of given bit strings, with their
linear cross-entropy.

## 0.6.14

A deep circuit on a line, contracted qubit by qubit along time, keeps a boundary of
only the bonds between two neighbouring qubits: about half the depth for a
controlled-Z brickwork. The contraction search rarely found that tree on its own.

- Network::amplitude_split_placed builds the same network as amplitude_split, index
  for index, with each index's place in the circuit: a qubit and a time.
- tensor_places, sweep_orders and sweep_path turn the places into the trees that sweep
  qubit by qubit, or time by time.
- find_path_seeded and find_path_restarts_seeded score such trees beside the trials and
  polish the best of them all alike. A seed that is not a tree of the network is
  ignored.
- The engine's tensor_network method and the thorough shortcut lens take both sweeps as
  seeds.

On the 70-qubit random graph-state circuit, one amplitude's largest intermediate falls
from 2^48 to 2^36, and its multiply-adds from 2^56.1 to 2^48.7, in the thorough lens.
With 16 trials and no seeds the search finds 2^59. The pinned plans in
tests/bit_identity.rs call find_path itself and are unchanged.

The job service answers four design checks: POST /v1/critique, /v1/equivalent,
/v1/improve and /v1/shortcuts, with the matching MCP tools. They run in its own process
within bounds:
- each counts against the client's submissions;
- at most two run at once, and one that waits ten seconds is refused with a 503;
- equivalence work past 4e9 gate amplitudes, and a thorough search, are refused with a
  422 naming the local command.
The smoke script checks each one. It now follows a job that outlasts /v1/run's wait,
as a client does, instead of failing on a loaded host.

wai-quantum-cli 0.1.2 carries the faster contraction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 02:40:04 -04:00

288 lines
19 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The Studio's assistant: a language model on this machine, with the engine
// as its tools. The model is any server with the chat-completions interface,
// tool calls included: the JouleClaw runtime, a llama.cpp server, others. By default
// it is local, and nothing leaves the machine.
//
// Tools first: the model asks the engine (lint, critique, draw, plan, run, the
// equivalence check) and may state only numbers the engine returned. Every program it proposes is checked by the
// engine before the Studio offers it: read as the engine reads it, and run on
// this device. A proposal that does not parse goes back to the model once, with
// the engine's reason, to be corrected.
//
// The reader is the author. The assistant speaks only when asked, and by default
// it asks a question before it proposes (the stance, which the reader sets). For
// Alternatives it is a source of candidates, never the judge: each one it writes
// is read, measured and compared by the engine before the Studio shows it.
const SYSTEM = `You are the assistant in Quantum Studio, an editor for OpenQASM programs.
Tools run the Studio's own engine:
- get_program: the program in the editor, the job's settings and the last result.
- lint_qasm: read a program as the engine reads it (its qubits and gates, or the first problem and its line).
- critique_qasm: the program's measures (gates, two-qubit gates, depth, T gates, whether it is Clifford, a modelled fidelity) and its smells, each with its lines.
- check_equivalent: whether two programs are the same circuit, and how the engine knows.
- classical_shortcuts: every exact classical route to simulating a program and its cost; a cheap route proves it classically easy, none being cheap proves nothing.
- draw_circuit: the circuit as text.
- plan_job: the method that would run a job, why, and the memory it needs.
- run_job: run a job on this device; counts, expectation values, amplitudes and the accuracy of each.
Use them. Never state a probability, count, amplitude, expectation value or cost that a tool did not return; quote the tool's figure.
The engine reads OpenQASM 3 and the OpenQASM 2 forms in common use: registers, the standard gates, gate definitions, ctrl and negctrl modifiers, measurement and reset anywhere, and if on measured bits. It refuses loops, inv and pow.
When you write a program, run it with run_job and also show the whole program in one \`\`\`qasm block; the Studio checks it and runs it before offering it.
For a state, a probability or an amplitude, run the program and quote the result rather than working it out yourself.
Write plain text: no Markdown headings, no LaTeX. Write states as |00⟩ and roots as √2. Qubit 0 is the rightmost bit of a basis state.
Answer briefly.`;
// How the assistant helps, which the reader chooses. Asking first is the default:
// a question the reader answers teaches more than an answer they read.
export const STANCES = {
questions: { label: 'Ask me questions first', text: 'The user is the author and is learning. Before you propose a program or a change, ask one short question that helps them see it themselves: what they expect a line to do, or what a result shows. Answer a direct question from the tools, then ask one question back that moves them forward. Write a whole program only when they ask you to.' },
suggest: { label: 'Suggest changes', text: 'The user is the author. Suggest changes as small edits to their program, each naming its line and the reason the tools gave; write a whole program only when they ask for one.' },
write: { label: 'Write programs', text: 'When a change is wanted, write the whole program as described above.' },
};
export const TOOLS = [
{ type: 'function', function: { name: 'get_program', description: 'The program in the editor, the job settings, and a summary of the last result.', parameters: { type: 'object', properties: {} } } },
{ type: 'function', function: { name: 'lint_qasm', description: 'Read an OpenQASM program as the engine reads it: its qubits, gates and measurements, or the first problem with its line.', parameters: { type: 'object', required: ['qasm'], properties: { qasm: { type: 'string' } } } } },
{ type: 'function', function: { name: 'critique_qasm', description: 'A program\'s measures (gates by kind, two-qubit gates, depth, two-qubit depth, T count, whether it is a Clifford circuit, a fidelity under reference error rates, which is a model and not a run) and its smells: gates that cancel, rotations that merge or do nothing, idle or unmeasured qubits, each with its lines.', parameters: { type: 'object', required: ['qasm'], properties: { qasm: { type: 'string' } } } } },
{ type: 'function', function: { name: 'check_equivalent', description: 'Whether two programs are the same circuit up to a global phase, and how the engine knows: equal tableaus (Clifford, any size), every basis state (to 8 qubits), random inputs (to 22 qubits, evidence rather than proof), or unchecked. b defaults to the program in the editor.', parameters: { type: 'object', required: ['a'], properties: { a: { type: 'string' }, b: { type: 'string' } } } } },
{ type: 'function', function: { name: 'classical_shortcuts', description: 'Every exact classical route the engine knows for simulating a program (stabilizer tableau, cut-rank sum, exact matrix product state at a rigorous bond bound, light cone, tensor network when thorough, state vector), each with its memory and the log2 of its operations, and the cheapest for each question. A cheap route proves the program classically easy; none being cheap proves nothing about hardness.', parameters: { type: 'object', properties: { qasm: { type: 'string' }, thorough: { type: 'boolean' } } } } },
{ type: 'function', function: { name: 'draw_circuit', description: 'A program\'s circuit drawn as text.', parameters: { type: 'object', required: ['qasm'], properties: { qasm: { type: 'string' } } } } },
{
type: 'function',
function: {
name: 'plan_job',
description: 'The method a job would run on and why, with the memory it needs, without running it.',
parameters: { type: 'object', required: ['qasm'], properties: { qasm: { type: 'string' }, shots: { type: 'integer' }, observables: { type: 'array', items: { type: 'string' } }, method: { type: 'string' } } },
},
},
{
type: 'function',
function: {
name: 'run_job',
description: 'Run a job on this device: measurement counts, Pauli expectation values (as "Z0 Z1") and/or amplitudes (bit strings, highest qubit first), with the method used and its accuracy.',
parameters: {
type: 'object',
required: ['qasm'],
properties: { qasm: { type: 'string' }, shots: { type: 'integer' }, observables: { type: 'array', items: { type: 'string' } }, amplitudes: { type: 'array', items: { type: 'string' } }, method: { type: 'string' } },
},
},
},
];
const clip = (s, n = 6000) => (s.length > n ? s.slice(0, n) + `… (${s.length - n} more characters)` : s);
// A result as a model reads it: what was computed, not the receipt.
export function summary(job) {
const r = job?.result || {};
const counts = r.counts ? Object.entries(r.counts).sort((a, b) => b[1] - a[1]).slice(0, 16) : undefined;
return {
method: job?.method, why: job?.why, accuracy: r.accuracy, qubits: r.qubits, gates: r.gates,
counts: counts && Object.fromEntries(counts), distinct_outcomes: r.distinct_outcomes,
expectations: r.expectations, amplitudes: r.amplitudes?.slice(0, 16), dynamic: r.dynamic, warning: r.warning,
};
}
// The ```qasm (or ```openqasm) blocks of an answer.
export function proposals(text) {
const out = [];
const re = /```(?:qasm|openqasm|openqasm3)?\s*\n([\s\S]*?)```/gi;
for (let m; (m = re.exec(text)); ) if (/\b(qubit|qreg|OPENQASM)\b/.test(m[1])) out.push(m[1].trim() + '\n');
return out;
}
// A model behind a chat-completions endpoint, called from this page.
export class HttpModel {
constructor(endpoint, name) { this.endpoint = endpoint.replace(/\/+$/, ''); this.name = name; }
async chat(body) {
const res = await fetch(`${this.endpoint}/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
const v = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(v.error?.message || v.error || `the model answered ${res.status}`);
return v;
}
async models() {
const res = await fetch(`${this.endpoint}/models`);
if (!res.ok) throw new Error(`the model server answered ${res.status}`);
return (await res.json()).data?.map((m) => m.id) ?? [];
}
}
// The same, called by the desktop app (no browser origin rules in the way).
export class DesktopModel {
constructor(endpoint, name) { this.endpoint = endpoint.replace(/\/+$/, ''); this.name = name; this.invoke = window.__TAURI__.core.invoke; }
async chat(body) {
const v = JSON.parse(await this.invoke('chat', { endpoint: this.endpoint, body: JSON.stringify(body) }));
if (v.error && !v.choices) throw new Error(v.error.message || v.error);
return v;
}
async models() {
const v = JSON.parse(await this.invoke('models', { endpoint: this.endpoint }));
if (v.error && !v.data) throw new Error(v.error.message || v.error);
return v.data?.map((m) => m.id) ?? [];
}
}
export class Assistant {
// engine: the Studio's local engine; context(): {qasm, job, last} as the editor holds them;
// stance(): a key of STANCES.
constructor({ engine, model, context, stance = () => 'questions' }) {
this.engine = engine;
this.model = model;
this.context = context;
this.stance = stance;
this.history = [];
}
// Candidates for Alternatives, from one call without tools and outside the
// conversation: [{idea, qasm}]. The engine checks each; nothing here does.
async muse(prompt, temperature) {
const res = await this.model.chat({ model: this.model.name || undefined, temperature, messages: [{ role: 'system', content: MUSE }, { role: 'user', content: prompt }] });
return ideas(unlatex((res.choices?.[0]?.message?.content || '').replace(/<think>[\s\S]*?<\/think>\s*/g, '')));
}
improve(qasm, k = 3) {
return this.muse(`Write ${k} programs that are the same circuit as this one (the same unitary up to a global phase, and the same measurements) but cheaper: fewer two-qubit gates, less depth or fewer T gates. Before each, one line that starts "Idea:" and says what it changes. Each program whole, in its own \`\`\`qasm block.\n\n\`\`\`qasm\n${qasm}\n\`\`\``, 0.4);
}
explore(qasm, aim, k = 4) {
return this.muse(`Imagine ${k} different programs in the spirit of this one${aim ? `, toward this aim: ${aim}` : ''}. Make them differ from each other in kind, not only in their angles: another structure, another entangler, another symmetry, another use of the qubits. Before each, one line that starts "Idea:" and says what it tries. Each program whole, in its own \`\`\`qasm block.\n\n\`\`\`qasm\n${qasm}\n\`\`\``, 0.9);
}
async tool(name, args) {
const ctx = this.context();
const job = (a) => {
const j = { qasm: a.qasm };
for (const k of ['shots', 'observables', 'amplitudes', 'method']) if (a[k] != null && !(Array.isArray(a[k]) && !a[k].length)) j[k] = a[k];
if (!j.shots && !j.observables && !j.amplitudes) j.shots = 1000;
return j;
};
switch (name) {
case 'get_program': return { qasm: ctx.qasm, job: ctx.job, last_result: ctx.last ? summary(ctx.last) : null };
case 'lint_qasm': return this.engine.lint(args.qasm ?? ctx.qasm);
case 'critique_qasm': return this.engine.critique(args.qasm ?? ctx.qasm);
case 'check_equivalent': return this.engine.equivalent(args.a ?? ctx.qasm, args.b ?? ctx.qasm);
case 'classical_shortcuts': return this.engine.shortcuts(args.qasm ?? ctx.qasm, !!args.thorough);
case 'draw_circuit': return { text: (await this.engine.draw(args.qasm ?? ctx.qasm, 80)).text };
case 'plan_job': return this.engine.plan(job({ ...args, qasm: args.qasm ?? ctx.qasm }));
case 'run_job': return summary(await this.engine.run(job({ ...args, qasm: args.qasm ?? ctx.qasm })));
default: throw new Error(`no tool ${name}`);
}
}
// Ask; `on(event)` hears each step: {type: 'tool', name, args, result} and
// finally {type: 'answer', text, proposals: [{qasm, lint, job}]}.
async ask(text, on = () => {}) {
const ctx = this.context();
const used = []; // programs the model passed to the tools, other than the editor's
const ranWith = new Map(); // program → the settings the model ran it with
const heard = [ctx.qasm, JSON.stringify(ctx.job ?? {}), JSON.stringify(ctx.last ? summary(ctx.last) : {})]; // what the engine and the editor told it
const messages = [
{ role: 'system', content: `${SYSTEM}\n${(STANCES[this.stance()] || STANCES.questions).text}` },
...this.history,
{ role: 'user', content: `${text}\n\n(The program in the editor:)\n\`\`\`qasm\n${ctx.qasm}\n\`\`\`` },
];
let retried = false;
for (let round = 0; round < 8; round++) {
// The first turn must ask the engine something, so every answer starts from it.
const res = await this.model.chat({ model: this.model.name || undefined, messages, tools: TOOLS, tool_choice: round === 0 ? 'required' : 'auto', temperature: 0.2 });
const msg = res.choices?.[0]?.message;
if (!msg) throw new Error('the model gave no answer');
messages.push({ role: 'assistant', content: msg.content ?? '', ...(msg.tool_calls?.length ? { tool_calls: msg.tool_calls } : {}) });
if (msg.tool_calls?.length) {
for (const call of msg.tool_calls) {
let args = {};
try { args = JSON.parse(call.function?.arguments || '{}'); } catch (e) {}
let result;
try { result = await this.tool(call.function?.name, args); } catch (e) { result = { error: e.message }; }
if (typeof args.qasm === 'string' && args.qasm.trim() && args.qasm.trim() !== ctx.qasm.trim()) used.push(args.qasm.trim() + '\n');
if (call.function?.name === 'run_job') {
const eff = pick(args, ['shots', 'observables', 'amplitudes', 'method']);
if (!eff.shots && !eff.observables && !eff.amplitudes) eff.shots = 1000; // as the tool ran it
ranWith.set((args.qasm ?? ctx.qasm).trim(), eff);
}
on({ type: 'tool', name: call.function?.name, args, result });
messages.push({ role: 'tool', tool_call_id: call.id, content: clip(JSON.stringify(result)) });
heard.push(JSON.stringify(args), JSON.stringify(result)); // what it asked, and what it was told
}
continue;
}
const answer = unlatex((msg.content || '').replace(/<think>[\s\S]*?<\/think>\s*/g, '').trim());
// Check each proposal as the engine reads it; a broken one goes back once.
// The answer's programs, and the last one the model ran or checked through a tool
// when the answer shows none: either way, read by the engine here.
const written = proposals(answer);
const shown = written.length ? written : used.slice(-1);
const checked = [];
for (const qasm of shown) checked.push({ qasm, lint: await this.engine.lint(qasm) });
const broken = checked.find((p) => !p.lint.ok);
if (broken && !retried) {
retried = true;
on({ type: 'retry', error: broken.lint.error });
messages.push({ role: 'user', content: `The engine could not read the program you proposed: ${broken.lint.error}. Give the corrected whole program in one \`\`\`qasm block.` });
continue;
}
for (const p of checked) {
if (!p.lint.ok) continue;
// Run as the model ran it, so the counts it quoted are the counts shown; else
// with the editor's settings.
const theirs = ranWith.get(p.qasm.trim());
const settings = theirs ?? { ...(ctx.job?.shots ? {} : { shots: 1000 }), ...pick(ctx.job, ['shots', 'observables']) };
try { p.job = await this.engine.run({ qasm: p.qasm, ...settings }); } catch (e) { p.error = e.message; }
}
this.history.push({ role: 'user', content: text }, { role: 'assistant', content: answer });
this.history = this.history.slice(-12);
on({ type: 'answer', text: answer, proposals: checked, usage: res.usage, unsourced: unsourced(answer, heard.join(' ')) });
return;
}
throw new Error('the model kept calling tools without answering');
}
}
// The muse's brief: candidates, not answers, and no figures.
const MUSE = `You propose OpenQASM 3 programs for Quantum Studio's Alternatives. The Studio's engine reads, measures and compares every program you write; you do not judge them. Write each program whole, in its own \`\`\`qasm block, each after one line that starts "Idea:". State no counts, probabilities or costs. Use only what the engine reads: registers, the standard gates, gate definitions, ctrl and negctrl modifiers, measurement and reset, and if on measured bits; no loops, inv or pow.`;
// The ideas in a muse's answer: each \`\`\`qasm block with the "Idea:" line
// before it.
export function ideas(text) {
const out = [];
const re = /\`\`\`(?:qasm|openqasm|openqasm3)?\s*\n([\s\S]*?)\`\`\`/gi;
let from = 0;
for (let m; (m = re.exec(text)); ) {
const before = text.slice(from, m.index);
from = m.index + m[0].length;
if (!/\b(qubit|qreg|OPENQASM)\b/.test(m[1])) continue;
const said = [...before.matchAll(/^[\s>*#-]*(?:\d+[.)]\s*)?\**idea\**\s*[:.]\**\s*(.+)$/gim)].pop();
out.push({ idea: said ? said[1].replace(/\*+/g, '').trim().replace(/\.$/, '') : '', qasm: m[1].trim() + '\n' });
}
return out;
}
// The figures in an answer's prose that no tool returned and the program does not
// hold: a decimal, a percentage, or a whole number of two digits or more.
export function unsourced(answer, heard) {
const prose = answer.replace(/```[\s\S]*?```/g, ' ');
const figures = prose.match(/(?<![\w.])\d+(?:\.\d+)?%?|(?<![\w.])\.\d+%?/g) ?? [];
const out = [];
for (const f of figures) {
const bare = f.replace(/%$/, '');
if (!/[.%]/.test(f) && bare.length < 2) continue; // a qubit's index, a step's number
if (heard.includes(bare) || out.includes(f)) continue;
out.push(f);
}
return out;
}
// LaTeX a model writes despite being asked not to, as plain Unicode.
export function unlatex(t) {
return t
.replace(/\$+/g, '')
.replace(/\\frac\{([^{}]*)\}\{\\sqrt\{([^{}]*)\}\}/g, '$1/√$2')
.replace(/\\frac\{([^{}]*)\}\{([^{}]*)\}/g, '($1)/($2)')
.replace(/\\sqrt\{([^{}]*)\}/g, '√$1')
.replace(/\\rangle/g, '⟩').replace(/\\langle/g, '⟨')
.replace(/\\(Phi|Psi|psi|phi|theta|pi|alpha|beta|gamma|otimes|cdot|pm)\b/g, (_, w) => ({ Phi: 'Φ', Psi: 'Ψ', psi: 'ψ', phi: 'φ', theta: 'θ', pi: 'π', alpha: 'α', beta: 'β', gamma: 'γ', otimes: '⊗', cdot: '·', pm: '±' })[w])
.replace(/\^\{?\+\}?/g, '⁺').replace(/\^\{?-\}?/g, '⁻')
.replace(/\\(left|right)/g, '');
}
function pick(o, keys) {
const out = {};
for (const k of keys) if (o && o[k] != null && !(Array.isArray(o[k]) && !o[k].length)) out[k] = o[k];
return out;
}