Tutorial: Integrating Dobot Magician with OpenAI for Natural Language Robot Control

This tutorial walks you through how to connect your Dobot Magician robot to OpenAI using Python inside DobotLab, enabling the robot to respond to natural language instructions like “move 2 inches to the left.”

Prerequisites

Hardware/Software Requirements:

    • Dobot Magician (standard model)
    • DobotLab installed and working
    • Python Lab enabled within DobotLab
    • Internet access

Step 1: Install Required Python Packages in DobotLab

    1. Visit Dobot Lab https://dobotlab.dobot.cc/ and create a login.
    2. Select Python Lab.
    3. Download and Install Dobot Link

    1. Connect to the Robot

    1. Towards the top, click Lib Management.

    1. Make sure you are in PIP Installation Mode.
    2. Run the following commands (one at a time):

pip install openai

pip install requests

pip install tk

If the packages are already installed, you’ll see messages like Requirement already satisfied.

Step 2: Get Your OpenAI API Key

    1. Visit https://platform.openai.com/ and log in or create an OpenAI account.
    2. Navigate to https://platform.openai.com/account/api-keys.
    3. If you have not already added billing information, you will need to do so in order to use the API.
    4. Once your account is funded or on a free trial, click Create new secret key.
    5. Copy and save the API key — you’ll need it later in your script.
    6. (Optional but recommended) Go to API key permissions and restrict access to only chat completions for security.
  1.  

Step 3: Create Your Control Script

Paste the following code into Python Lab. Replace sk-… with your real API key

				
					import openai
from DobotEDU import *
import tkinter as tk
from tkinter import simpledialog

# Set your OpenAI API key
openai.api_key = "sk-xxx"  # Replace with your actual key

# Define the home pose at startup
initial_pose = magician.get_pose()
HOME_X = initial_pose['x']
HOME_Y = initial_pose['y']
HOME_Z = initial_pose['z']
HOME_R = initial_pose['r']
HOME_JOINT_ANGLES = initial_pose['jointAngle']

# Limit how far we allow the robot to move per command
MAX_OFFSET = 50  # mm per command in any direction

def constrain_delta(delta):
    """Limit relative move to ±MAX_OFFSET."""
    return max(-MAX_OFFSET, min(MAX_OFFSET, delta))

# Main command loop
while True:
    root = tk.Tk()
    root.withdraw()
    user_prompt = simpledialog.askstring("Robot Command", "What should the robot do?")
    
    if not user_prompt:
        print("Prompt canceled.")
        break

    # Get the current pose before generating response
    pose = magician.get_pose()
    print("\n[Current Pose BEFORE GPT Prompt]:")
    print(f"X: {pose['x']}, Y: {pose['y']}, Z: {pose['z']}, R: {pose['r']}")
    print(f"Joint Angles: {pose['jointAngle']}")

    # Generate GPT command based on user prompt and current state
    response = openai.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {
                "role": "system",
                "content": (
                    "You are a robot motion assistant. Respond only with Python code using:\n"
                    "magician.ptp(mode=7, x=?, y=?, z=?, r=?)\n"
                    "Use RELATIVE movement in millimeters based on the current pose.\n"
                   "\n"
                    "Directions: the commands below translate to the corresponding movements of the robot \n"
                    "For example, if the prompt is Move forward 20mm, the robot should move 20mm in +X."
                    "The movements are as follows:"
                    "- forward = +X\n"
                    "- backward/back = -X\n"
                    "- right = +Y\n"
                    "- left = -Y\n"
                    "- up = +Z\n"
                    "- down = -Z\n"
                    "\n"
                    "Respond with exact Python code only."
                )
            },
            {"role": "user", "content": user_prompt}
        ]
    )

    code = response.choices[0].message.content
    print("\n[OpenAI Response]:")
    print(code)
    
    if "magician.ptp" in code:
        try:
            # Parse code into dictionary of deltas
            args = eval(code.strip().replace("magician.ptp", "dict"))
            print(f"[Parsed Args]: {args}")
            
            # Constrain the deltas to ±MAX_OFFSET
            safe_x = constrain_delta(args['x'])
            safe_y = constrain_delta(args['y'])
            safe_z = constrain_delta(args['z'])
            safe_r = constrain_delta(args.get('r', 0))
            
            # Execute the relative move
            magician.ptp(mode=7, x=safe_x, y=safe_y, z=safe_z, r=safe_r)
            
        except Exception as e:
            print("Execution error:", e)
    else:
        print("OpenAI did not return a valid ptp command.")

				
			
Step 4: Run It
    1. Run the script in Python Lab.
    2. A popup will ask you for a natural language command (e.g. “move 10 mm forward and 5 mm up”).
    3. OpenAI interprets it and sends back a valid command.
    4. The robot moves accordingly.
    5. You’ll be prompted again after each move.
Safety Note

This tutorial uses eval() and exec() to interpret code returned by OpenAI. In a production environment, you should:

    • Sanitize responses carefully
    • Implement bounds checking (as we’ve done with constrain())
    • Consider using structured output from OpenAI (like JSON)

Get Your Roadmap

Stay in the loop!

Sign up for our monthly newsletter with the the latest in maker education, workforce development and skills based training, engineering education, and more!