Skip to content
Aditya Bhalsod
← AI
AIIntermediate

Treating LLM Output as Untrusted Input in a PyQt6 Desktop App

How AutoPCB, my PyQt6 desktop app, extracts, checks and falls back on model replies from five providers, and where those checks stop short of a real EDA flow.

  • #python
  • #pyqt
  • #llm
  • #ollama
  • #validation
Contents
  1. One interface for five backends
  2. Ask for a shape you can extract
  3. Check before the next stage
  4. What the fallback actually is
  5. Rules in code, opinions from the model
  6. Where this stops

AutoPCB is a PyQt6 desktop app. You describe a circuit in plain English and get a schematic, Verilog, a SPICE netlist, a bill of materials and a design-rule report. The README calls it IC design. In practice it is a chain of model calls with plain Python around each one, and it never launches a synthesis or simulation tool.

The plain Python is the part worth writing about. Every reply is extracted, parsed, checked and sometimes replaced before the next stage sees it, and the same code runs against Ollama, LM Studio, NVIDIA's hosted API, any OpenAI-style router and Anthropic.

One interface for five backends

Every call goes through AIProvider, which has two methods: complete(system, user) returns text and health_check() says whether the backend is reachable. Nothing above it knows which model it is talking to.

Python
class AIProvider:
    def complete(
        self, system: str, user: str, *, max_tokens: int = 8000, temperature: float = 0.2
    ) -> str:
        raise NotImplementedError

    def health_check(self) -> bool:
        raise NotImplementedError


class NvidiaAIProvider(_OpenAICompatibleProvider):
    label = PROVIDER_LABELS[PROVIDER_NVIDIA]
    requires_key = True
    health_path = "/models"
    chat_path = "/chat/completions"

Anthropic has its own class because it uses the official SDK. The other four share _OpenAICompatibleProvider, which POSTs a chat-completions payload with "stream": False and reads choices[0].message.content. A subclass sets a label, whether a key is required, a health path and a chat path. NVIDIA and the router use /chat/completions because their default base URLs already end in /v1.

AIProviderFactory keeps a name-to-class registry that plugins extend through ctx.register_ai_provider.

Ask for a shape you can extract

Each stage prompt demands one of two shapes. The spec, design, DRC, auto-fix and chat stages must return JSON only. The Verilog and SPICE stages must return one fenced block. Models break this, so extraction is lenient: a fenced block first, then the first balanced object.

Python
def _extract_json(text: str) -> dict:
    m = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, flags=re.DOTALL)
    candidate = m.group(1) if m else None
    if candidate is None:
        depth = 0
        start = -1
        for i, ch in enumerate(text):
            if ch == "{":
                if depth == 0:
                    start = i
                depth += 1
            elif ch == "}":
                depth -= 1
                if depth == 0 and start >= 0:
                    candidate = text[start : i + 1]
                    break
    # no candidate, or json.loads fails: raise AIParseError
    return json.loads(candidate)

The scan does not understand strings, so a brace inside a value ends it early, which surfaces as an AIParseError. For code, _extract_code tries the language tag, then any fence, then the raw text.

Retries come in two layers. _call makes up to three attempts on provider errors, with 1, 2 and 4 second backoff. _retrying_json makes up to three attempts when parsing fails, with the same prompt and no hint about what was wrong.

Check before the next stage

SpecParser turns the spec JSON into dataclasses. A missing name or ic_type, a non-numeric supply_voltage, or an ic_type outside digital, analog, mixed and power raises SpecValidationError. Other problems are coerced: an unknown pin direction becomes input, an unknown pin type becomes signal, and a spec with no pins gets VDD and GND. I reject ic_type outright because it picks which DRC checks run and which analyses the fallback netlist includes.

After the design call, DesignEngine.design adds VDD and GND nets if the model forgot them, then auto_place assigns every position in five lanes (power, inputs, signal, outputs, ground). The prompt never asks for coordinates.

The code stages get lighter checks.

Python
# VerilogGenerator.finalize
if "module" not in code or "endmodule" not in code:
    code = cls.fallback(design)
cls.lint(code)

# VerilogGenerator.lint
opens = code.count("(")
closes = code.count(")")
if opens != closes:
    raise VerilogLintError(f"unbalanced parentheses ({opens} vs {closes})")

Counting parentheses is not parsing Verilog. It catches a reply cut off mid-module, not a wrong one. For SPICE, NetlistGenerator.finalize adds .title, .end and .op when missing, then validate reads lines that start with R, C, L, M, Q, X, V, I or D and collects their node tokens. It raises only if there are no nodes or no ground node (0 or GND). Floating nodes and a missing VDD source are logged, never rejected.

What the fallback actually is

When validation fails, the generators substitute their own output. The Verilog fallback declares the ports from the spec and drives each output with assign <name> = 1'b0; and a comment calling the logic a placeholder or a TODO. The SPICE fallback maps component types to R, C, L, M, Q, D, V or X lines. It writes c.pins in as node names instead of looking each pin up in the design's nets, then appends default .model lines.

OutputProduced byChecked by
SpecModel (JSON)SpecParser
Components and netsModel (JSON)VDD and GND injection, then DRC
Timing, power and area estimatesModel (JSON)Nothing, copied through as numbers
VerilogModel, or a stubmodule keywords and bracket counts
SPICEModel, or a fallbackNode heuristic
DRCPython rules plus model rulesMerged report

The app never calls yosys or ngspice. install.py checks that both are on PATH and the settings dialog stores two path fields, but nothing reads them. The README says they validate and simulate; the checks above are the only validation in the code.

Rules in code, opinions from the model

The deterministic DRC checks unconnected pins, VDD and GND nets, nets with fewer than two connections, digital fan-out above 8 and bypass capacitors. The model then reviews the design and the first 6000 characters of the netlist, and the two reports are merged.

Python
det = self._drc_engine.run_deterministic(self._current_design)
ai_worker = self._ai.run_drc(self._current_design.to_dict(), self._current_spice)
...
ai_worker.error.connect(lambda _m: self._after_drc(det))
ai_worker.response_ready.connect(_fold_ai)

If the model call fails, the user still gets the deterministic report. Plugin rules run last, and a rule that raises is logged and skipped.

Where this stops

This shape suits a tool where a person reads the result. It breaks where the checks are weaker than the claim: bracket counts and a node heuristic cannot tell you a module synthesizes or a netlist simulates, and nothing here computes the timing, power and area numbers.

I would call yosys and ngspice, since the settings fields already exist, and feed their errors into the retry instead of re-sending the same prompt. I would also mark fallback output as a placeholder in the file banner.

Found this useful? Share it with your team.

Keep reading

More from AI and beyond