Python API Reference
This reference covers CircuitGen's Python functions, classes, and exceptions, including their parameters, return values, defaults, and behavior.
For installation and step-by-step usage examples, see the Python documentation.
The installed package version is available as circuitgen.__version__.
Functions
generate()
Generate a schematic from a circuit description. CircuitGen sends the description to the selected provider, checks and repairs the returned netlist, then renders and optionally saves it. Both the provider ID and model ID are required.
generate(
description: str,
*,
provider: str,
model: str,
api_key: str | None = None,
output: str | Path | None = "",
optimize: bool = False,
color: str = "#000000",
correction: str = "",
style: SchematicStyle | None = None,
output_format: str | None = None,
timeout: float = 120,
retry_transient: bool = False,
clarify: bool = False,
) -> CircuitResult
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
description | str | Required | Circuit request in natural language. It must be non-empty. |
provider | str | Required | Provider ID returned by list_providers(), or a supported alias (google, claude, chatgpt, or grok). Matching is case-insensitive. No provider is selected automatically. |
model | str | Required | Non-empty model ID accepted by that provider and available to the supplied key. CircuitGen does not check the provider's model catalog first. |
api_key | str | None | None | Explicit key. A non-empty value takes precedence over the provider's environment variable; otherwise the environment variable is used. CLI-saved credentials are not read. |
output | str | Path | None | "" | Destination path. Empty or omitted saves circuit.<format> in the current working directory (circuit.svg by default, or circuit.png when output_format="png"); None skips the initial save. A recognized filename suffix selects the format unless output_format is set. |
optimize | bool | False | Try additional bounded placement candidates and choose a better-scoring verified layout when available. It does not change circuit connectivity. |
color | str | "#000000" | Base schematic ink color as a six-digit #RRGGBB value. |
correction | str | "" | Extra correction context included with the original request. CircuitGen may also make up to two repair requests if a returned netlist fails checks. |
style | SchematicStyle | None | None | Optional background, drawing colors, and label visibility overrides. Applied to the rendered SVG before export. |
output_format | str | None | None | "svg", "png", or "pdf" (case-insensitive). If omitted, a recognized output suffix is used; otherwise SVG. An explicit format controls file content but does not change a supplied filename's suffix. |
timeout | float | 120 | Per-request timeout in seconds. Must be greater than 0 and at most 600. |
retry_transient | bool | False | Retry one transient provider failure when its retry delay is at most two seconds or is not supplied. |
clarify | bool | False | Allow a provider clarification request when essential wiring details are unclear. |
Returns
A CircuitResult containing the normalized netlist, SVG, model, selected output format, and available ERCReport.
Raises
CircuitErrorfor a missing or unsupported provider/model, missing API key, or other request and configuration errors.RequestDecisionError(aCircuitErrorsubclass) specifically when local screening refuses a request or marks it out of scope.TypeErrorifapi_keyis supplied with a non-string value.ClarificationRequiredwhen essential wiring information is needed and clarification is enabled or required by the request.ProviderRequestErrorfor provider HTTP, network, timeout, or response failures.NetlistGenerationErrorwhen generated output remains invalid after repair attempts, or when an explicitly requested value conflicts with a requested electrical target.NetlistRenderErrorwhen the returned netlist cannot be rendered.ValueErrorfor an invalid timeout or output format; rendering failures (including an invalid base color) are wrapped inNetlistRenderError.RuntimeErrorcan indicate a missing export renderer; file-system exceptions propagate if saving fails.
Notes
The explicit key is tried first; when it is None or blank, the provider-specific environment variable is used. API key names are listed in AI Providers. A transient retry is separate from the bounded netlist repair requests. The generated drawing retains SVG text in result.svg even when the saved file is PNG or PDF.
Example
from circuitgen import generate
result = generate(
"A 9 V battery powering a red LED through a resistor.",
provider="<provider-id>",
model="<model-id>",
api_key="<api-key>",
output="led.svg",
)
from_netlist()
Validate and render a supplied netlist without contacting an AI provider. Use it when the component connections are already specified.
from_netlist(
data: dict[str, Any],
*,
output: str | Path | None = "",
optimize: bool = False,
color: str = "#000000",
style: SchematicStyle | None = None,
output_format: str | None = None,
) -> CircuitResult
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
data | dict[str, Any] | Required | Mapping with components and nets; see Netlists. |
output | str | Path | None | "" | Destination. Empty or omitted writes circuit.<format> in the current working directory (circuit.svg by default, or circuit.png when output_format="png"); None keeps the result in memory. |
optimize | bool | False | Try additional bounded placement candidates and choose a better-scoring verified layout when possible. |
color | str | "#000000" | Base drawing color as six-digit #RRGGBB. |
style | SchematicStyle | None | None | Optional appearance overrides. |
output_format | str | None | None | "svg", "png", or "pdf"; an explicit value wins over the path suffix. Otherwise a recognized suffix selects the format, falling back to SVG. |
Returns
A CircuitResult. The source mapping is not modified; recognized values in the returned netlist are normalized.
Raises
NetlistRenderError when structural validation or schematic rendering fails; ValueError for an unsupported output format; export RuntimeError if a required renderer is unavailable; file-system exceptions if saving fails.
Notes
Parent directories are created when saving, and an existing destination is overwritten. If an explicit format conflicts with the filename extension, the explicit format determines the written data while the filename is left unchanged.
Example
from circuitgen import from_netlist
result = from_netlist(netlist, output="diagrams/led.pdf")
render()
Render a netlist or an already validated CircuitModel in memory. Unlike from_netlist(), this function does not create a CircuitResult or save a file.
render(
model: CircuitModel | dict[str, Any],
*,
optimize: bool = False,
color: str = "#000000",
style: SchematicStyle | None = None,
output_format: str = "svg",
) -> str | bytes
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
model | CircuitModel | dict[str, Any] | Required | A validated model or netlist mapping. |
optimize | bool | False | Try additional bounded placement candidates where available. |
color | str | "#000000" | Base drawing color as six-digit #RRGGBB. |
style | SchematicStyle | None | None | Optional appearance overrides. |
output_format | str | "svg" | "svg", "png", or "pdf". |
Returns
SVG text for "svg"; bytes for "png" and "pdf".
Raises
TypeError if model is neither a CircuitModel nor a dictionary. For a dictionary, validation, rendering, format, and export errors raised during rendering are wrapped in NetlistRenderError. For a CircuitModel, routing errors propagate as CircuitError, while unsupported formats or an invalid base color raise ValueError and unavailable export dependencies raise RuntimeError.
Notes
PNG and PDF use resvg-py; PDF also uses Pillow. Both are declared project dependencies in pyproject.toml, so a normal CircuitGen installation installs them. The imports are lazy, and the runtime error applies if a dependency is missing from the active environment.
Example
from circuitgen import render
svg_text = render(netlist)
pdf_data = render(netlist, output_format="pdf")
validate()
Check whether a netlist has valid structure and run the implemented electrical rule checks when structural validation succeeds. It does not render an image.
validate(data: dict[str, Any]) -> ValidationResult
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
data | dict[str, Any] | Required | Netlist mapping to check. |
Returns
A ValidationResult. valid reports structural validity; electrical findings are in electrical_report and do not change this flag.
Raises
Expected structural problems (CircuitError, ValueError, TypeError, or KeyError) are returned in errors. Unexpected exception types may propagate.
Example
from circuitgen import validate
result = validate(netlist)
if result.valid:
print(result.electrical_report.format_text())
else:
print(result.errors)
list_providers()
Return the provider identifiers supported by the current installation, in configured order.
list_providers() -> list[str]
Returns
A new list of provider IDs accepted by generate(). It does not check account access, API keys, or model availability.
Example
from circuitgen import list_providers
print(list_providers())
list_symbols()
Return the built-in component type identifiers that CircuitGen can draw.
list_symbols() -> list[str]
Returns
A new, alphabetically sorted list. Explicit custom components supplied with their own pins are not included. See Components for symbols and pin names.
Example
from circuitgen import list_symbols
print(list_symbols())
decide_request()
Run local request screening before an AI call. It handles clear out-of-scope, refused, and simple clarification cases; it does not assess general electrical correctness.
decide_request(description: str) -> RequestDecision
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
description | str | Required | Circuit request to screen. Must be a non-empty string. |
Returns
A RequestDecision, with status set to "ready", "needs_clarification", "out_of_scope", or "refused".
Raises
CircuitError if the description is not a non-empty string.
Example
from circuitgen import decide_request
decision = decide_request("Connect a battery to an LED through a resistor")
check_electrical_rules()
Validate a netlist structurally, then return the library's conservative electrical rule findings. This lower-level helper is available from circuitgen.erc; it is not re-exported from the package root. The root-level validate() calls the same checks and also returns the structural model.
check_electrical_rules(raw: dict[str, Any]) -> ERCReport
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
raw | dict[str, Any] | Required | Netlist to structurally validate and inspect. |
Returns
An ERCReport containing findings. These rules are limited checks, not circuit simulation or a safety certification.
Raises
Structural validation errors propagate as CircuitError, ValueError, TypeError, or KeyError from model validation.
Example
from circuitgen.erc import check_electrical_rules
report = check_electrical_rules(netlist)
Classes
CircuitResult
Mutable dataclass returned by generate() and from_netlist(). It keeps the rendered SVG and netlist even when the selected export is PNG or PDF.
CircuitResult(
svg: str,
netlist: dict[str, Any],
model: CircuitModel | None = None,
output_path: str | None = None,
output_format: str = "svg",
electrical_report: ERCReport | None = None,
) -> None
Attributes
| Name | Type | Default | Description |
|---|---|---|---|
svg | str | Required | Rendered SVG source with appearance styling applied. |
netlist | dict[str, Any] | Required | Netlist with recognized values normalized. |
model | CircuitModel | None | None | Validated connectivity and resolved symbols, when provided by the workflow. |
output_path | str | None | None | Absolute path of the most recently saved output. |
output_format | str | "svg" | Format selected when the result was created. |
electrical_report | ERCReport | None | None | Electrical findings, if available. |
CircuitResult.encode()
Signature
encode(self, output_format: str | None = None) -> str | bytes
Return the stored drawing as SVG text or encode it as PNG or PDF bytes. An omitted or None format uses self.output_format.
Parameters and returns
| Name | Type | Default | Description |
|---|---|---|---|
output_format | str | None | None | "svg", "png", or "pdf"; otherwise uses the result format. |
Returns str for SVG and bytes for PNG/PDF. Unsupported formats raise ValueError; missing export dependencies raise RuntimeError.
CircuitResult.save()
Signature
save(
self,
path: str | Path,
*,
output_format: str | None = None,
) -> str
Write the schematic to disk, create parent directories as needed, update output_path, and return the resolved destination path. Existing files are overwritten.
Parameters and returns
| Name | Type | Default | Description |
|---|---|---|---|
path | str | Path | Required | Destination. An empty or whitespace-only path uses circuit.<format> in the current working directory. |
output_format | str | None | None | Optional explicit "svg", "png", or "pdf"; otherwise a recognized filename suffix is used, then self.output_format. |
Returns the absolute path as str. An explicit format wins even when the filename suffix says otherwise; the filename is not rewritten. Unsupported formats raise ValueError; encoding failures raise RuntimeError; file-system errors propagate.
ValidationResult
Frozen dataclass returned by validate(). Attribute assignment is blocked, but the errors value is a normal mutable list.
ValidationResult(
valid: bool,
errors: list[str] = <factory>,
model: CircuitModel | None = None,
electrical_report: ERCReport | None = None,
) -> None
Attributes
| Name | Type | Default | Description |
|---|---|---|---|
valid | bool | Required | Whether structural validation passed. ERC findings do not change this value. |
errors | list[str] | A new empty list | Structural validation messages when invalid. |
model | CircuitModel | None | None | Validated model when valid is true. |
electrical_report | ERCReport | None | None | ERC results for a structurally valid model; otherwise None. |
Each instance gets its own errors list through a dataclass default factory.
CircuitModel
Frozen dataclass returned as ValidationResult.model. It contains the validated netlist's components, nets, and symbol specifications. Its fields cannot be reassigned, though the dictionaries they refer to remain mutable.
CircuitModel(
components: dict[str, Component],
nets: dict[str, tuple[str, ...]],
symbols: dict[str, SymbolSpec] = <factory>,
) -> None
Attributes
| Name | Type | Default | Description |
|---|---|---|---|
components | dict[str, Component] | Required | Component objects keyed by component ID. Each contains cid, kind, value, and a pin-to-net mapping. The value class is defined in circuitgen.engine, not re-exported from the package root. |
nets | dict[str, tuple[str, ...]] | Required | Net names mapped to terminal references such as R1.a. |
symbols | dict[str, SymbolSpec] | A new empty dict | Resolved symbol specification for each component; SymbolSpec is defined in circuitgen.symbols and is not a package-root export. |
The symbols field uses a default factory, so a fresh dictionary is created for each instance.
SchematicStyle
Frozen dataclass containing optional appearance changes accepted by generate(), from_netlist(), and render(). It is applied to generated SVG before encoding.
SchematicStyle(
background: str = "transparent",
component_color: str | None = None,
wire_color: str | None = None,
text_color: str | None = None,
show_component_ids: bool = True,
show_component_values: bool = True,
) -> None
Attributes
| Name | Type | Default | Description |
|---|---|---|---|
background | str | "transparent" | "transparent", "white", "black", or six-digit #RRGGBB. |
component_color | str | None | None | Hex color for symbol outlines and filled symbol shapes; None leaves base drawing colors unchanged. |
wire_color | str | None | None | Hex color for wires and junction dots. |
text_color | str | None | None | Hex color for component names, values, pin labels, and marks. |
show_component_ids | bool | True | Show or hide component ID/name labels. |
show_component_values | bool | True | Show or hide value labels; source polarity marks are retained. |
Every provided color must be a six-digit hex string. Invalid values raise ValueError during construction. None means no override for the optional color fields.
The color argument on the rendering functions sets the base ink color. Non-None component_color, wire_color, and text_color values override the corresponding parts of that base color; background and the visibility flags are applied independently.
SchematicStyle.apply()
Signature
apply(self, svg: str) -> str
Return an SVG string with the style overrides added. It does not re-render or validate the drawing. It has no explicit input validation beyond the operations performed on the supplied string.
RequestDecision
Frozen dataclass returned by decide_request(). It reports the local screening result and any clarification details.
RequestDecision(
status: str,
question: str = "",
assumption: str = "",
) -> None
Attributes
| Name | Type | Default | Description |
|---|---|---|---|
status | str | Required | "ready", "needs_clarification", "out_of_scope", or "refused" for decisions produced by decide_request(). The constructor does not enforce these values. |
question | str | "" | Clarifying question, if one is needed. |
assumption | str | "" | Suggested assumption, if available. |
ERCIssue
Frozen dataclass describing one ERC finding. Import it from circuitgen.erc; it is not re-exported from the package root.
ERCIssue(
severity: str,
code: str,
message: str,
refs: tuple[str, ...] = (),
suggestion: str = "",
) -> None
Attributes
| Name | Type | Default | Description |
|---|---|---|---|
severity | str | Required | Finding level, used as "error", "warning", or "info" by the checker. |
code | str | Required | Stable finding code. |
message | str | Required | Human-readable description. |
refs | tuple[str, ...] | () | Related component or terminal references. |
suggestion | str | "" | Suggested follow-up, when available. |
ERCReport
Frozen dataclass returned in ValidationResult.electrical_report and by check_electrical_rules(). Import it from circuitgen.erc; it is not re-exported from the package root.
ERCReport(issues: tuple[ERCIssue, ...]) -> None
Attributes and properties
| Name | Type | Description |
|---|---|---|
issues | tuple[ERCIssue, ...] | All findings. |
errors | tuple[ERCIssue, ...] | Findings whose severity is "error". |
warnings | tuple[ERCIssue, ...] | Findings whose severity is "warning". |
infos | tuple[ERCIssue, ...] | Findings whose severity is "info". |
ok | bool | False when definite errors exist; warnings alone do not make it false. |
ERCReport.as_dict()
Signature
as_dict(self) -> dict[str, Any]
Return a JSON-compatible mapping with ok, severity counts under summary, and serialized findings under issues.
ERCReport.format_text()
Signature
format_text(self) -> str
Return a plain-text summary followed by each finding and any suggestion. When the report is empty, the text says that no implemented checks detected an issue.
Exceptions
CircuitError
Base exception for CircuitGen request, validation, and rendering errors. It inherits directly from Python's Exception. The class has no custom initializer or additional attributes; its message is available through the usual exception interface. Several errors below subclass it.
NetlistRenderError
Subclass of CircuitError, defined in circuitgen.api and re-exported from circuitgen. Raised by from_netlist() and dictionary-based render() when validation or rendering fails; also used by the generation workflow if its generated netlist cannot render.
NetlistRenderError(message: str, netlist: dict[str, Any])
message becomes the exception text. The netlist attribute stores the original supplied or generated mapping for inspection. Export-format and file-writing failures are not generally converted to this exception.
NetlistGenerationError
Subclass of CircuitError, defined in circuitgen.ai and re-exported from circuitgen. Raised when provider output remains invalid after the bounded correction attempts, or when a requested electrical target conflicts with explicitly requested component values.
NetlistGenerationError(message: str, netlist: dict[str, Any])
The netlist attribute contains the last generated mapping when one is available. A failure before a netlist is parsed may instead raise CircuitError without a netlist attribute.
ClarificationRequired
Subclass of CircuitError, defined in circuitgen.ai and re-exported from circuitgen. Raised when the provider or local screening needs essential connection details before a netlist can be generated.
ClarificationRequired(question: str, assumption: str = "")
The exception text is the question. Attributes: question contains that prompt; assumption contains a suggested assumption or an empty string.
RequestDecisionError
Subclass of CircuitError, defined in circuitgen.ai and re-exported from circuitgen. Raised when request screening marks a description as refused or out of scope.
RequestDecisionError(status: str)
The status attribute is "refused" or "out_of_scope"; the exception text gives the corresponding short explanation.
ProviderRequestError
Subclass of CircuitError, defined in circuitgen.ai. Import it with from circuitgen.ai import ProviderRequestError; it is not re-exported from the package root. Provider adapters raise it for HTTP, network, timeout, and malformed-response failures.
ProviderRequestError(
message: str,
*,
status: int | None = None,
transient: bool = False,
kind: str | None = None,
retry_after: float | None = None,
)
Attributes
| Name | Type | Default | Description |
|---|---|---|---|
status | int | None | None | HTTP status code, when the provider returned one. |
transient | bool | False | Whether the adapter classified the failure as transient. |
kind | str | None | None | Stored value is inferred from status when omitted: mapped status codes get a category; other or absent codes become "provider". The class does not restrict manually supplied values. |
retry_after | float | None | None | Parsed provider retry delay in seconds, if available. |
The implementation classifies provider failures as authentication, quota, access, model_unavailable, rate_limit, timeout, temporary, network, bad_response, or provider. For manually constructed exceptions, omitted kind is inferred for HTTP statuses 401, 402, 403, 404, 429, 503, and 504; other statuses use provider. Provider adapters may apply more specific classifications, such as treating HTTP 408 as a timeout. transient is set by the adapter. With retry_transient=True, generate() makes at most one immediate retry when the error is transient and the delay is absent or no more than two seconds; longer delays are not waited out.