엔터프라이즈 등급 제작 준비가 된 다중 에이전트 오케스트레이션 프레임 워크
? 트위터 • ? 불화 • 떼 플랫폼 • ? 선적 서류 비치
범주 | 특징 | 이익 |
---|---|---|
? 엔터프라이즈 아키텍처 | • 생산 준비 인프라 • 높은 신뢰성 시스템 • 모듈 식 디자인 • 포괄적 인 로깅 | • 다운 타임 감소 • 쉽게 유지 보수 • 더 나은 디버깅 • 향상된 모니터링 |
? 에이전트 오케스트레이션 | • 계층 적 무리 • 병렬 처리 • 순차 워크 플로우 • 그래프 기반 워크 플로우 • 동적 에이전트 재 배열 | • 복잡한 작업 처리 • 성능 향상 • 유연한 워크 플로 • 최적화 된 실행 |
통합 기능 | • 멀티 모델 지원 • 맞춤형 에이전트 생성 • 광범위한 도구 라이브러리 • 여러 메모리 시스템 | • 제공자 유연성 • 맞춤형 솔루션 • 확장 된 기능 • 향상된 메모리 관리 |
? 확장 성 | • 동시 처리 • 자원 관리 •로드 밸런싱 • 수평 스케일링 | • 더 높은 처리량 • 효율적인 자원 사용 • 더 나은 성능 • 쉬운 스케일링 |
개발자 도구 | • 간단한 API • 광범위한 문서 • 활동적인 커뮤니티 • CLI 도구 | • 더 빠른 개발 • 쉽게 학습 곡선 • 지역 사회 지원 • 빠른 배포 |
? 보안 기능 | • 오류 처리 • 요율 제한 • 모니터링 통합 • 감사 기록 | • 신뢰성 향상 • API 보호 • 더 나은 모니터링 • 향상된 추적 |
고급 기능 | • 스프레드 시트 warm • 그룹 채팅 • 에이전트 레지스트리 • 에이전트의 혼합 | • 대량 에이전트 관리 • 공동 작업 AI • 중앙 집중식 제어 • 복잡한 솔루션 |
? 제공자 지원 | • Openai • 의인성 • ChromADB • 맞춤형 제공 업체 | • 제공자 유연성 • 스토리지 옵션 • 맞춤형 통합 • 공급 업체 독립성 |
? 생산 기능 | • 자동 회수 • 비동기 지원 • 환경 관리 • 안전성을 입력하십시오 | • 더 나은 신뢰성 • 성능 향상 • 쉬운 구성 • 더 안전한 코드 |
사용 사례 지원 | • 작업 별 에이전트 • 맞춤형 워크 플로 • 산업 솔루션 • 확장 가능한 프레임 워크 | • 빠른 배포 • 유연한 솔루션 • 산업 준비 • 쉬운 사용자 정의 |
python3.10
이상!$ pip install -U swarms
와, 떼를 설치하는 것을 잊지 마십시오!.env
파일은 OPENAI_API_KEY
, ANTHROPIC_API_KEY
와 같은 제공자의 API 키가있는 파일.env
변수를 설정하십시오 : WORKSPACE_DIR="agent_workspace"
또는 export WORKSPACE_DIR="agent_workspace"
로 터미널에서 수행하십시오.swarms onboarding
. 생산 등급 구현 세부 정보는 문서를 참조하십시오.
부분 | 모래밭 |
---|---|
설치 | 설치 |
QuickStart | 시작하세요 |
에이전트 내부 메커니즘 | 에이전트 아키텍처 |
에이전트 API | 에이전트 API |
외부 에이전트 그립 테이프, 자동 토지 등 통합 | 외부 API 통합 |
Yaml에서 에이전트 생성 | Yaml에서 에이전트 생성 |
왜 떼가 필요한가 | 다중 기관 협업이 필요한 이유 |
떼 건축 분석 | 떼 건축 |
비즈니스 문제에 대한 올바른 무리 선택 ¶ | 여기를 클릭하십시오 |
agentrearrange 문서 | 여기를 클릭하십시오 |
$ pip3 install -U swarms
pip3 install -U swarms
으로 Swarm을 다운로드 했으므로 CLI
에 액세스 할 수 있습니다. 지금 CLI로 탑승하십시오.
swarms onboarding
이 명령을 실행할 수도 있습니다.
swarms help
CLI에 대한 자세한 내용을 보려면 여기를 클릭하십시오
다음은 시작할 수있는 스크립트입니다. 보다 포괄적 인 문서를 보려면 문서를 방문하십시오.
예제 이름 | 설명 | 예제 유형 | 링크 |
---|---|---|---|
예제 떼 | 떼 기능을 보여주는 간단한 예제 모음. | 기본 사용 | https://github.com/the-swarm-corporation/swarms-examples?tab=readme-ov-file |
자세한 해설서 | 다양한 사용 사례 및 시나리오에 대한 레시피가있는 포괄적 인 안내서. | 고급 사용 | https://github.com/the-swarm-corporation/cookbook |
Agent
클래스 Agent
클래스는 작업을 자율적으로 실행하도록 설계된 Swarms 프레임 워크의 기본 구성 요소입니다. LLM, 도구 및 장기 메모리 기능을 융합하여 풀 스택 에이전트를 생성합니다. Agent
클래스는 고도로 사용자 정의 할 수 있으므로 행동과 상호 작용을 세밀하게 제어 할 수 있습니다.
run
방법 run
메소드는 Agent
인스턴스가있는 작업을 실행하기위한 기본 진입 점입니다. 작업 문자열을 기본 입력 작업으로 받아들이고 에이전트의 구성에 따라 처리합니다. VLM이있는 경우 이미지를 처리하기 위해 img="image_filepath.png
와 같은 img
매개 변수도 허용 할 수 있습니다.
Agent
클래스는 행동을 특정 요구에 맞게 조정하기위한 다양한 설정을 제공합니다. 일부 주요 설정에는 다음이 포함됩니다.
환경 | 설명 | 기본값 |
---|---|---|
agent_name | 에이전트의 이름. | "DefaultAgent" |
system_prompt | 에이전트에 사용하라는 시스템 프롬프트. | "기본 시스템 프롬프트." |
llm | 처리 작업에 사용할 언어 모델. | OpenAIChat 인스턴스 |
max_loops | 작업을 위해 실행할 최대 루프 수. | 1 |
autosave | 에이전트 상태의 자동 절도를 활성화하거나 비활성화합니다. | 거짓 |
dashboard | 에이전트의 대시 보드를 활성화하거나 비활성화합니다. | 거짓 |
verbose | 에이전트 출력의 진실성을 제어합니다. | 거짓 |
dynamic_temperature_enabled | 언어 모델의 동적 온도 조정을 활성화하거나 비활성화합니다. | 거짓 |
saved_state_path | 에이전트의 상태를 저장하는 길. | "Agent_state.json" |
user_name | 에이전트와 관련된 사용자 이름. | "default_user" |
retry_attempts | 실패한 작업에 대한 재시험 시도 횟수. | 1 |
context_length | 작업에 대해 고려해야 할 상황의 최대 길이. | 200000 |
return_step_meta | 출력에서 스텝 메타 데이터를 반환할지 여부를 제어합니다. | 거짓 |
output_type | 반환 할 출력 유형 (예 : "JSON", "String"). | "끈" |
import os
from swarms import Agent
from swarm_models import OpenAIChat
from swarms . prompts . finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT ,
)
from dotenv import load_dotenv
load_dotenv ()
# Get the OpenAI API key from the environment variable
api_key = os . getenv ( "OPENAI_API_KEY" )
# Create an instance of the OpenAIChat class
model = OpenAIChat (
openai_api_key = api_key , model_name = "gpt-4o-mini" , temperature = 0.1
)
# Initialize the agent
agent = Agent (
agent_name = "Financial-Analysis-Agent" ,
system_prompt = FINANCIAL_AGENT_SYS_PROMPT ,
llm = model ,
max_loops = 1 ,
autosave = True ,
dashboard = False ,
verbose = True ,
dynamic_temperature_enabled = True ,
saved_state_path = "finance_agent.json" ,
user_name = "swarms_corp" ,
retry_attempts = 1 ,
context_length = 200000 ,
return_step_meta = False ,
output_type = "string" ,
streaming_on = False ,
)
agent . run (
"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria"
)
고급 문서 이해, 분석 및 검색 능력을 위해 RAG (Relational Agent Graph)를 사용하여 준-인피 나이트 장기 메모리가 장착 된 Agent
.
RAG 통합을위한 인어 다이어그램
그래프 TD
[rag로 대리인 초기화] -> b [수신 작업]
b-> C [쿼리 장기 메모리]
C-> D [컨텍스트가있는 프로세스 작업]
d-> e [응답 생성]
e-> f [장기 메모리 업데이트]
f-> g [return output]
1 단계 : ChromADB 클라이언트 초기화
import os
from swarms_memory import ChromaDB
# Initialize the ChromaDB client for long-term memory management
chromadb = ChromaDB (
metric = "cosine" , # Metric for similarity measurement
output_dir = "finance_agent_rag" , # Directory for storing RAG data
# docs_folder="artifacts", # Uncomment and specify the folder containing your documents
)
2 단계 : 모델을 정의합니다
from swarm_models import Anthropic
from swarms . prompts . finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT ,
)
# Define the Anthropic model for language processing
model = Anthropic ( anthropic_api_key = os . getenv ( "ANTHROPIC_API_KEY" ))
3 단계 : 헝겊으로 에이전트를 초기화합니다
from swarms import Agent
# Initialize the agent with RAG capabilities
agent = Agent (
agent_name = "Financial-Analysis-Agent" ,
system_prompt = FINANCIAL_AGENT_SYS_PROMPT ,
agent_description = "Agent creates a comprehensive financial analysis" ,
llm = model ,
max_loops = "auto" , # Auto-adjusts loops based on task complexity
autosave = True , # Automatically saves agent state
dashboard = False , # Disables dashboard for this example
verbose = True , # Enables verbose mode for detailed output
streaming_on = True , # Enables streaming for real-time processing
dynamic_temperature_enabled = True , # Dynamically adjusts temperature for optimal performance
saved_state_path = "finance_agent.json" , # Path to save agent state
user_name = "swarms_corp" , # User name for the agent
retry_attempts = 3 , # Number of retry attempts for failed tasks
context_length = 200000 , # Maximum length of the context to consider
long_term_memory = chromadb , # Integrates ChromaDB for long-term memory management
return_step_meta = False ,
output_type = "string" ,
)
# Run the agent with a sample task
agent . run (
"What are the components of a startups stock incentive equity plan"
)
우리는 JSON, YAML, TOML, PDFS 업로드, 배치 작업 등을 사용하여 에이전트 상태를 절약하기 위해 방대한 기능을 제공합니다!
방법 테이블
방법 | 설명 |
---|---|
to_dict() | 에이전트 객체를 사전으로 변환합니다. |
to_toml() | 에이전트 객체를 TOML 문자열로 변환합니다. |
model_dump_json() | 모델을 JSON 파일로 덤프합니다. |
model_dump_yaml() | 모델을 YAML 파일로 덤프합니다. |
ingest_docs() | 에이전트의 지식 기반에 문서를 수집합니다. |
receive_message() | 사용자로부터 메시지를 받고 처리합니다. |
send_agent_message() | 에이전트에서 사용자에게 메시지를 보냅니다. |
filtered_run() | 필터링 된 시스템 프롬프트로 에이전트를 실행합니다. |
bulk_run() | 여러 시스템 프롬프트로 에이전트를 실행합니다. |
add_memory() | 에이전트에 메모리를 추가합니다. |
check_available_tokens() | 에이전트의 사용 가능한 토큰 수를 확인합니다. |
tokens_checks() | 에이전트에 대한 토큰 검사를 수행합니다. |
print_dashboard() | 에이전트의 대시 보드를 인쇄합니다. |
get_docs_from_doc_folders() | 문서 폴더에서 모든 문서를 가져옵니다. |
activate_agentops() | 에이전트 작업을 활성화합니다. |
check_end_session_agentops() | 에이전트 작업에 대한 세션 종료를 확인합니다. |
# # Convert the agent object to a dictionary
print ( agent . to_dict ())
print ( agent . to_toml ())
print ( agent . model_dump_json ())
print ( agent . model_dump_yaml ())
# Ingest documents into the agent's knowledge base
agent . ingest_docs ( "your_pdf_path.pdf" )
# Receive a message from a user and process it
agent . receive_message ( name = "agent_name" , message = "message" )
# Send a message from the agent to a user
agent . send_agent_message ( agent_name = "agent_name" , message = "message" )
# Ingest multiple documents into the agent's knowledge base
agent . ingest_docs ( "your_pdf_path.pdf" , "your_csv_path.csv" )
# Run the agent with a filtered system prompt
agent . filtered_run (
"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria?"
)
# Run the agent with multiple system prompts
agent . bulk_run (
[
"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria?" ,
"Another system prompt" ,
]
)
# Add a memory to the agent
agent . add_memory ( "Add a memory to the agent" )
# Check the number of available tokens for the agent
agent . check_available_tokens ()
# Perform token checks for the agent
agent . tokens_checks ()
# Print the dashboard of the agent
agent . print_dashboard ()
# Fetch all the documents from the doc folders
agent . get_docs_from_doc_folders ()
# Activate agent ops
agent . activate_agentops ()
agent . check_end_session_agentops ()
# Dump the model to a JSON file
agent . model_dump_json ()
print ( agent . to_toml ())
Agent
다음은 Pydantic Basemodel을 섭취하고 동시에 출력하는 에이전트의 예입니다.
from pydantic import BaseModel , Field
from swarms import Agent
from swarm_models import Anthropic
# Initialize the schema for the person's information
class Schema ( BaseModel ):
name : str = Field (..., title = "Name of the person" )
agent : int = Field (..., title = "Age of the person" )
is_student : bool = Field (..., title = "Whether the person is a student" )
courses : list [ str ] = Field (
..., title = "List of courses the person is taking"
)
# Convert the schema to a JSON string
tool_schema = Schema (
name = "Tool Name" ,
agent = 1 ,
is_student = True ,
courses = [ "Course1" , "Course2" ],
)
# Define the task to generate a person's information
task = "Generate a person's information based on the following schema:"
# Initialize the agent
agent = Agent (
agent_name = "Person Information Generator" ,
system_prompt = (
"Generate a person's information based on the following schema:"
),
# Set the tool schema to the JSON string -- this is the key difference
tool_schema = tool_schema ,
llm = Anthropic (),
max_loops = 3 ,
autosave = True ,
dashboard = False ,
streaming_on = True ,
verbose = True ,
interactive = True ,
# Set the output type to the tool schema which is a BaseModel
output_type = tool_schema , # or dict, or str
metadata_output_type = "json" ,
# List of schemas that the agent can handle
list_base_models = [ tool_schema ],
function_calling_format_type = "OpenAI" ,
function_calling_type = "json" , # or soon yaml
)
# Run the agent to generate the person's information
generated_data = agent . run ( task )
# Print the generated data
print ( f"Generated data: { generated_data } " )
제조, 물류 및 건강 분야에서 다양한 실제 작업에 유용한 여러 양식을 가진 에이전트를 실행하십시오.
import os
from dotenv import load_dotenv
from swarms import Agent
from swarm_models import GPT4VisionAPI
# Load the environment variables
load_dotenv ()
# Initialize the language model
llm = GPT4VisionAPI (
openai_api_key = os . environ . get ( "OPENAI_API_KEY" ),
max_tokens = 500 ,
)
# Initialize the task
task = (
"Analyze this image of an assembly line and identify any issues such as"
" misaligned parts, defects, or deviations from the standard assembly"
" process. IF there is anything unsafe in the image, explain why it is"
" unsafe and how it could be improved."
)
img = "assembly_line.jpg"
## Initialize the workflow
agent = Agent (
agent_name = "Multi-ModalAgent" ,
llm = llm ,
max_loops = "auto" ,
autosave = True ,
dashboard = True ,
multi_modal = True
)
# Run the workflow on a task
agent . run ( task , img )
ToolAgent
ToolAgent는 JSON 기능 호출을 통해 도구를 사용할 수있는 에이전트입니다. Huggingface에서 오픈 소스 모델을 섭취하며 매우 모듈 식 및 플러그인 및 재생입니다. 곧 모든 모델에 일반적인 지원을 추가하는 데 도움이 필요합니다.
from pydantic import BaseModel , Field
from transformers import AutoModelForCausalLM , AutoTokenizer
from swarms import ToolAgent
from swarms . utils . json_utils import base_model_to_json
# Load the pre-trained model and tokenizer
model = AutoModelForCausalLM . from_pretrained (
"databricks/dolly-v2-12b" ,
load_in_4bit = True ,
device_map = "auto" ,
)
tokenizer = AutoTokenizer . from_pretrained ( "databricks/dolly-v2-12b" )
# Initialize the schema for the person's information
class Schema ( BaseModel ):
name : str = Field (..., title = "Name of the person" )
agent : int = Field (..., title = "Age of the person" )
is_student : bool = Field (
..., title = "Whether the person is a student"
)
courses : list [ str ] = Field (
..., title = "List of courses the person is taking"
)
# Convert the schema to a JSON string
tool_schema = base_model_to_json ( Schema )
# Define the task to generate a person's information
task = (
"Generate a person's information based on the following schema:"
)
# Create an instance of the ToolAgent class
agent = ToolAgent (
name = "dolly-function-agent" ,
description = "Ana gent to create a child data" ,
model = model ,
tokenizer = tokenizer ,
json_schema = tool_schema ,
)
# Run the agent to generate the person's information
generated_data = agent . run ( task )
# Print the generated data
print ( f"Generated data: { generated_data } " )
다른 에이전트 프레임 워크에서 외부 에이전트를 통합하는 것은 쉬운 일입니다.
단계 :
Agent
물려받는 새로운 클래스를 만듭니다.run(task: str) -> str
메서드를 만듭니다.예를 들어, Griptape에서 에이전트를 만드는 방법에 대한 예입니다.
다음은 Agent
클래스에서 Swarms 의 상속 및 실행을 재정의하여 Swarms 프레임 워크와 통합되는 사용자 정의 Griptape 에이전트를 만드는 방법입니다 run(task: str) -> str
메서드.
from swarms import (
Agent as SwarmsAgent ,
) # Import the base Agent class from Swarms
from griptape . structures import Agent as GriptapeAgent
from griptape . tools import (
WebScraperTool ,
FileManagerTool ,
PromptSummaryTool ,
)
# Create a custom agent class that inherits from SwarmsAgent
class GriptapeSwarmsAgent ( SwarmsAgent ):
def __init__ ( self , * args , ** kwargs ):
# Initialize the Griptape agent with its tools
self . agent = GriptapeAgent (
input = "Load {{ args[0] }}, summarize it, and store it in a file called {{ args[1] }}." ,
tools = [
WebScraperTool ( off_prompt = True ),
PromptSummaryTool ( off_prompt = True ),
FileManagerTool (),
],
* args ,
** kwargs ,
# Add additional settings
)
# Override the run method to take a task and execute it using the Griptape agent
def run ( self , task : str ) -> str :
# Extract URL and filename from task (you can modify this parsing based on task structure)
url , filename = task . split (
","
) # Example of splitting task string
# Execute the Griptape agent with the task inputs
result = self . agent . run ( url . strip (), filename . strip ())
# Return the final result as a string
return str ( result )
# Example usage:
griptape_swarms_agent = GriptapeSwarmsAgent ()
output = griptape_swarms_agent . run (
"https://griptape.ai, griptape.txt"
)
print ( output )
SwarmsAgent
클래스에서 물려 받고 그립 테이프 에이전트를 통합하는 맞춤형 클래스.WebScraperTool
, PromptSummaryTool
, FileManagerTool
)에 통합 된 도구를 통해 웹 스크래핑, 요약 및 파일 관리가 가능합니다.이제이 사용자 정의 그립 테이프 에이전트를 Swarms 프레임 워크 에 쉽게 연결하여 작업을 실행하는 데 사용할 수 있습니다!
무리는 공동 목표를 달성하기 위해 협력하여 협력하는 두 명의 에이전트 그룹을 말합니다. 이 에이전트는 복잡한 작업을 수행하기 위해 서로 상호 작용하는 LLM과 같은 소프트웨어 엔티티가 될 수 있습니다. 떼의 개념은 개미 식민지 또는 새 무리와 같은 자연 시스템에서 영감을 얻어 간단한 개별 행동이 복잡한 그룹 역학 및 문제 해결 기능을 초래합니다.
Swarm Architectures는 Swarm 내의 에이전트 간의 커뮤니케이션을 설정하고 관리하도록 설계되었습니다. 이러한 아키텍처는 에이전트가 상호 작용하고 정보를 공유하며 자신의 행동을 조정하여 원하는 결과를 달성하는 방법을 정의합니다. Swarm Architectures의 몇 가지 주요 측면은 다음과 같습니다.
계층 적 커뮤니케이션 : 계층 적 무리에서, 의사 소통은 상위 수준의 에이전트에서 하위 수준 에이전트로 흐릅니다. 고급 에이전트는 코디네이터, 작업을 배포하고 결과를 집계하는 역할을합니다. 이 구조는 하향식 제어 및 의사 결정이 필요한 작업에 효율적입니다.
병렬 커뮤니케이션 : 병렬 무리로, 에이전트는 독립적으로 작동하며 필요에 따라 서로 통신합니다. 이 아키텍처는 종속성없이 동시에 처리 할 수있는 작업에 적합하여 더 빠른 실행 및 확장 성을 허용합니다.
순차적 커뮤니케이션 : 순차적 떼는 각 에이전트의 출력이 다음 에이전트의 입력이되는 선형 순서로 작업을 처리합니다. 이를 통해 종속성이있는 작업이 올바른 순서로 처리되어 워크 플로의 무결성을 유지합니다.
메쉬 커뮤니케이션 : 메쉬 떼에서 에이전트가 완전히 연결되어 있으며, 모든 에이전트가 다른 에이전트와 통신 할 수 있습니다. 이 설정은 높은 유연성과 중복성을 제공하므로 동적 상호 작용이 필요한 복잡한 시스템에 이상적입니다.
연합 커뮤니케이션 : Federated Swarm에는 정보 및 결과를 공유하여 협력하는 여러 독립 무리가 포함됩니다. 각 떼는 자율적으로 작동하지만 더 큰 작업에 기여하여 다른 노드에 걸쳐 분산 문제 해결을 가능하게합니다.
Swarm Architectures는 이러한 통신 패턴을 활용하여 에이전트가 효율적으로 협력하여 당면한 작업의 특정 요구 사항에 적응할 수 있도록합니다. Swarm Architectures는 명확한 통신 프로토콜 및 상호 작용 모델을 정의함으로써 여러 에이전트의 원활한 오케스트레이션을 가능하게하여 성능 및 문제 해결 기능을 향상시킵니다.
이름 | 설명 | 코드 링크 | 사용 사례 |
---|---|---|---|
계층 적 무리 | 에이전트가 계층 구조로 구성되는 시스템, 상위 수준의 에이전트가 복잡한 작업을 달성하기 위해 하위 수준 에이전트를 조정합니다. | 코드 링크 | 제조 프로세스 최적화, 다단계 영업 관리, 의료 자원 조정 |
에이전트 재 배열 | 에이전트가 작업 요구 사항 및 환경 조건에 따라 동적으로 자체 재배치하는 설정. | 코드 링크 | 적응 형 제조 라인, 동적 판매 영역 재정렬, 유연한 의료 직원 |
동시 워크 플로 | 에이전트는 다른 작업을 동시에 수행하여 더 큰 목표를 달성하기 위해 조정합니다. | 코드 링크 | 동시 생산 라인, 병렬 판매 운영, 동시 환자 치료 프로세스 |
순차적 조정 | 에이전트는 특정 시퀀스에서 작업을 수행하며, 한 작업이 완료되면 다음 작업이 시작됩니다. | 코드 링크 | 단계별 조립 라인, 순차적 판매 프로세스, 단계별 환자 치료 워크 플로우 |
병렬 처리 | 에이전트는 전체 프로세스의 속도를 높이기 위해 동시에 작업의 다른 부분을 동시에 작업합니다. | 코드 링크 | 제조, 동시 판매 분석, 동시 의료 테스트의 병렬 데이터 처리 |
에이전트의 혼합 | 복잡한 문제를 해결하기 위해 다른 기능을 가진 에이전트가 결합되는 이질적인 떼. | 코드 링크 | 재무 예측, 다양한 기술이 필요한 복잡한 문제 해결 |
그래프 워크 플로 | 에이전트는 DAG (Directed Acyclic Graph) 형식으로 협력하여 종속성 및 병렬 작업을 관리합니다. | 코드 링크 | AI 중심 소프트웨어 개발 파이프 라인, 복잡한 프로젝트 관리 |
그룹 채팅 | 에이전트는 채팅과 같은 상호 작용에 참여하여 공동으로 결정에 도달합니다. | 코드 링크 | 실시간 협업 의사 결정, 계약 협상 |
에이전트 레지스트리 | 에이전트가 저장, 검색 및 동적으로 호출되는 중앙 집중식 레지스트리. | 코드 링크 | 동적 에이전트 관리, 진화 권장 엔진 |
스프레드 시트 떼 | CSV 파일과 같은 구조화 된 형식의 에이전트 출력을 추적하여 스케일로 작업을 관리합니다. | 코드 링크 | 대규모 마케팅 분석, 재무 감사 |
숲 떼 | 복잡한 의사 결정 프로세스를 위해 트리와 같은 계층 구조로 에이전트를 구성하는 떼 구조. | 코드 링크 | 다단계 워크 플로, 계층 적 강화 학습 |
떼 라우터 | 작업 요구 사항 및 사용 가능한 에이전트를 기반으로 떼 아키텍처를 경로 및 선택합니다. | 코드 링크 | 동적 작업 라우팅, 적응 형 떼 아키텍처 선택, 최적화 된 에이전트 할당 |
SequentialWorkflow
순차 워크 플로우를 사용하면 Agent
와 순차적으로 작업을 실행 한 다음 최대 루프를 지정할 때까지 출력을 다음 에이전트로 전달할 수 있습니다.
그래프 lr
A [에이전트 1] -> B [에이전트 2]
B-> C [에이전트 3]
C-> D [에이전트 4]
D-> E [MAX 루프]
e-> f [끝]
방법 | 설명 | 매개 변수 | 반환 값 |
---|---|---|---|
__init__ | 순차적 인 플로우를 초기화하십시오 | agents : 에이전트 객체 목록max_loops : 최대 반복 수verbose : 장황한 생산량에 대한 부울 | 없음 |
run | 워크 플로를 실행하십시오 | input_data : 첫 번째 에이전트의 초기 입력 | 모든 에이전트가 처리 된 후 최종 출력 |
입력 | 유형 | 설명 |
---|---|---|
agents | 목록 [에이전트] | 순차적으로 실행할 에이전트 객체 목록 |
max_loops | int | 전체 시퀀스가 반복 될 최대 횟수 |
verbose | 부 | 사실이라면 실행 중에 자세한 정보를 인쇄하십시오 |
run
메소드는 모든 에이전트가 입력을 순차적으로 처리 한 후 최종 출력을 반환합니다.
이 예에서 각 Agent
순차적으로 실행되는 작업을 나타냅니다. 각 에이전트의 출력은 최대 루프 수에 도달 할 때까지 순서대로 다음 에이전트로 전달됩니다. 이 워크 플로는 데이터 처리 파이프 라인 또는 이전 단계의 출력에 의존하는 복잡한 계산과 같은 특정 순서로 일련의 단계를 실행 해야하는 작업에 특히 유용합니다.
import os
from swarms import Agent , SequentialWorkflow
from swarm_models import OpenAIChat
# model = Anthropic(anthropic_api_key=os.getenv("ANTHROPIC_API_KEY"))
company = "Nvidia"
# Get the OpenAI API key from the environment variable
api_key = os . getenv ( "GROQ_API_KEY" )
# Model
model = OpenAIChat (
openai_api_base = "https://api.groq.com/openai/v1" ,
openai_api_key = api_key ,
model_name = "llama-3.1-70b-versatile" ,
temperature = 0.1 ,
)
# Initialize the Managing Director agent
managing_director = Agent (
agent_name = "Managing-Director" ,
system_prompt = f"""
As the Managing Director at Blackstone, your role is to oversee the entire investment analysis process for potential acquisitions.
Your responsibilities include:
1. Setting the overall strategy and direction for the analysis
2. Coordinating the efforts of the various team members and ensuring a comprehensive evaluation
3. Reviewing the findings and recommendations from each team member
4. Making the final decision on whether to proceed with the acquisition
For the current potential acquisition of { company } , direct the tasks for the team to thoroughly analyze all aspects of the company, including its financials, industry position, technology, market potential, and regulatory compliance. Provide guidance and feedback as needed to ensure a rigorous and unbiased assessment.
""" ,
llm = model ,
max_loops = 1 ,
dashboard = False ,
streaming_on = True ,
verbose = True ,
stopping_token = "<DONE>" ,
state_save_file_type = "json" ,
saved_state_path = "managing-director.json" ,
)
# Initialize the Vice President of Finance
vp_finance = Agent (
agent_name = "VP-Finance" ,
system_prompt = f"""
As the Vice President of Finance at Blackstone, your role is to lead the financial analysis of potential acquisitions.
For the current potential acquisition of { company } , your tasks include:
1. Conducting a thorough review of { company } ' financial statements, including income statements, balance sheets, and cash flow statements
2. Analyzing key financial metrics such as revenue growth, profitability margins, liquidity ratios, and debt levels
3. Assessing the company's historical financial performance and projecting future performance based on assumptions and market conditions
4. Identifying any financial risks or red flags that could impact the acquisition decision
5. Providing a detailed report on your findings and recommendations to the Managing Director
Be sure to consider factors such as the sustainability of { company } ' business model, the strength of its customer base, and its ability to generate consistent cash flows. Your analysis should be data-driven, objective, and aligned with Blackstone's investment criteria.
""" ,
llm = model ,
max_loops = 1 ,
dashboard = False ,
streaming_on = True ,
verbose = True ,
stopping_token = "<DONE>" ,
state_save_file_type = "json" ,
saved_state_path = "vp-finance.json" ,
)
# Initialize the Industry Analyst
industry_analyst = Agent (
agent_name = "Industry-Analyst" ,
system_prompt = f"""
As the Industry Analyst at Blackstone, your role is to provide in-depth research and analysis on the industries and markets relevant to potential acquisitions.
For the current potential acquisition of { company } , your tasks include:
1. Conducting a comprehensive analysis of the industrial robotics and automation solutions industry, including market size, growth rates, key trends, and future prospects
2. Identifying the major players in the industry and assessing their market share, competitive strengths and weaknesses, and strategic positioning
3. Evaluating { company } ' competitive position within the industry, including its market share, differentiation, and competitive advantages
4. Analyzing the key drivers and restraints for the industry, such as technological advancements, labor costs, regulatory changes, and economic conditions
5. Identifying potential risks and opportunities for { company } based on the industry analysis, such as disruptive technologies, emerging markets, or shifts in customer preferences
Your analysis should provide a clear and objective assessment of the attractiveness and future potential of the industrial robotics industry, as well as { company } ' positioning within it. Consider both short-term and long-term factors, and provide evidence-based insights to inform the investment decision.
""" ,
llm = model ,
max_loops = 1 ,
dashboard = False ,
streaming_on = True ,
verbose = True ,
stopping_token = "<DONE>" ,
state_save_file_type = "json" ,
saved_state_path = "industry-analyst.json" ,
)
# Initialize the Technology Expert
tech_expert = Agent (
agent_name = "Tech-Expert" ,
system_prompt = f"""
As the Technology Expert at Blackstone, your role is to assess the technological capabilities, competitive advantages, and potential risks of companies being considered for acquisition.
For the current potential acquisition of { company } , your tasks include:
1. Conducting a deep dive into { company } ' proprietary technologies, including its robotics platforms, automation software, and AI capabilities
2. Assessing the uniqueness, scalability, and defensibility of { company } ' technology stack and intellectual property
3. Comparing { company } ' technologies to those of its competitors and identifying any key differentiators or technology gaps
4. Evaluating { company } ' research and development capabilities, including its innovation pipeline, engineering talent, and R&D investments
5. Identifying any potential technology risks or disruptive threats that could impact { company } ' long-term competitiveness, such as emerging technologies or expiring patents
Your analysis should provide a comprehensive assessment of { company } ' technological strengths and weaknesses, as well as the sustainability of its competitive advantages. Consider both the current state of its technology and its future potential in light of industry trends and advancements.
""" ,
llm = model ,
max_loops = 1 ,
dashboard = False ,
streaming_on = True ,
verbose = True ,
stopping_token = "<DONE>" ,
state_save_file_type = "json" ,
saved_state_path = "tech-expert.json" ,
)
# Initialize the Market Researcher
market_researcher = Agent (
agent_name = "Market-Researcher" ,
system_prompt = f"""
As the Market Researcher at Blackstone, your role is to analyze the target company's customer base, market share, and growth potential to assess the commercial viability and attractiveness of the potential acquisition.
For the current potential acquisition of { company } , your tasks include:
1. Analyzing { company } ' current customer base, including customer segmentation, concentration risk, and retention rates
2. Assessing { company } ' market share within its target markets and identifying key factors driving its market position
3. Conducting a detailed market sizing and segmentation analysis for the industrial robotics and automation markets, including identifying high-growth segments and emerging opportunities
4. Evaluating the demand drivers and sales cycles for { company } ' products and services, and identifying any potential risks or limitations to adoption
5. Developing financial projections and estimates for { company } ' revenue growth potential based on the market analysis and assumptions around market share and penetration
Your analysis should provide a data-driven assessment of the market opportunity for { company } and the feasibility of achieving our investment return targets. Consider both bottom-up and top-down market perspectives, and identify any key sensitivities or assumptions in your projections.
""" ,
llm = model ,
max_loops = 1 ,
dashboard = False ,
streaming_on = True ,
verbose = True ,
stopping_token = "<DONE>" ,
state_save_file_type = "json" ,
saved_state_path = "market-researcher.json" ,
)
# Initialize the Regulatory Specialist
regulatory_specialist = Agent (
agent_name = "Regulatory-Specialist" ,
system_prompt = f"""
As the Regulatory Specialist at Blackstone, your role is to identify and assess any regulatory risks, compliance requirements, and potential legal liabilities associated with potential acquisitions.
For the current potential acquisition of { company } , your tasks include:
1. Identifying all relevant regulatory bodies and laws that govern the operations of { company } , including industry-specific regulations, labor laws, and environmental regulations
2. Reviewing { company } ' current compliance policies, procedures, and track record to identify any potential gaps or areas of non-compliance
3. Assessing the potential impact of any pending or proposed changes to relevant regulations that could affect { company } ' business or create additional compliance burdens
4. Evaluating the potential legal liabilities and risks associated with { company } ' products, services, and operations, including product liability, intellectual property, and customer contracts
5. Providing recommendations on any regulatory or legal due diligence steps that should be taken as part of the acquisition process, as well as any post-acquisition integration considerations
Your analysis should provide a comprehensive assessment of the regulatory and legal landscape surrounding { company } , and identify any material risks or potential deal-breakers. Consider both the current state and future outlook, and provide practical recommendations to mitigate identified risks.
""" ,
llm = model ,
max_loops = 1 ,
dashboard = False ,
streaming_on = True ,
verbose = True ,
stopping_token = "<DONE>" ,
state_save_file_type = "json" ,
saved_state_path = "regulatory-specialist.json" ,
)
# Create a list of agents
agents = [
managing_director ,
vp_finance ,
industry_analyst ,
tech_expert ,
market_researcher ,
regulatory_specialist ,
]
swarm = SequentialWorkflow (
name = "blackstone-private-equity-advisors" ,
agents = agents ,
)
print (
swarm . run (
"Analyze nvidia if it's a good deal to invest in now 10B"
)
)
AgentRearrange
Einops와 Einsum에서 영감을 얻은 AgentRearrange
오케스트레이션 기술을 사용하면 다양한 에이전트 간의 관계를 정의하고 매핑 할 수 있습니다. 복잡한 워크 플로를 조정하기위한 강력한 도구를 제공하여 a -> a1 -> a2 -> a3
과 같은 선형 및 순차적 관계를 지정하거나 첫 번째 에이전트가 3 개의 에이전트에게 메시지를 동시에 보내는 동시 관계를 지정할 수 있습니다. a -> a1, a2, a3
. 이 수준의 사용자 정의는 에이전트가 필요에 따라 병렬 또는 순서대로 작동 할 수있는 매우 효율적이고 역동적 인 워크 플로를 생성 할 수 있습니다. AgentRearrange
기술은 Swarms 라이브러리에 귀중한 추가 기능으로, 에이전트의 오케스트레이션에 대한 새로운 수준의 유연성과 제어를 제공합니다. 자세한 정보 및 예는 공식 문서를 참조하십시오.
방법 | 설명 | 매개 변수 | 반환 값 |
---|---|---|---|
__init__ | agentrearrange를 초기화하십시오 | agents : 에이전트 객체 목록flow : 에이전트 흐름을 설명하는 문자열 | 없음 |
run | 워크 플로를 실행하십시오 | input_data : 첫 번째 에이전트의 초기 입력 | 모든 에이전트가 처리 된 후 최종 출력 |
입력 | 유형 | 설명 |
---|---|---|
agents | 목록 [에이전트] | 조정할 에이전트 개체 목록 |
flow | str | 에이전트의 흐름을 설명하는 문자열 (예 : "A-> B, C") |
run
메소드는 모든 에이전트가 지정된 흐름에 따라 입력을 처리 한 후 최종 출력을 반환합니다.
from swarms import Agent , AgentRearrange
from swarm_models import Anthropic
# Initialize the director agent
director = Agent (
agent_name = "Director" ,
system_prompt = "Directs the tasks for the workers" ,
llm = Anthropic (),
max_loops = 1 ,
dashboard = False ,
streaming_on = True ,
verbose = True ,
stopping_token = "<DONE>" ,
state_save_file_type = "json" ,
saved_state_path = "director.json" ,
)
# Initialize worker 1
worker1 = Agent (
agent_name = "Worker1" ,
system_prompt = "Generates a transcript for a youtube video on what swarms are" ,
llm = Anthropic (),
max_loops = 1 ,
dashboard = False ,
streaming_on = True ,
verbose = True ,
stopping_token = "<DONE>" ,
state_save_file_type = "json" ,
saved_state_path = "worker1.json" ,
)
# Initialize worker 2
worker2 = Agent (
agent_name = "Worker2" ,
system_prompt = "Summarizes the transcript generated by Worker1" ,
llm = Anthropic (),
max_loops = 1 ,
dashboard = False ,
streaming_on = True ,
verbose = True ,
stopping_token = "<DONE>" ,
state_save_file_type = "json" ,
saved_state_path = "worker2.json" ,
)
# Create a list of agents
agents = [ director , worker1 , worker2 ]
# Define the flow pattern
flow = "Director -> Worker1 -> Worker2"
# Using AgentRearrange class
agent_system = AgentRearrange ( agents = agents , flow = flow )
output = agent_system . run (
"Create a format to express and communicate swarms of llms in a structured manner for youtube"
)
print ( output )
HierarhicalSwarm
곧 올다 ...
GraphSwarm
GraphSwarm
은 그래프 이론의 힘을 활용하여 복잡한 작업을 조정하도록 설계된 워크 플로 관리 시스템입니다. 이를 통해 DAG (Directed Acyclic Graph)의 생성은 작업과 에이전트 간의 종속성을 모델링 할 수 있습니다. 이를 통해 효율적인 작업 할당, 실행 및 모니터링이 가능합니다.
GraphSwarm
작동 방식에 대한 분석은 다음과 같습니다.
GraphSwarm
워크 플로우는 에이전트 또는 작업 일 수있는 노드로 구성됩니다. 에이전트는 작업을 실행할 책임이 있으며 작업은 수행 해야하는 특정 작업을 나타냅니다. 이 예에서는 2 개의 에이전트 ( agent1
및 agent2
)와 하나의 작업 ( task1
)이 생성됩니다.agent1
및 agent2
task1
에 연결하도록 만들어지며, 이는 두 에이전트가 task1
실행할 수 있음을 나타냅니다.GraphSwarm
워크 플로우에는 진입 지점 (워크 플로가 시작된 위치) 및 엔드 포인트 (워크 플로우가 끝나는 위치)의 정의가 필요합니다. 이 예에서, agent1
및 agent2
진입 점으로 설정되고, task1
종말점으로 설정됩니다.GraphSwarm
워크 플로를 그래픽으로 나타내는 시각화 기능을 제공합니다. 이를 통해 워크 플로 구조를 쉽게 이해하고 디버깅 할 수 있습니다.GraphSwarm
워크 플로우는 입력 지점에서 엔드 포인트로 그래프를 통과하여 실행됩니다. 이 경우, agent1
과 agent2
동시에 task1
실행하고 결과가 수집됩니다.task1
실행 한 결과는 "작업 완료"입니다. GraphSwarm
다음을 포함하여 몇 가지 이점을 제공합니다.
GraphSwarm
활용하면 복잡한 워크 플로를 효율적으로 관리 할 수 있으며 작업을 조정하고 확장 가능한 방식으로 실행할 수 있습니다.
방법 | 설명 | 매개 변수 | 반환 값 |
---|---|---|---|
add_node | 그래프에 노드를 추가하십시오 | node : 노드 객체 | 없음 |
add_edge | 그래프에 가장자리를 추가하십시오 | edge : 가장자리 객체 | 없음 |
set_entry_points | 그래프의 진입 점을 설정하십시오 | entry_points : 노드 ID 목록 | 없음 |
set_end_points | 그래프의 종말점을 설정하십시오 | end_points : 노드 ID 목록 | 없음 |
visualize | 그래프의 시각적 표현을 생성합니다 | 없음 | 그래프의 문자열 표현 |
run | 워크 플로를 실행하십시오 | 없음 | 실행 결과 사전 |
입력 | 유형 | 설명 |
---|---|---|
Node | 물체 | 그래프 (에이전트 또는 작업)의 노드를 나타냅니다. |
Edge | 물체 | 두 노드를 연결하는 에지를 나타냅니다 |
entry_points | List [str] | 워크 플로가 시작되는 노드 ID 목록 |
end_points | List [str] | 워크 플로가 끝나는 노드 ID 목록 |
run
메소드는 그래프에서 모든 노드의 실행 결과를 포함하는 사전을 반환합니다.
import os
from dotenv import load_dotenv
from swarms import Agent , Edge , GraphWorkflow , Node , NodeType
from swarm_models import OpenAIChat
load_dotenv ()
api_key = os . environ . get ( "OPENAI_API_KEY" )
llm = OpenAIChat (
temperature = 0.5 , openai_api_key = api_key , max_tokens = 4000
)
agent1 = Agent ( llm = llm , max_loops = 1 , autosave = True , dashboard = True )
agent2 = Agent ( llm = llm , max_loops = 1 , autosave = True , dashboard = True )
def sample_task ():
print ( "Running sample task" )
return "Task completed"
wf_graph = GraphWorkflow ()
wf_graph . add_node ( Node ( id = "agent1" , type = NodeType . AGENT , agent = agent1 ))
wf_graph . add_node ( Node ( id = "agent2" , type = NodeType . AGENT , agent = agent2 ))
wf_graph . add_node (
Node ( id = "task1" , type = NodeType . TASK , callable = sample_task )
)
wf_graph . add_edge ( Edge ( source = "agent1" , target = "task1" ))
wf_graph . add_edge ( Edge ( source = "agent2" , target = "task1" ))
wf_graph . set_entry_points ([ "agent1" , "agent2" ])
wf_graph . set_end_points ([ "task1" ])
print ( wf_graph . visualize ())
# Run the workflow
results = wf_graph . run ()
print ( "Execution results:" , results )
MixtureOfAgents
이것은 논문을 기반으로 한 구현입니다. "혼합 된 -Agents는 https://arxiv.org/abs/2406.04692에서 사용할 수있는"Mix-of-Agents는 큰 언어 모델 기능을 향상시킵니다. GPT-4 OMNI를 능가하는 Alpacaeval 2.0, MT-Bench 및 Flask에서 최첨단 (SOTA) 결과를 달성합니다. 이 아키텍처는 특히 병렬화와 다른 루프에서 순차적 처리가 필요한 작업에 적합합니다.
방법 | 설명 | 매개 변수 | 반환 값 |
---|---|---|---|
__init__ | 혼합물 에이전트를 초기화하십시오 | name : 떼의 이름agents : 에이전트 객체 목록layers : 처리 계층 수final_agent : 최종 처리를위한 에이전트 | 없음 |
run | 떼를 실행하십시오 | task : 떼에 대한 입력 작업 | 모든 에이전트가 처리 된 후 최종 출력 |
입력 | 유형 | 설명 |
---|---|---|
name | str | 떼의 이름 |
agents | 목록 [에이전트] | 떼에서 사용할 에이전트 개체 목록 |
layers | int | 떼의 처리 층 수 |
final_agent | 대리인 | 최종 처리를 담당하는 에이전트 |
run
메소드는 모든 에이전트가 지정된 레이어 및 최종 에이전트에 따라 입력을 처리 한 후 최종 출력을 반환합니다.
import os
from swarm_models import OpenAIChat
from swarms import Agent , MixtureOfAgents
api_key = os . getenv ( "OPENAI_API_KEY" )
# Create individual agents with the OpenAIChat model
model = OpenAIChat (
openai_api_key = api_key , model_name = "gpt-4" , temperature = 0.1
)
# Agent 1: Financial Statement Analyzer
agent1 = Agent (
agent_name = "FinancialStatementAnalyzer" ,
llm = model ,
system_prompt = """You are a Financial Statement Analyzer specializing in 10-K SEC reports. Your primary focus is on analyzing the financial statements, including the balance sheet, income statement, and cash flow statement.
Key responsibilities:
1. Identify and explain significant changes in financial metrics year-over-year.
2. Calculate and interpret key financial ratios (e.g., liquidity ratios, profitability ratios, leverage ratios).
3. Analyze trends in revenue, expenses, and profitability.
4. Highlight any red flags or areas of concern in the financial statements.
5. Provide insights on the company's financial health and performance based on the data.
When analyzing, consider industry standards and compare the company's performance to its peers when possible. Your analysis should be thorough, data-driven, and provide actionable insights for investors and stakeholders.""" ,
max_loops = 1 ,
autosave = True ,
dashboard = False ,
verbose = True ,
dynamic_temperature_enabled = True ,
saved_state_path = "financial_statement_analyzer_state.json" ,
user_name = "swarms_corp" ,
retry_attempts = 1 ,
context_length = 200000 ,
return_step_meta = False ,
)
# Agent 2: Risk Assessment Specialist
agent2 = Agent (
agent_name = "RiskAssessmentSpecialist" ,
llm = model ,
system_prompt = """You are a Risk Assessment Specialist focusing on 10-K SEC reports. Your primary role is to identify, analyze, and evaluate potential risks disclosed in the report.
Key responsibilities:
1. Thoroughly review the "Risk Factors" section of the 10-K report.
2. Identify and categorize different types of risks (e.g., operational, financial, legal, market, technological).
3. Assess the potential impact and likelihood of each identified risk.
4. Analyze the company's risk mitigation strategies and their effectiveness.
5. Identify any emerging risks not explicitly mentioned but implied by the company's operations or market conditions.
6. Compare the company's risk profile with industry peers when possible.
Your analysis should provide a comprehensive overview of the company's risk landscape, helping stakeholders understand the potential challenges and uncertainties facing the business. Be sure to highlight any critical risks that could significantly impact the company's future performance or viability.""" ,
max_loops = 1 ,
autosave = True ,
dashboard = False ,
verbose = True ,
dynamic_temperature_enabled = True ,
saved_state_path = "risk_assessment_specialist_state.json" ,
user_name = "swarms_corp" ,
retry_attempts = 1 ,
context_length = 200000 ,
return_step_meta = False ,
)
# Agent 3: Business Strategy Evaluator
agent3 = Agent (
agent_name = "BusinessStrategyEvaluator" ,
llm = model ,
system_prompt = """You are a Business Strategy Evaluator specializing in analyzing 10-K SEC reports. Your focus is on assessing the company's overall strategy, market position, and future outlook.
Key responsibilities:
1. Analyze the company's business description, market opportunities, and competitive landscape.
2. Evaluate the company's products or services, including their market share and growth potential.
3. Assess the effectiveness of the company's current business strategy and its alignment with market trends.
4. Identify key performance indicators (KPIs) and evaluate the company's performance against these metrics.
5. Analyze management's discussion and analysis (MD&A) section to understand their perspective on the business.
6. Identify potential growth opportunities or areas for improvement in the company's strategy.
7. Compare the company's strategic position with key competitors in the industry.
Your analysis should provide insights into the company's strategic direction, its ability to create value, and its potential for future growth. Consider both short-term and long-term perspectives in your evaluation.""" ,
max_loops = 1 ,
autosave = True ,
dashboard = False ,
verbose = True ,
dynamic_temperature_enabled = True ,
saved_state_path = "business_strategy_evaluator_state.json" ,
user_name = "swarms_corp" ,
retry_attempts = 1 ,
context_length = 200000 ,
return_step_meta = False ,
)
# Aggregator Agent
aggregator_agent = Agent (
agent_name = "10KReportAggregator" ,
llm = model ,
system_prompt = """You are the 10-K Report Aggregator, responsible for synthesizing and summarizing the analyses provided by the Financial Statement Analyzer, Risk Assessment Specialist, and Business Strategy Evaluator. Your goal is to create a comprehensive, coherent, and insightful summary of the 10-K SEC report.
Key responsibilities:
1. Integrate the financial analysis, risk assessment, and business strategy evaluation into a unified report.
2. Identify and highlight the most critical information and insights from each specialist's analysis.
3. Reconcile any conflicting information or interpretations among the specialists' reports.
4. Provide a balanced view of the company's overall performance, risks, and strategic position.
5. Summarize key findings and their potential implications for investors and stakeholders.
6. Identify any areas where further investigation or clarification may be needed.
Your final report should be well-structured, easy to understand, and provide a holistic view of the company based on the 10-K SEC report. It should offer valuable insights for decision-making while acknowledging any limitations or uncertainties in the analysis.""" ,
max_loops = 1 ,
autosave = True ,
dashboard = False ,
verbose = True ,
dynamic_temperature_enabled = True ,
saved_state_path = "10k_report_aggregator_state.json" ,
user_name = "swarms_corp" ,
retry_attempts = 1 ,
context_length = 200000 ,
return_step_meta = False ,
)
# Create the Mixture of Agents class
moa = MixtureOfAgents (
agents = [ agent1 , agent2 , agent3 ],
aggregator_agent = aggregator_agent ,
aggregator_system_prompt = """As the 10-K Report Aggregator, your task is to synthesize the analyses provided by the Financial Statement Analyzer, Risk Assessment Specialist, and Business Strategy Evaluator into a comprehensive and coherent report.
Follow these steps:
1. Review and summarize the key points from each specialist's analysis.
2. Identify common themes and insights across the analyses.
3. Highlight any discrepancies or conflicting interpretations, if present.
4. Provide a balanced and integrated view of the company's financial health, risks, and strategic position.
5. Summarize the most critical findings and their potential impact on investors and stakeholders.
6. Suggest areas for further investigation or monitoring, if applicable.
Your final output should be a well-structured, insightful report that offers a holistic view of the company based on the 10-K SEC report analysis.""" ,
layers = 3 ,
)
# Example usage
company_name = "NVIDIA"
out = moa . run (
f"Analyze the latest 10-K SEC report for { company_name } . Provide a comprehensive summary of the company's financial performance, risk profile, and business strategy."
)
print ( out )
SpreadSheetSwarm
은 수천 명의 에이전트의 동시 관리 및 감독을 위해 설계되어 효율적인 작업 처리 및 출력 분석을위한 일대일 접근 방식을 용이하게합니다.
방법 | 설명 | 매개 변수 | 반환 값 |
---|---|---|---|
__init__ | Spreadsheetswarm을 초기화하십시오 | name : 떼의 이름description : 떼에 대한 설명agents : 에이전트 객체 목록autosave_on : AutoSave를 활성화하는 부울save_file_path : 스프레드 시트를 저장하는 경로run_all_agents : 모든 에이전트를 실행하는 부울max_loops : 최대 루프 수 | 없음 |
run | 떼를 실행하십시오 | task : 떼에 대한 입력 작업 | 에이전트 출력 사전 |
입력 | 유형 | 설명 |
---|---|---|
name | str | 떼의 이름 |
description | str | 떼의 목적에 대한 설명 |
agents | 목록 [에이전트] | 떼에서 사용할 에이전트 개체 목록 |
autosave_on | 부 | 결과의 자동 절도를 활성화합니다 |
save_file_path | str | 스프레드 시트 결과를 저장하는 경로 |
run_all_agents | 부 | 모든 에이전트를 실행할 것인지 또는 관련성에 따라 선택할지 여부 |
max_loops | int | 최대 처리 루프 수 |
run
메소드는 작업을 처리 한 각 에이전트의 출력을 포함하는 사전을 반환합니다.
문서에서 자세히 알아보십시오.
import os
from swarms import Agent
from swarm_models import OpenAIChat
from swarms . structs . spreadsheet_swarm import SpreadSheetSwarm
# Define custom system prompts for each social media platform
TWITTER_AGENT_SYS_PROMPT = """
You are a Twitter marketing expert specializing in real estate. Your task is to create engaging, concise tweets to promote properties, analyze trends to maximize engagement, and use appropriate hashtags and timing to reach potential buyers.
"""
INSTAGRAM_AGENT_SYS_PROMPT = """
You are an Instagram marketing expert focusing on real estate. Your task is to create visually appealing posts with engaging captions and hashtags to showcase properties, targeting specific demographics interested in real estate.
"""
FACEBOOK_AGENT_SYS_PROMPT = """
You are a Facebook marketing expert for real estate. Your task is to craft posts optimized for engagement and reach on Facebook, including using images, links, and targeted messaging to attract potential property buyers.
"""
LINKEDIN_AGENT_SYS_PROMPT = """
You are a LinkedIn marketing expert for the real estate industry. Your task is to create professional and informative posts, highlighting property features, market trends, and investment opportunities, tailored to professionals and investors.
"""
EMAIL_AGENT_SYS_PROMPT = """
You are an Email marketing expert specializing in real estate. Your task is to write compelling email campaigns to promote properties, focusing on personalization, subject lines, and effective call-to-action strategies to drive conversions.
"""
# Example usage:
api_key = os . getenv ( "OPENAI_API_KEY" )
# Model
model = OpenAIChat (
openai_api_key = api_key , model_name = "gpt-4o-mini" , temperature = 0.1
)
# Initialize your agents for different social media platforms
agents = [
Agent (
agent_name = "Twitter-RealEstate-Agent" ,
system_prompt = TWITTER_AGENT_SYS_PROMPT ,
llm = model ,
max_loops = 1 ,
dynamic_temperature_enabled = True ,
saved_state_path = "twitter_realestate_agent.json" ,
user_name = "realestate_swarms" ,
retry_attempts = 1 ,
),
Agent (
agent_name = "Instagram-RealEstate-Agent" ,
system_prompt = INSTAGRAM_AGENT_SYS_PROMPT ,
llm = model ,
max_loops = 1 ,
dynamic_temperature_enabled = True ,
saved_state_path = "instagram_realestate_agent.json" ,
user_name = "realestate_swarms" ,
retry_attempts = 1 ,
),
Agent (
agent_name = "Facebook-RealEstate-Agent" ,
system_prompt = FACEBOOK_AGENT_SYS_PROMPT ,
llm = model ,
max_loops = 1 ,
dynamic_temperature_enabled = True ,
saved_state_path = "facebook_realestate_agent.json" ,
user_name = "realestate_swarms" ,
retry_attempts = 1 ,
),
Agent (
agent_name = "LinkedIn-RealEstate-Agent" ,
system_prompt = LINKEDIN_AGENT_SYS_PROMPT ,
llm = model ,
max_loops = 1 ,
dynamic_temperature_enabled = True ,
saved_state_path = "linkedin_realestate_agent.json" ,
user_name = "realestate_swarms" ,
retry_attempts = 1 ,
),
Agent (
agent_name = "Email-RealEstate-Agent" ,
system_prompt = EMAIL_AGENT_SYS_PROMPT ,
llm = model ,
max_loops = 1 ,
dynamic_temperature_enabled = True ,
saved_state_path = "email_realestate_agent.json" ,
user_name = "realestate_swarms" ,
retry_attempts = 1 ,
),
]
# Create a Swarm with the list of agents
swarm = SpreadSheetSwarm (
name = "Real-Estate-Marketing-Swarm" ,
description = "A swarm that processes real estate marketing tasks using multiple agents on different threads." ,
agents = agents ,
autosave_on = True ,
save_file_path = "real_estate_marketing_spreadsheet.csv" ,
run_all_agents = False ,
max_loops = 2 ,
)
# Run the swarm
swarm . run (
task = """
Create posts to promote luxury properties in North Texas, highlighting their features, location, and investment potential. Include relevant hashtags, images, and engaging captions.
Property:
$10,399,000
1609 Meandering Way Dr, Roanoke, TX 76262
Link to the property: https://www.zillow.com/homedetails/1609-Meandering-Way-Dr-Roanoke-TX-76262/308879785_zpid/
What's special
Unveiling a new custom estate in the prestigious gated Quail Hollow Estates! This impeccable residence, set on a sprawling acre surrounded by majestic trees, features a gourmet kitchen equipped with top-tier Subzero and Wolf appliances. European soft-close cabinets and drawers, paired with a double Cambria Quartzite island, perfect for family gatherings. The first-floor game room&media room add extra layers of entertainment. Step into the outdoor sanctuary, where a sparkling pool and spa, and sunken fire pit, beckon leisure. The lavish master suite features stunning marble accents, custom his&her closets, and a secure storm shelter.Throughout the home,indulge in the visual charm of designer lighting and wallpaper, elevating every space. The property is complete with a 6-car garage and a sports court, catering to the preferences of basketball or pickleball enthusiasts. This residence seamlessly combines luxury&recreational amenities, making it a must-see for the discerning buyer.
Facts & features
Interior
Bedrooms & bathrooms
Bedrooms: 6
Bathrooms: 8
Full bathrooms: 7
1/2 bathrooms: 1
Primary bedroom
Bedroom
Features: Built-in Features, En Suite Bathroom, Walk-In Closet(s)
Cooling
Central Air, Ceiling Fan(s), Electric
Appliances
Included: Built-In Gas Range, Built-In Refrigerator, Double Oven, Dishwasher, Gas Cooktop, Disposal, Ice Maker, Microwave, Range, Refrigerator, Some Commercial Grade, Vented Exhaust Fan, Warming Drawer, Wine Cooler
Features
Wet Bar, Built-in Features, Dry Bar, Decorative/Designer Lighting Fixtures, Eat-in Kitchen, Elevator, High Speed Internet, Kitchen Island, Pantry, Smart Home, Cable TV, Walk-In Closet(s), Wired for Sound
Flooring: Hardwood
Has basement: No
Number of fireplaces: 3
Fireplace features: Living Room, Primary Bedroom
Interior area
Total interior livable area: 10,466 sqft
Total spaces: 12
Parking features: Additional Parking
Attached garage spaces: 6
Carport spaces: 6
Features
Levels: Two
Stories: 2
Patio & porch: Covered
Exterior features: Built-in Barbecue, Barbecue, Gas Grill, Lighting, Outdoor Grill, Outdoor Living Area, Private Yard, Sport Court, Fire Pit
Pool features: Heated, In Ground, Pool, Pool/Spa Combo
Fencing: Wrought Iron
Lot
Size: 1.05 Acres
Details
Additional structures: Outdoor Kitchen
Parcel number: 42232692
Special conditions: Standard
Construction
Type & style
Home type: SingleFamily
Architectural style: Contemporary/Modern,Detached
Property subtype: Single Family Residence
"""
)
ForestSwarm
ForestSwarm
아키텍처는 나무 모음에서 가장 적합한 에이전트를 동적으로 선택하여 효율적인 작업 할당을 위해 설계되었습니다. 이는 에이전트가 당면한 작업과의 관련성에 따라 선택되는 비동기 작업 처리를 통해 달성됩니다. 관련성은 각 에이전트와 관련된 시스템 프롬프트와 작업 자체에 존재하는 키워드 간의 유사성을 계산하여 결정됩니다. ForestSwarm
의 작동 방식에 대한 심층적 인 이해는 공식 문서를 참조하십시오.
방법 | 설명 | 매개 변수 | 반환 값 |
---|---|---|---|
__init__ | ForestSwarm을 초기화하십시오 | trees : 나무 물체 목록 | 없음 |
run | Forestswarm을 실행하십시오 | task : 떼에 대한 입력 작업 | 가장 관련성이 높은 에이전트의 출력 |
입력 | 유형 | 설명 |
---|---|---|
trees | 목록 [나무] | 트리 객체 목록, 각각은 treeagent 객체를 포함합니다 |
task | str | ForestSwarm에서 처리해야 할 작업 |
run
메소드는 입력 작업에 따라 선택된 가장 관련성있는 에이전트의 출력을 반환합니다.
from swarms . structs . tree_swarm import TreeAgent , Tree , ForestSwarm
# Create agents with varying system prompts and dynamically generated distances/keywords
agents_tree1 = [
TreeAgent (
system_prompt = """You are an expert Stock Analysis Agent with deep knowledge of financial markets, technical analysis, and fundamental analysis. Your primary function is to analyze stock performance, market trends, and provide actionable insights. When analyzing stocks:
1. Always start with a brief overview of the current market conditions.
2. Use a combination of technical indicators (e.g., moving averages, RSI, MACD) and fundamental metrics (e.g., P/E ratio, EPS growth, debt-to-equity).
3. Consider both short-term and long-term perspectives in your analysis.
4. Provide clear buy, hold, or sell recommendations with supporting rationale.
5. Highlight potential risks and opportunities specific to each stock or sector.
6. Use bullet points for clarity when listing key points or metrics.
7. If relevant, compare the stock to its peers or sector benchmarks.
Remember to maintain objectivity and base your analysis on factual data. If asked about future performance, always include a disclaimer about market unpredictability. Your goal is to provide comprehensive, accurate, and actionable stock analysis to inform investment decisions.""" ,
agent_name = "Stock Analysis Agent" ,
),
TreeAgent (
system_prompt = """You are a highly skilled Financial Planning Agent, specializing in personal and corporate financial strategies. Your role is to provide comprehensive financial advice tailored to each client's unique situation. When creating financial plans:
1. Begin by asking key questions about the client's financial goals, current situation, and risk tolerance.
2. Develop a holistic view of the client's finances, including income, expenses, assets, and liabilities.
3. Create detailed, step-by-step action plans to achieve financial goals.
4. Provide specific recommendations for budgeting, saving, and investing.
5. Consider tax implications and suggest tax-efficient strategies.
6. Incorporate risk management and insurance planning into your recommendations.
7. Use charts or tables to illustrate financial projections and scenarios.
8. Regularly suggest reviewing and adjusting the plan as circumstances change.
Always prioritize the client's best interests and adhere to fiduciary standards. Explain complex financial concepts in simple terms, and be prepared to justify your recommendations with data and reasoning.""" ,
agent_name = "Financial Planning Agent" ,
),
TreeAgent (
agent_name = "Retirement Strategy Agent" ,
system_prompt = """You are a specialized Retirement Strategy Agent, focused on helping individuals and couples plan for a secure and comfortable retirement. Your expertise covers various aspects of retirement planning, including savings strategies, investment allocation, and income generation during retirement. When developing retirement strategies:
1. Start by assessing the client's current age, desired retirement age, and expected lifespan.
2. Calculate retirement savings goals based on desired lifestyle and projected expenses.
3. Analyze current retirement accounts (e.g., 401(k), IRA) and suggest optimization strategies.
4. Provide guidance on asset allocation and rebalancing as retirement approaches.
5. Explain various retirement income sources (e.g., Social Security, pensions, annuities).
6. Discuss healthcare costs and long-term care planning.
7. Offer strategies for tax-efficient withdrawals during retirement.
8. Consider estate planning and legacy goals in your recommendations.
Use Monte Carlo simulations or other statistical tools to illustrate the probability of retirement success. Always emphasize the importance of starting early and the power of compound interest. Be prepared to adjust strategies based on changing market conditions or personal circumstances.""" ,
),
]
agents_tree2 = [
TreeAgent (
system_prompt = """You are a knowledgeable Tax Filing Agent, specializing in personal and business tax preparation and strategy. Your role is to ensure accurate tax filings while maximizing legitimate deductions and credits. When assisting with tax matters:
1. Start by gathering all necessary financial information and documents.
2. Stay up-to-date with the latest tax laws and regulations, including state-specific rules.
3. Identify all applicable deductions and credits based on the client's situation.
4. Provide step-by-step guidance for completing tax forms accurately.
5. Explain tax implications of various financial decisions.
6. Offer strategies for tax-efficient investing and income management.
7. Assist with estimated tax payments for self-employed individuals or businesses.
8. Advise on record-keeping practices for tax purposes.
Always prioritize compliance with tax laws while ethically minimizing tax liability. Be prepared to explain complex tax concepts in simple terms and provide rationale for your recommendations. If a situation is beyond your expertise, advise consulting a certified tax professional or IRS resources.""" ,
agent_name = "Tax Filing Agent" ,
),
TreeAgent (
system_prompt = """You are a sophisticated Investment Strategy Agent, adept at creating and managing investment portfolios to meet diverse financial goals. Your expertise covers various asset classes, market analysis, and risk management techniques. When developing investment strategies:
1. Begin by assessing the client's investment goals, time horizon, and risk tolerance.
2. Provide a comprehensive overview of different asset classes and their risk-return profiles.
3. Create diversified portfolio recommendations based on modern portfolio theory.
4. Explain the benefits and risks of various investment vehicles (e.g., stocks, bonds, ETFs, mutual funds).
5. Incorporate both passive and active investment strategies as appropriate.
6. Discuss the importance of regular portfolio rebalancing and provide a rebalancing strategy.
7. Consider tax implications of investment decisions and suggest tax-efficient strategies.
8. Provide ongoing market analysis and suggest portfolio adjustments as needed.
Use historical data and forward-looking projections to illustrate potential outcomes. Always emphasize the importance of long-term investing and the risks of market timing. Be prepared to explain complex investment concepts in clear, accessible language.""" ,
agent_name = "Investment Strategy Agent" ,
),
TreeAgent (
system_prompt = """You are a specialized ROTH IRA Agent, focusing on the intricacies of Roth Individual Retirement Accounts. Your role is to provide expert guidance on Roth IRA rules, benefits, and strategies to maximize their value for retirement planning. When advising on Roth IRAs:
1. Explain the fundamental differences between traditional and Roth IRAs.
2. Clarify Roth IRA contribution limits and income eligibility requirements.
3. Discuss the tax advantages of Roth IRAs, including tax-free growth and withdrawals.
4. Provide guidance on Roth IRA conversion strategies and their tax implications.
5. Explain the five-year rule and how it affects Roth IRA withdrawals.
6. Offer strategies for maximizing Roth IRA contributions, such as the backdoor Roth IRA method.
7. Discuss how Roth IRAs fit into overall retirement and estate planning strategies.
8. Provide insights on investment choices within a Roth IRA to maximize tax-free growth.
Always stay current with IRS regulations regarding Roth IRAs. Be prepared to provide numerical examples to illustrate the long-term benefits of Roth IRAs. Emphasize the importance of considering individual financial situations when making Roth IRA decisions.""" ,
agent_name = "ROTH IRA Agent" ,
),
]
# Create trees
tree1 = Tree ( tree_name = "Financial Tree" , agents = agents_tree1 )
tree2 = Tree ( tree_name = "Investment Tree" , agents = agents_tree2 )
# Create the ForestSwarm
multi_agent_structure = ForestSwarm ( trees = [ tree1 , tree2 ])
# Run a task
task = "What are the best platforms to do our taxes on"
output = multi_agent_structure . run ( task )
print ( output )
SwarmRouter
SwarmRouter
클래스는 작업 실행을 위해 다양한 유형의 Swarm을 관리하도록 설계된 유연한 라우팅 시스템입니다. AgentRearrange
, MixtureOfAgents
, SpreadSheetSwarm
, SequentialWorkflow
및 ConcurrentWorkflow
포함한 다양한 떼 유형과 상호 작용할 수있는 통합 인터페이스를 제공합니다. 우리는 새로운 아키텍처를 진행함에 따라 점점 더 많은 떼 아키텍처를 지속적으로 추가 할 것입니다.
name
(str) : Swarmrouter 인스턴스의 이름.description
(str) : Swarmrouter 인스턴스 설명.max_loops
(int) : 수행 할 최대 루프 수.agents
(목록 [에이전트]) : 떼에서 사용할 에이전트 객체 목록.swarm_type
(swarmtype) : 사용할 떼 유형.swarm
(Union [AgentrearRange, MixtureOfagents, Spreadsheetswarm, 순차적 인 작업 플로우, 동시 작업 플로우]) : 인스턴스화 된 Swarm Object.logs
(list [swarmlog]) : 작업 중에 캡처 된 로그 항목 목록. __init__(self, name: str, description: str, max_loops: int, agents: List[Agent], swarm_type: SwarmType, *args, **kwargs)
: warmrouter를 초기화합니다._create_swarm(self, *args, **kwargs)
: 지정된 떼 유형을 생성하고 반환합니다._log(self, level: str, message: str, task: str, metadata: Dict[str, Any])
: 로그 항목을 만들고 로그 목록에 추가하십시오.run(self, task: str, *args, **kwargs)
: 선택한 떼에서 지정된 작업을 실행하십시오.get_logs(self)
: 기록 된 모든 항목을 검색합니다. import os
from dotenv import load_dotenv
from swarms import Agent
from swarm_models import OpenAIChat
from swarms . structs . swarm_router import SwarmRouter , SwarmType
load_dotenv ()
# Get the OpenAI API key from the environment variable
api_key = os . getenv ( "GROQ_API_KEY" )
# Model
model = OpenAIChat (
openai_api_base = "https://api.groq.com/openai/v1" ,
openai_api_key = api_key ,
model_name = "llama-3.1-70b-versatile" ,
temperature = 0.1 ,
)
# 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:
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
3. Pulling out relevant market data from industry reports and analyses
4. Extracting operational KPIs from management presentations and internal reports
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."""
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
2. Summarizing legal documents, highlighting key terms and potential risks
3. Condensing industry reports to capture essential market trends and competitive dynamics
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
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:
1. Analyzing historical financial statements to identify trends and potential issues
2. Evaluating the quality of earnings and potential adjustments to EBITDA
3. Assessing working capital requirements and cash flow dynamics
4. Analyzing capital structure and debt capacity
5. Evaluating financial projections and underlying assumptions
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:
1. Analyzing industry trends, growth drivers, and potential disruptors
2. Evaluating competitive landscape and market positioning
3. Assessing market size, segmentation, and growth potential
4. Analyzing customer dynamics, including concentration and loyalty
5. Identifying potential regulatory or macroeconomic impacts on the market
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:
1. Evaluating operational efficiency and identifying improvement opportunities
2. Analyzing supply chain and procurement processes
3. Assessing sales and marketing effectiveness
4. Evaluating IT systems and digital capabilities
5. Identifying potential synergies in merger or add-on acquisition scenarios
Provide detailed operational analysis to uncover value creation opportunities and potential risks."""
# Initialize specialized agents
data_extractor_agent = Agent (
agent_name = "Data-Extractor" ,
system_prompt = DATA_EXTRACTOR_PROMPT ,
llm = model ,
max_loops = 1 ,
autosave = True ,
verbose = True ,
dynamic_temperature_enabled = True ,
saved_state_path = "data_extractor_agent.json" ,
user_name = "pe_firm" ,
retry_attempts = 1 ,
context_length = 200000 ,
output_type = "string" ,
)
summarizer_agent = Agent (
agent_name = "Document-Summarizer" ,
system_prompt = SUMMARIZER_PROMPT ,
llm = model ,
max_loops = 1 ,
autosave = True ,
verbose = True ,
dynamic_temperature_enabled = True ,
saved_state_path = "summarizer_agent.json" ,
user_name = "pe_firm" ,
retry_attempts = 1 ,
context_length = 200000 ,
output_type = "string" ,
)
financial_analyst_agent = Agent (
agent_name = "Financial-Analyst" ,
system_prompt = FINANCIAL_ANALYST_PROMPT ,
llm = model ,
max_loops = 1 ,
autosave = True ,
verbose = True ,
dynamic_temperature_enabled = True ,
saved_state_path = "financial_analyst_agent.json" ,
user_name = "pe_firm" ,
retry_attempts = 1 ,
context_length = 200000 ,
output_type = "string" ,
)
market_analyst_agent = Agent (
agent_name = "Market-Analyst" ,
system_prompt = MARKET_ANALYST_PROMPT ,
llm = model ,
max_loops = 1 ,
autosave = True ,
verbose = True ,
dynamic_temperature_enabled = True ,
saved_state_path = "market_analyst_agent.json" ,
user_name = "pe_firm" ,
retry_attempts = 1 ,
context_length = 200000 ,
output_type = "string" ,
)
operational_analyst_agent = Agent (
agent_name = "Operational-Analyst" ,
system_prompt = OPERATIONAL_ANALYST_PROMPT ,
llm = model ,
max_loops = 1 ,
autosave = True ,
verbose = True ,
dynamic_temperature_enabled = True ,
saved_state_path = "operational_analyst_agent.json" ,
user_name = "pe_firm" ,
retry_attempts = 1 ,
context_length = 200000 ,
output_type = "string" ,
)
# Initialize the SwarmRouter
router = SwarmRouter (
name = "pe-document-analysis-swarm" ,
description = "Analyze documents for private equity due diligence and investment decision-making" ,
max_loops = 1 ,
agents = [
data_extractor_agent ,
summarizer_agent ,
financial_analyst_agent ,
market_analyst_agent ,
operational_analyst_agent ,
],
swarm_type = "ConcurrentWorkflow" , # or "SequentialWorkflow" or "ConcurrentWorkflow" or
)
# Example usage
if __name__ == "__main__" :
# Run a comprehensive private equity document analysis task
result = router . run (
"Where is the best place to find template term sheets for series A startups. Provide links and references"
)
print ( result )
# Retrieve and print logs
for log in router . get_logs ():
print ( f" { log . timestamp } - { log . level } : { log . message } " )
다른 떼 유형으로 여러 Swarmrouter 인스턴스를 만들 수 있습니다.
sequential_router = SwarmRouter (
name = "SequentialRouter" ,
agents = [
data_extractor_agent ,
summarizer_agent ,
financial_analyst_agent ,
market_analyst_agent ,
operational_analyst_agent ,
],
swarm_type = SwarmType . SequentialWorkflow
)
concurrent_router = SwarmRouter (
name = "ConcurrentRouter" ,
agents = [
data_extractor_agent ,
summarizer_agent ,
financial_analyst_agent ,
market_analyst_agent ,
operational_analyst_agent ,
],
swarm_type = SwarmType . ConcurrentWorkflow
)
사용 사례 : 복잡한 다중 단계 작업을위한 에이전트 순서 최적화.
rearrange_router = SwarmRouter (
name = "TaskOptimizer" ,
description = "Optimize agent order for multi-step tasks" ,
max_loops = 3 ,
agents = [
data_extractor_agent ,
summarizer_agent ,
financial_analyst_agent ,
market_analyst_agent ,
operational_analyst_agent ,
],
swarm_type = SwarmType . AgentRearrange ,
flow = f" { data_extractor . name } -> { analyzer . name } -> { summarizer . name } "
)
result = rearrange_router . run ( "Analyze and summarize the quarterly financial report" )
사용 사례 : 포괄적 인 분석을 위해 다양한 전문가 에이전트를 결합합니다.
mixture_router = SwarmRouter (
name = "ExpertPanel" ,
description = "Combine insights from various expert agents" ,
max_loops = 1 ,
agents = [
data_extractor_agent ,
summarizer_agent ,
financial_analyst_agent ,
market_analyst_agent ,
operational_analyst_agent ,
],
swarm_type = SwarmType . MixtureOfAgents
)
result = mixture_router . run ( "Evaluate the potential acquisition of TechStartup Inc." )
Kye Gomez의 Swarms의 제작자 및 리드 관리자와 함께 설치, 사용 예제를 시작하고 맞춤형 사용 사례를 구축하기 시작하는 방법을 보여줄 것입니다! 여기를 클릭하십시오
문서는 다음과 같습니다. docs.swarms.world
Swarms 패키지는 극도로 사용 가능성과 이해를 위해 세분화 된 것으로 제작되었으며, Agent
패키지는 swarms.agents
과 같은 다양한 모듈로 나뉘어져 있으며, 사전 제작 된 에이전트를 보유하는 swarms.structs
. 에이전트 구조. 가장 중요한 3 가지는 structs
, models
및 agents
입니다.
├── __init__.py
├── agents
├── artifacts
├── memory
├── schemas
├── models - > swarm_models
├── prompts
├── structs
├── telemetry
├── tools
├── utils
└── workers
가장 쉬운 방법은 good first issue
태그로 문제를 선택하는 것입니다. 기고 가이드 라인을 여기에서 읽으십시오. 버그 보고서? 여기 파일 | 기능 요청? 여기에 파일
Swarms는 오픈 소스 프로젝트이며 기부금은 매우 환영합니다. 기여하려면 새로운 기능을 만들거나 버그를 수정하거나 인프라를 개선 할 수 있습니다. 로드맵 토론에 참여하려면 Contributing.md와 기고위원회를 참조하십시오!
여기에서 우리를 지원함으로써 구현할 버그, 기능 및 데모를 가속화합니다.
떼에 대한 실시간 지원, 아이디어 및 토론을 위해 전 세계의 성장하는 커뮤니티에 가입 하시겠습니까?
GNU Affero 일반 공개 라이센스