Graph, Game, Control Theory and Reinforcement Learning
Four older fields explain how agent systems flow, correct themselves, learn from outcomes and behave toward one another.
Graph theory describes workflows and communication between agents. Control theory explains why feedback loops settle, oscillate or run away. Reinforcement learning studies choosing actions from rewards. Game theory studies what happens when several decision makers affect one another. You rarely need the full mathematics, but these ideas help you spot design faults before users do.
What you will learn: graph analysis of workflows and agent networks, stability of feedback loops, rewards and exploration, and incentives among agents.
Prerequisites: basic Python. Math, Search and Algorithms for Agent Engineers helps.
Graphs in agent systems
A graph is a set of nodes joined by edges. Edges may have direction and weight. Agent systems are full of them.
| Graph | Nodes and edges | Useful question |
|---|---|---|
| Workflow | Steps and transitions | Can every state reach an end? |
| Task dependencies | Tasks and "waits for" | What can run in parallel? |
| Agent network | Agents and message paths | Is there a single point of failure? |
| Delegation | Who gave work or authority to whom | Can authority grow along a chain? |
| Data lineage | Items and "made from" | What does a change affect? |
| Concept | Meaning |
|---|---|
| Path | A sequence of connected edges |
| Cycle | A path returning to its start |
| Directed acyclic graph | Directed edges with no cycles; can be ordered |
| Reachability | Which nodes can be reached from a node |
| Degree and centrality | How connected or important a node is by some measure |
| Cut point | A node whose removal splits the graph |
Analyze a workflow
"""Analyze a workflow as a graph: order, longest path and cycles."""
from graphlib import CycleError, TopologicalSorter
# step: (minutes, steps it waits for)
steps = {"intake": (1, []), "search": (4, ["intake"]),
"query": (2, ["intake"]), "draft": (3, ["search", "query"]),
"review": (5, ["draft"])}
graph = {name: set(needs) for name, (_, needs) in steps.items()}
order = list(TopologicalSorter(graph).static_order())
finish, via = {}, {}
for name in order:
minutes, needs = steps[name]
start = max((finish[n] for n in needs), default=0)
finish[name] = start + minutes
via[name] = max(needs, key=finish.get) if needs else None
path, node = [], max(finish, key=finish.get)
while node:
path.append(node)
node = via[node]
total = sum(m for m, _ in steps.values())
print("one at a time:", total, "min")
print("in parallel: ", max(finish.values()), "min")
print("critical path:", " -> ".join(reversed(path)))
graph["search"].add("review") # "loop back if review fails"
try:
list(TopologicalSorter(graph).static_order())
except CycleError as error:
print("cycle found among:", sorted(set(error.args[1])))
Output:
one at a time: 15 min
in parallel: 13 min
critical path: intake -> search -> draft -> review
cycle found among: ['draft', 'review', 'search']
Running search and query together saves only two minutes, because the longest chain, the critical path, passes through search. Making the query faster would change nothing. Adding a retry edge creates a cycle, so the steps can no longer be put in a fixed order. Cycles are legitimate in agent loops, but each needs an exit condition and a limit. In multi-agent designs, also count messages: if every agent talks to every other, ten agents have forty-five pairs to keep consistent. See Topologies, Specialist Teams and Debate.
Control theory: acting on feedback
A control loop measures the current state, compares it with a goal and applies a correction. An agent that runs tests, reads the failures and edits code is such a loop, as is an autoscaler.
"""Correct a queue length with feedback: gain and delay decide stability."""
def run(gain, delay, target=100.0, steps=40):
level, history = 0.0, [0.0]
for t in range(steps):
observed = history[max(0, t - delay)]
level += gain * (target - observed)
history.append(level)
return history
print("gain delay peak dip after final value verdict")
for gain, delay in [(0.3, 0), (1.8, 0), (2.2, 0), (0.3, 3), (0.1, 3)]:
h = run(gain, delay)
errors = [abs(100 - v) for v in h]
reached = next((i for i, v in enumerate(h) if v >= 100 - 0.5), None)
dip = f"{min(h[reached:]):.0f}"
if errors[-1] < 1:
verdict = "settled"
elif max(errors[-8:]) > max(errors[-16:-8]):
verdict = "growing"
else:
verdict = "not settled yet"
print(f"{gain:>4} {delay:>5} {max(h):>7.0f} {dip:>10} {h[-1]:>12.0f} {verdict}")
Output:
gain delay peak dip after final value verdict
0.3 0 100 100 100 settled
1.8 0 180 36 100 settled
2.2 0 122581 -146877 -146877 growing
0.3 3 156 71 104 not settled yet
0.1 3 100 100 100 settled
The numbers are a simplified model: each step adds a correction proportional to the observed error. A modest gain with no delay approaches the target smoothly. A larger gain overshoots to 180, falls to 36 and still settles. A slightly larger one grows without bound. With a delay of three steps, the previously safe gain of 0.3 overshoots and is still off target after forty steps, while 0.1 behaves well. The lesson transfers: when feedback is slow, correct more gently, or wait for the effect before correcting again.
| Control idea | Agent counterpart |
|---|---|
| Gain | How big a change each iteration makes |
| Delay | Slow tests, caches and eventually consistent data |
| Noise | Flaky tests and variable model output |
| Dead band | Ignoring tiny differences to avoid churn |
| Saturation | Rate limits and budgets cap the action |
| Stability | The loop converges instead of thrashing |
Language model loops are not linear systems, so formal stability results do not apply directly. Use the ideas to ask good questions, and enforce iteration limits and progress checks, as in Agent Decisions: Confidence, Stopping, Loops and Budgets.
Reinforcement learning fundamentals
In reinforcement learning an agent observes a state, chooses an action and receives a reward. A policy maps states to actions, and the aim is to maximize reward over time.
| Term | Meaning |
|---|---|
| Markov decision process | The standard model of states, actions, transitions and rewards |
| Return | Accumulated reward, often discounting the future |
| Value function | Expected return from a state or action |
| Exploration and exploitation | Trying options against using the best known |
| Policy gradient | Adjusting a policy directly toward higher reward |
| Offline learning | Learning from recorded data without new interaction |
| Reward hacking | Achieving reward without achieving the intent |
The simplest case, a multi-armed bandit, has no changing state: pick one of several options and observe the result. This fits choosing among models or tools.
"""Learn which of three options works best while still serving requests."""
import random
TRUE_RATE = {"small": 0.60, "medium": 0.75, "large": 0.80} # hidden
COST = {"small": 0.01, "medium": 0.05, "large": 0.40}
def run(cost_weight, epsilon=0.1, rounds=20000, seed=7):
rng = random.Random(seed)
pulls = {a: 0 for a in TRUE_RATE}
value = {a: 0.0 for a in TRUE_RATE}
for t in range(rounds):
untried = [a for a in pulls if pulls[a] == 0]
if untried:
arm = untried[0]
elif rng.random() < epsilon:
arm = rng.choice(list(pulls))
else:
arm = max(value, key=value.get)
success = rng.random() < TRUE_RATE[arm]
reward = success - cost_weight * COST[arm]
pulls[arm] += 1
value[arm] += (reward - value[arm]) / pulls[arm]
return pulls, value
for weight in (0.0, 1.0):
pulls, value = run(weight)
print(f"cost weight {weight}:")
for arm in pulls:
print(f" {arm:<6} chosen {pulls[arm]:>5} estimate {value[arm]:.2f}")
Output:
cost weight 0.0:
small chosen 657 estimate 0.61
medium chosen 691 estimate 0.78
large chosen 18652 estimate 0.80
cost weight 1.0:
small chosen 662 estimate 0.60
medium chosen 18679 estimate 0.70
large chosen 659 estimate 0.38
With no cost penalty the learner settles on the large option, which succeeds most often. Once cost counts in the reward, it prefers the medium one. Nothing about the options changed; the definition of "good" did. The 10% exploration keeps estimates of the others alive, at a price. The simulation also assumes fixed success rates, immediate feedback and identical requests. Real traffic changes, success is often known late or not at all, and exploring with real users may be unacceptable for risky actions.
Reinforcement learning and language models
Preference-based methods shape model behavior after initial training. Reinforcement learning from human feedback trains a reward model from comparisons and optimizes against it. Direct preference optimization learns from preference pairs without a separate reinforcement learning loop. Methods such as GRPO have been used with rewards that a program can check, for example whether tests pass. Most agent builders use models trained this way rather than training their own. If you do train, the reward definition and held-out evaluation deserve more care than the algorithm. See Learning, Self-Improvement, World Models and RL.
Reward "tests pass" and a learner may weaken the tests. Reward "ticket closed" and it may close tickets unresolved. Protect the checker from the agent, combine several signals and read samples of high-reward behavior.
Game theory and coordination
Game theory studies choices whose results depend on others' choices. A Nash equilibrium is a combination in which no participant gains by changing alone. It need not be good for the group.
"""Two agents share a rate limit. What does each do if it acts selfishly?"""
from itertools import product
ACTIONS = ("polite", "greedy")
BASE = {("polite", "polite"): (6, 6), ("polite", "greedy"): (2, 8),
("greedy", "polite"): (8, 2), ("greedy", "greedy"): (3, 3)}
def stable_outcomes(payoff):
"""Pure Nash equilibria: no agent gains by changing alone."""
found = []
for a, b in product(ACTIONS, repeat=2):
best_a = all(payoff[a, b][0] >= payoff[x, b][0] for x in ACTIONS)
best_b = all(payoff[a, b][1] >= payoff[a, y][1] for y in ACTIONS)
if best_a and best_b:
found.append((a, b, payoff[a, b]))
return found
def with_charge(charge):
return {(a, b): (u - charge * (a == "greedy"), v - charge * (b == "greedy"))
for (a, b), (u, v) in BASE.items()}
for charge in (0, 1.5, 3):
print(f"charge for greed {charge}:")
for a, b, scores in stable_outcomes(with_charge(charge)):
print(f" stable: {a} / {b}, payoffs {scores}, "
f"total value before charges {sum(BASE[a, b])}")
Output:
charge for greed 0:
stable: greedy / greedy, payoffs (3, 3), total value before charges 6
charge for greed 1.5:
stable: polite / greedy, payoffs (2.0, 6.5), total value before charges 10
stable: greedy / polite, payoffs (6.5, 2.0), total value before charges 10
charge for greed 3:
stable: polite / polite, payoffs (6, 6), total value before charges 12
With no charge, both agents grab capacity and each receives 3, although mutual restraint would give 6. This is the structure of the prisoner's dilemma. A moderate charge leads to two lopsided stable outcomes in which one agent yields. A larger charge makes politeness stable for both. The designer changed the rules rather than asking the agents to be considerate. This is mechanism design. In real systems, quotas enforced by a scheduler are usually simpler and more dependable than prices.
| Situation | Idea | Practical measure |
|---|---|---|
| Shared rate limit or budget | Common resource | Per-agent quotas |
| Task allocation | Auctions and contract nets | A coordinator assigns using stated criteria |
| Agents rating each other | Incentives to agree | Independent checks against ground truth |
| Negotiation with outside parties | Conflicting goals | Hard limits in code, human approval |
| Voting among agents | Aggregation | Helps only if errors are not strongly shared |
Language model agents do not necessarily behave like the rational players of textbook games. They may be swayed by wording, concede too easily or repeat one another. Measure behavior. Research on multi-agent language model systems has also cataloged ordinary engineering failures: the MAST study describes fourteen failure modes in three groups, covering system design, misalignment between agents and task verification. Clear roles, shared state and real verification address many of them, as discussed in Single-Agent vs Multi-Agent Systems.
Which tool for which symptom
| Symptom | Look at |
|---|---|
| Workflow stalls or never ends | Graph cycles and reachability |
| End-to-end time barely improves | Critical path |
| Agent keeps undoing its own change | Feedback delay and correction size |
| Choosing among options with uncertain results | Bandit methods, with guarded exploration |
| Agents compete or collude in unhelpful ways | Incentives and rules |
A coding agent alternates between two edits because test results arrive from a stale build. The team ties each result to the code version it tested, makes the agent wait for the matching result, limits attempts and stops when the same error returns. The change is control theory in plain clothes: remove delay confusion and damp repeated correction.
Know the limits of each model
Each of these fields gains its precision from assumptions. Checking them tells you how far to trust a conclusion.
| Field | Typical assumption | Where agent systems differ |
|---|---|---|
| Graph analysis | The edges are known and complete | A model may choose steps that were never drawn |
| Control | The system responds in a regular way | The same correction can produce very different edits |
| Bandits | Reward rates stay fixed and arrive quickly | Models, traffic and tools change; outcomes arrive late |
| Reinforcement learning | The reward captures the aim | Checkers have gaps that can be exploited |
| Game theory | Players pursue stated payoffs consistently | Behavior shifts with prompts and context |
A practical way to use them is to build a small model first, as the examples here do. If a design is unstable, deadlocks or rewards bad behavior even in a toy version with generous assumptions, it is unlikely to behave better in production. If the toy version looks fine, that is permission to test the real system, not proof that it works. Simulation with scripted or model-driven participants, described in Golden Datasets, Synthetic Data and Simulation, is the natural next step.
Common mistakes
- Allowing cycles without limits.
- Speeding up steps off the critical path.
- Correcting again before the last change has taken effect.
- Optimizing one reward that can be gamed.
- Exploring on high-risk actions.
- Assuming agents will cooperate because they were asked to.
- Treating agreement among similar models as verification.
Checklist
- Workflows are drawn and checked for dead ends and cycles.
- The critical path is known before optimizing.
- Loops have limits, progress checks and damping.
- Observations are tied to the version they describe.
- Rewards and checkers are protected and sampled.
- Exploration is restricted to safe choices.
- Shared resources have enforced quotas.
- Multi-agent behavior is measured, not assumed.
Frequently asked questions
Do language model agents learn from their rewards while running?
Usually not. Model weights stay fixed unless a training process updates them. Systems may adapt through stored memory, prompts or routing statistics, which are different mechanisms.
Must every workflow be acyclic?
No. Retry and revision loops are normal. Give each a clear exit and a maximum number of rounds.
When is a bandit better than a fixed choice?
When several safe options exist, outcomes are measurable soon and conditions change. Otherwise periodic offline evaluation is simpler.
Is game theory needed for one organization's agents?
Rarely in formal terms. It is a useful reminder that agents with separate goals and shared resources need enforced rules.
References and further reading
- Sutton and Barto: Reinforcement Learning, second edition
- Åström and Murray: Feedback Systems
- Shoham and Leyton-Brown: Multiagent Systems
- Cemri et al.: Why do multi-agent LLM systems fail?
- Rafailov et al.: Direct preference optimization
- Shao et al.: DeepSeekMath, which introduced GRPO
- Python graphlib documentation
Next steps
Formal Verification and Testing Foundations
Check that rules really hold.
Graphs, State Machines, Parallelism and Sagas
Turn graphs into orchestration.
Securing, Evaluating and Running Multi-Agent Systems
Run agent teams safely.