Skip to content
← Back to blog

LABIIUM insight

Why Code Is the Right Medium for AI Laboratory Agents

By Nobora
Concept illustration of code controlling programmable laboratory equipment, with an oscilloscope and circuit board in LABIIUM’s charcoal and violet palette.

An engineer asks an AI agent to measure an amplifier’s frequency response. Answering requires more than choosing a button: configure a signal generator, acquire input and output waveforms, calculate gain, repeat across frequencies, inspect unexpected results and save the evidence.

That sequence is a program.

For programmable electronics laboratories, code should be the default execution medium for AI agents. It uses a capability that coding models are explicitly trained to develop, turns measurement procedures into auditable programs, lets the runtime handle routine work while the agent concentrates on experimental decisions, and builds new measurement capabilities from the instruments already on the bench. Natural language remains the way to explain the goal. Code makes the proposed procedure concrete.

This is an engineering position, not a claim that code wins every agent benchmark or that a working script proves a measurement is valid. The strongest design combines generated code with a constrained instrument interface and independently enforced operating limits.

Build on LLMs’ training and demonstrated ability to write code#

Code is not an arbitrary notation imposed on an LLM. Code-trained models learn patterns of functions, loops, API use and testing from program data. The original Codex research, for example, explicitly fine-tuned a language model on public GitHub code and evaluated generated Python programs for functional correctness. This establishes a basis for learned programming capability; instrument-specific API documentation still matters. Evaluating Large Language Models Trained on Code

A clear Python interface therefore lets a laboratory agent apply a skill it already possesses: turn a specification into a program using documented components. It can read a function signature, inspect examples, combine operations and use execution feedback to diagnose mistakes. Familiar syntax reduces the need to invent a new interaction language for each piece of equipment.

A coding agent already works through a useful cycle: inspect an interface, propose an implementation, execute a test, observe an error and revise. Laboratory automation also requires composing unfamiliar interfaces, handling imperfect observations and checking whether the result answers the question.

There is direct research evidence for using code as an agent’s action format. In CodeAct, executable Python let agents compose tools and process their results. On its 82-task multi-tool benchmark, GPT-4-1106-preview achieved 74.4% success with code, compared with 52.4% using JSON actions; average interaction turns fell from 7.6 to 5.5. But in the paper’s separate single-API evaluation, JSON did better for that model. These are software-tool results, not a laboratory performance estimate. They support code especially for composition, rather than every individual action. CodeAct, ICML 2024

The Code as Policies project provides a complementary example: language models generated programs that combined perception outputs, control APIs, arithmetic and feedback logic on robot platforms. Its relevance to laboratory agents is the mechanism: a small set of useful primitives can support many procedures when composed in code. Code as Policies

Our intuition follows from that evidence: a laboratory agent should use the medium that already expresses experiments well, rather than translate every experimental step into another conversational turn.

A measurement goal flows through an executable procedure to laboratory equipment, with evidence returning to the agent.

The agent chooses a method; code executes its repeated operations and returns measurements and warnings for the next decision. Concept illustration; the code shown is pseudocode, not a PyTestLab API example.

Describe the experiment, not the instrument plumbing#

Start with one measurement. Save this simulated bench configuration as bench.yaml:

bench_name: Article demo
simulate: true
instruments:
  psu:
    profile: keysight/EDU36311A
  dmm:
    profile: keysight/EDU34450A

Then ask the instrument for the quantity you need:

from pytestlab import Bench

with Bench.open("bench.yaml") as bench:
    reading = bench.dmm.measure("dc_voltage")
    print(reading.values)

The bench file names the instruments. The experiment asks for a DC-voltage measurement. PyTestLab's factory, profile and driver handle instrument construction and device-specific command details.

Build a repeatable experiment#

Suppose we want to characterize a power supply's output at three setpoints, taking three readings at each point with a separate multimeter. The useful abstraction is a bench with named instruments and a measurement session that understands the sweep.

In PyTestLab, bench.yaml defines the psu and dmm aliases, their profiles and connections. Opening the bench constructs the instrument drivers through PyTestLab's factory. The experiment code can then operate on those roles:

from pytestlab import Bench, MeasurementSession

with Bench.open("bench.yaml") as bench:
    with MeasurementSession(bench=bench) as session:
        session.parameter("voltage", [1.0, 2.0, 3.0], unit="V")
        session.parameter("repeat", range(3))

        @session.acquire
        def measured_voltage(psu, dmm, voltage):
            psu.channel(1).set(voltage=voltage, current_limit=0.1).on()
            return dmm.measure("dc_voltage")

        experiment = session.run()
        bench.psu.channel(1).off()
        experiment.save_parquet("voltage-sweep.parquet")

The session executes the nine parameter combinations, supplies the instrument objects and setpoint to the acquisition function, and collects the returned measurement results. The script names the sweep and measurement; PyTestLab handles the iteration, instrument construction and structured experiment data. Connection details stay in the bench configuration, and device-specific commands stay behind the instrument interface.

The result supports a useful next question: how does measured voltage compare with the requested setpoint, and how much do the repeated readings vary? The agent can examine the experiment data, calculate those differences and propose a finer sweep where needed. Keeping the returned MeasurementResult also retains its measurement metadata rather than reducing it to a printed number.

Example scope: these snippets use the current PyTestLab development API (0.3.0, based on d6a948ab with ongoing local changes), not the older PyPI 0.2.4 API. The exact bench configuration and snippets were checked in simulation without operating hardware. Simulated readings are placeholders, not a model of a connected circuit or evidence of a physical measurement. Physical procedures need reviewed connections, limits, settling and shutdown behavior; the example settings are not universal safe settings.

The important change is where the work lives. The model expresses the measurement intention; the session carries out its repeated operations. The saved experiment gives the agent a structured result to reason about.

The same division appears in Program-Aided Language Models (PAL): the model translates a problem into code, while an interpreter performs the computation. PAL evaluated mathematical and symbolic tasks, not instruments, but the architectural lesson transfers: use the model to formulate the operation and the runtime to carry it out. PAL, ICML 2023

Three advantages follow.

1. Repetition belongs in the runtime#

The runtime can execute ordinary loop iterations without asking the model to choose the same next action repeatedly. This can reduce model round trips for predictable work. It does not make instrument acquisition, settling or communication intrinsically faster.

Nor does code automatically beat a well-designed tool such as run_frequency_sweep. A high-level tool can already perform the whole operation. Code becomes especially useful when a new task needs a composition that the existing tool catalog does not provide.

2. Waveforms can stay beside the analysis#

An oscilloscope waveform can contain many more values than an agent needs to read in conversation. Python can calculate amplitudes, detect clipping, fit a response or save a plot locally. The model can receive a concise summary and references to the underlying records.

Keeping raw arrays out of the conversational context can reduce unnecessary data transfer. The original observations should still be retained, and the summary must preserve warnings that affect interpretation. A clean-looking gain curve should never conceal failed acquisitions.

Local waveform analysis sends a summary and evidence links to the agent while retaining raw observations.

Analyse waveform data locally, return a concise summary with warnings and references, and retain the original observations. Conceptual illustration, not recorded measurement data.

3. The procedure becomes deterministic, auditable and reproducible#

Once a reviewed program is fixed, ordinary loops and calculations follow explicit rules rather than a fresh model-generated decision at every step. With the same inputs, configuration and deterministic dependencies, those computations can be repeated. A stochastic model can propose the procedure without becoming the mechanism that executes every operation.

That makes three different properties practical:

  • Deterministic procedure: the sampling sequence, calculation and stopping conditions are specified in code. External timing and observations can still change which branch executes.
  • Auditability: a reviewer can inspect exactly which operation is requested, which units are used and how a reported value is calculated. Version control exposes changes between runs.
  • Reproducibility: another researcher can rerun the saved procedure with recorded dependencies and configuration, rather than try to reconstruct it from a conversation.

Physical measurements will still vary because of noise, drift, timing, calibration and the device itself. Reproducible code makes the method reproducible; it does not promise identical physical values. Preserve the instrument configuration, connections, calibration context and raw data alongside the program.

A complete experiment record combines procedure, configuration and observations; repeated runs use the same method but produce new readings.

Preserve the procedure, configuration and observations so the method can be inspected and repeated. Physical values can still vary with noise, drift and timing. Conceptual illustration, not measured data.

Let the agent reason about the experiment, not count loop iterations#

An agent adds more value deciding whether a frequency range is appropriate than repeatedly choosing the next frequency from an already approved list. It should be able to examine an unexpected peak, propose a finer sweep, compare competing explanations and decide what evidence is needed next.

The runtime can handle the mechanical work: iterate the selected points, collect repeated readings, validate their format, calculate summaries and write files. Return a useful summary to the agent when a decision is actually required, or when the procedure encounters an unexpected condition.

This reduces the amount of routine orchestration placed in the model's conversational context. It is an architectural opportunity to spend reasoning effort on higher-level tasks, not a guarantee that a particular model will reason better. The program still needs explicit checkpoints where an unexpected condition should stop execution rather than be silently processed.

Code extends what the bench can do#

An instrument's front panel exposes a finite set of functions. Its programmable interface can become the building block for many more. Code can combine acquisitions, calculations and decisions into a measurement capability that no individual instrument provides as a built-in button.

Consider four examples:

Existing capability Capability built in software
A generator sets a frequency; a scope acquires input and output signals A frequency-response procedure calculates gain at each point and assembles the response curve, using the same amplitude convention on both channels
The bench can repeat that acquisition at selected frequencies An adaptive sweep first searches coarsely, then adds points around a peak or transition within a defined range and measurement budget
A scope exports a time-domain waveform Custom analysis estimates a decay time, measures settling against an application-specific threshold, or compares the waveform with a reference
A supply, generator and scope each expose programmable operations A coordinated characterization procedure applies an approved operating condition, sets the stimulus, acquires the response and associates the results with the settings

These are examples of procedures that can be implemented with suitable instrument interfaces, not a claim that the short multimeter example above implements them. Their usefulness comes from composition. A new experimental requirement does not always need a new instrument feature; it may need a new program using capabilities the hardware already has.

For an agent, that changes the scope of assistance. It can propose and construct a new measurement method from documented operations, rather than only select among a fixed menu of prewritten tests. A researcher might ask for a denser sweep around an unexpected resonance, a different analysis criterion, or the same characterization at several permitted operating points. The agent can revise the procedure while retaining the validated lower-level instrument interface.

Software does not increase the hardware's analog bandwidth, voltage rating, sampling capability or calibrated accuracy. Nor does sequentially commanding two instruments establish precise synchronization; tasks that require it need suitable triggers, clocks and timing support. Code extends the procedures and analyses available to the user, within the bench's physical limits.

That makes the instrument API especially important: it is the boundary between creative composition at the experiment level and the operations the equipment can actually perform.

A conceptual frequency-response sweep uses coarse sample points and denser sampling around a feature.

Software can compose existing instrument operations into an adaptive sweep, first searching broadly and then refining near a feature. Schematic illustration, not a wiring diagram or measured response; physical instrument limits are unchanged.

Prefer meaningful instrument APIs over piles of command strings#

Code is only as useful as the interface it calls.

An agent writing raw SCPI commands must get the model-specific syntax, query semantics, units and sequence right. A higher-level instrument API can expose the intent directly and centralize device-specific translation. That lets the generated procedure concentrate on the measurement rather than repeat driver implementation.

For example, the responsibilities should remain separate:

Layer Responsibility
Human or agent Define the measurement goal and propose a procedure
Experiment code Coordinate the sweep, checks and analysis
Instrument interface Validate operations and translate them for the device
Runtime and protection layer Enforce access, operating limits and execution bounds
Evidence store Preserve settings, observations, errors and provenance

This is why LABIIUM develops PyTestLab: a Python toolbox with instrument abstractions, declarative bench configuration and structured measurement workflows. A consistent interface gives both people and agents a clearer foundation for experiment code. It should not be interpreted as universal instrument support or a guarantee that generated procedures are correct.

Code and MCP solve different parts of the problem#

MCP gives an agent a standard way to discover and call tools. Code expresses computation and control flow. An agent can use an MCP tool to submit a reviewed program, or generated code can coordinate approved operations exposed through a service.

Anthropic describes this combination in its code execution with MCP architecture: tools can be exposed as code APIs, with intermediate data processed before returning selected results to the model. This provides a practical implementation pattern, not a measured laboratory benefit.

Choosing code does not require abandoning structured tools. In a hybrid design, narrowly scoped tools can handle connection setup and privileged actions, while code performs bounded orchestration and analysis.

The useful question is therefore: which decisions should the model make, and which operations should a runtime execute reliably without another model decision?

For repeated arithmetic, loops and parsing, a runtime is usually the clearer place. For interpreting an unexpected result or deciding whether a different experiment is needed, the agent can return to reasoning with the new evidence.

Write the loop once. Let Python run it.#

Using the same simulated bench.yaml, the agent can express a three-point procedure directly:

from pytestlab import Bench

with Bench.open("bench.yaml") as bench:
    readings = []
    for voltage in [1.0, 2.0, 3.0]:
        bench.psu.channel(1).set(voltage=voltage, current_limit=0.1).on()
        readings.append(bench.dmm.measure("dc_voltage"))
    bench.psu.channel(1).off()

With a per-command tool design, the agent would request a setpoint and a reading, then repeat those requests for the next points. Here it can prepare and submit the procedure once: Python runs the loop locally and returns the collected results. The instrument commands still happen. What changes is where the loop lives.

The procedure is also reusable: change the setpoint list or add a calculation without designing a new tool for every variation. An MCP server can expose a whole procedure or a code runner too. The distinction is per-command orchestration versus procedure-level execution, not a limitation inherent to MCP.

Code and MCP tool calls pass through an external control layer before reaching a physical laboratory experiment.

Code composes logic and analysis; MCP provides tool discovery and calls. In a laboratory architecture, access restrictions, operating limits and execution bounds must be enforced outside agent-written code. This is a conceptual architecture, not a claim that MCP itself provides physical protection.

A coding agent can still make a bad measurement#

A script can run perfectly while measuring the wrong thing. It may use the wrong termination, confuse peak-to-peak voltage with RMS, sample before settling or fit a curve to clipped data. Software execution success is weaker than experimental success.

A practical code-based architecture therefore needs several distinct checks:

  • Before execution: check the proposed procedure, dependencies, units, instrument roles and allowed operating envelope.
  • During execution: enforce limits outside agent-written code; bound duration and resource use; retain errors and partial results.
  • After execution: assess whether the observations satisfy the measurement task, with an appropriate reference or validity check.

A finally block is useful cleanup, but it cannot guarantee safety after a power loss, driver failure or disconnected cable. Protection must match the actual hazards of the bench. Likewise, a Python sandbox controls computing resources; it does not by itself make a physical experiment safe.

When a narrow tool is the better choice#

Code is not the right interface for every action. Reading one verified measurement through a fixed tool may be simpler than generating a script. A validated procedure with a few parameters may be better exposed as a high-level operation. A hard real-time control loop belongs in an appropriate controller, not an LLM-generated conversational workflow.

The case for code is strongest when tasks involve new combinations of existing capabilities, repeated measurements, substantial numerical data or procedures that researchers will want to inspect and reuse.

Give the agent a laboratory programming interface#

The opportunity is larger than letting an AI click the same controls as a person. A laboratory agent can turn a measurement goal into an explicit procedure, execute it through appropriate interfaces and produce an inspectable experimental record.

Code is a natural bridge between those stages. It can turn a collection of programmable instruments into new, inspectable measurement procedures without waiting for every workflow to become a built-in instrument feature. Its value comes from composition, executable feedback and reusable artifacts, combined with the growing ability of agents to work with software.

For an initial pilot, choose one existing measurement script and ask an agent to explain, modify and validate it against a defined task. Compare the result with your current workflow using task completion, review effort and the quality of the evidence. Do not judge it solely by whether the code runs.

Try it in your browser: open the simulated RC low-pass bench, change resistance or capacitance, rerun the Python procedure, and inspect the gain and phase. This is a virtual circuit example, not a physical hardware measurement.

Explore PyTestLab’s instrument and bench abstractions, read LABIIUM’s published research, or discuss a laboratory automation workflow.

More articles

Research & development

Get LABIIUM updates

Research papers, PyTestLab releases and notes on instrument automation from LABIIUM.

Research and development updates. Unsubscribe anytime.