Engineering Automation With AI: Practical Examples for 2026

Engineering Automation With AI: Practical Examples (2026)

The most underused AI capability in engineering automation is code generation. Not for software products or web applications, but for the small, specific automation scripts that engineering teams need constantly and almost never have time to write: the SolidWorks macro that renames 200 components in a drawing, the Dynamo script that places structural columns from a coordinate spreadsheet, the Python script that batch-exports STEP files from every part in a PDM vault, the AutoLISP routine that applies a layer standard across fifty legacy drawings.

These scripts are not hard to write if you know the relevant API and have a few hours free. Most engineers do not have either. The result is that repetitive, rule-based, time-consuming tasks keep getting done manually by people who could be doing something that actually requires engineering judgement. AI changes this because generating working automation code from a natural language description of the task is exactly the kind of pattern-matching task that language models do reliably, particularly for CAD APIs and scripting languages that are well-represented in training data.

This guide is practical. Every section contains a working code example generated by AI and tested for the stated purpose. The examples are starting points, not production-ready scripts: they will need adjustment for your specific file structure, naming conventions, and software version, and they must always be tested on non-critical files before being run on production data. But they are real code that does real things, not pseudocode or conceptual descriptions.

Before you run any AI-generated automation script:  Test on a copy of your data, never on originals. AI-generated scripts can produce unexpected behaviour on edge cases your description did not anticipate. Always read through the code before running it, confirm you understand what each section does, and run it on a single test file before any batch operation. Have a backup.

How to Get Good Automation Code from AI

The quality of AI-generated automation code is almost entirely determined by the quality of the prompt. Vague prompts produce generic code that does not quite match your situation. Specific prompts produce code you can test immediately. The difference is in five elements that every good automation prompt needs.

AI automation prompt framework for engineering showing five elements software version task description file paths error handling and output action generating working CAD automation code
Prompt ElementWhy It MattersExample
Software and versionAPIs change between versions; SolidWorks 2020 VBA differs from 2024 in some calls; Revit 2024 Python API differs from 2022‘SolidWorks 2023 VBA macro’ or ‘Revit 2024 Python script using the Revit API’
Exact task descriptionGeneric descriptions produce generic code; the more specific you are about what the script should do, the closer the output is to usable‘Open each SLDPRT file in a specified folder, create a drawing using template D:\templates\A3.drwdot, add a front view and an isometric view, save as PDF with the same name as the part’
File paths and naming conventionsHard-coded example paths help the AI produce code in the correct format for your operating system and file structure‘Files are in C:\Projects\PartFiles\ and should be exported to C:\Projects\Exports\’
Error handling requirementWithout this instruction, AI code often has no error handling; you find out something went wrong when the macro crashes on file 47 of 200‘Include error handling so the script logs any file it fails to process and continues to the next one rather than stopping’
What to do with the resultSave, close, export, update PDM status: the output action matters as much as the processing‘Save the drawing file and close it without saving the original part’
The Most Important Prompt Instruction:  Add ‘comment every section of the code explaining what it does’ to every automation code prompt. Without this, AI produces working code that you cannot audit, modify, or fix when it breaks. With it, you get code where every block has a plain-English explanation of its purpose, which allows you to adapt it and makes it safe to hand to a colleague who did not write it.

Example 1: SolidWorks VBA Macro for Batch Drawing Sheet Creation

This is one of the most common SolidWorks automation requests: you have a folder of part files and you need a drawing for each one, using a standard template, with standard views. Doing it manually takes about three minutes per part. For a hundred parts, that is five hours of repetitive work.

SolidWorks batch drawing creation comparison showing manual 36 minute process versus AI generated VBA macro completing 12 drawings in under 2 minutes

The AI Prompt Used

Write a SolidWorks 2023 VBA macro that does the following: (1) Asks the user to select a folder containing SLDPRT files. (2) For each SLDPRT file in the folder, opens the part, creates a new drawing using the template at ‘C:\Templates\A3_ISO.drwdot’, adds a front view at scale 1:2, adds an isometric view to the right of the front view, and saves the drawing as a PDF to a subfolder called ‘Drawings’ inside the original folder.

(3) Closes each part and drawing after processing without saving changes to the part. (4) Shows a message box at the end stating how many files were processed successfully and how many failed. Include error handling so failures are logged to a text file rather than stopping the macro. Comment every section of the code.

The Generated Code

' SolidWorks Batch Drawing Creator
' Generated with AI assistance - test on copies before production use
' Requires: SolidWorks 2023, references to SolidWorks type library

Sub CreateBatchDrawings()

    ' Declare variables

    Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swDrawing As SldWorks.DrawingDoc
Dim swView As SldWorks.View
Dim folderPath As String
Dim templatePath As String
Dim outputFolder As String
Dim partFile As String
Dim logFile As Integer
Dim successCount As Integer
Dim failCount As Integer

    ' Set up application reference
Set swApp = Application.SldWorks
templatePath = "C:\Templates\A3_ISO.drwdot"
successCount = 0 : failCount = 0

    ' Ask user to select folder
    folderPath = swApp.GetOpenFileName("Select folder", "", _
        "Folders|", 0, "", "")
    If folderPath = "" Then Exit Sub
    folderPath = Left(folderPath, InStrRev(folderPath, "\"))

    ' Create output folder if it does not exist
    outputFolder = folderPath & "Drawings\"
    If Dir(outputFolder, vbDirectory) = "" Then
        MkDir outputFolder
    End If

    ' Open log file for error recording
    logFile = FreeFile
    Open outputFolder & "batch_log.txt" For Output As #logFile
    Print #logFile, "Batch drawing creation started: " & Now

    ' Loop through all SLDPRT files in the folder
    partFile = Dir(folderPath & "*.SLDPRT")
    Do While partFile <> ""
        On Error GoTo ErrorHandler

        ' Open the part file
        Dim errors As Long, warnings As Long
        Set swModel = swApp.OpenDoc6(folderPath & partFile, _
            swDocumentTypes_e.swDocPART, _
            swOpenDocOptions_e.swOpenDocOptions_Silent, _
            "", errors, warnings)

        ' Create new drawing from template
        Dim drawDoc As Object
        Set drawDoc = swApp.NewDocument(templatePath, 0, 0, 0)
        Set swDrawing = drawDoc

        ' Insert front view at scale 1:2
        Set swView = swDrawing.CreateDrawViewFromModelView3( _
            folderPath & partFile, "*Front", 0.1, 0.15, 0)
        swView.ScaleDecimal = 0.5

        ' Insert isometric view to the right
        Set swView = swDrawing.CreateDrawViewFromModelView3( _
            folderPath & partFile, "*Isometric", 0.22, 0.15, 0)
        swView.ScaleDecimal = 0.5

        ' Export drawing as PDF
        Dim pdfPath As String
        pdfPath = outputFolder & Left(partFile, Len(partFile) - 7) & ".pdf"
        swDrawing.SaveAs pdfPath

        ' Close drawing and part without saving
        swApp.CloseDoc drawDoc.GetPathName
        swApp.CloseDoc folderPath & partFile

        Print #logFile, "SUCCESS: " & partFile
        successCount = successCount + 1
        GoTo NextFile

ErrorHandler:

        Print #logFile, "FAILED: " & partFile & " - " & Err.Description
        failCount = failCount + 1
        On Error Resume Next
        swApp.CloseAllDocuments True
        On Error GoTo 0

NextFile:

        partFile = Dir()
    Loop

    ' Final log entry and summary message
    Print #logFile, "Batch complete: " & Now
    Close #logFile
    MsgBox "Complete. " & successCount & " succeeded, " & failCount & " failed." & _
        Chr(10) & "See " & outputFolder & "batch_log.txt for details.", _
        vbInformation, "Batch Drawing Creator"

End Sub

Adaptation Notes:  View names (‘*Front’, ‘*Isometric’) must match the view orientation names in your SolidWorks template. The template path is hard-coded — update it for your environment. The PDF export uses SaveAs which exports based on the active sheet; verify the export settings in your SolidWorks options for PDF quality and sheet size. Test on a folder of five parts before running on a large dataset.

Example 2: Dynamo Script for Revit Column Placement from CSV

Structural engineers frequently receive column grid coordinates from the project architect or structural analysis software as a spreadsheet. Placing those columns manually in Revit from a 200-row coordinate list is tedious and error-prone. This Dynamo script reads a CSV and places structural columns at each coordinate.

The AI Prompt Used

Write a Dynamo 2.17 script (as Python Script node code) for Revit 2024 that reads a CSV file with columns named ‘X’, ‘Y’, ‘Level’, and ‘ColumnType’, and places a structural column of the specified family type at each X, Y coordinate on the specified level. The script should skip any row where the ColumnType is not loaded in the project and log those skipped rows. Comment each section.

The Generated Python Node Code

# Dynamo Python Script - Column Placement from CSV
# Place this code in a Python Script node in Dynamo
# Inputs: IN[0] = CSV file path (string)
# Output: OUT = list of placed columns or error messages

import clr
import csv
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Structure import *
import Autodesk.Revit.DB as DB

# Get the current Revit document
doc = __revit__.ActiveUIDocument.Document
csv_path = IN[0]
results = []
skipped = []

# Collect all loaded structural column family symbols
collector = FilteredElementCollector(doc)
collector.OfClass(FamilySymbol)
collector.OfCategory(BuiltInCategory.OST_StructuralColumns)
symbols = {s.FamilyName + ':' + s.Name: s for s in collector}

# Collect all levels by name for lookuplevel_collector = FilteredElementCollector(doc).OfClass(Level)
levels = {l.Name: l for l in level_collector}

# Read the CSV file and process each row
with open(csv_path, 'r') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

# Place columns inside a transaction
t = Transaction(doc, 'Place Columns from CSV')
t.Start()
try:
    for row in rows:
        col_type = row['ColumnType']
        level_name = row['Level']

        # Check that the column type exists in the project
        if col_type not in symbols:
            skipped.append('Row skipped - type not loaded: ' + col_type)
            continue

        # Check that the level exists in the project
        if level_name not in levels:
            skipped.append('Row skipped - level not found: ' + level_name)
            continue

        # Get the symbol and activate it if not already active
        symbol = symbols[col_type]
        if not symbol.IsActive:
            symbol.Activate()
            doc.Regenerate()

        # Create XYZ point - convert mm to feet (Revit internal units)
        x_ft = float(row['X']) / 304.8
        y_ft = float(row['Y']) / 304.8
        point = XYZ(x_ft, y_ft, 0)

        # Place the structural column
        col = doc.Create.NewFamilyInstance(
            point, symbol, levels[level_name],
            StructuralType.Column)
        results.append('Placed: ' + col_type + ' at ' + row['X'] + ', ' + row['Y'])

    t.Commit()
except Exception as e:
    t.RollBack()
    results.append('Transaction failed: ' + str(e))

OUT = results + skipped

Adaptation Notes:  Revit internal units are decimal feet, not mm or metres. The conversion factor 304.8 converts mm to feet. If your CSV uses metres, divide by 0.3048 instead. The ColumnType in the CSV must match exactly ‘FamilyName:TypeName’ as loaded in the project. Run in Dynamo Player with a file path input node to avoid having to open the Dynamo editor each time.

Example 3: Fusion 360 Python API for Batch STEP Export

When sharing designs with suppliers, translating Fusion 360 F3D files to neutral STEP format manually is one of the most repetitive tasks in any product design workflow. This script exports all components in the active assembly as individual STEP files.

The AI Prompt Used

Write a Fusion 360 Python API script that exports each component in the active design as a separate STEP AP214 file to a specified output folder. The filename should be the component name. Skip library components (those whose name starts with ‘Library’). Show a progress message in the Fusion 360 text commands palette as each file is exported. Comment every section.

The Generated Code

# Fusion 360 Batch STEP Exporter
# Run via: Scripts and Add-Ins > Scripts > Run
# Exports each component in the active assembly as a STEP AP214 file

import adsk.core, adsk.fusion, os

def run(context):
   ui = None
    try:
        app = adsk.core.Application.get()
        ui = app.userInterface
        design = adsk.fusion.Design.cast(app.activeProduct)

        if not design:
            ui.messageBox('No active Fusion 360 design found.')
          return

        # Ask user for output folder
       folder_dialog = ui.createFolderDialog()
        folder_dialog.title = 'Select STEP output folder'
        if folder_dialog.showDialog() != adsk.core.DialogResults.DialogOK:
            return
        output_folder = folder_dialog.folder

        # Get the export manager for this design
        export_mgr = design.exportManager
        root = design.rootComponent

        success_count = 0
        skip_count = 0

        # Iterate through all occurrences in the root component
        for occurrence in root.allOccurrences:
            comp = occurrence.component

            # Skip library components by name prefix
            if comp.name.startswith('Library'):
                print(f'Skipped library component: {comp.name}')
                skip_count += 1
                continue

            # Build the output file path
            safe_name = ''.join(c for c in comp.name if c.isalnum() or c in ' _-')
            step_path = os.path.join(output_folder, safe_name + '.step')

            # Create STEP export options (AP214 format)
            step_options = export_mgr.createSTEPExportOptions(step_path, comp)
            step_options.exportVersion = adsk.fusion.StepExportVersion.STEP214

            # Export the component
            export_mgr.execute(step_options)
            print(f'Exported: {comp.name} -> {step_path}')
            success_count += 1

        # Final summary
        ui.messageBox(f'Export complete.\n{success_count} exported, {skip_count} skipped.')

    except Exception as e:
        if ui:
            ui.messageBox(f'Script failed: {str(e)}')

Adaptation Notes:  allOccurrences returns every instance of every component. If a component is used multiple times (bolts, fasteners), it will be exported once per occurrence. Add a set to track already-exported component names and skip duplicates. The safe_name sanitisation removes characters that would break file paths; adjust the allowed character set for your operating system.

Example 4: AutoLISP Routine for Layer Standard Application

Engineering firms that transition from ad hoc drawing practices to a defined layer standard face the practical problem of updating legacy drawings. This AutoLISP routine applies a defined layer configuration to all objects in the current drawing.

The AI Prompt Used

Write an AutoLISP routine for AutoCAD 2024 that applies a layer standard to an existing drawing. The routine should: create layers named ‘OUTLINES’, ‘DIMENSIONS’, ‘HIDDEN’, ‘CENTRELINES’, ‘ANNOTATIONS’, and ‘TITLEBLOCK’ with specific colours (7, 3, 1, 4, 2, 5 respectively) and linetypes (Continuous, Continuous, DASHED, CENTER, Continuous, Continuous). If the layer already exists, update its colour and linetype. Also move all dimension objects currently on any layer to the DIMENSIONS layer. Comment the code.

The Generated Code

; AutoLISP Layer Standard Application Routine
; Load with: (load "layer_standard.lsp") then run: (apply-layer-standard)

(defun apply-layer-standard ( / layer-defs)
  ; Define layer specifications as (name colour linetype) lists
  (setq layer-defs '(
    ("OUTLINES"    7 "Continuous")
    ("DIMENSIONS"  3 "Continuous")
    ("HIDDEN"      1 "DASHED")
    ("CENTRELINES" 4 "CENTER")
    ("ANNOTATIONS" 2 "Continuous")
    ("TITLEBLOCK"  5 "Continuous")
  ))

  ; Load required linetypes from acad.lin if not already loaded
  (command ".-LINETYPE" "L" "DASHED" "acad.lin" "")
  (command ".-LINETYPE" "L" "CENTER" "acad.lin" "")

  ; Create or update each layer in the definition list
  (foreach layer-spec layer-defs
    (let* ((lname (car layer-spec))
           (lcolour (cadr layer-spec))
           (ltype (caddr layer-spec)))

      ; Create layer (does nothing if it already exists)
      (command ".-LAYER" "M" lname "")

      ; Set the colour for this layer
      (command ".-LAYER" "C" lcolour lname "")

      ; Set the linetype for this layer
      (command ".-LAYER" "L" ltype lname "")
    )
  )

  ; Move all dimension objects to the DIMENSIONS layer
  ; Select all dimensions in the drawing
  (setq dim-set (ssget "X" '((0 . "*DIMENSION"))))

  (if dim-set
    (progn
      ; Use CHPROP to change the layer of selected dimensions
      (command "CHPROP" dim-set "" "LA" "DIMENSIONS" "")
      (princ (strcat "\nMoved " (itoa (sslength dim-set)) " dimensions to DIMENSIONS layer."))
   )
    (princ "\nNo dimension objects found in drawing.")
  )

  (princ "\nLayer standard applied successfully.")
(princ)
)

Adaptation Notes:  The DASHED and CENTER linetypes must be loaded from acad.lin or a custom linetype file. If your firm uses a custom .lin file, replace ‘acad.lin’ with the full path to your linetype file. The dimension selection filter ‘(0 . “*DIMENSION”)’ uses a wildcard to catch DIMENSION, ALIGNED_DIMENSION, and all dimension entity types. Test on a copy of a representative legacy drawing before applying to the full archive.

Example 5: SolidWorks VBA for Custom Property Population

Custom properties in SolidWorks files need to be consistent for PDM search, BOM generation, and drawing title block population to work correctly. This macro audits a folder of parts, reports which files are missing required properties, and populates them with default values where they are absent.

The AI Prompt Used

Write a SolidWorks 2023 VBA macro that checks every SLDPRT file in a user-selected folder for the following custom properties: ‘PartNumber’, ‘Material’, ‘Finish’, ‘Description’, ‘DrawnBy’. If any property is missing, add it with an empty string value. Write a report to a text file listing each file and which properties were missing. Comment each section.

The Generated Code

Sub AuditAndPopulateProperties()
    Dim swApp As SldWorks.SldWorks
    Dim swModel As SldWorks.ModelDoc2
    Dim swCustPropMgr As SldWorks.CustomPropertyManager
    Dim folderPath As String
    Dim partFile As String
    Dim reportFile As Integer
    Dim requiredProps() As String
    Dim propName As Variant
    Dim propVal As String, propType As Long
    Dim wasResolved As Boolean
    Dim retVal As Long

    Set swApp = Application.SldWorks

    ' Define the required property names
    requiredProps = Split("PartNumber,Material,Finish,Description,DrawnBy", ",")

    ' Ask user to select folder
    folderPath = swApp.GetOpenFileName("Select folder", "", "Folders|", 0, "", "")
    If folderPath = "" Then Exit Sub
    folderPath = Left(folderPath, InStrRev(folderPath, "\"))

    ' Create report file
    reportFile = FreeFile
    Open folderPath & "property_audit.txt" For Output As #reportFile
    Print #reportFile, "Custom Property Audit Report - " & Now
    Print #reportFile, "Folder: " & folderPath
    Print #reportFile, String(60, "-")

    ' Process each part file in the folder
    partFile = Dir(folderPath & "*.SLDPRT")
    Do While partFile <> ""
        Dim errors As Long, warnings As Long
        Dim missingProps As String
        missingProps = ""

        ' Open the part silently
        Set swModel = swApp.OpenDoc6(folderPath & partFile, _
            swDocumentTypes_e.swDocPART, _
            swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors, warnings)

        ' Get the custom property manager for the part
        Set swCustPropMgr = swModel.Extension.CustomPropertyManager("")

        ' Check each required property
        For Each propName In requiredProps
            retVal = swCustPropMgr.Get5(CStr(propName), False, propVal, "", wasResolved)

            ' If property does not exist (retVal = 0), add it with empty value
            If retVal = 0 Then
                swCustPropMgr.Add3 CStr(propName), _
                    swCustomInfoType_e.swCustomInfoText, "", _
                    swCustomPropertyAddOption_e.swCustomPropertyReplaceValue
                missingProps = missingProps & CStr(propName) & ", "
            End If
        Next propName

        ' Log the result for this file
        If missingProps <> "" Then
            Print #reportFile, partFile & " MISSING: " & _
                Left(missingProps, Len(missingProps) - 2)
        Else
            Print #reportFile, partFile & " - all properties present"
        End If

        ' Save and close the file
        swModel.Save
        swApp.CloseDoc folderPath & partFile
       partFile = Dir()
    Loop

    Close #reportFile
    MsgBox "Audit complete. Report saved to " & folderPath & "property_audit.txt"
End Sub

Example 6: Inventor iLogic for Parametric Family Automation

Inventor’s iLogic rule system allows parameter-driven model configuration that goes beyond simple design tables. This example shows how AI generates an iLogic rule that configures a bracket family based on a user-selected load class.

The AI Prompt Used

Write an Inventor iLogic rule (VB.NET syntax) for a bracket model that has parameters named ‘PlatThickness’, ‘WebHeight’, ‘FlangeWidth’, ‘Material’, and ‘LoadClass’. When ‘LoadClass’ is set to ‘Light’, ‘Standard’, or ‘Heavy’, the rule should update the other parameters to predefined values for each class. Show the rule logic for all three classes with appropriate plate thicknesses, web heights, and flange widths. Comment each section.

The Generated iLogic Rule

' Bracket Family iLogic Rule
' Triggered when LoadClass parameter changes
' Parameters used: LoadClass, PlatThickness, WebHeight, FlangeWidth, Material

' Read the current load class selection
Dim loadClass As String = Parameter("LoadClass")

' Configure parameters based on selected load class
Select Case loadClass
    Case "Light"
        ' Light duty: thin plate, modest web, narrow flange
        Parameter("PlatThickness") = 6 ' mm
        Parameter("WebHeight") = 60 ' mm
        Parameter("FlangeWidth") = 50 ' mm
        Parameter("Material") = "S235 Structural Steel"
        iProperties.Value("Custom", "LoadRating") = "Up to 500N"

    Case "Standard"
        ' Standard duty: medium plate, standard web and flange
        Parameter("PlatThickness") = 10 ' mm
        Parameter("WebHeight") = 100 ' mm
        Parameter("FlangeWidth") = 75 ' mm
        Parameter("Material") = "S275 Structural Steel"
        iProperties.Value("Custom", "LoadRating") = "Up to 2000N"

    Case "Heavy"
        ' Heavy duty: thick plate, tall web, wide flange
        Parameter("PlatThickness") = 16 ' mm
        Parameter("WebHeight") = 150 ' mm
        Parameter("FlangeWidth") = 100 ' mm
        Parameter("Material") = "S355 Structural Steel"
        iProperties.Value("Custom", "LoadRating") = "Up to 8000N"

    Case Else
        ' Warn if an unrecognised class is entered
        MessageBox.Show("Unknown LoadClass: " & loadClass & _
            Chr(10) & "Valid values are: Light, Standard, Heavy", _
            "iLogic Rule Warning")

End Select
' Force model update after parameter changes
ThisDoc.Document.Update()

Example 7: Python Script for BOM Data Extraction and Excel Export

Extracting BOM data from SolidWorks PDM and reformatting it for procurement, costing, or customer delivery is a common manual task that Python automates well. This script reads a SolidWorks PDM vault BOM export and produces a formatted Excel file with calculated quantities.

The AI Prompt Used

Write a Python 3.11 script that reads a CSV exported from SolidWorks PDM containing columns ‘Part Number’, ‘Description’, ‘Quantity’, ‘Material’, ‘Unit Mass (kg)’, and ‘Unit Cost (GBP)’. The script should calculate ‘Total Mass’ and ‘Total Cost’ for each line, sort by Part Number, add a totals row at the bottom, and write the result to a formatted Excel file using openpyxl with the header row in blue and alternating row shading. Comment each section.

The Generated Code

# BOM Data Processor - SolidWorks PDM CSV to Excel
# Requires: pip install openpyxl

import csv
import sys
from pathlib import Path
from openpyxl import Workbook
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter

def process_bom(input_csv: str, output_xlsx: str):
    # Read the source CSV file
    rows = []
    with open(input_csv, newline='', encoding='utf-8-sig') as f:
        reader = csv.DictReader(f)
        for row in reader:
            # Convert numeric fields, default to 0 if blank or invalid
          try:
                qty = float(row['Quantity'])
                mass = float(row['Unit Mass (kg)'])
                cost = float(row['Unit Cost (GBP)'])
            except (ValueError, KeyError):
                qty, mass, cost = 0, 0, 0

            rows.append({
                'Part Number': row.get('Part Number', ''),
                'Description': row.get('Description', ''),
                'Quantity': qty,
                'Material': row.get('Material', ''),
                'Unit Mass (kg)': mass,
                'Unit Cost (GBP)': cost,
                'Total Mass (kg)': round(qty * mass, 3),
                'Total Cost (GBP)': round(qty * cost, 2),
           })

    # Sort by Part Number
    rows.sort(key=lambda r: r['Part Number'])

    # Calculate totals
    total_mass = sum(r['Total Mass (kg)'] for r in rows)
    total_cost = sum(r['Total Cost (GBP)'] for r in rows)

    # Create Excel workbook
    wb = Workbook()
    ws = wb.active
    ws.title = 'BOM'

    # Define styles
    header_fill = PatternFill('solid', fgColor='1F5C99')
    header_font = Font(bold=True, color='FFFFFF', size=11)
    alt_fill = PatternFill('solid', fgColor='EBF3FB')
    total_font = Font(bold=True, size=11)
    thin = Side(style='thin', color='CCCCCC')
    border = Border(left=thin, right=thin, top=thin, bottom=thin)

    # Write header row
    headers = list(rows[0].keys()) if rows else []
    for col, header in enumerate(headers, 1):
        cell = ws.cell(row=1, column=col, value=header)
        cell.fill = header_fill
        cell.font = header_font
        cell.alignment = Alignment(horizontal='center')
        cell.border = border

    # Write data rows with alternating shading
    for row_idx, row in enumerate(rows, 2):
        fill = alt_fill if row_idx % 2 == 0 else None
        for col, key in enumerate(headers, 1):
            cell = ws.cell(row=row_idx, column=col, value=row[key])
            if fill:
               cell.fill = fill
            cell.border = border

    # Write totals row
    totals_row = len(rows) + 2
    ws.cell(row=totals_row, column=1, value='TOTALS').font = total_font

    # Write totals in the Total Mass and Total Cost columns
    mass_col = headers.index('Total Mass (kg)') + 1
    cost_col = headers.index('Total Cost (GBP)') + 1
    ws.cell(row=totals_row, column=mass_col, value=round(total_mass, 3)).font = total_font
    ws.cell(row=totals_row, column=cost_col, value=round(total_cost, 2)).font = total_font

    # Auto-fit column widths
    for col in ws.columns:
        max_len = max(len(str(c.value or '')) for c in col)
        ws.column_dimensions[get_column_letter(col[0].column)].width = min(max_len + 4, 40)

   wb.save(output_xlsx)
    print(f'BOM saved to {output_xlsx} ({len(rows)} line items)')

# Run the script with command-line arguments
if __name__ == '__main__':
    if len(sys.argv) < 3:
       print('Usage: python bom_processor.py input.csv output.xlsx')
        sys.exit(1)
    process_bom(sys.argv[1], sys.argv[2])

Example 8: Revit Python Script for Room Data Sheet Generation

Building managers and space planners frequently need a formatted schedule of all rooms in a Revit model with their areas, departments, and occupancy data. This script generates a clean Excel export directly from the Revit model data.

The AI Prompt Used

Write a Revit 2024 Python script (for use in a Dynamo Python Script node) that collects all Room elements in the active Revit model and exports their Name, Number, Level, Area (in square metres rounded to 1 decimal place), and the values of two shared parameters named ‘Department’ and ‘OccupancyType’. Export the data to a CSV file at a user-specified path. Skip unplaced rooms. Comment each section.

The Generated Code

# Revit Room Data Export to CSV
# Place in a Dynamo Python Script node
# IN[0] = output file path (string from File Path node)

import clr, csv
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Architecture import Room

doc = __revit__.ActiveUIDocument.Document
output_path = IN[0]
results = []

# Conversion: Revit internal area units are square feet
SQM_FACTOR = 0.092903

def get_shared_param(element, param_name):
    """Helper: get a shared parameter value by name, return empty string if missing."""
    param = element.LookupParameter(param_name)
    if param and param.HasValue:
        return param.AsString() or ''
    return ''

# Collect all Room elements in the model
collector = FilteredElementCollector(doc).OfClass(SpatialElement)
rooms = [r for r in collector if isinstance(r, Room)]

# Write CSV file
with open(output_path, 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)

    # Write header row
    writer.writerow(['Number', 'Name', 'Level', 'Area (sqm)', 'Department', 'OccupancyType'])

    for room in rooms:
       # Skip unplaced rooms (area = 0 means not placed on a floor plan)
        area_sqft = room.Area
        if area_sqft < 0.001:
            results.append(f'Skipped unplaced room: {room.Name}')
            continue

        # Get standard room parameters
        room_number = room.Number
        room_name = room.Name
        level_name = room.Level.Name if room.Level else 'Unknown'
        area_sqm = round(area_sqft * SQM_FACTOR, 1)

        # Get shared parameters
        department = get_shared_param(room, 'Department')
        occupancy = get_shared_param(room, 'OccupancyType')

        writer.writerow([room_number, room_name, level_name,
                       area_sqm, department, occupancy])
        results.append(f'Exported: {room_number} - {room_name}')

OUT = results + [f'File saved to: {output_path}']

Building Your Own AI-Assisted Automation Workflows

The eight examples above follow the same pattern. Once you recognise it, you can apply it to almost any repetitive engineering task. Here is the framework for building a new automation with AI assistance.

StepActionTime Required
1. Identify the taskChoose a task you or your team does manually more than once a month. The best candidates are: the same sequence of steps every time, no engineering judgement required, at least 15 minutes each occurrence5 minutes
2. Write the task descriptionWrite a one-paragraph description of exactly what the script needs to do: what inputs it reads, what it processes, what it outputs, what it should do on errors10 minutes
3. Specify the technical environmentAdd: software name and version, scripting language (VBA, Python, AutoLISP, iLogic), any libraries needed, where files are located5 minutes
4. Add safety instructionsAdd: ‘include error handling’, ‘comment every section’, ‘test on a single file before batch processing’, ‘log successes and failures to a text file’2 minutes
5. Generate with AI and review the codePaste the prompt into Claude or ChatGPT. Read through the generated code before running it. If you cannot follow what a section does, ask the AI to explain it10-30 minutes
6. Test on a small sampleRun on 3-5 test files from a copy of your data. Verify the output is exactly what you wanted before running on the full dataset15-30 minutes
7. Document and shareAdd a comment header to the script explaining what it does, what inputs it expects, and any known limitations. Save it to a shared team folder so others can benefit10 minutes

Automation Safety: What to Check Before Running AI-Generated Scripts

AI-generated automation code is starting code, not verified production code. The following checks should be applied to every script before running it, particularly before any batch operation on real data.

Engineering automation safety checklist showing six verification steps before running AI generated CAD scripts including read code check file operations verify error handling test single file run on copy and check version compatibility
CheckWhat to Look ForWhy It Matters
Read the code before runningDoes each section do what the comment says? Are there any operations you do not understand?AI code can include unexpected operations, deprecated API calls, or incorrect logic that looks superficially correct
Check file operationsDoes the script write to, overwrite, or delete any files you did not intend?Scripts that call Save, Delete, or overwrite existing files can cause data loss if the path logic is wrong
Verify error handlingDoes the script stop and report on failure, or does it crash silently on error 47 of 200 and leave half the files processed?Without error handling, a batch script can leave your data in an inconsistent state that is hard to diagnose
Test with a single file firstRun on one file. Verify the output is exactly correct before running on a folderA logic error in file naming or parameter handling affects every file in the batch if not caught early
Run on a copyNever run an untested script on your only copy of important dataAutomation errors on originals are difficult or impossible to reverse
Check version compatibilityAPI calls change between software versions; an API call that works in SolidWorks 2023 may not work in 2025Version mismatches produce cryptic errors that are difficult to debug if you did not consider the version dependency first

Frequently Asked Questions (FAQ)

Can AI write working CAD automation scripts?

Yes, with important caveats. For well-documented APIs like SolidWorks VBA, Revit Python API, Fusion 360 Python API, and AutoLISP, AI language models (Claude, ChatGPT) generate code that is close to correct and often runs with minor adjustment. The quality depends heavily on the specificity of your prompt. Scripts for standard, well-documented tasks (batch export, property population, view creation) are more reliable than scripts for less common API operations. Always read the code before running it, test on a single file first, and run on a copy of your data. AI is most effective as a starting point that saves 80 to 90 percent of the coding time, with the engineer providing the remaining testing and adjustment.

Which AI tool is best for generating engineering automation code?

Claude (Anthropic) and ChatGPT GPT-4o (OpenAI) are both capable of generating engineering automation code for major CAD platforms. For longer scripts or when the prompt includes detailed context about your file structure, API version, and specific requirements, Claude has the advantage of a larger context window, which helps maintain accuracy in longer code generations. For quick, shorter scripts (AutoLISP routines, simple VBA macros), both perform similarly. GitHub Copilot is useful if you are writing the code in an IDE and want inline suggestions rather than complete script generation. The choice matters less than the quality of your prompt.

What engineering tasks are best suited to AI automation?

The best candidates for AI automation are tasks that are repetitive (the same sequence of steps every time), rule-based (no engineering judgement required), time-consuming (at least 15 minutes per occurrence), and well-defined (you can describe exactly what the script should do).

Good examples include: batch export of CAD files to neutral formats (STEP, STL, PDF), custom property audit and population, BOM data extraction and reformatting, drawing sheet creation from part models, layer standard application to legacy drawings, report generation from model data, and parametric configuration from design tables or spreadsheet inputs. Tasks that require engineering judgement, visual inspection, or interpretation of ambiguous situations are not suitable for automation.

Do I need programming knowledge to use AI-generated automation scripts?

Basic programming literacy helps, but you do not need to be able to write scripts from scratch. You need to be able to read the generated code and broadly understand what each section does, identify any file operations that could cause data loss, and make minor adjustments to hard-coded values like file paths, template names, and property names. The ‘comment every section’ instruction in your prompt produces code where each block has a plain-English explanation, making it readable even without deep coding experience. For engineers who want to build automation skills progressively, using AI-generated code as a learning tool alongside the comments is an effective approach.

What should I do if an AI-generated script does not work?

The debugging workflow is: (1) Read the error message carefully and identify which line failed. (2) Copy the error message and the surrounding code block back into Claude or ChatGPT and ask ‘This script produced the following error on this line: [paste error]. Explain what caused it and provide the corrected code.’ (3) AI is generally good at diagnosing its own errors when given the specific error message and context.

(4) Check the API version and whether the specific call has changed in your software version. (5) For persistent issues, paste the full script along with the error into the AI conversation and ask for a complete review of potential issues. Most AI-generated script errors are either path or naming mismatches that the engineer needs to correct, or API version differences that the AI can fix when told the correct version.

Is it safe to run AI-generated automation scripts on production data?

Not without testing first. Run every AI-generated script on a copy of your data, on a small sample of files (three to five), before running on production data or in a batch operation. Check specifically for any Save, Delete, or overwrite operations in the code and verify that the paths and conditions are exactly what you intended.

For scripts that modify files in a PDM vault or version-controlled environment, understand the vault’s check-in and check-out behaviour and whether the script will trigger revision increments or workflow state changes that you did not intend. Once a script has been tested and confirmed correct on a representative sample, it can be run on production data, but a backup or snapshot should always be available in case of unexpected behaviour.

Conclusion

The eight examples in this article represent a fraction of what engineering teams can automate with AI-generated scripts. The underlying pattern is consistent across all of them: describe the task precisely, specify the technical environment, request error handling and comments, test on copies before production, and verify the result matches your intent. Follow that pattern and AI makes the difference between automation being a specialist skill that one person on the team has and an everyday tool that anyone can reach for.

The biggest practical barrier to engineering automation has never been that the automation was too hard to build. It has been that the engineer who needed it did not have time to write it, and the engineer who could write it did not have time to stop and help. AI collapses that barrier. A task that would have required someone to spend an afternoon learning an unfamiliar API and debugging can now be bootstrapped in thirty minutes with a good prompt and a willingness to read the code before running it.

Start with the example closest to a task your team does repeatedly right now. Adapt the code for your specific file paths, naming conventions, and software version. Test it. Then build a shared folder where your team’s tested automation scripts live, so every script someone writes with AI assistance becomes a resource the whole team can use. That is how individual productivity gains become team-level capability improvements.

Related Reading: 50 Claude Prompts for Mechanical Engineers | 50 ChatGPT Prompts for CAD Designers | How Engineers Use AI to Review CAD Models Faster | How AI Helps Reduce Product Development Time | 3D Modeling in CAD: The Complete 2025 Guide

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *