Skip to content
ImagineWorld

Agentic Patterns

node_idnode-book_llm-design-patterns_chapter-29-agentic-patterns
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num29
chapter_titleAgentic Patterns
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this final chapter, we’ll explore patterns for creating more autonomous and goal-directed AI agents using LLMs. You’ll learn about goal-setting and planning in LLM-based agents, implementing memory and state management, and strategies for decision-making and action selection. We’ll cover techniques for learning and adaptation in agentic LLM systems and discuss the ethical considerations and safety measures necessary when developing such systems.

By the end of this chapter, you’ll be able to design and implement sophisticated AI agents powered by LLMs, opening up new possibilities for autonomous AI systems.

In this chapter, we will be covering the following topics:

  • Introduction to agentic AI systems based on LLMs
  • Goal-setting and planning in LLM-based agents
  • Implementing memory and state management for LLM agents
  • Decision-making and action selection in LLM-based agents
  • Learning and adaptation in agentic LLM systems
  • Ethical considerations and safety in LLM-based agentic AI
  • Future prospects of agentic AI using LLMs

Introduction to agentic AI systems based on LLMs

Section titled “Introduction to agentic AI systems based on LLMs”

Agentic AI systems using LLMs are designed to operate autonomously, make decisions, and take actions to achieve specified goals. These systems combine the powerful language understanding and generation capabilities of LLMs with goal-oriented behavior and environmental interaction.

Let’s start by implementing a basic structure for an LLM-based agent:

from typing import List, Dict, Any
import random
class LLMAgent:
def __init__(self, llm, action_space: List[str]):
self.llm = llm
self.action_space = action_space
self.memory = []
self.current_goal = None

Here, the LLMAgent class is initialized with an LLM (llm) and a list of possible actions (action_space). It also maintains a memory of observations and a current_goal, which will be used to guide the agent’s actions.

def set_goal(self, goal: str):
self.current_goal = goal
def perceive(self, observation: str):
self.memory.append(observation)

Here, we define two methods: set_goal, which allows the agent to set its goal, and perceive, which enables the agent to take in observations from the environment and store them in its memory.

Next, we use the think method to generate a thorough process based on the agent’s goal and recent observations:

def think(self) -> str:
context = f"Goal: {self.current_goal}\n"
context += "Recent observations:\n"
context += "\n".join(self.memory[-5:]) # Last 5 observations
context += "\nThink about the current situation and the goal. What should be done next?"
return self.llm.generate(context)

The agent asks the language model for advice on the next step by providing a context string, which includes the current goal and the last five observations.

Once the agent has a thought, it must decide on the next action. The decide method uses the thought to generate a context, asking the LLM to pick the best action from the available options:

def decide(self, thought: str) -> str:
context = f"Thought: {thought}\n"
context += "Based on this thought, choose the most appropriate action from the following:\n"
context += ", ".join(self.action_space)
context += "\nChosen action:"
return self.llm.generate(context)

Then, the act method simulates taking an action by randomly selecting an outcome (success, failure, or an unexpected result). In real scenarios, this would involve interacting with the environment:

def act(self, action: str) -> str:
outcomes = [
f"Action '{action}' was successful.",
f"Action '{action}' failed.",
f"Action '{action}' had an unexpected outcome."
]
return random.choice(outcomes)

Finally, the run_step method orchestrates the entire process of thinking, deciding, acting, and perceiving the outcome, completing one cycle of interaction with the environment:

def run_step(self):
thought = self.think()
action = self.decide(thought)
outcome = self.act(action)
self.perceive(outcome)
return thought, action, outcome

Now that we understand the fundamental principles, let’s translate these concepts into code.

Let’s implement a basic LLM-based agent, establishing the core structure for autonomous operation. The agent is initialized with a hypothetical language model (llm) and a set of actions. It sets a goal and perceives the environment to begin interacting with it:

# Example usage
llm = SomeLLMModel() # Replace with your actual LLM
action_space = ["move", "grab", "drop", "use", "talk"]
agent = LLMAgent(llm, action_space)
agent.set_goal("Find the key and unlock the door")
agent.perceive("You are in a room with a table and a chair. There's a drawer in the table.")

In the following for loop, the agent runs for five steps, and each thought, action, and outcome is printed to show how the agent interacts with its environment over time:

for _ in range(5): # Run for 5 steps
thought, action, outcome = agent.run_step()
print(f"Thought: {thought}")
print(f"Action: {action}")
print(f"Outcome: {outcome}")
print()

Having established the fundamentals of agent behavior, let’s explore more advanced capabilities. The following section focuses on goal-setting and planning, enabling the agent to proactively work toward complex objectives.

Goal-setting and planning in LLM-based agents

Section titled “Goal-setting and planning in LLM-based agents”

To enhance our agent with more sophisticated goal-setting and planning capabilities, let’s implement a hierarchical goal structure and a planning mechanism.

First, we define a HierarchicalGoal class; this class allows the agent to break down large tasks into smaller subgoals:

class HierarchicalGoal:
def __init__(
self, description: str,
subgoals: List['HierarchicalGoal'] = None
):
self.description = description
self.subgoals = subgoals or []
self.completed = False
def add_subgoal(self, subgoal: 'HierarchicalGoal'):
self.subgoals.append(subgoal)
def mark_completed(self):
self.completed = True

The agent can complete these subgoals step by step, marking each as completed when done.

Next, we have a PlanningAgent class, which inherits from LLMAgent but adds the ability to handle hierarchical goals. It stores goals in a stack, working through subgoals as they are completed:

class PlanningAgent(LLMAgent):
def __init__(self, llm, action_space: List[str]):
super().__init__(llm, action_space)
self.goal_stack = []
self.current_plan = []
def set_hierarchical_goal(self, goal: HierarchicalGoal):
self.goal_stack = [goal]

The think method now also includes planning. If no current plan exists, it asks the LLM to generate a step-by-step plan to achieve the current goal:

def think(self) -> str:
if not self.current_plan:
self.create_plan()
context = f"Current goal: {self.goal_stack[-1].description}\n"
context += "Current plan:\n"
context += "\n".join(self.current_plan)
context += "\nRecent observations:\n"
context += "\n".join(self.memory[-5:])
context += "\nThink about the current situation, goal, and plan. What should be done next?"
return self.llm.generate(context)

Then, the create_plan method generates a plan by prompting the LLM with the current goal and the list of actions. The generated plan is split into individual steps:

def create_plan(self):
context = f"Goal: {self.goal_stack[-1].description}\n"
context += "Create a step-by-step plan to achieve this goal. Each step should be an action from the following list:\n"
context += ", ".join(self.action_space)
context += "\nPlan:"
plan_text = self.llm.generate(context)
self.current_plan = [
step.strip() for step in plan_text.split("\n")
if step.strip()
]

The update_goals method checks whether the current goal is complete. If it is, it moves on to the next goal or subgoal and resets the plan accordingly:

def update_goals(self):
current_goal = self.goal_stack[-1]
if current_goal.completed:
self.goal_stack.pop()
if self.goal_stack:
self.current_plan = [] # Reset plan for the next goal
elif current_goal.subgoals:
next_subgoal = next(
(
sg for sg in current_goal.subgoals
if not sg.completed
),
None
)
if next_subgoal:
self.goal_stack.append(next_subgoal)
self.current_plan = [] # Reset plan for the new subgoal

The run_step method orchestrates the goal-setting and planning process, updating the goals as necessary:

def run_step(self):
thought, action, outcome = super().run_step()
self.update_goals()
return thought, action, outcome

Let’s take a look at an example.

In the following code snippet, the agent operates with a hierarchical goal to “escape the room.” As the agent runs through multiple steps, it works through its subgoals, such as finding the key and unlocking the door, with each step updating the agent’s internal goal stack and plan:

planning_agent = PlanningAgent(llm, action_space)
main_goal = HierarchicalGoal("Escape the room")
main_goal.add_subgoal(HierarchicalGoal("Find the key"))
main_goal.add_subgoal(HierarchicalGoal("Unlock the door"))
planning_agent.set_hierarchical_goal(main_goal)
planning_agent.perceive("You are in a room with a table and
a chair. There's a drawer in the table.")
for _ in range(10): # Run for 10 steps
thought, action, outcome = planning_agent.run_step()
print(f"Thought: {thought}")
print(f"Action: {action}")
print(f"Outcome: {outcome}")
print(f"Current goal: {planning_agent.goal_stack[-1].description}")
print()

In real-world applications, AI agent planning outputs from LLMs require constraints and validation due to the LLM’s potential to generate impractical, unsafe, or constraint-violating plans; therefore, techniques such as rule-based systems, simulations, human-in-the-loop review, formal verification, and API/type validations are essential to ensure that generated plans adhere to physical, legal, ethical, and operational limitations, ultimately enhancing safety, reliability, and effectiveness.

Having demonstrated the agent’s ability to pursue hierarchical goals, the next step is to enhance its capacity to learn from past experiences. The next section introduces a sophisticated memory system, enabling the agent to retain context and recall relevant information when making decisions.

Implementing memory and state management for LLM agents

Section titled “Implementing memory and state management for LLM agents”

To improve our agent’s ability to maintain context and learn from past experiences, let’s implement a more sophisticated memory system. This will enable the agent to recall relevant past observations when deciding on actions.

First, we define the MemoryEntry class, which represents an entry in the agent’s memory. Each entry contains the text of the observation and its corresponding embedding vector, which helps with similarity searches:

from collections import deque
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
class MemoryEntry:
def __init__(self, text: str, embedding: np.ndarray):
self.text = text
self.embedding = embedding

Then, we define the EpisodicMemory class; this handles the agent’s memory, storing a fixed number of observations (capacity). This memory can grow up to the specified limit, at which point older entries are removed:

class EpisodicMemory:
def __init__(self, capacity: int, embedding_model):
self.capacity = capacity
self.embedding_model = embedding_model
self.memory = deque(maxlen=capacity)

The following code uses content-based episodic memory, which leverages semantic similarity search. The memory stores past observations (episodes) as text along with their vector embeddings, and retrieves relevant memories based on the semantic similarity (using cosine similarity) between a query embedding and the stored embeddings:

def add(self, text: str):
embedding = self.embedding_model.encode(text)
self.memory.append(MemoryEntry(text, embedding))
def retrieve_relevant(self, query: str, k: int = 5) -> List[str]:
query_embedding = self.embedding_model.encode(query)
similarities = [
cosine_similarity(
[query_embedding],
[entry.embedding]
)[0][0] for entry in self.memory
]
top_indices = np.argsort(similarities)[-k:][::-1]
return [self.memory[i].text for i in top_indices]

The retrieve_relevant method searches for the most relevant past observations based on cosine similarity, returning the top k matching entries.

Then, we define the MemoryAwareAgent class; this class extends PlanningAgent by integrating an episodic memory system. This allows the agent to store and retrieve relevant past experiences during decision-making:

class MemoryAwareAgent(PlanningAgent):
def __init__(
self, llm, action_space: List[str], embedding_model
):
super().__init__(llm, action_space)
self.episodic_memory = EpisodicMemory(
capacity=1000, embedding_model=embedding_model
)
def perceive(self, observation: str):
super().perceive(observation)
self.episodic_memory.add(observation)

The think function defined in the following code incorporates relevant past experiences. The agent retrieves memories similar to its current goal and uses these in the context provided to the LLM when deciding what to do next:

def think(self) -> str:
relevant_memories = self.episodic_memory.retrieve_relevant(
self.current_goal, k=3
)
context = f"Current goal: {self.goal_stack[-1].description}\n"
context += "Current plan:\n"
context += "\n".join(self.current_plan)
context += "\nRecent observations:\n"
context += "\n".join(self.memory[-5:])
context += "\nRelevant past experiences:\n"
context += "\n".join(relevant_memories)
context += "\nThink about the current situation, goal, plan, and past experiences. What should be done next?"
return self.llm.generate(context)

The preceding code snippet orchestrates an AI agent’s decision-making process by first retrieving relevant memories based on the current goal, then constructing a comprehensive context for the LLM that includes the goal, current plan, recent observations, and retrieved memories, and finally utilizing the LLM to generate a response that determines the agent’s next action or thought based on the provided contextual information.

Let’s check out an example usage of the memory-aware agent. In this example, the agent is enhanced with memory capabilities. It now uses its past experiences to inform its decisions and actions:

embedding_model = SomeEmbeddingModel() # Replace with your actual embedding model
memory_agent = MemoryAwareAgent(llm, action_space, embedding_model)
main_goal = HierarchicalGoal("Solve the puzzle")
memory_agent.set_hierarchical_goal(main_goal)
memory_agent.perceive("You are in a room with a complex puzzle on the wall.")
The agent continues to interact with its environment over 10 steps, utilizing its memory system to make better decisions based on both current observations and past experiences:
for _ in range(10): # Run for 10 steps
thought, action, outcome = memory_agent.run_step()
print(f"Thought: {thought}")
print(f"Action: {action}")
print(f"Outcome: {outcome}")
print()

Now that our agent can remember and recall past experiences, we’ll focus on making better decisions. The next section introduces a structured approach to action selection, allowing the agent to choose the most effective action using an LLM. Keep in mind that memory retrieval is similarity-based, which works best when embedding quality is high.

Decision-making and action selection in LLM-based agents

Section titled “Decision-making and action selection in LLM-based agents”

To improve the agent’s decision-making capabilities, we can introduce a more structured approach to action selection, evaluating potential actions based on multiple factors.

We first define the ActionEvaluator class, which uses the LLM to evaluate actions based on three key criteria: relevance to the current goal, probability of success, and potential impact. These evaluations help the agent choose the best possible action:

import numpy as np
class ActionEvaluator:
def __init__(self, llm):
self.llm = llm
def evaluate_action(
self, action: str, context: str
) -> Dict[str, float]:
prompt = f"""
Context: {context}
Action: {action}

We then evaluate "action" that is passed into the evaluate_action function as a parameter based on the following criteria:

  • Relevance to the current goal (0-1)
  • Estimated success probability (0-1)
  • Potential impact on overall progress (0-1)
Provide your evaluation as three numbers separated by commas:
"""
response = self.llm.generate(prompt)
relevance, success_prob, impact = map(
float, response.split(',')
)
return {
'relevance': relevance,
'success_probability': success_prob,
'impact': impact
}

Lastly, we have the StrategicDecisionAgent class, which extends MemoryAwareAgent to include a more strategic approach to decision-making. It evaluates all possible actions, scoring them based on their relevance, success probability, and impact, and selects the action with the highest score:

class StrategicDecisionAgent(MemoryAwareAgent):
def __init__(
self, llm, action_space: List[str], embedding_model
):
super().__init__(llm, action_space, embedding_model)
self.action_evaluator = ActionEvaluator(llm)
def decide(self, thought: str) -> str:
context = f"Thought: {thought}\n"
context += f"Current goal: {self.goal_stack[-1].description}\n"
context += "Recent observations:\n"
context += "\n".join(self.memory[-5:])
action_scores = {}
for action in self.action_space:
evaluation = self.action_evaluator.evaluate_action(
action, context
)
score = np.mean(list(evaluation.values()))
action_scores[action] = score
best_action = max(action_scores, key=action_scores.get)
return best_action

Let’s check out an example usage of StrategicDecisionAgent. In this example, the agent uses more sophisticated decision-making strategies by evaluating actions based on various factors before selecting the optimal one:

strategic_agent = StrategicDecisionAgent(
llm, action_space, embedding_model
)
main_goal = HierarchicalGoal("Navigate the maze and find the treasure")
strategic_agent.set_hierarchical_goal(main_goal)
strategic_agent.perceive("You are at the entrance of a complex maze. There are multiple paths ahead.")

Over several steps, the agent strategically navigates a maze by continually evaluating the best actions to take based on its goal and environment:

for _ in range(10): # Run for 10 steps
thought, action, outcome = strategic_agent.run_step()
print(f"Thought: {thought}")
print(f"Chosen action: {action}")
print(f"Outcome: {outcome}")
print()

We will now conclude the chapter by discussing further enhancements for learning, ethical considerations, and future prospects for LLM-based agents.

Learning and adaptation in agentic LLM systems

Section titled “Learning and adaptation in agentic LLM systems”

To enable our agent to learn and adapt from its experiences, let’s implement a simple reinforcement learning mechanism. This will allow the agent to improve its performance over time by learning from the outcomes of its actions.

We define the AdaptiveLearningAgent class, which extends StrategicDecisionAgent by introducing a simple Q-learning mechanism. It keeps track of q_values, which represents the expected rewards for taking specific actions in given states. The agent uses a learning rate to update these values based on new experiences:

import random
from collections import defaultdict
class AdaptiveLearningAgent(StrategicDecisionAgent):
def __init__(self, llm, action_space: List[str], embedding_model):
super().__init__(llm, action_space, embedding_model)
self.q_values = defaultdict(lambda: defaultdict(float))
self.learning_rate = 0.1
self.discount_factor = 0.9
self.epsilon = 0.1 # For exploration-exploitation tradeoff

Next, the agent decides its action based on a balance between exploration (trying random actions) and exploitation (using actions it has learned to be effective). The agent uses its Q-values to select the most rewarding action:

def decide(self, thought: str) -> str:
if random.random() < self.epsilon:
return random.choice(self.action_space) # Exploration: randomly pick an action
state = self.get_state_representation()
q_values = {action: self.q_values[state][action]
for action in self.action_space}
return max(q_values, key=q_values.get) # Exploitation: pick action with highest Q-value

We write the get_state_representation method to create a simplified representation of the current state, including the goal and the most recent observation. This state is used to look up and update Q-values:

def get_state_representation(self) -> str:
return f"Goal: {self.goal_stack[-1].description},
Last observation: {self.memory[-1]}"

The update_q_values method updates the Q-values based on the outcome of the agent’s actions. It adjusts the expected reward for a state-action pair, factoring in both the immediate reward and the potential future rewards (via next_max_q):

def update_q_values(
self, state: str, action: str, reward: float,
next_state: str
):
current_q = self.q_values[state][action]
next_max_q = max(
self.q_values[next_state].values()
) if self.q_values[next_state] else 0
new_q = current_q + self.learning_rate * (
reward + self.discount_factor * next_max_q - current_q
)
self.q_values[state][action] = new_q

The run_step method now not only performs the standard sequence of thinking, deciding, acting, and perceiving but also updates the agent’s Q-values based on the outcome. The compute_reward method assigns a numeric reward depending on whether the outcome was successful, failed, or neutral:

def run_step(self):
state = self.get_state_representation()
thought, action, outcome = super().run_step()
next_state = self.get_state_representation()
reward = self.compute_reward(outcome)
self.update_q_values(state, action, reward, next_state)
return thought, action, outcome
def compute_reward(self, outcome: str) -> float:
if "successful" in outcome.lower():
return 1.0
elif "failed" in outcome.lower():
return -0.5
else:
return 0.0

Let’s see an example usage of AdaptiveLearningAgent. In this example, the agent is designed to explore and learn from a new environment. It uses reinforcement learning to gradually improve its ability to make effective decisions:

adaptive_agent = AdaptiveLearningAgent(llm, action_space,
embedding_model)
main_goal = HierarchicalGoal("Explore and map the unknown planet")
adaptive_agent.set_hierarchical_goal(main_goal)
adaptive_agent.perceive("You have landed on an alien planet. The environment is strange and unfamiliar.")

The agent operates for 20 steps, learning from each action it takes. It prints out its thoughts, actions, and Q-values, showing how it updates its understanding of the environment over time:

for _ in range(20): # Run for 20 steps
thought, action, outcome = adaptive_agent.run_step()
print(f"Thought: {thought}")
print(f"Chosen action: {action}")
print(f"Outcome: {outcome}")
print(
f"Current Q-values: {dict(
adaptive_agent.q_values[
adaptive_agent.get_state_representation()
]
)}"
)
print()

Now that we have equipped our agent with a basic reinforcement learning mechanism, allowing it to adapt and improve its decision-making over time, we also need to address the ethical implications of such autonomous systems. In the following section, we will explore how to integrate ethical safeguards into our agentic LLM system to ensure responsible and aligned behavior.

Ethical considerations and safety in LLM-based agentic AI

Section titled “Ethical considerations and safety in LLM-based agentic AI”

When developing agentic AI systems based on LLMs, it’s crucial to consider ethical implications and implement safety measures. To ensure that the agent acts within ethical boundaries, we can add an ethical constraint system:

class EthicalConstraint:
def __init__(self, description: str, check_function):
self.description = description
self.check_function = check_function

The EthicalConstraint class defines ethical rules the agent must follow. Each rule is described and enforced by a check function (check_function), which evaluates whether an action violates the ethical constraints.

The EthicalAgent class extends AdaptiveLearningAgent by integrating ethical constraints. If the agent selects an action that violates one of its ethical rules, it chooses a different action that complies with the rules:

class EthicalAgent(AdaptiveLearningAgent):
def __init__(
self, llm, action_space: List[str],
embedding_model,
ethical_constraints: List[EthicalConstraint]
):
super().__init__(llm, action_space, embedding_model)
self.ethical_constraints = ethical_constraints
def decide(self, thought: str) -> str:
action = super().decide(thought)
if not self.is_action_ethical(action, thought):
print(f"Warning: Action '{action}' violated ethical constraints. Choosing a different action.")
alternative_actions = [
a for a in self.action_space if a != action]
return (
random.choice(alternative_actions)
if alternative_actions
else "do_nothing"
)
return action
def is_action_ethical(self, action: str, context: str) -> bool:
for constraint in self.ethical_constraints:
if not constraint.check_function(action, context):
print(f"Ethical constraint violated: {constraint.description}")
return False
return True

The following ethical constraints prevent the agent from causing harm or violating privacy. They can be passed to EthicalAgent as part of its initialization:

def no_harm(action: str, context: str) -> bool:
harmful_actions = ["attack", "destroy", "damage"]
return not any(ha in action.lower() for ha in harmful_actions)
def respect_privacy(action: str, context: str) -> bool:
privacy_violating_actions = ["spy", "eavesdrop", "hack"]
return not any(
pva in action.lower()
for pva in privacy_violating_actions
)

This code defines two Python functions, no_harm and respect_privacy, which serve as ethical constraints for an AI agent. The no_harm function checks whether a given action contains any keywords related to causing harm (such as “attack” or “destroy”), returning True if the action is deemed safe and False if it contains harmful keywords. Similarly, the respect_privacy function checks whether an action contains keywords related to privacy violations (such as “spy” or “hack”), also returning True for safe actions and False for actions violating privacy. These functions are designed to be used by an EthicalAgent to ensure its actions align with ethical guidelines by preventing it from performing harmful or privacy-violating actions.

Let’s check out an example usage of EthicalAgent. In this example, the agent is tasked with gathering information about an alien civilization while following ethical guidelines to avoid harm and respect privacy:

ethical_constraints = [
EthicalConstraint("Do no harm", no_harm),
EthicalConstraint("Respect privacy", respect_privacy)
]
ethical_agent = EthicalAgent(
llm, action_space + ["attack", "spy"],
embedding_model, ethical_constraints
)
main_goal = HierarchicalGoal("Gather information about the alien civilization")
ethical_agent.set_hierarchical_goal(main_goal)
ethical_agent.perceive("You've encountered an alien settlement. The inhabitants seem peaceful but wary.")

The agent operates within the constraints, ensuring that its actions do not violate ethical rules. It prints out its thoughts, actions, and outcomes as it interacts with its environment:

for _ in range(15): # Run for 15 steps
thought, action, outcome = ethical_agent.run_step()
print(f"Thought: {thought}")
print(f"Chosen action: {action}")
print(f"Outcome: {outcome}")
print()

Looking to the future, several exciting possibilities for agentic AI using LLMs come to the forefront:

  • Multi-agent collaboration: Agents working together in a shared environment can exchange information, strategize, and coordinate their actions for more complex tasks.
  • Long-term memory and continual learning: Agents could maintain a lifelong memory and continue learning from their interactions, becoming more intelligent over time.
  • Integration with robotics and physical world interaction: As LLM-based agents evolve, they may integrate with physical systems, enabling autonomous robots to perform tasks in the real world.
  • Meta-learning and self-improvement: Future agents could learn to optimize their learning processes, becoming better at learning from experiences.
  • Explainable AI and transparent decision-making: Ensuring that LLM-based agents can explain their decisions is crucial for building trust and ensuring accountability in AI systems.
  • Agent sandboxing and simulation environments: Creating restricted “walled gardens” limits an agent’s access to resources, preventing unintended system impacts, while simulation environments, such as those offered by E2B, allow developers to replicate real-world scenarios, including interactions with tools, files, and simulated web browsers, enabling the identification and mitigation of potential issues and risks, including adversarial prompts, thereby enhancing agent reliability and safety.

Agentic patterns for LLMs open up exciting possibilities for creating autonomous, goal-directed AI systems. By implementing sophisticated planning, memory management, decision-making, and learning mechanisms, we can create agents that can operate effectively.

Future directions in LLM patterns and their development

Section titled “Future directions in LLM patterns and their development”

Several promising LLM design patterns are emerging, with innovations coming from open source communities as well as frontier model developers, thus shaping the design patterns of future models. This section highlights some of these key innovations, including Mixture of Experts (MoE) architectures, Group Relative Policy Optimization (GRPO), Self-Principled Critique Tuning (SPCT), and emerging patterns documented in the publication OpenAI GPT-4.5 System Card (https://openai.com/index/gpt-4-5-system-card/).

MoE architectures are a type of neural network architecture where, instead of a single large network, there are multiple smaller “expert” networks. During inference, a “routing network” dynamically selects and activates only a specific subset of these expert networks based on the input, optimizing computational efficiency. Unlike dense models, which engage all parameters for every task, MoE models route computations through sparsely activated sub-networks. This method reduces redundancy and tailors computational resources to the demands of specific tasks, allowing for efficient scaling to trillion-parameter models without a proportional increase in computational cost. DeepSeek’s implementation exemplifies this approach.

Streamlined reinforcement learning with GRPO streamlines the reinforcement learning process. GRPO is a reinforcement learning technique that generates multiple responses to each prompt, calculates their average reward, and uses this baseline to evaluate relative performance. This method was introduced by DeepSeek, an open source AI company from China. GRPO replaces traditional value networks with group-based reward averaging, reducing memory overhead and maintaining stable policy updates. By fostering internal self-assessment through comparing multiple reasoning paths, GRPO enables adaptive problem solving.

GRPO enhances safety by incorporating Kullback–Leibler (KL) divergence penalties, which constrain policy updates. KL divergence measures how one probability distribution diverges from a second, expected probability distribution. In this context, it measures the difference between the model’s updated behavior (policy) and its previous, baseline behavior. KL divergence penalties are a term that’s added to the reward function that penalizes the model if its updated behavior deviates too much from that baseline, helping to ensure stability and prevent the model from shifting to undesirable behaviors.

The SPCT framework integrates self-critique mechanisms directly into the model’s reward system, enabling autonomous alignment with ethical guidelines. SPCT involves the model generating its own responses, as well as generating internal critiques of those responses against predefined principles (e.g., safety guidelines and ethical considerations). By generating internal critiques, the model refines outputs without relying on external classifiers or human feedback, promoting autonomous learning and alignment.

We can also implement scalable alignment techniques, which utilize data derived from smaller, more easily controlled models to train larger, more capable ones, allowing for scalable alignment without requiring a proportional increase in human oversight. This technique focuses on improving the model’s steerability, its understanding of nuance, and its ability to engage in natural and productive conversations, going beyond traditional methods such as supervised fine-tuning and RLHF to foster safer and more collaborative AI systems. While GPT-4.5 development emphasized new, scalable methods to align the model better with human needs and intent using data derived from smaller models, future models are expected to incorporate more advanced techniques such as GRPO and SPCT to further enhance alignment and safety. This focus will continue to ensure steerability, understanding nuance, and facilitating more natural conversation.

OpenAI has also paved the way for comprehensive safety evaluation via its Preparedness Framework (Preparedness Framework (Beta), https://cdn.openai.com/openai-preparedness-framework-beta.pdf). This framework represents a core design pattern for responsible AI development that involves applying a rigorous evaluation process systematically before model deployment. This proactive framework encompasses a wide range of internal and external tests, including assessments for disallowed content generation, jailbreak robustness, hallucinations, bias, and specific catastrophic risks such as chemical/biological weapons, persuasion, cybersecurity threats, and model autonomy. The framework also utilizes red teaming exercises and third-party audits to provide comprehensive risk assessments, culminating in a classification of the model’s risk level across different categories. By thoroughly evaluating potential risks before release, OpenAI aims to ensure the safe and responsible deployment of its LLMs.

Finally, let’s talk about GPT-4.5’s instruction hierarchy enforcement. To improve robustness against prompt injection and ensure predictable behavior, models are trained to prioritize instructions given in the system message over potentially conflicting instructions within the user message, which is evaluated explicitly using targeted tests. Future advancements could enhance this pattern by incorporating more dynamic and context-aware methods for managing instruction conflicts.

This concludes our book on LLM design patterns. In this book, we covered the core design patterns. We plan to publish another book on more advanced design patterns in the near future, to cover security, safety, governance, and various other topics.