SuperAPI AI Directory

solidworks-automation

General & other

View repository

Updated 10-15 23:27

About this skill

SolidWorks Automation Skills

Quick Start

Environment Requirements

  • Windows system; native SolidWorks operations target SolidWorks 2026 for support and acceptance, while open-format headless writing does not require CAD software to be installed
  • Python 3.10+; native Windows CAD automation additionally requires pywin32 / comtypes
  • MCP/tool-based invocation requires mcp / pydantic
  • Final drawing delivery review requires PyMuPDF; it reads back the actual dimension text boundaries from a PDF exported by SolidWorks, and is already included in requirements.txt
  • When processing GLB/GLTF/OBJ/STL mesh reference models, you may also need trimesh / pygltflib / numpy / Pillow
  • If using via OpenClaw, ensure the skill directory is located in ~/.openclaw/skills/solidworks-automation/ or ~/.agents/skills/solidworks-automation/

Entry Self-Check

All agents must run the skill self-check before performing SolidWorks automation:

python SKILL_DIR/scripts/sw_preflight.py

Before desktop or CLI execution, it is recommended to run environment diagnostics first:

python SKILL_DIR/scripts/cad_studio.py doctor

capabilities.yaml is the single source of truth for capabilities shared by Skill, MCP, queue, and UI. Capability levels are verified、pilot、reference_only or not_implemented; the latter two must not be used for unattended delivery. This manifest also maintains atomic operation routing for Python, C# PIA/Add-in, native C++, SWBasic, OCCT, and external solvers; before execution you can query with python scripts/backend_router.py --list , with rules in references/language-backend-routing.md.

Multiple Entries and Multiple Backends

  • CAD Studio and Skill/CLI/MCP are peer entries, sharing Automation Job, NeutralCadDocument, Preview Manifest, Evidence Graph, and the capability manifest.
  • When SolidWorks/AutoCAD cannot be detected, only block native formats such as SLDPRT/SLDASM/SLDDRW/DWG ; open-format tasks are preferentially routed to headless_open_format_writing.
  • Headless writing uses scripts/headless_cad_writer.py; the OCCT/OCP isolated process actually writes STEP, IGES, BREP, STL, OBJ, and GLB, while the 2D backend writes DXF, SVG, PDF, and PNG, and generates geometry and SHA-256 evidence.
  • DXF delivery additionally generates preview_scene; existing DXF can be converted into a restricted PreviewScene via python scripts/cad_studio.py preview-dxf --input drawing.dxf --output drawing.scene.json or MCP cadstudio_build_dxf_preview_scene . This command only reads whitelisted entities and refuses to overwrite old files.
  • OCCT currently covers boxes, cylinders, boolean union, cylindrical hole cutting, ruled/restricted smooth Loft, line/single-arc Sweep, closed-shell Knit, and open-face Thicken; for complex paths, self-intersecting offsets, or missing OCP runtime, remain blocked. It is forbidden to fake support by changing file extensions or using empty files.
  • delivery-preview may only display the actual artifacts of the current task; fixed samples must be marked demo-showcase and isDemo: true, and must not enter delivery judgment.

Rules:

  1. When a missing comtypes / win32com / pythoncom is detected, show the user a friendly confirmation: 检测到当前 Python 环境缺少 comtypes / win32com 库,是否授权 AI 自动为您配置本地环境?[Y/N]
  2. After the user inputs Y / yes , the agent may automatically execute python -m pip install "pywin32>=305" "comtypes>=1.2.0" in the local shell to fill in dependencies; if the user refuses, stop and provide manual installation commands.
  3. When no SolidWorks installation or COM registration is detected, stop native SolidWorks operations; if native format is not required and fallbackPolicy=allow_open_formats, continue executing the headless open-format backend, and do not mark the entire task as failed.

Python dependency reminder

Install dependencies minimally according to the task; do not force-install mesh conversion libraries during ordinary part modeling; engineering drawing delivery requires the standard requirements.txt PyMuPDF in:

# 核心 SolidWorks COM 自动化依赖
python -m pip install -r SKILL_DIR\requirements.txt

# 仅在需要 GLB/GLTF/OBJ/STL 网格检查、缩放或转换时安装
python -m pip install -r SKILL_DIR\requirements-mesh.txt

Before executing tasks involving GLB/GLTF/FBX/BLEND to OBJ/STL conversion, first use importlib.util.find_spec() to check whether trimesh、pygltflib、PIL is available; if missing, first inform the user which libraries need to be installed and their purpose, then install them or provide manual commands.

Connect to SolidWorks

import sys; sys.path.insert(0, r"SKILL_DIR/scripts")
from sw_connect import mm
from sw_part import sketch, sketch_circle, extrude_boss
from sw_sketch_quality import fully_define_sketch
from sw_session import SolidWorksSession

with SolidWorksSession(version=2026) as session:
    model = session.new_part()

    with sketch(model, "Front Plane") as sketch_name:
        sketch_circle(model, 0, 0, mm(25))
        fully_define_sketch(model)

    if extrude_boss(model, sketch_name, mm(50)) is None:
        raise RuntimeError("拉伸失败")
    if not session.save(model, r"C:\temp\cylinder.sldprt"):
        raise RuntimeError("保存失败")
    if not session.export(model, r"C:\temp\cylinder.step"):
        raise RuntimeError("导出失败")

Replace SKILL_DIR with the actual installation path of this skill.

For model delivery, read back the sketch's constraint status, dimensions, and relations; do not use batch Fix as a substitute for design parameters; after saving and reopening, verify that the sketch is consumed by the target feature, key dimensions can be changed, and hole positions remain correct. Basic circles/rectangles can use fully_define_sketch(); complex sketches should explicitly define design dimensions and relations, then use inspect_model_sketches() for acceptance; when evidence is lacking, retain manual review.

The session context only cleans up documents registered in this round and empty instances whose ownership is confirmed; when the document budget is reached, handle this round's files first. When execution is marked as failed, rebuild fails, the check result is unknown, or manual review has not yet been completed, do not claim the task is complete. Remote MCP retrieves PNGs or original files via artifact_refs and verifies SHA-256; see the rules in mcp-server/README.md.

Core workflow

Select the corresponding module according to user needs:

Requirement Script Reference document
Entry self-check and dependency completion scripts/sw_preflight.py references/troubleshooting.md
Headless CAD open-format writing scripts/headless_cad_writer.py、scripts/cad_studio.py write-open-format capabilities.yaml, common CAD Core Schema
Advanced capability/type library detection scripts/sw_capability_probe.py references/complex-mechanical-routing.md
Python/C#/C++/SWBasic/OCCT backend selection scripts/backend_router.py references/language-backend-routing.md、capabilities.yaml
C# in-process Add-in host, events, and UI scripts/sw_addin_host.ps1、scripts/sw_addin_host.py references/solidworks-addin-host.md
Multi-model macro generation protection scripts/sw_macro_guard.py references/openclaw.md
Friendly session API scripts/sw_session.py -
Connection and document management scripts/sw_connect.py -
Appearance and materials scripts/sw_appearance.py references/appearance.md
Part modeling (sketch + features) scripts/sw_part.py references/part-modeling.md
Standard external spur gear solid scripts/sw_gear.py references/gears.md
Blind hole/counterbore/countersink/slot with semicircular ends and hole position acceptance scripts/sw_hole_features.py、scripts/sw_review.py references/complex-hole-features.md、references/review.md
Natural language to parametric design plan / VibeCAD subskills/solidworks-vibecad/scripts/plan_from_brief.py subskills/solidworks-vibecad/SKILL.md、subskills/solidworks-vibecad/README.md
Multi-fillet/chamfer CNC machined part subskills/solidworks-fillet-chamfer-cnc/scripts/create_cnc_mount_template.py; for advanced fillets use verify_advanced_fillets.py subskills/solidworks-fillet-chamfer-cnc/SKILL.md、subskills/solidworks-fillet-chamfer-cnc/references/cnc-fillet-chamfer-lessons.md
Screw holes/threaded holes, tapped pilot holes subskills/solidworks-threaded-holes/scripts/create_threaded_hole_template.py subskills/solidworks-threaded-holes/SKILL.md、subskills/solidworks-threaded-holes/references/threaded-hole-lessons.md
AutoCAD DWG/DXF 2D drafting, line art to CAD, batch drawing modification subskills/autocad-automation/scripts/acad_draw.py、subskills/autocad-automation/scripts/acad_review.py subskills/autocad-automation/SKILL.md、subskills/autocad-automation/references/troubleshooting.md
Assembly operations, gear linkage/hinge/draggable motion mates scripts/sw_assembly.py references/assembly.md
Motion Study motion cases, rotary motors, and result auditing scripts/sw_motion.py references/motion-study.md、references/complex-mechanical-routing.md
Engineering drawing output scripts/sw_drawing.py references/drawing.md
File export scripts/sw_export.py references/export.md
Configuration family creation/activation, parameter modification, and custom properties scripts/sw_document_data.py references/advanced.md
Assembly BOM CSV and Pack and Go scripts/sw_delivery.py references/export.md
OBJ/STL high-fidelity mesh reference import scripts/sw_import_mesh_reference.py references/mesh-reference-import.md
Result self-review scripts/sw_review.py references/review.md
Semantic entity reference scripts/sw_entity_reference.py Gradually replace Face1/Edge1 and screen coordinates
DFM manufacturing risk review scripts/dfm_review.py、scripts/dfm_profiles.py、scripts/cad_studio.py check-dfm Supplier profile, B-Rep evidence, machining, sheet metal, laser cutting, 3D printing, and injection molding declarative rule checks
Routing neutral review and preconditions scripts/routing_review.py、scripts/cad_studio.py check-routing、scripts/cad_studio.py routing-preflight Endpoints, segments, lengths, bend radii, collisions/clearances, supports, Routing BOM; native writes must wait for add-in/license evidence
FEA preconditions, inputs, and restricted solving scripts/fea_analysis.py、scripts/fea_convergence.py、scripts/cad_studio.py fea-preflight/prepare-fea/run-fea/run-fea-convergence CalculiX 2.23 has verified linear/nonlinear static, plasticity, surface contact, final-step COPEN/CPRESS/CSLIP, and linear/nonlinear mesh convergence; all still require engineering review
Complex surfaces and molds scripts/advanced_geometry.py、scripts/advanced_geometry_ocp.py、scripts/advanced_surface_ocp.py、scripts/cad_studio.py review-advanced-geometry/create-ocp-loft/create-ocp-surface Ruled/smooth Loft, restricted Sweep/Knit/Thicken can be written and reopened as B-Rep; G1/G2 and curvature radii only return discrete sampling evidence
Local MCP Server mcp-server/server.py mcp-server/README.md、references/mcp-server.md
MCP protocol verification scripts/validate_mcp.py mcp-server/README.md
Unwrapped API verification - references/api-lookup.md
OpenClaw controls SolidWorks - references/openclaw.md
Sheet metal/weldments/simulation/properties - references/advanced.md
Enterprise Agent / local-first with cloud RAG apps/desktop/cad_workbench/knowledge_retrieval.py references/enterprise-agent-rag.md
Codex/Claude/Gemini/OpenCode Provider Adapter apps/desktop/cad_workbench/agent_providers.py references/agent-provider-architecture.md
Comprehensive mechanical engineering DAG automatic orchestration apps/desktop/cad_workbench/engineering_orchestrator.py references/complex-mechanical-routing.md
Common error troubleshooting - references/troubleshooting.md

Pack and Go has passed native regression three consecutive times on a basic two-part assembly in SW2026 SP01.1:SavePackAndGo() Actually outputs the assembly and two parts, all with status code 0, without using the staging fallback. In some versions, GetDocumentNames() may still enumerate only top-level files before saving; do not use AddExternalDocuments to supplement the assembly's native parts. You should perform a native save first, then audit the actual on-disk dependencies. If dependencies are still missing on disk,scripts/sw_delivery.py::pack_and_go() by default generates GetDependencies2 with a manifest and SHA-256 as a pilot staging package; when strict native semantics are required, use fallback_policy="blocked". External references, Toolbox, configurations, and drawings still require manual review, so the overall capability remains pilot.

How to Collaborate with OpenClaw

  1. First confirm the SolidWorks version, UI language, input file path, output path, and target operation (modeling / assembly / drawing / export).
  2. Prefer reusing {baseDir}/scripts existing modules under it; do not repeatedly hand-write COM connection logic.
  3. In OpenClaw's exec / shell capability, execute short, one-off Python scripts, with the minimal import set as follows:
import sys
sys.path.insert(0, r"{baseDir}/scripts")
from sw_connect import connect_solidworks, mm, deg, new_document
  1. After execution, check whether the returned object is None, whether saving/export succeeded, and whether the output file was written to disk.
  2. After generating or modifying a model, you must perform a result self-review: export at least one isometric preview image, and if necessary export front/top/right views, and visually check through screenshots or BMP whether the geometry matches the user's intent.
  3. If you need a more complete OpenClaw workflow, prompt examples, and troubleshooting suggestions, then read references/openclaw.md.

Usage Flow

  1. First run backend_router.pybased on atomic operations, then combine preferredBackend、requiredOutputs、nativeFormatRequired and fallbackPolicy to determine the backend; do not first assume that Python, C#, or SolidWorks are necessarily available. For ordinary tasks, prefer the Automation-equivalent interface; only escalate to native C++ when raw I* pointer semantics that are explicitly required to be supported only by unmanaged C++ are needed. Event subscriptions, PropertyManagerPage, TaskPane, or long-lived UI go through the solidworks_addin_ui_events route, preferring a C# Add-in; you must check HKLM registration, 64-bit TLB registration, and host-status.json, and cannot rely only on LoadAddIn=0 Claim success. The PMP Handler for SW2026 must be public, COM-visible, and provide a IDispatch class interface.
  2. When the native SolidWorks format is required, run sw_preflight.py; if dependencies are missing, request the user's authorization for automatic installation; if SolidWorks is missing, block only the native stage.
  3. When the native format is not required or an open-format fallback is allowed, run python scripts/cad_studio.py write-open-format --input model.cadstudio.json --out-dir output.
  4. When a quick manufacturability review is required, run python scripts/cad_studio.py check-dfm --input model.cadstudio.json --output output/dfm_report.json --process machining; supports --profile supplier.json and --brep-evidence brep.json. Return when the report is missing material, wall thickness, K-factor, slit, forming space, or the required B-Rep evidence blocked, and even if the rules pass, manual review is still required.
  5. For the native SolidWorks route, preferentially use SolidWorksSession() to manage connections, opening, creating, saving, and exporting; when lower-level control is needed, then combine functions such as sw_connect.py、sw_part.py .
  6. When the user's requirements lean toward natural language, the parameters are incomplete, or an "industry knowledge base + prompt template + parametric design plan" is needed, first read subskills/solidworks-vibecad/SKILL.md, and generate design_plan.json and an execution summary.
  7. For CNC parts, mounting bases, connecting blocks, and brackets with many fillets/chamfers, first read subskills/solidworks-fillet-chamfer-cnc/SKILL.md, and execute in the stable order of "base body -> outer contour fillets/chamfers -> hole/slot cutouts -> hole opening chamfers -> review".
  8. For screw holes, threaded holes, tapped holes, and M3/M4/M5/M6/M8 blind-hole or through-hole tasks, first read subskills/solidworks-threaded-holes/SKILL.md; by default, execute along the stable route of "parameter/hole position verification -> tapping pilot hole -> Metric Tap real Thread -> CosmeticThread/evidence helix fallback -> hole opening chamfer -> feature evidence after rebuild -> attributes and review". Hole Wizard, external threads, inch/pipe threads, and modifying holes on existing parts are still handled as pilot.

Gear routing gate: When the user says "draw/model/generate a gear", first read references/gears.md, and do not replace a solid gear requirement with a Gear Mate. Only for standard external spur gears with known module, number of teeth, pressure angle, face width, and shaft hole may scripts/sw_gear.pybe used; manufacturing tasks must not fabricate parameters, and only for a purely visual demo may default values be explicitly declared. Helical gears, bevel gears, internal gears, racks, worm gears/worm drives, profile shifts, or production-grade modification/backlash must be routed to a dedicated route or manually reviewed, and must not be forced onto the standard spur gear script. Only "gear linkage/transmission/mate" routes to sw_assembly.add_gear_mate_by_cylinders().

  1. For ordinary blind holes, through holes, cylindrical counterbores, conical countersinks, half-round end slots, or hole array tasks, read references/complex-hole-features.md and preferentially call scripts/sw_hole_features.py; creation parameter evidence must further be cross-checked with collect_geometry_measurements()、validate_hole_positions() and section views.
  2. For SolidWorks part drawings, assembly drawings, GB/T engineering drawings, dimension chains, hole tables, BOMs, title blocks, or drawing review tasks, first read subskills/solidworks-engineering-drawing/SKILL.md; this sub-skill consumes the root skill's model, hole/slot, and attribute evidence. For AutoCAD DWG/DXF, 2D drawings, converting line art to CAD, batch drawing modification, or AutoCAD native preview tasks, read subskills/autocad-automation/SKILL.md. Mechanical/3D printing hole deliverables must be handled as manufacturable drawings: all holes, slots, interfaces, sprue gates, screw holes, and screw bosses must be given specifications, quantities, and locating dimensions at the same time; when the drawing is crowded, use hole tables/slot tables, and do not replace key dimensions with long leaders.
  3. When the user requests a real product's "original appearance", "1:1 replica", or "not like a concept version", first read references/mesh-reference-import.md: public mesh/blueprint references take priority, and do not repeatedly refine a low-fidelity hand-made draft; when OBJ/STL needs to be imported, preferentially use scripts/sw_import_mesh_reference.py。
  4. If a VBA macro must be generated by a large model, first use sw_macro_guard.py for model routing, code validation, retries, and local template fallback.
  5. Use session.export() or sw_export.py to save/export files.
  6. Use sw_review.py to export a preview image and self-review; if GUI/desktop screenshot capability is available, open the SolidWorks view screenshot for re-checking.
  7. For sheet metal, weldments, complex surfaces, molds, Routing, Simulation/FEA, complex Motion, or configuration family tasks, first run sw_capability_probe.py and read references/complex-mechanical-routing.md; for Routing use routing-preflight/check-routing, for FEA use fea-preflight/prepare-fea/run-fea/run-fea-convergence, for complex surfaces use review-advanced-geometry/create-ocp-loft/create-ocp-surface. Passing FEA and advanced surface solving still requires review_required.
  8. When enterprise/project mechanical knowledge is needed, read references/enterprise-agent-rag.md; by default use only local knowledge; cloud RAG must be explicitly enabled, declare external_network , and complete manual approval.
  9. When a requirement simultaneously spans more than two engineering domains among parts, holes/slots/fillets, assembly Mates, Motion, drawings/BOM, and multi-format delivery, call apps/desktop/cad_workbench/engineering_orchestrator.py to generate a staged DAG. Critical CAD write operations must be executed serially according to dependencies, and each stage must independently save artifacts and acceptance evidence; local modifications only replan the affected stage and its successors, and it is forbidden to cram the entire engineering task into one overly long Prompt and then claim completion in one shot.

Default Bottom Lines for Mechanical Drawings

From now on, whenever this skill participates in CAD/mechanical structure/3D printing projects, these bottom lines are enforced by default:

  1. Do not treat a "comprehensible schematic" as a "manufacturable engineering drawing". Whenever holes, slots, interfaces, assembly holes, or printed enclosures are involved, overall dimensions, wall thickness/bottom thickness, hole/slot specifications, and locating dimensions must be completed.
  2. When the user requests "commonly used Chinese format", "national standard style", or "strict specification", domestic mechanical drafting conventions must be adopted: standard sheet size/drawing frame/title block, imitation Song Chinese text, layered line types, centerlines/dashed lines, real annotation entities, and technical requirements.
  3. Long leaders can only be used for local notes and cannot replace dimension chains; they must not cross views, press on holes, press on centerlines, press on dimension text, or intrude into the title block.
  4. Dense holes and slots must preferentially use hole tables, slot tables, or hole/slot detail tables, with location, specification, quantity, and positioning clearly written in the table; tables cannot become an excuse to evade locating dimensions.
  5. Before delivery, the preview image must be visually reviewed, and if missing dimensions, overlaps, line conflicts, or title block intrusion are found, rework first before reporting.

High-Fidelity Appearance/Public Mesh Reference Models

When the user requests high-fidelity appearance of real objects such as automobiles, consumer electronics, or sculptures, first distinguish between "visual reference models" and "engineering manufacturable parameter models":

  1. If the user wants it to "look like the original", preferentially request or search for public 3D models/multi-view blueprints, and record the source, author, license, and download date; do not claim that what is generated is an official Class-A or scan-level model.
  2. .glb/.gltf/.fbx/.blend first convert to .obj/.stl; OBJ preferentially retains materials, and STL serves as the no-material fallback.
  3. Before import, use the bounding box to confirm the coordinate axes and scale, then scale according to the real nominal dimensions.
  4. If Python conversion/scaling is needed, first confirm that the optional dependencies in requirements-mesh.txt are available; if missing, explain the purpose and prompt installation.
  5. When importing OBJ/STL into SolidWorks, use sw_import_mesh_reference.py; the key syntax is LoadFile4(path, "r", create_empty_dispatch_variant(), errors), do not use OpenDoc6() or pass None to LoadFile4()。
  6. Result review must examine the four views and key identifying features; "preview is not blank" cannot replace "looks like the user-specified object".
  7. If the user later wants an engineering-editable structure, it should be reverse-rebuilt from the mesh reference parts, and it must be clearly stated that the imported mesh part is not a parametric solid.

Multicolor Appearance Requirements

When the model contains a body, glass, light assemblies, tires, wheels, or other multiple colors:

  1. Read references/appearance.md, uniformly use sw_appearance.py, and do not pass ordinary Python list directly to COM material properties.
  2. Set the document-level color on the source part first; only use component-level color in the assembly when an override is needed.
  3. After each setting, call verify_appearance() or apply_component_palette() to read back the RGB; checking only the setter return value does not count as passing.
  4. Before saving and screenshots, call model.ClearSelection2(True);sw_review.save_preview() ; this cleanup is already built in.
  5. Visually confirm that at least three expected colors are actually visible; "preview is not blank" cannot replace a color check.
  6. When the appearance is abnormal, first run tests/solidworks_appearance_regression.py, then rebuild the user model.

MCP Server Usage

When the user asks to "make SolidWorks support MCP", "integrate Codex/Claude Desktop tool calls", or "not generate a long Python script every time":

  1. Read mcp-server/README.md.
  2. If the user requests automatic MCP configuration, preferentially run the multi-client registrar:powershell -ExecutionPolicy Bypass -File mcp-server/register_all_ai_mcp.ps1 -InstallDependencies; it will attempt to register Codex, Claude Code, Claude Desktop, Cursor, and Windsurf.
  3. Use the local stdio MCP server:python mcp-server/server.py.
  4. For CAD open-format writes, preferentially call cadstudio_write_open_format; for DFM, Routing, FEA, and complex geometry, call cadstudio_check_dfm、cadstudio_check_routing、cadstudio_routing_preflight、cadstudio_fea_preflight、cadstudio_prepare_fea、cadstudio_run_fea、cadstudio_run_fea_convergence、cadstudio_review_advanced_geometry、cadstudio_create_ocp_loft、cadstudio_create_ocp_surfacerespectively; for SolidWorks native operations, then call the whitelisted solidworks_* tools.
  5. Do not expose arbitrary Python/VBA execution tools; when adding MCP tools, reuse the verified wrappers in scripts/sw_*.py .
  6. SolidWorks COM operations must be executed serially; the MCP server internally already uses a global lock to reduce desktop session conflicts.
  7. The baseline demo uses examples/08_mini_fan_motion_assembly.py; it verifies automatic modeling, assembly, Mates, and Motion Study, and does not promise perfect fillet/chamfer appearance.

Motion Assembly Requirements

When the user asks to "make it move", "drag it in SolidWorks", "hinge", "gear linkage", or "real mechanical mates":

  1. First read the motion-type assembly workflow in references/assembly.md ; if the user explicitly requests Motion Study / motion study / motor, then read references/motion-study.md.
  2. Preferentially reuse sw_assembly.py in resolve_component()、get_assembly_entity()、find_largest_cylinder_face()、add_mate5_checked()、add_concentric_mate_by_cylinders()、add_gear_mate_by_cylinders().
  3. For rotating parts, use concentric Mates and lock_rotation=False, and do not use three reference planes to completely lock the shaft, gear, and top cover.
  4. For gear transmission, use real Gear Mates, and do not use scripted fake animation to pass off as mechanical mates.
  5. After creation, use collect_mate_feature_summary() or feature tree traversal to verify that real Mate features such as MateConcentric、MateGearDim exist under MateGroup.
  6. When a real motion study is needed, preferentially reuse sw_motion.create_motion_study()、add_constant_speed_rotary_motor_by_cylinders()、calculate_and_play() to create the Motion Study and motors.
  7. After calculation, call sw_motion.validate_motion_studies() or MCP solidworks_validate_motion_study, and check the type, duration, motor count, result existence, and results_out_of_date=False; if only the timeline, animation, or Calculate=True is not considered acceptance-passed.
  8. When an animation demo is needed, an additional script may be used to drive component poses or the Mate Controller, but it must be stated that an animation demo is not equivalent to interactive degrees of freedom; the final criterion is that it can be dragged in SolidWorks.

GPT / Kimi / Claude Multi-Model Strategy

When the agent needs to have a large model generate a VBA macro, it must go through scripts/sw_macro_guard.py:

  1. Model routing: The GPT series uses the original concise prompt; Kimi / Claude / unknown models automatically load a strongly formatted constraint prompt, forcing output of only VBA source code.
  2. Local template fallback: When model output fails or parsing fails, do not directly report an error; select a built-in VBA template based on user keywords (such as "cube", "cylinder", "extrude", "sketch") and continue execution.
  3. Output validation: Before execution, check SldWorks、ModelDoc2、Sub、End Sub, and only after passing is it allowed to be handed to SolidWorks; if it does not pass, retry.
  4. Timeout/retry: A single model request is recommended to have a 30s timeout; if parsing fails, automatically retry 1~2 times, and append stronger formatting instructions to the retry prompt.

Example:

from sw_macro_guard import build_prompt, fallback_macro_for_request, validate_vba_macro

prompt = build_prompt("画一个 50mm 圆柱", model_name="claude")
macro = fallback_macro_for_request("画一个 50mm 圆柱")
result = validate_vba_macro(macro)
assert result.ok, result.issues

Rules for Unwrapped APIs

When a task requires calling a SolidWorks API in scripts/ that has not yet been wrapped:

  1. First read references/api-lookup.md, then consult the official SolidWorks API documentation, or the local SolidWorks SDK / reference materials, to confirm the method signature, parameter meanings, enum values, return values, and version differences.
  2. Do not guess interfaces from memory; especially long-parameter COM methods,VARIANT / by-ref parameters, enum values, selection marks, and SaveAs -type interfaces.
  3. When writing code, keep a minimal runnable script and perform None / False checks on the return value of each step.
  4. After implementation, it must actually be run, the target file saved or exported, and sw_review.py used to generate a preview image and review report.
  5. Newly discovered pitfalls, error codes, compatible approaches, or stable wrappers must be added to references/troubleshooting.md or the corresponding module reference documentation; commonly used logic should then be consolidated into scripts/.

Result Self-Review

After every generation, modification, import, or export of CAD, a self-review must be performed unless the user explicitly says it is not needed:

  1. Check COM return values, feature objects, save/export return values, and output file size.
  2. Call model.ForceRebuild3(False)、model.ViewZoomtofit2() to refresh the model.
  3. Use scripts/sw_review.py 's run_review() to export the isometric/front/top/right preview image and write it to *_review_report.json.
  4. Read the evaluation.status、evaluation.issues、checks and preview image in the report; check via screenshot or exported BMP: whether the main body exists, whether the proportions/orientation are reasonable, whether key components are missing, whether there is obvious overlap or floating, and whether the file name and output path are correct.
  5. If problems are found, first fix the script and regenerate, then report; do not only report "save successful".

Example:

from sw_review import run_review

model.ForceRebuild3(False)
report, report_path = run_review(
    model,
    r"C:\temp\review",
    basename="car",
    expected_outputs=[r"C:\temp\car.sldprt", r"C:\temp\car.step"],
)
print(report_path)
print(report["evaluation"])

Key Notes

  • Units: APIs uniformly use meters. Use mm(50) to convert 50mm to 0.05m, and use deg(90) to convert angles
  • Version: Use SldWorks.Application to connect automatically, compatible with all versions
  • Selection: When a COM object can be obtained, prefer object-level Select2(); for reference planes, SelectByID2("PLANE")can be used, and sketches should not rely only on SelectByID2("SKETCH")
  • Sketch: It is recommended to use with sketch(model, "Front Plane") as sketch_name: to automatically enter/exit sketches;sw_part.py Caches sketch object references to avoid failures when selecting sketches by name in SW2024 Chinese version
  • Add Components: For assemblies, prioritize using sw_assembly.add_component(); under SW2024 Chinese version, AddComponent4 may return None, and the wrapper will use AddComponent5, silently open the part, reactivate the assembly, and retry
  • Appearance: For models with high color requirements, prioritize splitting into multi-part assemblies; material arrays must be grouped using SAFEARRAY(double) , and read back RGB for verification
  • VARIANT: by-ref parameters must be wrapped with VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I4, 0) - Reference Plane Names:start_sketch() will automatically be compatible with the English version's "Front/Top/Right Plane" and the Chinese version's "前视/上视/右视基准面"
  • Sketch Coordinates: Based on the local coordinate system of the sketch plane, unit is meters
  • Motion Assembly: Resolve components first, then select Mate entities;GetCorresponding() is used to map in-part faces/features to the assembly context; concentric Mates do not lock rotation by default
  • Motion Study:swmotionstudy.tlb needs to be loaded; under pywin32, CreateMotionStudy / Activate / Calculate may appear as a property, prioritize using sw_motion.motion_member() for compatibility