[BUFG][Majority Voting]

pull/415/head
Kye 11 months ago
parent b679ae9521
commit e38f48d3cc

@ -599,6 +599,54 @@ print(inference)
``` ```
## Majority Voting
Multiple-agents will evaluate an idea based off of an parsing or evaluation function. From papers like "[More agents is all you need](https://arxiv.org/pdf/2402.05120.pdf)
```python
from swarms import Agent, MajorityVoting, ChromaDB, Anthropic
# Initialize the llm
llm = Anthropic()
# Agents
agent1 = Agent(
llm = llm,
system_prompt="You are the leader of the Progressive Party. What is your stance on healthcare?",
agent_name="Progressive Leader",
agent_description="Leader of the Progressive Party",
long_term_memory=ChromaDB(),
max_steps=1,
)
agent2 = Agent(
llm=llm,
agent_name="Conservative Leader",
agent_description="Leader of the Conservative Party",
long_term_memory=ChromaDB(),
max_steps=1,
)
agent3 = Agent(
llm=llm,
agent_name="Libertarian Leader",
agent_description="Leader of the Libertarian Party",
long_term_memory=ChromaDB(),
max_steps=1,
)
# Initialize the majority voting
mv = MajorityVoting(
agents=[agent1, agent2, agent3],
output_parser=llm.majority_voting,
autosave=False,
verbose=True,
)
# Start the majority voting
mv.run("What is your stance on healthcare?")
```
## Real-World Deployment ## Real-World Deployment
### Multi-Agent Swarm for Logistics ### Multi-Agent Swarm for Logistics

@ -0,0 +1,42 @@
from swarms import Agent, MajorityVoting, ChromaDB, Anthropic
# Initialize the llm
llm = Anthropic()
# Agents
agent1 = Agent(
llm = llm,
system_prompt="You are the leader of the Progressive Party. What is your stance on healthcare?",
agent_name="Progressive Leader",
agent_description="Leader of the Progressive Party",
long_term_memory=ChromaDB(),
max_steps=1,
)
agent2 = Agent(
llm=llm,
agent_name="Conservative Leader",
agent_description="Leader of the Conservative Party",
long_term_memory=ChromaDB(),
max_steps=1,
)
agent3 = Agent(
llm=llm,
agent_name="Libertarian Leader",
agent_description="Leader of the Libertarian Party",
long_term_memory=ChromaDB(),
max_steps=1,
)
# Initialize the majority voting
mv = MajorityVoting(
agents=[agent1, agent2, agent3],
output_parser=llm.majority_voting,
autosave=False,
verbose=True,
)
# Start the majority voting
mv.run("What is your stance on healthcare?")

@ -1,21 +0,0 @@
from swarms import Agent, MajorityVoting, OpenAIChat
# Initialize the llm
llm = OpenAIChat()
# Initialize the agents
agent1 = Agent(agent_name="worker-1", llm=llm, max_loops=1)
agent2 = Agent(agent_name="worker-2", llm=llm, max_loops=1)
agent3 = Agent(agent_name="worker3", llm=llm, max_loops=1)
# Initialize the majority voting
mv = MajorityVoting(
agents=[agent1, agent2, agent3],
concurrent=True,
multithreaded=True,
)
# Start the majority voting
mv.run("What is the capital of France?")

@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api"
[tool.poetry] [tool.poetry]
name = "swarms" name = "swarms"
version = "4.2.7" version = "4.2.8"
description = "Swarms - Pytorch" description = "Swarms - Pytorch"
license = "MIT" license = "MIT"
authors = ["Kye Gomez <kye@apac.ai>"] authors = ["Kye Gomez <kye@apac.ai>"]

@ -17,3 +17,4 @@ from swarms.telemetry import * # noqa: E402, F403
from swarms.tokenizers import * # noqa: E402, F403 from swarms.tokenizers import * # noqa: E402, F403
from swarms.tools import * # noqa: E402, F403 from swarms.tools import * # noqa: E402, F403
from swarms.utils import * # noqa: E402, F403 from swarms.utils import * # noqa: E402, F403
from swarms.memory import * # noqa: E402, F403

@ -33,7 +33,8 @@ def get_gemini_api_key_env():
key = os.getenv("GEMINI_API_KEY") key = os.getenv("GEMINI_API_KEY")
if key is None: if key is None:
raise ValueError("Please provide a Gemini API key") raise ValueError("Please provide a Gemini API key")
return key return str(key)
# Main class # Main class

@ -1,15 +1,14 @@
import asyncio
import concurrent.futures import concurrent.futures
import re import re
import sys import sys
from collections import Counter from collections import Counter
from multiprocessing import Pool from typing import Any, Callable, List, Optional
from typing import Any, List
from loguru import logger from loguru import logger
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.conversation import Conversation from swarms.structs.conversation import Conversation
from swarms.utils.file_processing import create_file
# Configure loguru logger with advanced settings # Configure loguru logger with advanced settings
logger.remove() logger.remove()
@ -96,7 +95,6 @@ def most_frequent(
for i in clist: for i in clist:
current_frequency = sum(cmp_func(i, item) for item in clist) current_frequency = sum(cmp_func(i, item) for item in clist)
print(current_frequency)
if current_frequency > counter: if current_frequency > counter:
counter = current_frequency counter = current_frequency
num = i num = i
@ -104,7 +102,7 @@ def most_frequent(
return num, counter return num, counter
def majority_voting(answers: list): def majority_voting(answers: List[str]):
""" """
Performs majority voting on a list of answers and returns the most common answer. Performs majority voting on a list of answers and returns the most common answer.
@ -115,7 +113,12 @@ def majority_voting(answers: list):
The most common answer in the list. The most common answer in the list.
""" """
counter = Counter(answers) counter = Counter(answers)
answer = counter.most_common(1)[0][0] if counter:
answer = counter.most_common(1)[0][0]
else:
answer = "I don't know"
return answer return answer
@ -124,13 +127,11 @@ class MajorityVoting:
Class representing a majority voting system for agents. Class representing a majority voting system for agents.
Args: Args:
agents (List[Agent]): A list of agents to use in the majority voting system. agents (list): A list of agents to be used in the majority voting system.
concurrent (bool, optional): Whether to run the agents concurrently. Defaults to False. output_parser (function, optional): A function used to parse the output of the agents.
multithreaded (bool, optional): Whether to run the agents using multithreading. Defaults to False. If not provided, the default majority voting function is used.
multiprocess (bool, optional): Whether to run the agents using multiprocessing. Defaults to False. autosave (bool, optional): A boolean indicating whether to autosave the conversation to a file.
asynchronous (bool, optional): Whether to run the agents asynchronously. Defaults to False. verbose (bool, optional): A boolean indicating whether to enable verbose logging.
output_parser (callable, optional): A callable function to parse the output of the majority voting system. Defaults to None.
Examples: Examples:
>>> from swarms.structs.agent import Agent >>> from swarms.structs.agent import Agent
>>> from swarms.structs.majority_voting import MajorityVoting >>> from swarms.structs.majority_voting import MajorityVoting
@ -148,21 +149,13 @@ class MajorityVoting:
def __init__( def __init__(
self, self,
agents: List[Agent], agents: List[Agent],
concurrent: bool = False, output_parser: Optional[Callable] = majority_voting,
multithreaded: bool = False,
multiprocess: bool = False,
asynchronous: bool = False,
output_parser: callable = None,
autosave: bool = False, autosave: bool = False,
verbose: bool = False, verbose: bool = False,
*args, *args,
**kwargs, **kwargs,
): ):
self.agents = agents self.agents = agents
self.concurrent = concurrent
self.multithreaded = multithreaded
self.multiprocess = multiprocess
self.asynchronous = asynchronous
self.output_parser = output_parser self.output_parser = output_parser
self.autosave = autosave self.autosave = autosave
self.verbose = verbose self.verbose = verbose
@ -173,7 +166,7 @@ class MajorityVoting:
# If autosave is enabled, save the conversation to a file # If autosave is enabled, save the conversation to a file
if self.autosave: if self.autosave:
self.conversation.save() create_file(str(self.conversation), "majority_voting.json")
# Log the agents # Log the agents
logger.info("Initializing majority voting system") logger.info("Initializing majority voting system")
@ -198,69 +191,37 @@ class MajorityVoting:
""" """
# Route to each agent # Route to each agent
if self.concurrent: with concurrent.futures.ThreadPoolExecutor() as executor:
with concurrent.futures.ThreadPoolExecutor() as executor: logger.info("Running agents concurrently")
# Log the agents
logger.info("Running agents concurrently") futures = [
futures = [ executor.submit(agent.run, task, *args)
executor.submit(agent.run, task, *args)
for agent in self.agents
]
results = [
future.result()
for future in concurrent.futures.as_completed(
futures
)
]
elif self.multithreaded:
logger.info("Running agents using multithreading")
with concurrent.futures.ThreadPoolExecutor() as executor:
results = [
executor.submit(agent.run, task, *args)
for agent in self.agents
]
results = [future.result() for future in results]
elif self.multiprocess:
logger.info("Running agents using multiprocessing")
with Pool() as pool:
results = pool.starmap(
Agent.run,
[(agent, task, *args) for agent in self.agents],
)
elif self.asynchronous:
loop = asyncio.get_event_loop()
tasks = [
loop.run_in_executor(None, agent.run, task, *args)
for agent in self.agents for agent in self.agents
] ]
results = loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
else:
results = [ results = [
agent.run(task, *args) for agent in self.agents future.result()
for future in concurrent.futures.as_completed(futures)
] ]
# Add responses to conversation and log them # Add responses to conversation and log them
for agent, response in zip(self.agents, results): for agent, response in zip(self.agents, results):
logger.info(f"[{agent.agent_id}][{response}]") response = response if isinstance(response, list) else [response]
response = (
response if isinstance(response, list) else [response]
)
self.conversation.add(agent.agent_name, response) self.conversation.add(agent.agent_name, response)
logger.info(f"[{agent.agent_id}][{response}]") logger.info(f"[Agent][Name: {agent.agent_name}][Response: {response}]")
# Perform majority voting on the conversation # Perform majority voting on the conversation
majority_vote = majority_voting(self.conversation.responses) responses = [
message["content"]
# Log the majority vote for message in self.conversation.conversation_history
logger.info(f"Majority vote: {majority_vote}") if message["role"] == "agent"
]
# If an output parser is provided, parse the output
if self.output_parser: # If an output parser is provided, parse the responses
majority_vote = self.output_parser( if self.output_parser is not None:
majority_vote, *args, **kwargs majority_vote = self.output_parser(responses, *args, **kwargs)
) else:
majority_vote = majority_voting(responses)
# Return the majority vote # Return the majority vote
return majority_vote return majority_vote

Loading…
Cancel
Save