forked from kyegomez/swarms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunique_swarms_examples.py
306 lines (246 loc) · 8.98 KB
/
unique_swarms_examples.py
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
import asyncio
from typing import List
from swarms.structs.agent import Agent
from swarms.structs.swarming_architectures import (
broadcast,
circular_swarm,
exponential_swarm,
fibonacci_swarm,
grid_swarm,
linear_swarm,
mesh_swarm,
one_to_three,
prime_swarm,
sigmoid_swarm,
sinusoidal_swarm,
staircase_swarm,
star_swarm,
)
def create_finance_agents() -> List[Agent]:
"""Create specialized finance agents"""
return [
Agent(
agent_name="MarketAnalyst",
system_prompt="You are a market analysis expert. Analyze market trends and provide insights.",
model_name="gpt-4o-mini",
),
Agent(
agent_name="RiskManager",
system_prompt="You are a risk management specialist. Evaluate risks and provide mitigation strategies.",
model_name="gpt-4o-mini",
),
Agent(
agent_name="PortfolioManager",
system_prompt="You are a portfolio management expert. Optimize investment portfolios and asset allocation.",
model_name="gpt-4o-mini",
),
Agent(
agent_name="ComplianceOfficer",
system_prompt="You are a financial compliance expert. Ensure regulatory compliance and identify issues.",
model_name="gpt-4o-mini",
),
]
def create_healthcare_agents() -> List[Agent]:
"""Create specialized healthcare agents"""
return [
Agent(
agent_name="Diagnostician",
system_prompt="You are a medical diagnostician. Analyze symptoms and suggest potential diagnoses.",
model_name="gpt-4o-mini",
),
Agent(
agent_name="Treatment_Planner",
system_prompt="You are a treatment planning specialist. Develop comprehensive treatment plans.",
model_name="gpt-4o-mini",
),
Agent(
agent_name="MedicalResearcher",
system_prompt="You are a medical researcher. Analyze latest research and provide evidence-based recommendations.",
model_name="gpt-4o-mini",
),
Agent(
agent_name="PatientCareCoordinator",
system_prompt="You are a patient care coordinator. Manage patient care workflow and coordination.",
model_name="gpt-4o-mini",
),
]
def print_separator():
print("\n" + "=" * 50 + "\n")
def run_finance_circular_swarm():
"""Investment analysis workflow using circular swarm"""
print_separator()
print("FINANCE - INVESTMENT ANALYSIS (Circular Swarm)")
agents = create_finance_agents()
tasks = [
"Analyze Tesla stock performance for Q4 2024",
"Assess market risks and potential hedging strategies",
"Recommend portfolio adjustments based on analysis",
]
print("\nTasks:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")
result = circular_swarm(agents, tasks)
print("\nResults:")
for log in result["history"]:
print(f"\n{log['agent_name']}:")
print(f"Task: {log['task']}")
print(f"Response: {log['response']}")
def run_healthcare_grid_swarm():
"""Patient diagnosis and treatment planning using grid swarm"""
print_separator()
print("HEALTHCARE - PATIENT DIAGNOSIS (Grid Swarm)")
agents = create_healthcare_agents()
tasks = [
"Review patient symptoms: fever, fatigue, joint pain",
"Research latest treatment protocols",
"Develop preliminary treatment plan",
"Coordinate with specialists",
]
print("\nTasks:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")
result = grid_swarm(agents, tasks)
print("\nGrid swarm processing completed")
print(result)
def run_finance_linear_swarm():
"""Loan approval process using linear swarm"""
print_separator()
print("FINANCE - LOAN APPROVAL PROCESS (Linear Swarm)")
agents = create_finance_agents()[:3]
tasks = [
"Review loan application and credit history",
"Assess risk factors and compliance requirements",
"Generate final loan recommendation",
]
print("\nTasks:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")
result = linear_swarm(agents, tasks)
print("\nResults:")
for log in result["history"]:
print(f"\n{log['agent_name']}:")
print(f"Task: {log['task']}")
print(f"Response: {log['response']}")
def run_healthcare_star_swarm():
"""Complex medical case management using star swarm"""
print_separator()
print("HEALTHCARE - COMPLEX CASE MANAGEMENT (Star Swarm)")
agents = create_healthcare_agents()
tasks = [
"Complex case: Patient with multiple chronic conditions",
"Develop integrated care plan",
]
print("\nTasks:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")
result = star_swarm(agents, tasks)
print("\nResults:")
for log in result["history"]:
print(f"\n{log['agent_name']}:")
print(f"Task: {log['task']}")
print(f"Response: {log['response']}")
def run_finance_mesh_swarm():
"""Market risk assessment using mesh swarm"""
print_separator()
print("FINANCE - MARKET RISK ASSESSMENT (Mesh Swarm)")
agents = create_finance_agents()
tasks = [
"Analyze global market conditions",
"Assess currency exchange risks",
"Evaluate sector-specific risks",
"Review portfolio exposure",
]
print("\nTasks:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")
result = mesh_swarm(agents, tasks)
print("\nResults:")
for log in result["history"]:
print(f"\n{log['agent_name']}:")
print(f"Task: {log['task']}")
print(f"Response: {log['response']}")
def run_mathematical_finance_swarms():
"""Complex financial analysis using mathematical swarms"""
print_separator()
print("FINANCE - MARKET PATTERN ANALYSIS")
agents = create_finance_agents()
tasks = [
"Analyze historical market patterns",
"Predict market trends using technical analysis",
"Identify potential arbitrage opportunities",
]
print("\nTasks:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")
print("\nFibonacci Swarm Results:")
result = fibonacci_swarm(agents, tasks.copy())
print(result)
print("\nPrime Swarm Results:")
result = prime_swarm(agents, tasks.copy())
print(result)
print("\nExponential Swarm Results:")
result = exponential_swarm(agents, tasks.copy())
print(result)
def run_healthcare_pattern_swarms():
"""Patient monitoring using pattern swarms"""
print_separator()
print("HEALTHCARE - PATIENT MONITORING PATTERNS")
agents = create_healthcare_agents()
task = "Monitor and analyze patient vital signs: BP, heart rate, temperature, O2 saturation"
print(f"\nTask: {task}")
print("\nStaircase Pattern Analysis:")
result = staircase_swarm(agents, task)
print(result)
print("\nSigmoid Pattern Analysis:")
result = sigmoid_swarm(agents, task)
print(result)
print("\nSinusoidal Pattern Analysis:")
result = sinusoidal_swarm(agents, task)
print(result)
async def run_communication_examples():
"""Communication patterns for emergency scenarios"""
print_separator()
print("EMERGENCY COMMUNICATION PATTERNS")
# Finance market alert
finance_sender = create_finance_agents()[0]
finance_receivers = create_finance_agents()[1:]
market_alert = "URGENT: Major market volatility detected - immediate risk assessment required"
print("\nFinance Market Alert:")
print(f"Alert: {market_alert}")
result = await broadcast(
finance_sender, finance_receivers, market_alert
)
print("\nBroadcast Results:")
for log in result["history"]:
print(f"\n{log['agent_name']}:")
print(f"Response: {log['response']}")
# Healthcare emergency
health_sender = create_healthcare_agents()[0]
health_receivers = create_healthcare_agents()[1:4]
emergency_case = "EMERGENCY: Trauma patient with multiple injuries - immediate consultation required"
print("\nHealthcare Emergency:")
print(f"Case: {emergency_case}")
result = await one_to_three(
health_sender, health_receivers, emergency_case
)
print("\nConsultation Results:")
for log in result["history"]:
print(f"\n{log['agent_name']}:")
print(f"Response: {log['response']}")
async def run_all_examples():
"""Execute all swarm examples"""
print("\n=== SWARM ARCHITECTURE EXAMPLES ===\n")
# Finance examples
run_finance_circular_swarm()
run_finance_linear_swarm()
run_finance_mesh_swarm()
run_mathematical_finance_swarms()
# Healthcare examples
run_healthcare_grid_swarm()
run_healthcare_star_swarm()
run_healthcare_pattern_swarms()
# Communication examples
await run_communication_examples()
print("\n=== ALL EXAMPLES COMPLETED ===")
if __name__ == "__main__":
asyncio.run(run_all_examples())