Repository navigation
Expand file tree
/
Copy pathexample_multi_agent_caching.py
More file actions
344 lines (283 loc) · 11.2 KB
/
Copy pathexample_multi_agent_caching.py
File metadata and controls
344 lines (283 loc) · 11.2 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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
"""
Multi-Agent Caching Example - Super Fast Agent Loading
This example demonstrates how to use the agent caching system with multiple agents
to achieve 10-100x speedup in agent loading and reuse.
"""
import time
from swarms import Agent
from swarms.utils.agent_cache import (
cached_agent_loader,
simple_lru_agent_loader,
AgentCache,
get_agent_cache_stats,
clear_agent_cache,
)
def create_trading_team():
"""Create a team of trading agents."""
# Create multiple agents for different trading strategies
agents = [
Agent(
agent_name="Quantitative-Trading-Agent",
agent_description="Advanced quantitative trading and algorithmic analysis agent",
system_prompt="""You are an expert quantitative trading agent with deep expertise in:
- Algorithmic trading strategies and implementation
- Statistical arbitrage and market making
- Risk management and portfolio optimization
- High-frequency trading systems
- Market microstructure analysis""",
max_loops=1,
model_name="gpt-5.4",
temperature=0.1,
),
Agent(
agent_name="Risk-Management-Agent",
agent_description="Portfolio risk assessment and management specialist",
system_prompt="""You are a risk management specialist focused on:
- Portfolio risk assessment and stress testing
- Value at Risk (VaR) calculations
- Regulatory compliance monitoring
- Risk mitigation strategies
- Capital allocation optimization""",
max_loops=1,
model_name="gpt-5.4",
temperature=0.2,
),
Agent(
agent_name="Market-Analysis-Agent",
agent_description="Real-time market analysis and trend identification",
system_prompt="""You are a market analysis expert specializing in:
- Technical analysis and chart patterns
- Market sentiment analysis
- Economic indicator interpretation
- Trend identification and momentum analysis
- Support and resistance level identification""",
max_loops=1,
model_name="gpt-5.4",
temperature=0.3,
),
Agent(
agent_name="Options-Trading-Agent",
agent_description="Options strategies and derivatives trading specialist",
system_prompt="""You are an options trading specialist with expertise in:
- Options pricing models and Greeks analysis
- Volatility trading strategies
- Complex options spreads and combinations
- Risk-neutral portfolio construction
- Derivatives market making""",
max_loops=1,
model_name="gpt-5.4",
temperature=0.15,
),
Agent(
agent_name="ESG-Investment-Agent",
agent_description="ESG-focused investment analysis and screening",
system_prompt="""You are an ESG investment specialist focusing on:
- Environmental, Social, and Governance criteria evaluation
- Sustainable investment screening
- Impact investing strategies
- ESG risk assessment
- Green finance and climate risk analysis""",
max_loops=1,
model_name="gpt-5.4",
temperature=0.25,
),
]
return agents
def basic_caching_example():
"""Basic example of caching multiple agents."""
print("=== Basic Multi-Agent Caching Example ===")
# Create our trading team
trading_team = create_trading_team()
print(f"Created {len(trading_team)} trading agents")
# First load - agents will be processed and cached
print("\n🔄 First load (will cache agents)...")
start_time = time.time()
cached_team_1 = cached_agent_loader(trading_team)
first_load_time = time.time() - start_time
print(
f"✅ First load: {len(cached_team_1)} agents in {first_load_time:.3f}s"
)
# Second load - agents will be retrieved from cache (super fast!)
print("\n⚡ Second load (from cache)...")
start_time = time.time()
cached_team_2 = cached_agent_loader(trading_team)
second_load_time = time.time() - start_time
print(
f"🚀 Second load: {len(cached_team_2)} agents in {second_load_time:.3f}s"
)
print(
f"💨 Speedup: {first_load_time/second_load_time:.1f}x faster!"
)
# Show cache statistics
stats = get_agent_cache_stats()
print(f"📊 Cache stats: {stats}")
return cached_team_1
def custom_cache_example():
"""Example using a custom cache for specific use cases."""
print("\n=== Custom Cache Example ===")
# Create a custom cache with specific settings
custom_cache = AgentCache(
max_memory_cache_size=50, # Cache up to 50 agents
cache_dir="trading_team_cache", # Custom cache directory
enable_persistent_cache=True, # Enable disk persistence
auto_save_interval=120, # Auto-save every 2 minutes
)
# Create agents
trading_team = create_trading_team()
# Load with custom cache
print("🔧 Loading with custom cache...")
start_time = time.time()
cached_team = cached_agent_loader(
trading_team,
cache_instance=custom_cache,
parallel_loading=True,
)
load_time = time.time() - start_time
print(f"✅ Loaded {len(cached_team)} agents in {load_time:.3f}s")
# Get custom cache stats
stats = custom_cache.get_cache_stats()
print(f"📊 Custom cache stats: {stats}")
# Cleanup
custom_cache.shutdown()
return cached_team
def simple_lru_example():
"""Example using the simple LRU cache approach."""
print("\n=== Simple LRU Cache Example ===")
trading_team = create_trading_team()
# First load with simple LRU
print("🔄 First load with simple LRU...")
start_time = time.time()
lru_team_1 = simple_lru_agent_loader(trading_team)
first_time = time.time() - start_time
# Second load (cached)
print("⚡ Second load with simple LRU...")
start_time = time.time()
simple_lru_agent_loader(trading_team)
cached_time = time.time() - start_time
print(
f"📈 Simple LRU - First: {first_time:.3f}s, Cached: {cached_time:.3f}s"
)
print(f"💨 Speedup: {first_time/cached_time:.1f}x faster!")
return lru_team_1
def team_workflow_simulation():
"""Simulate a real-world workflow with the cached trading team."""
print("\n=== Team Workflow Simulation ===")
# Create and cache the team
trading_team = create_trading_team()
cached_team = cached_agent_loader(trading_team)
# Simulate multiple analysis sessions
tasks = [
"Analyze the current market conditions for AAPL",
"What are the top 3 ETFs for gold coverage?",
"Assess the risk profile of a tech-heavy portfolio",
"Identify options strategies for volatile markets",
"Evaluate ESG investment opportunities in renewable energy",
]
print(
f"🎯 Running {len(tasks)} analysis tasks with {len(cached_team)} agents..."
)
session_start = time.time()
for i, (agent, task) in enumerate(zip(cached_team, tasks)):
print(f"\n📋 Task {i+1}: {agent.agent_name}")
print(f" Question: {task}")
task_start = time.time()
# Run the agent on the task
response = agent.run(task)
task_time = time.time() - task_start
print(f" ⏱️ Completed in {task_time:.2f}s")
print(
f" 💡 Response: {response[:100]}..."
if len(response) > 100
else f" 💡 Response: {response}"
)
total_session_time = time.time() - session_start
print(f"\n🏁 Total session time: {total_session_time:.2f}s")
print(
f"📊 Average task time: {total_session_time/len(tasks):.2f}s"
)
def performance_comparison():
"""Compare performance with and without caching."""
print("\n=== Performance Comparison ===")
# Create test agents
test_agents = []
for i in range(10):
agent = Agent(
agent_name=f"Test-Agent-{i:02d}",
model_name="gpt-5.4",
system_prompt=f"You are test agent number {i}.",
max_loops=1,
)
test_agents.append(agent)
# Test without caching (creating new agents each time)
print("🔄 Testing without caching...")
no_cache_times = []
for _ in range(3):
start_time = time.time()
# Simulate creating new agents each time
new_agents = []
for agent in test_agents:
new_agent = Agent(
agent_name=agent.agent_name,
model_name=agent.model_name,
system_prompt=agent.system_prompt,
max_loops=agent.max_loops,
)
new_agents.append(new_agent)
no_cache_time = time.time() - start_time
no_cache_times.append(no_cache_time)
avg_no_cache_time = sum(no_cache_times) / len(no_cache_times)
# Clear cache for fair comparison
clear_agent_cache()
# Test with caching (first load)
print("🔧 Testing with caching (first load)...")
start_time = time.time()
cached_agent_loader(test_agents)
first_cache_time = time.time() - start_time
# Test with caching (subsequent loads)
print("⚡ Testing with caching (subsequent loads)...")
cache_times = []
for _ in range(3):
start_time = time.time()
cached_agent_loader(test_agents)
cache_time = time.time() - start_time
cache_times.append(cache_time)
avg_cache_time = sum(cache_times) / len(cache_times)
# Results
print(f"\n📊 Performance Results for {len(test_agents)} agents:")
print(f" 🐌 No caching (avg): {avg_no_cache_time:.4f}s")
print(f" 🔧 Cached (first load): {first_cache_time:.4f}s")
print(f" 🚀 Cached (avg): {avg_cache_time:.4f}s")
print(
f" 💨 Cache speedup: {avg_no_cache_time/avg_cache_time:.1f}x faster!"
)
# Final cache stats
final_stats = get_agent_cache_stats()
print(f" 📈 Final cache stats: {final_stats}")
def main():
"""Run all examples to demonstrate multi-agent caching."""
print("🤖 Multi-Agent Caching System Examples")
print("=" * 50)
try:
# Run examples
basic_caching_example()
custom_cache_example()
simple_lru_example()
performance_comparison()
team_workflow_simulation()
print("\n✅ All examples completed successfully!")
print("\n🎯 Key Benefits of Multi-Agent Caching:")
print("• 🚀 10-100x faster agent loading from cache")
print(
"• 💾 Persistent disk cache survives application restarts"
)
print("• 🧠 Intelligent LRU memory management")
print("• 🔄 Background preloading for zero-latency access")
print("• 📊 Detailed performance monitoring")
print("• 🛡️ Thread-safe with memory leak prevention")
print("• ⚡ Parallel processing for multiple agents")
except Exception as e:
print(f"❌ Error running examples: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()