๐ŸŸข Technician Track
Tutorial 5 of 10
๐ŸŸข TECHNICIAN TRACK โ€ข BEGINNER

Tutorial #5: Prompt Engineering for IEC 61131-3 ST Code Generation

Controlled AI Code Drafting

โœ… CORE MISSION OF THIS TUTORIAL

By the end of this tutorial, the reader will be able to:

  • โœ… Understand what prompt engineering really is in engineering terms
  • โœ… Control format, structure, and limitations of generated PLC code
  • โœ… Generate read-only IEC 61131-3 Structured Text (ST) drafts
  • โœ… Prevent unsafe, hallucinated, or uncontrolled code generation
  • โœ… Prepare for Few-Shot Validation in Tutorial #6

This tutorial establishes the human-to-AI control interface for industrial code generation.

โš ๏ธ

โš ๏ธ SAFETY BOUNDARY REMINDER

This tutorial provides recommendations only.

It must never be connected to:

  • Live PLCs
  • Production deployment pipelines
  • Safety-rated controllers
  • Motion or power systems

> All outputs are advisory-only and always require explicit human approval before any real-world action.

๐ŸŒ VENDOR-AGNOSTIC ENGINEERING NOTE

This tutorial uses:

  • โ–ธ Generic IEC 61131-3 Structured Text (ST)
  • โ–ธ Standard Python + OpenAI client
  • โ–ธ No PLC runtimes, hardware connections, or vendor SDKs

The patterns apply equally to TwinCAT, Siemens TIA Portal (SCL), CODESYS, Rockwell ST, and all IEC-compliant environments.

1๏ธโƒฃ CONCEPT OVERVIEW โ€” WHAT PROMPT ENGINEERING REALLY IS

In engineering terms: A prompt is a control interface, not a question.

Bad mental model:
"I ask the AI something nicely."

Correct mental model:
"I specify operating constraints for a probabilistic system."

For PLC generation, prompt engineering controls:

  • โœ… Output format
  • โœ… Language (ST only)
  • โœ… Scope (no overreach)
  • โœ… Safety boundaries
  • โœ… Determinism (via temperature=0, though not strictly guaranteed)

Note on Determinism: While setting temperature=0 increases consistency, LLM outputs are never 100% deterministic. Identical prompts may occasionally produce slightly different formatting or phrasing. Always review generated code.

2๏ธโƒฃ REFERENCE ARCHITECTURE โ€” HUMAN-IN-THE-LOOP CODE DRAFTING

You โ†’ Structured Prompt โ†’ LLM โ†’ Read-Only ST Draft โ†’ You Review โ†’ You Decide

Controlled Code Generation Pipeline

graph LR
    A[Engineer<br/>Define Requirements] --> B[Structured Prompt<br/>Constrained Input]
    B --> C[LLM<br/>Generate ST Code]
    C --> D[Read-Only Draft<br/>No Execution]
    D --> E[Engineer Review<br/>Human Validation]
    E --> F{Acceptable?}
    F -->|No| A
    F -->|Yes| G[Manual Integration]

    style A fill:#1a1a1e,stroke:#00ff7f,stroke-width:2px,color:#00ff7f
    style B fill:#1a1a1e,stroke:#9e4aff,stroke-width:2px,color:#fff
    style C fill:#1a1a1e,stroke:#9e4aff,stroke-width:2px,color:#fff
    style D fill:#1a1a1e,stroke:#fec20b,stroke-width:2px,color:#fec20b
    style E fill:#1a1a1e,stroke:#00ff7f,stroke-width:2px,color:#00ff7f
    style F fill:#1a1a1e,stroke:#ff4fd8,stroke-width:2px,color:#ff4fd8
    style G fill:#1a1a1e,stroke:#00ff7f,stroke-width:2px,color:#00ff7f

Human authority at every step โ€” LLM is a text generator, not a decision maker

Boundaries

  • โœ… AI generates text only
  • โœ… No compilation
  • โœ… No download to PLC
  • โœ… No execution
  • โœ… Human is always the gatekeeper

3๏ธโƒฃ CLEAN EDUCATIONAL SCENARIO

We want to generate a very simple IEC 61131-3 ST motor start/stop block:

Requirements

  • โ–ธ Boolean inputs: StartButton (momentary), StopButton (momentary)
  • โ–ธ Boolean output: MotorRunning (latched)
  • โœ… Stateful start/stop behavior (set/reset pattern)
  • โŒ No timers, safety interlocks, or fault handling
  • โ–ธ Priority: Stop takes precedence if both buttons pressed

We will learn how to force the LLM to stay inside these boundaries.

Why Prompt Structure Matters

Compare two fundamentally different approaches to AI code generation:

โŒ Uncontrolled Prompt

graph LR
    A[Vague Prompt] --> B[LLM]
    B --> C[Unpredictable Output]
    C --> D[โŒ Risk]

    style A fill:#1a1a1e,stroke:#ff4fd8,stroke-width:2px,color:#ff4fd8
    style B fill:#1a1a1e,stroke:#9e4aff,stroke-width:2px,color:#fff
    style C fill:#1a1a1e,stroke:#fec20b,stroke-width:2px,color:#fec20b
    style D fill:#1a1a1e,stroke:#ff4fd8,stroke-width:2px,color:#ff4fd8

Dangerous: Adds safety logic, timers, features you didn't ask for

โœ… Controlled Prompt

graph LR
    A[Structured Prompt] --> B[LLM]
    B --> C[Constrained Output]
    C --> D[โœ… Reviewable]

    style A fill:#1a1a1e,stroke:#00ff7f,stroke-width:2px,color:#00ff7f
    style B fill:#1a1a1e,stroke:#9e4aff,stroke-width:2px,color:#fff
    style C fill:#1a1a1e,stroke:#04d9ff,stroke-width:2px,color:#fff
    style D fill:#1a1a1e,stroke:#00ff7f,stroke-width:2px,color:#00ff7f

Safe: Generates only what you specified, in a reviewable format

4๏ธโƒฃ PRACTICAL EXPERIMENTS

๐Ÿงช Experiment 1: Uncontrolled vs Controlled Prompt

Objective

See the difference between a loose prompt (unsafe, verbose) and a controlled prompt (deterministic, auditable).

Part A โ€” Uncontrolled Prompt (What NOT to Do)

Python
from openai import OpenAI

client = OpenAI()

bad_prompt = "Generate PLC code for a motor controller."

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "user", "content": bad_prompt}
    ]
)

print(response.choices[0].message.content)

Expected (Unstable) Output May Include:
โŒ Safety logic you didn't ask for
โŒ Timers
โŒ Fault latching
โŒ Vendor-specific constructs
โŒ Commentary mixed with code

This is unreviewable and unsafe by construction.

Part B โ€” Controlled Engineering Prompt (IEC 61131-3 ST)

Python
controlled_prompt = '''You are generating IEC 61131-3 Structured Text (ST) only.

Rules:
- Output only code.
- No comments.
- No safety logic.
- No timers.
- No vendor-specific libraries.
- No additional features.

Task:
Create a basic motor start/stop logic with:

Inputs:
- StartButton : BOOL (momentary pushbutton, rising edge triggers start)
- StopButton  : BOOL (momentary pushbutton, rising edge triggers stop)

Output:
- MotorRunning : BOOL (latched output, persists across PLC scans)

Behavior:
- Use a set/reset pattern (stateful across scans).
- MotorRunning becomes TRUE when StartButton is pressed.
- MotorRunning becomes FALSE when StopButton is pressed.
- If both buttons pressed simultaneously, StopButton takes priority (safety first).
'''
response = client.chat.completions.create(
    model="gpt-4o-mini",
    temperature=0,  # For more deterministic output
    messages=[
        {"role": "user", "content": controlled_prompt}
    ]
)

print(response.choices[0].message.content)

Example Output (Actual results may vary slightly)

IF StartButton THEN
    MotorRunning := TRUE;
END_IF;

IF StopButton THEN
    MotorRunning := FALSE;
END_IF;
  • โœ… Read-only draft
  • โœ… No execution
  • โœ… Human-reviewed
  • โ–ธ Cost: Varies by model/pricing | Runtime: typically seconds

๐Ÿงช Experiment 2: Forcing Output Structure with a Generic ST Code Template

Objective

Force the AI to generate only inside a predefined IEC 61131-3 ST template.

Python Code

Python
template_prompt = '''Generate ONLY the executable ST code that fills the body below.

CRITICAL INSTRUCTIONS:
- Output ONLY the code that goes in the <INSERT CODE HERE> section.
- Do NOT repeat the VAR blocks or template structure.
- Do NOT add comments or explanations.
- Use a set/reset pattern for stateful motor control.

TEMPLATE:

VAR_INPUT
    StartButton : BOOL;  (* Momentary pushbutton *)
    StopButton  : BOOL;  (* Momentary pushbutton *)
END_VAR

VAR_OUTPUT
    MotorRunning : BOOL;  (* Latched output *)
END_VAR

(* CODE BELOW *)
<INSERT CODE HERE>
'''
response = client.chat.completions.create(
    model="gpt-4o-mini",
    temperature=0,  # For more deterministic output
    messages=[
        {"role": "user", "content": template_prompt}
    ]
)

print(response.choices[0].message.content)

Expected Output

IF StartButton THEN
    MotorRunning := TRUE;
END_IF;

IF StopButton THEN
    MotorRunning := FALSE;
END_IF;

Interpretation

  • โ–ธ โœ… Structural confinement
  • โ–ธ โœ… No unsafe expansion
  • โ–ธ โœ… Draft-only output (body code only)
  • โ–ธ Cost: Varies by model/pricing | Runtime: typically seconds

๐Ÿ”’ EXPLICIT OPERATIONAL PROHIBITIONS

  • โŒ Using generated code directly in production
  • โŒ Downloading code to PLCs
  • โŒ Bypassing code review
  • โŒ Generating safety logic without validation
  • โŒ Trusting output without human inspection

โœ… KEY TAKEAWAYS

  • โœ… A prompt is a safety and control interface
  • โœ… Unstructured prompts produce unreviewable risk
  • โœ… Structured prompts produce auditable drafts
  • โœ… You can fully control: Language, Scope, Features, Format
  • โœ… AI must be treated like a junior engineer under supervision

๐Ÿ”œ NEXT TUTORIAL

#6 โ€” Few-Shot Learning for PLC Validation

You will extend this system by supplying validated PLC examples, teaching the AI what 'good' looks like, and improving consistency across generations.

๐Ÿงญ ENGINEERING POSTURE

This tutorial enforced:

  • โ–ธ Constraint-first design over creative freedom
  • โ–ธ Draft-only generation over execution
  • โ–ธ Human authority over machine output
  • โ–ธ Reviewability over automation

โœ… END OF TUTORIAL #5