From 16c8fe076b67eb87449424b8cfec5187dedb2a71 Mon Sep 17 00:00:00 2001 From: Kye Date: Fri, 11 Aug 2023 22:47:32 -0400 Subject: [PATCH] boss node fix cleanup Former-commit-id: 3b1e51a20703f656db55cdab9a21c8b79c9c1d88 --- .readthedocs.yaml | 32 -------------- swarms/agents/base.py | 12 +++--- swarms/boss/boss_node.py | 74 +++++++++++++++++++++------------ swarms/workers/vortex_worker.py | 2 +- 4 files changed, 53 insertions(+), 67 deletions(-) delete mode 100644 .readthedocs.yaml diff --git a/.readthedocs.yaml b/.readthedocs.yaml deleted file mode 100644 index 9cfe617a..00000000 --- a/.readthedocs.yaml +++ /dev/null @@ -1,32 +0,0 @@ -# .readthedocs.yaml -# Read the Docs configuration file -# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details - -# Required -version: 2 - -# Set the OS, Python version and other tools you might need -build: - os: ubuntu-22.04 - tools: - python: "3.11" - # You can also specify other tool versions: - # nodejs: "19" - # rust: "1.64" - # golang: "1.19" - -# Build documentation in the "docs/" directory with Sphinx -sphinx: - configuration: docs/conf.py - -# Optionally build your docs in additional formats such as PDF and ePub -# formats: -# - pdf -# - epub - -# Optional but recommended, declare the Python requirements required -# to build your documentation -# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html -# python: -# install: -# - requirements: docs/requirements.txt \ No newline at end of file diff --git a/swarms/agents/base.py b/swarms/agents/base.py index 6c7122d6..51f3cb31 100644 --- a/swarms/agents/base.py +++ b/swarms/agents/base.py @@ -7,20 +7,18 @@ from pydantic import ValidationError from swarms.agents.memory.base import VectorStoreRetriever from swarms.agents.memory.base_memory import BaseChatMessageHistory, ChatMessageHistory - from swarms.agents.memory.document import Document from swarms.agents.models.base import AbstractModel - -from swarms.agents.models.prompts.base import ( - AIMessage, - HumanMessage, - SystemMessage, -) from swarms.agents.models.prompts.agent_prompt_auto import ( MessageFormatter, PromptConstructor, ) from swarms.agents.models.prompts.agent_prompt_generator import FINISH_NAME +from swarms.agents.models.prompts.base import ( + AIMessage, + HumanMessage, + SystemMessage, +) from swarms.agents.tools.base import BaseTool from swarms.agents.utils.Agent import AgentOutputParser from swarms.agents.utils.human_input import HumanInputRun diff --git a/swarms/boss/boss_node.py b/swarms/boss/boss_node.py index e36fa07c..f91bf615 100644 --- a/swarms/boss/boss_node.py +++ b/swarms/boss/boss_node.py @@ -104,18 +104,19 @@ class BossNodeInitializer: class BossNode: def __init__(self, - # vectorstore, + llm=None, + vectorstore=None, + agent_executor=None, + max_iterations=5, + human_in_the_loop=None, objective: Optional[str] = None, boss_system_prompt: Optional[str] = "You are a boss planner in a swarm...", api_key=None, worker_node=None, llm_class=OpenAI, - max_iterations=5, verbose=False, ): - self.api_key = api_key or os.getenv("OPENAI_API_KEY") - # self.vectorstore = vectorstore self.worker_node = worker_node self.boss_system_prompt = boss_system_prompt self.llm_class = llm_class @@ -123,54 +124,73 @@ class BossNode: self.verbose = verbose if not self.api_key: - raise ValueError("[BossNode][ValueError][API KEY must be provided either as an argument or as an environment variable API_KEY]") - - self.llm = self.initialize_llm(self.llm_class) + raise ValueError("[MasterBossNode][ValueError][API KEY must be provided either as an argument or as an environment variable API_KEY]") + + # Initialize components if not provided + self.llm = llm if llm else self._initialize_llm(self.llm_class) + self.vectorstore = vectorstore if vectorstore else self._initialize_vectorstore() + # Setting up todo_chain and agent_executor todo_prompt = PromptTemplate.from_template(boss_system_prompt) todo_chain = LLMChain(llm=self.llm, prompt=todo_prompt) - tools = [ Tool(name="TODO", func=todo_chain.run, description="useful for when you need to come up with todo lists..."), self.worker_node ] suffix = """Question: {task}\n{agent_scratchpad}""" prefix = """You are a Boss in a swarm who performs one task based on the following objective: {objective}. Take into account these previously completed tasks: {context}.\n """ - prompt = ZeroShotAgent.create_prompt(tools, prefix=prefix, suffix=suffix, input_variables=["objective", "task", "context", "agent_scratchpad"],) llm_chain = LLMChain(llm=self.llm, prompt=prompt) agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=[tool.name for tool in tools]) + self.agent_executor = agent_executor if agent_executor else AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=self.verbose) - self.agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=self.verbose) - - vectorstore = self.initialize_vectorstore() + # Setup BabyAGI + try: + self.baby_agi = BabyAGI.from_llm( + llm=self.llm, + vectorstore=self.vectorstore, + task_execution_chain=self.agent_executor, + max_iterations=self.max_iterations, + human_in_the_loop=human_in_the_loop + ) + except ValidationError as e: + logging.error(f"Validation Error while initializing BabyAGI: {e}") + raise + except Exception as e: + logging.error(f"Unexpected Error while initializing BabyAGI: {e}") + raise - self.boss_initializer = BossNodeInitializer( - llm=self.llm, - vectorstore=vectorstore, - agent_executor=self.agent_executor, - max_iterations=self.max_iterations, - ) - self.task = self.boss_initializer.create_task(objective) + self.task = self._create_task(objective) - def initialize_llm(self, llm_class, temperature=0.5): + def _initialize_llm(self, llm_class, temperature=0.5): try: return llm_class(openai_api_key=self.api_key, temperature=temperature) except Exception as e: logging.error(f"Failed to initialize language model: {e}") raise e - - def initialize_vectorstore(self): - try: - embeddings_model = OpenAIEmbeddings(openai_api_key=self.openai_api_key) + + def _initialize_vectorstore(self): + try: + embeddings_model = OpenAIEmbeddings(openai_api_key=self.api_key) embedding_size = 8192 index = faiss.IndexFlatL2(embedding_size) return FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {}) except Exception as e: logging.error(f"Failed to initialize vector store: {e}") return None - - def run(self): - self.boss_initializer.run(self.task) + def _create_task(self, objective): + if not objective: + logging.error("Objective cannot be empty.") + raise ValueError("Objective cannot be empty.") + return {"objective": objective} + def run(self): + if not self.task: + logging.error("Task cannot be empty.") + raise ValueError("Task cannot be empty.") + try: + self.baby_agi(self.task) + except Exception as e: + logging.error(f"Error while executing task: {e}") + raise \ No newline at end of file diff --git a/swarms/workers/vortex_worker.py b/swarms/workers/vortex_worker.py index efbea22d..106e0f0a 100644 --- a/swarms/workers/vortex_worker.py +++ b/swarms/workers/vortex_worker.py @@ -58,7 +58,7 @@ class VortexWorkerAgent: self.chat_history_file = chat_history_file self.llm = llm or self.init_llm(ChatOpenAI) - self.tools = self.init_tools() + self.tools = tools or self.init_tools() self.vectorstore = self.init_vectorstore() self.agent = self.create_agent()