Skip to content

Commit 638e9e2

Browse files
committed
code cleanup op
1 parent 156bc59 commit 638e9e2

File tree

6 files changed

+109
-60
lines changed

6 files changed

+109
-60
lines changed

examples/multi_agent/agent_router_examples/agent_router_example.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,12 @@
2929
"You are a medical lab and imaging interpretation agent. Take the patient's test results, imaging findings, and vitals, "
3030
"and interpret them in context of their symptoms. Suggest relevant follow-up diagnostics or considerations for the physician."
3131
),
32-
),
32+
),
3333
],
3434
)
3535

3636
result = agent_router.run(
3737
"I have a headache, fever, and cough. What could be wrong?"
3838
)
3939

40-
print(result.agent_name)
40+
print(result.agent_name)

swarms/structs/agent_router.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,11 +83,13 @@ def _generate_embedding(self, text: str) -> List[float]:
8383
f"Unexpected embedding response structure: {type(response.data[0])}"
8484
)
8585
else:
86-
logger.error(f"Unexpected response structure: {response}")
86+
logger.error(
87+
f"Unexpected response structure: {response}"
88+
)
8789
raise ValueError(
8890
f"Unexpected embedding response structure: {type(response)}"
8991
)
90-
92+
9193
return embedding_vector
9294

9395
except Exception as e:
@@ -278,7 +280,7 @@ def find_best_agent(
278280
except Exception as e:
279281
logger.error(f"Error finding best agent: {str(e)}")
280282
raise
281-
283+
282284
def run(self, task: str) -> Optional[AgentType]:
283285
"""
284286
Run the agent router on a given task.

swarms/structs/majority_voting.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,15 @@ def reliability_check(self):
168168
title="Majority Voting",
169169
)
170170

171-
def run(self, task: str, streaming_callback: Optional[Callable[[str, str, bool], None]] = None, *args, **kwargs) -> List[Any]:
171+
def run(
172+
self,
173+
task: str,
174+
streaming_callback: Optional[
175+
Callable[[str, str, bool], None]
176+
] = None,
177+
*args,
178+
**kwargs,
179+
) -> List[Any]:
172180
"""
173181
Runs the majority voting system with multi-loop functionality and returns the majority vote.
174182
@@ -200,24 +208,30 @@ def run(self, task: str, streaming_callback: Optional[Callable[[str, str, bool],
200208
role=agent.agent_name,
201209
content=output,
202210
)
203-
211+
204212
# Set streaming_on for the consensus agent based on the provided streaming_callback
205-
self.consensus_agent.streaming_on = streaming_callback is not None
213+
self.consensus_agent.streaming_on = (
214+
streaming_callback is not None
215+
)
206216

207217
# Instead of a simple passthrough wrapper, match the callback invocation pattern from the provided reference for the consensus agent:
208218
consensus_agent_name = self.consensus_agent.agent_name
209219

210220
if streaming_callback is not None:
221+
211222
def consensus_streaming_callback(chunk: str):
212223
"""Wrapper for consensus agent streaming callback."""
213224
try:
214225
if chunk is not None and chunk.strip():
215-
streaming_callback(consensus_agent_name, chunk, False)
226+
streaming_callback(
227+
consensus_agent_name, chunk, False
228+
)
216229
except Exception as callback_error:
217230
if self.verbose:
218231
logger.warning(
219232
f"[STREAMING] Callback failed for {consensus_agent_name}: {str(callback_error)}"
220233
)
234+
221235
else:
222236
consensus_streaming_callback = None
223237

swarms/utils/pdf_to_text.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@ def pdf_to_text(pdf_path: str) -> str:
1212
FileNotFoundError: If the PDF file is not found at the specified path.
1313
Exception: If there is an error in reading the PDF file.
1414
"""
15-
15+
1616
try:
1717
import pypdf
1818
except ImportError:
19-
raise ImportError("pypdf is not installed. Please install it using `pip install pypdf`.")
19+
raise ImportError(
20+
"pypdf is not installed. Please install it using `pip install pypdf`."
21+
)
2022

2123
try:
2224
# Open the PDF file

tests/structs/test_agent_router.py

Lines changed: 67 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import pytest
1+
22
# from unittest.mock import Mock, patch
33

44
from swarms.structs.agent_router import AgentRouter
@@ -98,7 +98,7 @@ def test_generate_embedding_success():
9898
"""Test successful embedding generation with real API."""
9999
router = AgentRouter()
100100
result = router._generate_embedding("test text")
101-
101+
102102
assert result is not None
103103
assert isinstance(result, list)
104104
assert len(result) > 0
@@ -118,24 +118,28 @@ def test_add_agent_success():
118118
print_on=False,
119119
streaming_on=True,
120120
)
121-
121+
122122
router.add_agent(agent)
123123

124124
assert len(router.agents) == 1
125125
assert len(router.agent_embeddings) == 1
126126
assert len(router.agent_metadata) == 1
127127
assert router.agents[0] == agent
128128
assert router.agent_metadata[0]["name"] == "test_agent"
129-
129+
130130
# Test that agent can stream
131131
streamed_chunks = []
132-
132+
133133
def streaming_callback(chunk: str):
134134
streamed_chunks.append(chunk)
135-
136-
response = agent.run("Say hello", streaming_callback=streaming_callback)
135+
136+
response = agent.run(
137+
"Say hello", streaming_callback=streaming_callback
138+
)
137139
assert response is not None
138-
assert len(streamed_chunks) > 0 or response != "", "Agent should stream or return response"
140+
assert (
141+
len(streamed_chunks) > 0 or response != ""
142+
), "Agent should stream or return response"
139143

140144

141145
def test_add_agents_multiple():
@@ -173,17 +177,21 @@ def test_add_agents_multiple():
173177
assert len(router.agents) == 3
174178
assert len(router.agent_embeddings) == 3
175179
assert len(router.agent_metadata) == 3
176-
180+
177181
# Test that all agents can stream
178182
for agent in agents:
179183
streamed_chunks = []
180-
184+
181185
def streaming_callback(chunk: str):
182186
streamed_chunks.append(chunk)
183-
184-
response = agent.run("Say hi", streaming_callback=streaming_callback)
187+
188+
response = agent.run(
189+
"Say hi", streaming_callback=streaming_callback
190+
)
185191
assert response is not None
186-
assert len(streamed_chunks) > 0 or response != "", f"Agent {agent.agent_name} should stream or return response"
192+
assert (
193+
len(streamed_chunks) > 0 or response != ""
194+
), f"Agent {agent.agent_name} should stream or return response"
187195

188196

189197
def test_find_best_agent_success():
@@ -214,19 +222,23 @@ def test_find_best_agent_success():
214222
router.add_agent(agent2)
215223

216224
result = router.find_best_agent("Extract data from documents")
217-
225+
218226
assert result is not None
219227
assert result in [agent1, agent2]
220-
228+
221229
# Test that the found agent can stream
222230
streamed_chunks = []
223-
231+
224232
def streaming_callback(chunk: str):
225233
streamed_chunks.append(chunk)
226-
227-
response = result.run("Test task", streaming_callback=streaming_callback)
234+
235+
response = result.run(
236+
"Test task", streaming_callback=streaming_callback
237+
)
228238
assert response is not None
229-
assert len(streamed_chunks) > 0 or response != "", "Found agent should stream or return response"
239+
assert (
240+
len(streamed_chunks) > 0 or response != ""
241+
), "Found agent should stream or return response"
230242

231243

232244
def test_find_best_agent_no_agents():
@@ -253,14 +265,16 @@ def test_update_agent_history_success():
253265
)
254266

255267
router.add_agent(agent)
256-
268+
257269
# Run agent to create history
258270
streamed_chunks = []
259-
271+
260272
def streaming_callback(chunk: str):
261273
streamed_chunks.append(chunk)
262-
263-
agent.run("Hello, how are you?", streaming_callback=streaming_callback)
274+
275+
agent.run(
276+
"Hello, how are you?", streaming_callback=streaming_callback
277+
)
264278

265279
# Update agent history
266280
router.update_agent_history("test_agent")
@@ -322,7 +336,7 @@ def test_agent_router_edge_cases():
322336
def test_router_with_agent_streaming():
323337
"""Test that agents in router can stream when run."""
324338
router = AgentRouter()
325-
339+
326340
agent1 = Agent(
327341
agent_name="streaming_agent1",
328342
agent_description="Agent for testing streaming",
@@ -333,7 +347,7 @@ def test_router_with_agent_streaming():
333347
print_on=False,
334348
streaming_on=True,
335349
)
336-
350+
337351
agent2 = Agent(
338352
agent_name="streaming_agent2",
339353
agent_description="Another agent for testing streaming",
@@ -344,27 +358,32 @@ def test_router_with_agent_streaming():
344358
print_on=False,
345359
streaming_on=True,
346360
)
347-
361+
348362
router.add_agent(agent1)
349363
router.add_agent(agent2)
350-
364+
351365
# Test each agent streams
352366
for agent in router.agents:
353367
streamed_chunks = []
354-
368+
355369
def streaming_callback(chunk: str):
356370
if chunk:
357371
streamed_chunks.append(chunk)
358-
359-
response = agent.run("Tell me a short joke", streaming_callback=streaming_callback)
372+
373+
response = agent.run(
374+
"Tell me a short joke",
375+
streaming_callback=streaming_callback,
376+
)
360377
assert response is not None
361-
assert len(streamed_chunks) > 0 or response != "", f"Agent {agent.agent_name} should stream"
378+
assert (
379+
len(streamed_chunks) > 0 or response != ""
380+
), f"Agent {agent.agent_name} should stream"
362381

363382

364383
def test_router_find_and_run_with_streaming():
365384
"""Test finding best agent and running it with streaming."""
366385
router = AgentRouter()
367-
386+
368387
agent1 = Agent(
369388
agent_name="math_agent",
370389
agent_description="Handles mathematical problems",
@@ -375,7 +394,7 @@ def test_router_find_and_run_with_streaming():
375394
print_on=False,
376395
streaming_on=True,
377396
)
378-
397+
379398
agent2 = Agent(
380399
agent_name="writing_agent",
381400
agent_description="Handles writing tasks",
@@ -386,23 +405,27 @@ def test_router_find_and_run_with_streaming():
386405
print_on=False,
387406
streaming_on=True,
388407
)
389-
408+
390409
router.add_agent(agent1)
391410
router.add_agent(agent2)
392-
411+
393412
# Find best agent for a math task
394413
best_agent = router.find_best_agent("Solve 2 + 2")
395-
414+
396415
if best_agent:
397416
streamed_chunks = []
398-
417+
399418
def streaming_callback(chunk: str):
400419
if chunk:
401420
streamed_chunks.append(chunk)
402-
403-
response = best_agent.run("What is 2 + 2?", streaming_callback=streaming_callback)
421+
422+
response = best_agent.run(
423+
"What is 2 + 2?", streaming_callback=streaming_callback
424+
)
404425
assert response is not None
405-
assert len(streamed_chunks) > 0 or response != "", "Best agent should stream when run"
426+
assert (
427+
len(streamed_chunks) > 0 or response != ""
428+
), "Best agent should stream when run"
406429

407430

408431
if __name__ == "__main__":
@@ -426,12 +449,12 @@ def streaming_callback(chunk: str):
426449
test_router_with_agent_streaming,
427450
test_router_find_and_run_with_streaming,
428451
]
429-
452+
430453
# Run all tests
431454
print("Running all tests...")
432455
passed = 0
433456
failed = 0
434-
457+
435458
for test_func in tests:
436459
try:
437460
print(f"\n{'='*60}")
@@ -444,9 +467,10 @@ def streaming_callback(chunk: str):
444467
print(f"✗ FAILED: {test_func.__name__}")
445468
print(f" Error: {str(e)}")
446469
import traceback
470+
447471
traceback.print_exc()
448472
failed += 1
449-
473+
450474
print(f"\n{'='*60}")
451475
print(f"Test Summary: {passed} passed, {failed} failed")
452476
print(f"{'='*60}")

0 commit comments

Comments
 (0)