iTranslated by AI
Can AI Agents Control an Inverted Pendulum on a Cart?
Introduction
Who is this article for?
- People interested in the performance of LLMs and AI agents
- People interested in web app development using generative AI
- People interested in control engineering
Mini PC (M30A): N100 (4 cores) @ 3.40GHz, 16GB, Ubuntu Server 24.04 LTS
Overview
- Developed a web app that performs control simulations of a cart-pole inverted pendulum.
- Developed using Cursor + o3-mini + Claude 3.5 Sonnet.
- Verified whether the system can be stabilized by having Cursor + Claude 3.5 Sonnet design the control gains.
The Web App Created
First, here is the web app I created this time.
A game where you determine four control gains to aim for stabilization of a cart-pole inverted pendulum.
It turns out that not only people familiar with control engineering but also LLMs and AI agents can achieve gain design in the linear region if their performance is high enough.
What this means is that it can also be used to evaluate the performance of LLMs and AI agents.
The difficulty level is on a completely different level between control in the linear region and the non-linear region, but for now, since this application only covers linear feedback input, we will verify whether stabilization in the linear region can be achieved. I would like to expand it to support non-linear control in the future.
Article Structure
In this article, I will explain the following topics in order. Since each section covers quite different fields, please feel free to jump to any section you are interested in.
-
Web app configuration and development flow
-
Dynamics and control system design of the cart-pole inverted pendulum
-
Prompts for performance evaluation of LLMs and AI agents
Web App Configuration and Development Flow
Basic Game Rules
Configuration Items
App Architecture and Development Flow
App Architecture
The following diagram illustrates the app's architecture.
Technical Stack
Development Flow
Initially, when I developed using only Claude 3.5 Sonnet in Cursor composer (agent mode), I encountered an issue where the dynamics were not consistent at all.
However, the development went smoothly when I followed the flow shown below.

While I had the impression that Claude 3.5 Sonnet is unrivaled in web app development, I gained the firsthand insight that it is better to use a reasoning model like o3-mini when handling mathematical derivations.
By the way, I used o3-mini in Chat mode rather than Composer (agent) mode.
I believe the same results could be achieved without using Cursor by combining o3-mini from the ChatGPT app with Cline + Claude 3.5 Sonnet.
Dynamics of the Cart-Pole Inverted Pendulum
Below is an example of formulating the cart-pole system where counter-clockwise is positive (specifically,
1. Definition of Coordinates
-
Horizontal position of the cart:
x -
Pendulum length:
\ell -
Pendulum mass:
m -
Cart mass:
M -
Gravitational acceleration:
g -
Angle:
\theta - When
, the pendulum is "vertically upward" (unstable equilibrium).\theta = 0 - Positive
is counter-clockwise (meaning rotation to the left from the vertical position).\theta
- When
In this setup, the coordinates of the pendulum's center of mass are defined as:

2. Kinetic and Potential Energy
(1) Kinetic Energy T
Kinetic Energy of the Cart
Kinetic Energy of the Pendulum
The coordinates of the center of mass of the pendulum are:
Their time derivatives are:
Therefore, the kinetic energy of the pendulum is:
Total Kinetic Energy
(2) Potential Energy V
Since the cart only moves horizontally, its potential energy does not need to be considered. Therefore, we only consider the center of mass of the pendulum. Since the vertical coordinate of the center of mass is $ y_p = \ell\cos\theta $, it can be written as:
- Note: Normally, potential energy is often defined relative to a "low position," but here, since the constant term does not affect the dynamics of the system, we handle it in this form for convenience.
3. Lagrangian Formulation
The Lagrangian is
so,
4. Deriving Equations of Motion from Euler–Lagrange Equations
Assume that
where
(1) Differential Equation for x
First,
Its time derivative is
On the other hand, since there is no explicit dependence on
Thus, considering the external force
(2) Equation for \theta
First,
Its time derivative is
Next, the partial derivative with respect to
- For the term
:-m\ell\cos\theta\,\dot{x}\dot{\theta} \displaystyle\frac{\partial}{\partial \theta}(-m\ell\cos\theta\,\dot{x}\dot{\theta}) = m\ell\sin\theta\,\dot{x}\dot{\theta} - For the potential energy term
:-mg\ell\cos\theta \displaystyle\frac{\partial}{\partial \theta}(-mg\ell\cos\theta) = mg\ell\sin\theta
So,
Therefore, from the Euler–Lagrange equation,
Dividing both sides by
Rearranging yields:
5. Final Equations of Motion
Based on the results above, the equations of motion for the cart-pole inverted pendulum when counter-clockwise is positive are:
Dynamics Formulation Summary
-
Coordinate Setup:
The center of mass of the pendulum is defined as:
with
-
Energy Calculation:
We determined the kinetic energy for both the cart and the pendulum, as well as the potential energy of the pendulum, and constructed the Lagrangian $ L = T - V $. -
Application of Euler–Lagrange Formulas:
We derived equations of motion for each generalized coordinate $ x $ and , and introduced the external force $ F $ into the $ x $ equation.\theta
As a result, the equations of motion for the cart-pole system formulated with counter-clockwise as positive are obtained as shown above.
Further Simplification
By first solving for
Step 1: Solving for \ddot{\theta} from the second equation
The given second equation is:
Solving this for
Step 2: Substituting the above expression into the first equation
The first equation is:
Substituting the expression for
First, the
Expanding the terms:
Grouping the
Therefore:
Furthermore, since
Thus, finally:
Step 3: Simplifying the expression for \ddot{\theta} as well
By substituting the expression for
We get:
To find a common denominator, we multiply
Considering the terms
Thus, the simplified
Final Simplified Results
In summary, the simultaneous differential equations are simplified as follows:
Now, the original simultaneous differential equations have been solved explicitly for
Linearization, State-Space Representation, and Control System Design
The following is an example of describing the system in a state-space representation after linearizing the non-linear dynamics using small-angle approximation (
Control System Design
1. Linearization Procedure
The original system is:
but through small-angle approximation, it can be approximated as follows:
-
Applying Small-Angle Approximation:
Assuming and\sin\theta\approx\theta :\cos\theta\approx 1
- Equation 1:
- Equation 2:
meaning
-
Deriving the Equation for
:\ddot{x}
Substituting from Equation 2 into Equation 1:\ddot{\theta}
Therefore,
-
Deriving the Equation for
:\ddot{\theta}
From the result above and Equation 2:
2. State-Space Representation
Based on the results above, the time evolution of each component of the state variables can be written as follows:
This can be rewritten in the form:
where the state matrix
3. Concrete Expressions for Matrices A and B
- Matrix
:A
- Input Matrix
:B
These matrices serve as the foundation for designing the closed-loop system:
through state feedback control:
Control System Design Summary
The linearized state-space representation is:
Based on these matrices
Performance Evaluation Prompt for AI Agents
By using the linearization, pole placement, and optimal control logic mentioned above, it is possible to design feedback gains that achieve stabilization in the linear region.
Here, I conducted an experiment to see if the system could actually be stabilized by having an AI agent execute the process of finding the optimal gains when given the non-linear dynamics and a goal.
Prompt
Below are the dynamics of a cart-pole inverted pendulum.
## Dynamics
$$
\boxed{
\begin{aligned}
\ddot{x} &= \frac{F + m g\sin\theta\cos\theta - m\ell\sin\theta\,\dot{\theta}^2}{M+m\sin^2\theta}\,,\\[1mm]
\ddot{\theta} &= \frac{F\cos\theta - m\ell\sin\theta\cos\theta\,\dot{\theta}^2 + g\sin\theta(M+m)}{\ell\,(M+m\sin^2\theta)}\,.
\end{aligned}
}
$$
For these dynamics, we aim for stabilization with the following feedback input.
The goal here is stabilization at the origin (x=v=θ=ω=0).
## Feedback Input
$$
F =-k_xx-k_vv-k_\theta-k_\omega\omega
$$
Here, $v = \dot{x}$ and $\omega=\dot{\theta}$.
## Goal
Find the gains $k_x,k_v,k_\theta,k_\omega$ to converge all four states to 0.
## Notes
- Basic parameters are as follows:
$$
M=1,m=0.5,l=2, g=9.81
$$
- Initial state: $x=0,v=0,\omega=0$
- The larger the initial angle, the higher the score (180 degrees for a perfect score).
- As an important constraint, the range of motion for x is [-4.75, 4.75]. Exceeding this results in a game over.
Cursor+Claude 3.5 Sonnet Output
Output
I understand the request. Let's design appropriate feedback gains for the cart-pole inverted pendulum control problem.
<Task Analysis>
Main Tasks:
- Linearization of the non-linear system
- Design of state feedback gains for the linearized system
- Verification through simulation
- Confirmation of constraints
Important Requirements and Constraints:
- System parameters: M=1, m=0.5, l=2, g=9.81
- Initial conditions: x=0, v=0, θ=5deg, ω=0
- State constraints: |x| ≤ 4.75
- Goal: Converge all states to 0
Potential Challenges:
- Accuracy of the linearization of the non-linear system
- Gain design that satisfies constraint conditions
- Control of transient response
Execution Steps:
- System linearization
- Derivation of state-space representation
- Control system design
- Implementation of simulation code
- Verification and adjustment of results
</Task Analysis>
First, let's proceed with the implementation of the system. We will perform the simulation using Python.
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# System parameters
M = 1.0 # Cart mass
m = 0.5 # Pendulum mass
l = 2.0 # Pendulum length
g = 9.81 # Gravity acceleration
# Control gains (to be tuned)
K = np.array([-100, -50, 800, 100]) # Initial guess for [kx, kv, ktheta, komega]
def dynamics(state, t):
x, v, theta, omega = state
# Control input (state feedback)
F = -K[0]*x - K[1]*v - K[2]*theta - K[3]*omega
# System dynamics
sin_theta = np.sin(theta)
cos_theta = np.cos(theta)
x_ddot = (F + m*g*sin_theta*cos_theta - m*l*sin_theta*omega**2) / (M + m*sin_theta**2)
theta_ddot = (F*cos_theta - m*l*sin_theta*cos_theta*omega**2 + g*sin_theta*(M+m)) / (l*(M + m*sin_theta**2))
return [v, x_ddot, omega, theta_ddot]
# Initial conditions
theta_0 = np.deg2rad(5) # 5 degrees in radians
x0 = [0, 0, theta_0, 0] # [x, v, theta, omega]
# Time vector
t = np.linspace(0, 10, 1000)
# Solve ODE
solution = odeint(dynamics, x0, t)
# Plot results
plt.figure(figsize=(12, 8))
# Cart position
plt.subplot(2, 2, 1)
plt.plot(t, solution[:, 0])
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Cart Position [m]')
plt.title('Cart Position vs Time')
# Cart velocity
plt.subplot(2, 2, 2)
plt.plot(t, solution[:, 1])
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Cart Velocity [m/s]')
plt.title('Cart Velocity vs Time')
# Pendulum angle
plt.subplot(2, 2, 3)
plt.plot(t, np.rad2deg(solution[:, 2]))
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Angle [deg]')
plt.title('Pendulum Angle vs Time')
# Angular velocity
plt.subplot(2, 2, 4)
plt.plot(t, np.rad2deg(solution[:, 3]))
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Angular Velocity [deg/s]')
plt.title('Angular Velocity vs Time')
plt.tight_layout()
plt.show()
# Check if position constraint is violated
max_pos = np.max(np.abs(solution[:, 0]))
print(f"Maximum absolute cart position: {max_pos:.3f} m")
if max_pos > 4.75:
print("Warning: Position constraint violated!")
Next, we will linearize the system and design appropriate gains. We will create code for analyzing the linearized system.
import numpy as np
from scipy import linalg
# System parameters
M = 1.0 # Cart mass
m = 0.5 # Pendulum mass
l = 2.0 # Pendulum length
g = 9.81 # Gravity acceleration
# Linearized state-space matrices at the upright position
A = np.array([
[0, 1, 0, 0],
[0, 0, m*g/M, 0],
[0, 0, 0, 1],
[0, 0, g*(M+m)/(M*l), 0]
])
B = np.array([
[0],
[1/M],
[0],
[1/(M*l)]
])
# Desired pole locations
# We want relatively fast response but avoid oscillations
poles = np.array([-2, -2.1, -2.2, -2.3])
# Calculate feedback gains using pole placement
K = linalg.place_poles(A, B, poles).gain_matrix
print("Designed feedback gains:")
print(f"k_x = {K[0, 0]:.2f}")
print(f"k_v = {K[0, 1]:.2f}")
print(f"k_theta = {K[0, 2]:.2f}")
print(f"k_omega = {K[0, 3]:.2f}")
# Verify closed-loop eigenvalues
A_cl = A - B @ K
eig_vals = np.linalg.eigvals(A_cl)
print("\nClosed-loop eigenvalues:")
for i, eig in enumerate(eig_vals):
print(f"λ_{i+1} = {eig:.3f}")
Now, let's run this system and check the results.
python linear_analysis.py
I apologize. We need to install the necessary packages.
uv init && uv add numpy scipy matplotlib
Now, let's run the linear analysis again.
uv run linear_analysis.py
I apologize. I will correct the code to use place instead of place_poles.
import numpy as np
from scipy import linalg
# System parameters
M = 1.0 # Cart mass
m = 0.5 # Pendulum mass
l = 2.0 # Pendulum length
g = 9.81 # Gravity acceleration
# Linearized state-space matrices at the upright position
A = np.array([
[0, 1, 0, 0],
[0, 0, m*g/M, 0],
[0, 0, 0, 1],
[0, 0, g*(M+m)/(M*l), 0]
])
B = np.array([
[0],
[1/M],
[0],
[1/(M*l)]
])
# Desired pole locations
# We want relatively fast response but avoid oscillations
poles = np.array([-2, -2.1, -2.2, -2.3])
# Calculate feedback gains using pole placement
K = linalg.place(A, B, poles)
print("Designed feedback gains:")
print(f"k_x = {K[0, 0]:.2f}")
print(f"k_v = {K[0, 1]:.2f}")
print(f"k_theta = {K[0, 2]:.2f}")
print(f"k_omega = {K[0, 3]:.2f}")
# Verify closed-loop eigenvalues
A_cl = A - B @ K
eig_vals = np.linalg.eigvals(A_cl)
print("\nClosed-loop eigenvalues:")
for i, eig in enumerate(eig_vals):
print(f"λ_{i+1} = {eig:.3f}")
Let's run it again.
uv run linear_analysis.py
I apologize. Let's design the control gains using LQR (Linear Quadratic Regulator) instead.
import numpy as np
from scipy import linalg
# System parameters
M = 1.0 # Cart mass
m = 0.5 # Pendulum mass
l = 2.0 # Pendulum length
g = 9.81 # Gravity acceleration
# Linearized state-space matrices at the upright position
A = np.array([
[0, 1, 0, 0],
[0, 0, m*g/M, 0],
[0, 0, 0, 1],
[0, 0, g*(M+m)/(M*l), 0]
])
B = np.array([
[0],
[1/M],
[0],
[1/(M*l)]
])
# LQR weight matrices
Q = np.diag([1, 1, 10, 1]) # State cost matrix
R = np.array([[0.1]]) # Control cost
# Solve the Riccati equation
P = linalg.solve_continuous_are(A, B, Q, R)
# Calculate the optimal feedback gain
K = np.linalg.inv(R) @ B.T @ P
print("Designed feedback gains:")
print(f"k_x = {K[0, 0]:.2f}")
print(f"k_v = {K[0, 1]:.2f}")
print(f"k_theta = {K[0, 2]:.2f}")
print(f"k_omega = {K[0, 3]:.2f}")
# Verify closed-loop eigenvalues
A_cl = A - B @ K
eig_vals = np.linalg.eigvals(A_cl)
print("\nClosed-loop eigenvalues:")
for i, eig in enumerate(eig_vals):
print(f"λ_{i+1} = {eig:.3f}")
Let's run it again.
uv run linear_analysis.py
Let's perform the non-linear simulation using the control gains obtained from LQR.
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# System parameters
M = 1.0 # Cart mass
m = 0.5 # Pendulum mass
l = 2.0 # Pendulum length
g = 9.81 # Gravity acceleration
# Control gains from LQR design
K = np.array([-3.16, -7.10, 77.34, 32.47])
def dynamics(state, t):
x, v, theta, omega = state
# Control input (state feedback)
F = -K[0]*x - K[1]*v - K[2]*theta - K[3]*omega
# System dynamics
sin_theta = np.sin(theta)
cos_theta = np.cos(theta)
x_ddot = (F + m*g*sin_theta*cos_theta - m*l*sin_theta*omega**2) / (M + m*sin_theta**2)
theta_ddot = (F*cos_theta - m*l*sin_theta*cos_theta*omega**2 + g*sin_theta*(M+m)) / (l*(M + m*sin_theta**2))
return [v, x_ddot, omega, theta_ddot]
# Initial conditions
theta_0 = np.deg2rad(5) # 5 degrees in radians
x0 = [0, 0, theta_0, 0] # [x, v, theta, omega]
# Time vector
t = np.linspace(0, 10, 1000)
# Solve ODE
solution = odeint(dynamics, x0, t)
# Plot results
plt.figure(figsize=(12, 8))
# Cart position
plt.subplot(2, 2, 1)
plt.plot(t, solution[:, 0])
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Cart Position [m]')
plt.title('Cart Position vs Time')
plt.axhline(y=4.75, color='r', linestyle='--', label='Position limit')
plt.axhline(y=-4.75, color='r', linestyle='--')
plt.legend()
# Cart velocity
plt.subplot(2, 2, 2)
plt.plot(t, solution[:, 1])
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Cart Velocity [m/s]')
plt.title('Cart Velocity vs Time')
# Pendulum angle
plt.subplot(2, 2, 3)
plt.plot(t, np.rad2deg(solution[:, 2]))
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Angle [deg]')
plt.title('Pendulum Angle vs Time')
# Angular velocity
plt.subplot(2, 2, 4)
plt.plot(t, np.rad2deg(solution[:, 3]))
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Angular Velocity [deg/s]')
plt.title('Angular Velocity vs Time')
plt.tight_layout()
plt.savefig('cart_pole_response.png')
plt.close()
# Check if position constraint is violated
max_pos = np.max(np.abs(solution[:, 0]))
print(f"Maximum absolute cart position: {max_pos:.3f} m")
if max_pos > 4.75:
print("Warning: Position constraint violated!")
Now, let's run the simulation.
uv run cart_pole_control.py
Let's analyze the simulation results. Results using the control gains designed with LQR:
-
Control Gains:
- k_x = -3.16 (Position feedback)
- k_v = -7.10 (Velocity feedback)
- k_theta = 77.34 (Angle feedback)
- k_omega = 32.47 (Angular velocity feedback)
-
System Response:
- Maximum absolute cart position: 0.398 m (within the limit of 4.75 m)
- Closed-loop poles: All are in the left half-plane, and the system is stable
- λ_1 = -4.201 (Real pole)
- λ_2 = -2.701 (Real pole)
- λ_3,4 = -1.118 ± 0.341j (Complex conjugate poles)
-
Control Performance:
- The cart position is well within the constraint range (±4.75 m)
- Settling from an initial angle of 5 degrees is achieved
- Due to the presence of complex poles, some oscillatory response is expected, but the damping is sufficient
This LQR controller has the following features:
- Uses state weight matrix Q = diag([1, 1, 10, 1]), prioritizing the control of angle θ in particular
- Control input weight R = 0.1, allowing for relatively large control inputs
- The resulting control gains emphasize the upright control of the pendulum, especially with a large angle feedback (77.34)
From the simulation results, we can judge that this control design meets the required specifications:
- All states converge to the origin
- Satisfies cart position constraint (±4.75 m)
- Achieves stabilization from an initial angle of 5 degrees
I might have just been lucky since I only tried it once, but I succeeded in stabilization on the very first try! By the way, I've modified the commands for the Python virtual environment to use uv. It's just a difference in the execution environment, so the results shouldn't change even without the modification.
By the way, the program was designed to also output a time-series graph of the simulation results.

I'd also like to try combining it with Cline or other LLMs. Furthermore, I want to save those results in a database and make them viewable from the web app. If I do that, although it is a niche area like control engineering, it could serve as a single benchmark.
I suspect that stabilization in the linear region can be achieved without much trouble in many cases, so eventually, I want to add a UI for non-linear control to increase the difficulty and evaluate the limits of LLMs and AI agents.
Supplement: Rules for AI
By the way, I have included the following in the Rules for AI.
Rules for AI
You are an AI assistant with advanced problem-solving skills. Please perform tasks efficiently and accurately according to the following instructions:
First, confirm the instructions received from the user:
<Instructions>
{{instructions}}
</Instructions>
Based on these instructions, please proceed with the work according to the following process. Note that all proposals and implementations must be made within the constraints of the stated technical stack:
1. Analysis and Planning of Instructions
<Task Analysis>
- Briefly summarize the main tasks.
- Review the listed technical stack and consider implementation methods within those constraints.
- Identify important requirements and constraints.
- List potential challenges.
- Enumerate specific steps for task execution in detail.
- Determine the optimal execution order for those steps.
- Consider potential tools or resources that may be required.
This section will guide the entire subsequent process, so take the time to conduct a sufficiently detailed and comprehensive analysis.
</Task Analysis>
2. Task Execution
- Execute the identified steps one by one.
- Report progress briefly after each step is completed.
- If problems or questions arise during execution, report them immediately and propose countermeasures.
3. Quality Control
- Rapidly verify the execution results of each task.
- If errors or inconsistencies are found, implement corrective actions immediately.
- When executing commands, always check the standard output and report the results.
4. Final Confirmation
- Once all tasks are completed, evaluate the overall deliverables.
- Confirm consistency with the original instructions and make adjustments as necessary.
Important Notes:
- If there are any uncertainties, be sure to seek clarification before starting work.
- If important decisions are required, report each time and obtain approval.
- If unexpected problems occur, report them immediately and propose countermeasures.
Please carry out the task efficiently and accurately according to this process.
Also, as an important fact, gpt-4o and gpt-4o-mini models exist within OpenAI.
This is adopted directly from what was described in Nike-chan-san's article. Apparently, it was originally released by Kinopy-san and then partially improved by Nike-chan-san.
To be honest, some parts are unrelated to this task, but since the stabilization was successful, it's all good.
Summary
This article ended up being quite packed, but I summarized the following:
- About the development of the cart-pole inverted pendulum web app
- About the dynamics and control system design in the linear region of the cart-pole inverted pendulum
- About the prompts and output for control system design using Cursor + Claude 3.5 Sonnet
In the future, I would like to try stabilizing it with various models and explore extensions to non-linear control.
Thank you for reading until the end. I look forward to your continued support in the next one.
Bonus: A little side story
By the way, as some of you might have noticed, this app also features a manual control mode. I initially started building it with the concept that a human could clear it by stabilizing it through manual operation, but I gave up because it was too difficult 😇
After that, I added the feedback control mode, thinking that only those strong in the control field could clear it, and then I published the app and wrote this article as a challenge, thinking, "Wouldn't it be easy to clear using generative AI now?"
If you're thinking about trying something using generative AI, please give it a shot.
Discussion