@ -1,4 +1,3 @@
import os
from typing import List , Optional
from typing import List , Optional
import chromadb
import chromadb
@ -8,8 +7,17 @@ from typing import Union, Callable, Any
from swarms import Agent
from swarms import Agent
class AgentRAG :
class AgentRouter :
""" A vector database for storing and retrieving agents based on their characteristics. """
"""
Initialize the AgentRouter .
Args :
collection_name ( str ) : Name of the collection in the vector database .
persist_directory ( str ) : Directory to persist the vector database .
n_agents ( int ) : Number of agents to return in queries .
* args : Additional arguments to pass to the chromadb Client .
* * kwargs : Additional keyword arguments to pass to the chromadb Client .
"""
def __init__ (
def __init__ (
self ,
self ,
@ -19,12 +27,6 @@ class AgentRAG:
* args ,
* args ,
* * kwargs ,
* * kwargs ,
) :
) :
"""
Initialize the AgentRAG .
Args :
persist_directory ( str ) : The directory to persist the ChromaDB data .
"""
self . collection_name = collection_name
self . collection_name = collection_name
self . n_agents = n_agents
self . n_agents = n_agents
self . persist_directory = persist_directory
self . persist_directory = persist_directory
@ -44,6 +46,9 @@ class AgentRAG:
Args :
Args :
agent ( Agent ) : The agent to add .
agent ( Agent ) : The agent to add .
Raises :
Exception : If there ' s an error adding the agent to the vector database.
"""
"""
try :
try :
agent_text = f " { agent . name } { agent . description } { agent . system_prompt } "
agent_text = f " { agent . name } { agent . description } { agent . system_prompt } "
@ -65,6 +70,12 @@ class AgentRAG:
def add_agents (
def add_agents (
self , agents : List [ Union [ Agent , Callable , Any ] ]
self , agents : List [ Union [ Agent , Callable , Any ] ]
) - > None :
) - > None :
"""
Add multiple agents to the vector database .
Args :
agents ( List [ Union [ Agent , Callable , Any ] ] ) : List of agents to add .
"""
for agent in agents :
for agent in agents :
self . add_agent ( agent )
self . add_agent ( agent )
@ -108,9 +119,14 @@ class AgentRAG:
Args :
Args :
task ( str ) : The task description .
task ( str ) : The task description .
* args : Additional arguments to pass to the collection . query method .
* * kwargs : Additional keyword arguments to pass to the collection . query method .
Returns :
Returns :
Optional [ Agent ] : The best matching agent , if found .
Optional [ Agent ] : The best matching agent , if found .
Raises :
Exception : If there ' s an error finding the best agent.
"""
"""
try :
try :
results = self . collection . query (
results = self . collection . query (
@ -150,171 +166,171 @@ class AgentRAG:
raise
raise
# Example usage
# # Example usage
if __name__ == " __main__ " :
# if __name__ == "__main__" :
from dotenv import load_dotenv
# from dotenv import load_dotenv
from swarm_models import OpenAIChat
# from swarm_models import OpenAIChat
load_dotenv ( )
# load_dotenv()
# Get the OpenAI API key from the environment variable
# # Get the OpenAI API key from the environment variable
api_key = os . getenv ( " GROQ_API_KEY " )
# api_key = os.getenv("GROQ_API_KEY" )
# Model
# # Model
model = OpenAIChat (
# model = OpenAIChat(
openai_api_base = " https://api.groq.com/openai/v1 " ,
# openai_api_base="https://api.groq.com/openai/v1",
openai_api_key = api_key ,
# openai_api_key=api_key,
model_name = " llama-3.1-70b-versatile " ,
# model_name="llama-3.1-70b-versatile",
temperature = 0.1 ,
# temperature=0.1,
)
# )
# Initialize the vector database
# # Initialize the vector database
vector_db = AgentRAG ( )
# vector_db = AgentRouter( )
# Define specialized system prompts for each agent
# # Define specialized system prompts for each agent
DATA_EXTRACTOR_PROMPT = """ You are a highly specialized private equity agent focused on data extraction from various documents. Your expertise includes:
# DATA_EXTRACTOR_PROMPT = """You are a highly specialized private equity agent focused on data extraction from various documents. Your expertise includes:
1. Extracting key financial metrics ( revenue , EBITDA , growth rates , etc . ) from financial statements and reports
# 1. Extracting key financial metrics (revenue, EBITDA, growth rates, etc.) from financial statements and reports
2. Identifying and extracting important contract terms from legal documents
# 2. Identifying and extracting important contract terms from legal documents
3. Pulling out relevant market data from industry reports and analyses
# 3. Pulling out relevant market data from industry reports and analyses
4. Extracting operational KPIs from management presentations and internal reports
# 4. Extracting operational KPIs from management presentations and internal reports
5. Identifying and extracting key personnel information from organizational charts and bios
# 5. Identifying and extracting key personnel information from organizational charts and bios
Provide accurate , structured data extracted from various document types to support investment analysis . """
# Provide accurate, structured data extracted from various document types to support investment analysis."""
SUMMARIZER_PROMPT = """ You are an expert private equity agent specializing in summarizing complex documents. Your core competencies include:
# SUMMARIZER_PROMPT = """You are an expert private equity agent specializing in summarizing complex documents. Your core competencies include:
1. Distilling lengthy financial reports into concise executive summaries
# 1. Distilling lengthy financial reports into concise executive summaries
2. Summarizing legal documents , highlighting key terms and potential risks
# 2. Summarizing legal documents, highlighting key terms and potential risks
3. Condensing industry reports to capture essential market trends and competitive dynamics
# 3. Condensing industry reports to capture essential market trends and competitive dynamics
4. Summarizing management presentations to highlight key strategic initiatives and projections
# 4. Summarizing management presentations to highlight key strategic initiatives and projections
5. Creating brief overviews of technical documents , emphasizing critical points for non - technical stakeholders
# 5. Creating brief overviews of technical documents, emphasizing critical points for non-technical stakeholders
Deliver clear , concise summaries that capture the essence of various documents while highlighting information crucial for investment decisions . """
# Deliver clear, concise summaries that capture the essence of various documents while highlighting information crucial for investment decisions. """
FINANCIAL_ANALYST_PROMPT = """ You are a specialized private equity agent focused on financial analysis. Your key responsibilities include:
# FINANCIAL_ANALYST_PROMPT = """You are a specialized private equity agent focused on financial analysis. Your key responsibilities include:
1. Analyzing historical financial statements to identify trends and potential issues
# 1. Analyzing historical financial statements to identify trends and potential issues
2. Evaluating the quality of earnings and potential adjustments to EBITDA
# 2. Evaluating the quality of earnings and potential adjustments to EBITDA
3. Assessing working capital requirements and cash flow dynamics
# 3. Assessing working capital requirements and cash flow dynamics
4. Analyzing capital structure and debt capacity
# 4. Analyzing capital structure and debt capacity
5. Evaluating financial projections and underlying assumptions
# 5. Evaluating financial projections and underlying assumptions
Provide thorough , insightful financial analysis to inform investment decisions and valuation . """
# Provide thorough, insightful financial analysis to inform investment decisions and valuation."""
MARKET_ANALYST_PROMPT = """ You are a highly skilled private equity agent specializing in market analysis. Your expertise covers:
# MARKET_ANALYST_PROMPT = """You are a highly skilled private equity agent specializing in market analysis. Your expertise covers:
1. Analyzing industry trends , growth drivers , and potential disruptors
# 1. Analyzing industry trends, growth drivers, and potential disruptors
2. Evaluating competitive landscape and market positioning
# 2. Evaluating competitive landscape and market positioning
3. Assessing market size , segmentation , and growth potential
# 3. Assessing market size, segmentation, and growth potential
4. Analyzing customer dynamics , including concentration and loyalty
# 4. Analyzing customer dynamics, including concentration and loyalty
5. Identifying potential regulatory or macroeconomic impacts on the market
# 5. Identifying potential regulatory or macroeconomic impacts on the market
Deliver comprehensive market analysis to assess the attractiveness and risks of potential investments . """
# Deliver comprehensive market analysis to assess the attractiveness and risks of potential investments."""
OPERATIONAL_ANALYST_PROMPT = """ You are an expert private equity agent focused on operational analysis. Your core competencies include:
# OPERATIONAL_ANALYST_PROMPT = """You are an expert private equity agent focused on operational analysis. Your core competencies include:
1. Evaluating operational efficiency and identifying improvement opportunities
# 1. Evaluating operational efficiency and identifying improvement opportunities
2. Analyzing supply chain and procurement processes
# 2. Analyzing supply chain and procurement processes
3. Assessing sales and marketing effectiveness
# 3. Assessing sales and marketing effectiveness
4. Evaluating IT systems and digital capabilities
# 4. Evaluating IT systems and digital capabilities
5. Identifying potential synergies in merger or add - on acquisition scenarios
# 5. Identifying potential synergies in merger or add-on acquisition scenarios
Provide detailed operational analysis to uncover value creation opportunities and potential risks . """
# Provide detailed operational analysis to uncover value creation opportunities and potential risks."""
# Initialize specialized agents
# # Initialize specialized agents
data_extractor_agent = Agent (
# data_extractor_agent = Agent(
agent_name = " Data-Extractor " ,
# agent_name="Data-Extractor",
system_prompt = DATA_EXTRACTOR_PROMPT ,
# system_prompt=DATA_EXTRACTOR_PROMPT,
llm = model ,
# llm=model,
max_loops = 1 ,
# max_loops=1,
autosave = True ,
# autosave=True,
verbose = True ,
# verbose=True,
dynamic_temperature_enabled = True ,
# dynamic_temperature_enabled=True,
saved_state_path = " data_extractor_agent.json " ,
# saved_state_path="data_extractor_agent.json",
user_name = " pe_firm " ,
# user_name="pe_firm",
retry_attempts = 1 ,
# retry_attempts=1,
context_length = 200000 ,
# context_length=200000,
output_type = " string " ,
# output_type="string",
)
# )
summarizer_agent = Agent (
# summarizer_agent = Agent(
agent_name = " Document-Summarizer " ,
# agent_name="Document-Summarizer",
system_prompt = SUMMARIZER_PROMPT ,
# system_prompt=SUMMARIZER_PROMPT,
llm = model ,
# llm=model,
max_loops = 1 ,
# max_loops=1,
autosave = True ,
# autosave=True,
verbose = True ,
# verbose=True,
dynamic_temperature_enabled = True ,
# dynamic_temperature_enabled=True,
saved_state_path = " summarizer_agent.json " ,
# saved_state_path="summarizer_agent.json",
user_name = " pe_firm " ,
# user_name="pe_firm",
retry_attempts = 1 ,
# retry_attempts=1,
context_length = 200000 ,
# context_length=200000,
output_type = " string " ,
# output_type="string",
)
# )
financial_analyst_agent = Agent (
# financial_analyst_agent = Agent(
agent_name = " Financial-Analyst " ,
# agent_name="Financial-Analyst",
system_prompt = FINANCIAL_ANALYST_PROMPT ,
# system_prompt=FINANCIAL_ANALYST_PROMPT,
llm = model ,
# llm=model,
max_loops = 1 ,
# max_loops=1,
autosave = True ,
# autosave=True,
verbose = True ,
# verbose=True,
dynamic_temperature_enabled = True ,
# dynamic_temperature_enabled=True,
saved_state_path = " financial_analyst_agent.json " ,
# saved_state_path="financial_analyst_agent.json",
user_name = " pe_firm " ,
# user_name="pe_firm",
retry_attempts = 1 ,
# retry_attempts=1,
context_length = 200000 ,
# context_length=200000,
output_type = " string " ,
# output_type="string",
)
# )
market_analyst_agent = Agent (
# market_analyst_agent = Agent(
agent_name = " Market-Analyst " ,
# agent_name="Market-Analyst",
system_prompt = MARKET_ANALYST_PROMPT ,
# system_prompt=MARKET_ANALYST_PROMPT,
llm = model ,
# llm=model,
max_loops = 1 ,
# max_loops=1,
autosave = True ,
# autosave=True,
verbose = True ,
# verbose=True,
dynamic_temperature_enabled = True ,
# dynamic_temperature_enabled=True,
saved_state_path = " market_analyst_agent.json " ,
# saved_state_path="market_analyst_agent.json",
user_name = " pe_firm " ,
# user_name="pe_firm",
retry_attempts = 1 ,
# retry_attempts=1,
context_length = 200000 ,
# context_length=200000,
output_type = " string " ,
# output_type="string",
)
# )
operational_analyst_agent = Agent (
# operational_analyst_agent = Agent(
agent_name = " Operational-Analyst " ,
# agent_name="Operational-Analyst",
system_prompt = OPERATIONAL_ANALYST_PROMPT ,
# system_prompt=OPERATIONAL_ANALYST_PROMPT,
llm = model ,
# llm=model,
max_loops = 1 ,
# max_loops=1,
autosave = True ,
# autosave=True,
verbose = True ,
# verbose=True,
dynamic_temperature_enabled = True ,
# dynamic_temperature_enabled=True,
saved_state_path = " operational_analyst_agent.json " ,
# saved_state_path="operational_analyst_agent.json",
user_name = " pe_firm " ,
# user_name="pe_firm",
retry_attempts = 1 ,
# retry_attempts=1,
context_length = 200000 ,
# context_length=200000,
output_type = " string " ,
# output_type="string",
)
# )
# Create agents (using the agents from the original code)
# # Create agents (using the agents from the original code)
agents_to_add = [
# agents_to_add = [
data_extractor_agent ,
# data_extractor_agent,
summarizer_agent ,
# summarizer_agent,
financial_analyst_agent ,
# financial_analyst_agent,
market_analyst_agent ,
# market_analyst_agent,
operational_analyst_agent ,
# operational_analyst_agent,
]
# ]
# Add agents to the vector database
# # Add agents to the vector database
for agent in agents_to_add :
# for agent in agents_to_add :
vector_db . add_agent ( agent )
# vector_db.add_agent(agent)
# Example task
# # Example task
task = " Analyze the financial statements of a potential acquisition target and identify key growth drivers. "
# task = " Analyze the financial statements of a potential acquisition target and identify key growth drivers."
# Find the best agent for the task
# # Find the best agent for the task
best_agent = vector_db . find_best_agent ( task )
# best_agent = vector_db.find_best_agent(task)
if best_agent :
# if best_agent:
logger . info ( f " Best agent for the task: { best_agent . name } " )
# logger.info(f"Best agent for the task: {best_agent.name}")
# Use the best agent to perform the task
# # Use the best agent to perform the task
result = best_agent . run ( task )
# result = best_agent.run(task)
print ( f " Task result: { result } " )
# print(f"Task result: {result}")
# Update the agent's history in the database
# # Update the agent's history in the database
vector_db . update_agent_history ( best_agent . name )
# vector_db.update_agent_history(best_agent.name)
else :
# else :
print ( " No suitable agent found for the task. " )
# print("No suitable agent found for the task.")
# Save the vector database
# # Save the vector database