-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathanthropic_patterns_simple_demo.py
More file actions
280 lines (229 loc) · 9.11 KB
/
Copy pathanthropic_patterns_simple_demo.py
File metadata and controls
280 lines (229 loc) · 9.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
"""
Anthropic Agent Patterns - Simple Demo
Demonstrates the three new Anthropic-inspired composition patterns
without requiring actual LLM API calls.
Usage:
python examples/anthropic_patterns_simple_demo.py
Requirements:
pip install empathy-framework
"""
import asyncio
from empathy_os.orchestration import (
DelegationChainStrategy,
PromptCachedSequentialStrategy,
ToolEnhancedStrategy,
get_strategy,
)
from empathy_os.orchestration.agent_templates import AgentTemplate
# ============================================================================
# Demo: Pattern 8 - Tool-Enhanced Strategy
# ============================================================================
async def demo_tool_enhanced():
"""Demonstrate tool-enhanced pattern (single agent with tools)."""
print("\n" + "=" * 60)
print("PATTERN 8: TOOL-ENHANCED STRATEGY")
print("=" * 60)
print("\nPrinciple: Use tools over multiple agents when possible")
# Create single agent
agent = AgentTemplate(
id="code-analyzer",
role="Code Analyzer",
capabilities=["code_analysis", "file_operations"],
tier_preference="CAPABLE",
tools=[],
default_instructions="Analyze code files and report findings.",
quality_gates={},
)
# Define tools for the agent
tools = [
{
"name": "read_file",
"description": "Read file contents",
"input_schema": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
},
},
{
"name": "analyze_ast",
"description": "Parse and analyze Python AST",
"input_schema": {
"type": "object",
"properties": {"code": {"type": "string"}},
"required": ["code"],
},
},
]
# Create strategy
strategy = ToolEnhancedStrategy(tools=tools)
print(f"\n✓ Created strategy: {strategy.__class__.__name__}")
print(f"✓ Agent: {agent.role}")
print(f"✓ Tools: {len(tools)} tools available")
print("\nThis pattern is more efficient than using:")
print(" - Agent 1: File reader")
print(" - Agent 2: AST analyzer")
print(" - Agent 3: Report generator")
# ============================================================================
# Demo: Pattern 9 - Prompt-Cached Sequential Strategy
# ============================================================================
async def demo_prompt_cached_sequential():
"""Demonstrate prompt-cached sequential pattern."""
print("\n" + "=" * 60)
print("PATTERN 9: PROMPT-CACHED SEQUENTIAL STRATEGY")
print("=" * 60)
print("\nPrinciple: Cache large unchanging contexts across agent calls")
# Create three agents that will share context
agents = [
AgentTemplate(
id="security-reviewer",
role="Security Reviewer",
capabilities=["security_analysis"],
tier_preference="CAPABLE",
tools=[],
default_instructions="Review code for security issues.",
quality_gates={},
),
AgentTemplate(
id="quality-validator",
role="Quality Validator",
capabilities=["quality_assessment"],
tier_preference="CAPABLE",
tools=[],
default_instructions="Assess code quality.",
quality_gates={},
),
AgentTemplate(
id="performance-analyst",
role="Performance Analyst",
capabilities=["performance_analysis"],
tier_preference="CAPABLE",
tools=[],
default_instructions="Analyze performance.",
quality_gates={},
),
]
# Large cached context (shared across all agents)
cached_context = """
# Codebase Architecture Documentation
[Imagine 10,000 lines of architecture docs, API specs, coding standards here]
This context is cached once and shared across all 3 agents,
reducing token costs by ~60% on cache hits.
"""
# Create strategy with cached context
strategy = PromptCachedSequentialStrategy(
cached_context=cached_context, cache_ttl=3600
)
print(f"\n✓ Created strategy: {strategy.__class__.__name__}")
print(f"✓ Agents: {len(agents)} agents will share cached context")
print(f"✓ Cache TTL: {strategy.cache_ttl} seconds")
print(f"✓ Context size: {len(cached_context)} characters")
print("\nBenefit: ~60% token cost reduction with cache hits")
# ============================================================================
# Demo: Pattern 10 - Delegation Chain Strategy
# ============================================================================
async def demo_delegation_chain():
"""Demonstrate delegation chain pattern."""
print("\n" + "=" * 60)
print("PATTERN 10: DELEGATION CHAIN STRATEGY")
print("=" * 60)
print("\nPrinciple: Keep hierarchies shallow (≤3 levels)")
# Create coordinator and specialists
coordinator = AgentTemplate(
id="task-coordinator",
role="Task Coordinator",
capabilities=["coordination", "planning"],
tier_preference="PREMIUM",
tools=[],
default_instructions="Coordinate complex tasks and delegate to specialists.",
quality_gates={},
)
specialist1 = AgentTemplate(
id="architecture-specialist",
role="Architecture Specialist",
capabilities=["architecture_analysis"],
tier_preference="CAPABLE",
tools=[],
default_instructions="Analyze system architecture.",
quality_gates={},
)
specialist2 = AgentTemplate(
id="implementation-specialist",
role="Implementation Specialist",
capabilities=["code_implementation"],
tier_preference="CAPABLE",
tools=[],
default_instructions="Implement code changes.",
quality_gates={},
)
# Create strategy with max depth enforcement
strategy = DelegationChainStrategy(max_depth=3)
print(f"\n✓ Created strategy: {strategy.__class__.__name__}")
print(f"✓ Max delegation depth: {strategy.max_depth} levels (enforced)")
print(f"✓ Coordinator: {coordinator.role}")
print(f"✓ Specialists: {specialist1.role}, {specialist2.role}")
print("\nHierarchy:")
print(" Level 0: Task Coordinator (analyzes, delegates)")
print(" └─> Level 1: Architecture Specialist (designs)")
print(" └─> Level 1: Implementation Specialist (implements)")
# ============================================================================
# Demo: Strategy Registry and Factory Pattern
# ============================================================================
async def demo_registry_and_factory():
"""Demonstrate strategy registry and factory pattern."""
print("\n" + "=" * 60)
print("STRATEGY REGISTRY & FACTORY PATTERN")
print("=" * 60)
print("\nAll 10 patterns accessible via get_strategy():")
# Patterns that can be instantiated without arguments
no_arg_patterns = [
"sequential",
"parallel",
"debate",
"teaching",
"refinement",
"adaptive",
"tool_enhanced",
"prompt_cached_sequential",
"delegation_chain",
]
# Patterns that require arguments (show but don't instantiate)
arg_patterns = [
"conditional", # Requires condition and branches
]
for pattern_name in no_arg_patterns:
strategy = get_strategy(pattern_name)
is_new = pattern_name in ["tool_enhanced", "prompt_cached_sequential", "delegation_chain"]
marker = " (NEW)" if is_new else ""
print(f" ✓ {pattern_name:30s} → {strategy.__class__.__name__}{marker}")
for pattern_name in arg_patterns:
print(f" ✓ {pattern_name:30s} → ConditionalStrategy (requires args)")
# ============================================================================
# Main Demo Runner
# ============================================================================
async def main():
"""Run all pattern demonstrations."""
print("\n🚀 ANTHROPIC AGENT PATTERNS - SIMPLE DEMO")
print("Demonstrating 3 new patterns in Empathy Framework v5.1.4+\n")
try:
# Pattern 8: Tool-Enhanced
await demo_tool_enhanced()
# Pattern 9: Prompt-Cached Sequential
await demo_prompt_cached_sequential()
# Pattern 10: Delegation Chain
await demo_delegation_chain()
# Registry and Factory
await demo_registry_and_factory()
print("\n" + "=" * 60)
print("✅ ALL PATTERNS DEMONSTRATED SUCCESSFULLY")
print("=" * 60)
print("\nNext steps:")
print(" 1. Read docs/architecture/anthropic-agent-patterns.md")
print(" 2. Try: python -c 'from empathy_os.orchestration import get_strategy; print(get_strategy(\"tool_enhanced\"))'")
print(" 3. Run tests: pytest tests/unit/test_anthropic_patterns.py -v")
except Exception as e:
print(f"\n❌ Error: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
asyncio.run(main())