"""
Pattern 05: Deliberative Agent Pattern
An agent that plans and reasons before acting, using symbolic representations.
"""
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from datetime import datetime
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
@dataclass
class BeliefState:
"""Symbolic representation of agent's beliefs."""
facts: Dict[str, Any] = field(default_factory=dict)
rules: List[str] = field(default_factory=list)
timestamp: datetime = field(default_factory=datetime.now)
@dataclass
class Plan:
"""A deliberated plan of actions."""
goal: str
steps: List[str]
expected_outcome: str
confidence: float
created_at: datetime = field(default_factory=datetime.now)
class DeliberativeAgentPattern:
"""
Deliberative Agent that:
- Maintains symbolic world model
- Plans before acting
- Reasons about consequences
- Uses explicit representation of knowledge
"""
def __init__(self, name: str = "DeliberativeAgent", model_name: str = "gpt-4"):
self.name = name
self.llm = ChatOpenAI(model=model_name, temperature=0.2)
self.beliefs = BeliefState()
self.plans: List[Plan] = []
self.execution_history: List[Dict[str, Any]] = []
def update_beliefs(self, fact_key: str, fact_value: Any):
"""Update the agent's belief state."""
self.beliefs.facts[fact_key] = fact_value
self.beliefs.timestamp = datetime.now()
print(f"š Belief updated: {fact_key} = {fact_value}")
def add_rule(self, rule: str):
"""Add a reasoning rule."""
self.beliefs.rules.append(rule)
print(f"š Rule added: {rule}")
def deliberate(self, goal: str) -> Plan:
"""Deliberate and create a plan to achieve a goal."""
print(f"\nš¤ Deliberating on goal: {goal}")
prompt = ChatPromptTemplate.from_messages([
("system", f"""You are {self.name}, a deliberative agent.
Carefully reason and plan before acting.
Current beliefs:
Facts: {{facts}}
Rules: {{rules}}
Create a detailed, step-by-step plan."""),
("human", "Goal: {goal}\n\nProvide a deliberated plan with steps and expected outcome:")
])
chain = prompt | self.llm
response = chain.invoke({
"facts": str(self.beliefs.facts),
"rules": str(self.beliefs.rules),
"goal": goal
})
# Parse response into plan (simplified)
plan_text = str(response.content)
steps = [line.strip() for line in plan_text.split("\n") if line.strip() and any(char.isdigit() for char in line)]
plan = Plan(
goal=goal,
steps=steps if steps else [plan_text],
expected_outcome="Goal achieved through deliberate action",
confidence=0.8
)
self.plans.append(plan)
print(f"ā
Plan created with {len(plan.steps)} steps")
return plan
def reason_about_action(self, action: str) -> Dict[str, Any]:
"""Reason about the consequences of an action."""
prompt = ChatPromptTemplate.from_messages([
("system", f"""You are {self.name}. Reason about action consequences.
Beliefs: {{beliefs}}
Rules: {{rules}}"""),
("human", "Action: {action}\n\nAnalyze: What are the likely consequences?")
])
chain = prompt | self.llm
response = chain.invoke({
"action": action,
"beliefs": str(self.beliefs.facts),
"rules": str(self.beliefs.rules)
})
return {
"action": action,
"reasoning": str(response.content),
"beliefs_considered": len(self.beliefs.facts)
}
def execute_plan(self, plan: Plan) -> Dict[str, Any]:
"""Execute a deliberated plan."""
print(f"\nšÆ Executing plan for: {plan.goal}")
results = []
for i, step in enumerate(plan.steps, 1):
print(f" Step {i}: {step}")
# In real implementation, this would actually execute the step
# Here we simulate with reasoning
reasoning = self.reason_about_action(step)
results.append(reasoning)
execution = {
"plan": plan.goal,
"steps_executed": len(plan.steps),
"results": results,
"success": True
}
self.execution_history.append(execution)
return execution
def run(self, goal: str, initial_beliefs: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""
Main execution: deliberate and execute a plan for a goal.
Args:
goal: The goal to achieve
initial_beliefs: Optional initial beliefs to set
Returns:
Dictionary with deliberation and execution results
"""
# Set initial beliefs
if initial_beliefs:
for key, value in initial_beliefs.items():
self.update_beliefs(key, value)
# Deliberate
plan = self.deliberate(goal)
# Execute
execution = self.execute_plan(plan)
return {
"agent": self.name,
"goal": goal,
"plan": {
"steps": plan.steps,
"confidence": plan.confidence
},
"execution": execution,
"beliefs": self.beliefs.facts
}
# Example usage
if __name__ == "__main__":
print("\n=== Deliberative Agent Example ===")
# Create deliberative agent
agent = DeliberativeAgentPattern(name="ThinkBot")
# Add reasoning rules
agent.add_rule("If weather is rainy, take umbrella")
agent.add_rule("If traffic is heavy, leave early")
agent.add_rule("If meeting is important, prepare materials")
# Set initial beliefs
initial_beliefs = {
"weather": "rainy",
"traffic": "heavy",
"meeting_time": "10:00 AM",
"current_time": "8:30 AM",
"meeting_importance": "high"
}
# Run deliberative process
result = agent.run(
goal="Attend the important meeting on time",
initial_beliefs=initial_beliefs
)
print("\n=== Deliberation Results ===")
print(f"Agent: {result['agent']}")
print(f"Goal: {result['goal']}")
print(f"\nPlan (Confidence: {result['plan']['confidence']}):")
for i, step in enumerate(result['plan']['steps'], 1):
print(f" {i}. {step}")
print(f"\nExecution: {result['execution']['steps_executed']} steps completed")
Agentic Architecture Pattern: Deliberative Agent
Pattern 05: 05 Deliberative Agent – Line-by-Line Explanation
Overview
Pattern 05: Deliberative Agent Pattern An agent that plans and reasons before acting, using symbolic representations.
Code Structure Analysis
File Information
- Pattern Number: 05
- Pattern Name: 05 Deliberative Agent
- File Path:
patterns\core_agent\05_deliberative_agent.py - Total Lines: 208
Detailed Code Explanation
Module Docstring
"""
Pattern 05: Deliberative Agent Pattern
An agent that plans and reasons before acting, using symbolic representations.
"""
Explanation: This module docstring describes the purpose and key features of the 05 Deliberative Agent pattern.
Imports Section
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from datetime import datetime
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI # First 20 imports shown
Explanation: The module imports necessary dependencies:
– from typing import Dict, Any, List, Optional: Type hints for better code documentation
– from dataclasses import dataclass, field: Data class decorators for clean data structures
– from datetime import datetime: Date and time utilities
– from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration
– from langchain_openai import ChatOpenAI: LangChain framework integration
Classes
BeliefState (Line 14)
Description: Symbolic representation of agent’s beliefs.
Plan (Line 22)
Description: A deliberated plan of actions.
DeliberativeAgentPattern (Line 31)
Description: Deliberative Agent that: – Maintains symbolic world model – Plans before acting – Reasons about consequences – Uses explicit representation of knowledge
Methods:
__init__ (Line 40)
def __init__(self, name, model_name):
"""No method docstring."""
Purpose: No method docstring.
Parameters:
– self: Instance reference
– name: Identifier or label
– model_name: LLM model to use (e.g., “gpt-4”)
update_beliefs (Line 47)
def update_beliefs(self, fact_key, fact_value):
"""Update the agent's belief state."""
Purpose: Update the agent’s belief state.
Parameters:
– self: Instance reference
– fact_key: Parameter for fact_key
– fact_value: Parameter for fact_value
add_rule (Line 53)
def add_rule(self, rule):
"""Add a reasoning rule."""
Purpose: Add a reasoning rule.
Parameters:
– self: Instance reference
– rule: Parameter for rule
deliberate (Line 58)
def deliberate(self, goal):
"""Deliberate and create a plan to achieve a goal."""
Purpose: Deliberate and create a plan to achieve a goal.
Parameters:
– self: Instance reference
– goal: Parameter for goal
reason_about_action (Line 96)
def reason_about_action(self, action):
"""Reason about the consequences of an action."""
Purpose: Reason about the consequences of an action.
Parameters:
– self: Instance reference
– action: Parameter for action
execute_plan (Line 118)
def execute_plan(self, plan):
"""Execute a deliberated plan."""
Purpose: Execute a deliberated plan.
Parameters:
– self: Instance reference
– plan: Parameter for plan
run (Line 140)
def run(self, goal, initial_beliefs):
"""Main execution: deliberate and execute a plan for a goal.
Args:
goal: The goal to achieve
initial_beliefs: Optional initial beliefs to set
Returns:
Dictionary with deliberation and execution results"""
Purpose: Main execution: deliberate and execute a plan for a goal.
Args: goal: The goal to achieve initial_beliefs: Optional initial beliefs to set
Returns: Dictionary with deliberation and execution results
Parameters:
– self: Instance reference
– goal: Parameter for goal
– initial_beliefs: Parameter for initial_beliefs
Design Patterns Used
- Strategy Pattern: Different execution strategies for various scenarios
- State Pattern: Managing different states in the workflow
- Chain of Responsibility: Sequential processing through workflow nodes
- Observer Pattern: Tracking and monitoring pattern execution
- Factory Pattern: Creating instances with proper configuration
Usage Example
# Initialize the pattern
pattern = BeliefState(name="example", model_name="gpt-4")
# Configure and execute
result = pattern.execute(data={"key": "value"})
# Check results
print(result)
Key Concepts
- LLM Integration: Uses LangChain/OpenAI for intelligent decision-making
- Workflow Orchestration: LangGraph manages execution flow through nodes
- State Management: TypedDict defines workflow state structure
- Error Handling: Comprehensive error handling and fallback mechanisms
- Extensibility: Designed for easy customization and extension
Extension Points
This pattern can be extended by: 1. Adding custom workflow nodes 2. Implementing additional validation logic 3. Integrating with external services 4. Customizing LLM prompts and responses 5. Adding monitoring and logging capabilities
Leave a Reply