
เฟรมเวิร์กการจัดทำแบบหลายเกณฑ์ระดับองค์กร
- Twitter • ? Discord • แพลตฟอร์ม Swarms • ? เอกสาร
| หมวดหมู่ | คุณสมบัติ | ประโยชน์ |
|---|---|---|
| - สถาปัตยกรรมองค์กร | •โครงสร้างพื้นฐานพร้อมการผลิต •ระบบความน่าเชื่อถือสูง •การออกแบบแบบแยกส่วน •การบันทึกที่ครอบคลุม | •การหยุดทำงานลดลง •การบำรุงรักษาง่ายขึ้น •ดีบักดีกว่า •การตรวจสอบขั้นสูง |
| - ตัวแทนออเคสตร้า | •ฝูงลำดับชั้น •การประมวลผลแบบขนาน •เวิร์กโฟลว์ตามลำดับ •เวิร์กโฟลว์ที่ใช้กราฟ •การจัดเรียงตัวแทนแบบไดนามิกใหม่ | •การจัดการงานที่ซับซ้อน •ปรับปรุงประสิทธิภาพ •เวิร์กโฟลว์ที่ยืดหยุ่น •การดำเนินการที่ดีที่สุด |
| ความสามารถในการรวม | •การสนับสนุนแบบหลายรูปแบบ •การสร้างตัวแทนที่กำหนดเอง •ห้องสมุดเครื่องมือที่กว้างขวาง •ระบบหน่วยความจำหลายระบบ | •ความยืดหยุ่นของผู้ให้บริการ •โซลูชั่นที่กำหนดเอง •ฟังก์ชั่นขยาย •การจัดการหน่วยความจำที่ปรับปรุงแล้ว |
| - ความยืดหยุ่น | •การประมวลผลพร้อมกัน •การจัดการทรัพยากร •โหลดบาลานซ์ •การปรับขนาดแนวนอน | •ปริมาณงานที่สูงขึ้น •การใช้ทรัพยากรที่มีประสิทธิภาพ •ประสิทธิภาพที่ดีขึ้น •ปรับขนาดได้ง่าย |
| เครื่องมือนักพัฒนา | • API ง่ายๆ •เอกสารที่กว้างขวาง •ชุมชนที่ใช้งานอยู่ •เครื่องมือ CLI | •การพัฒนาที่เร็วขึ้น •เส้นโค้งการเรียนรู้ง่าย •การสนับสนุนชุมชน •การปรับใช้อย่างรวดเร็ว |
| - คุณสมบัติด้านความปลอดภัย | •การจัดการข้อผิดพลาด •อัตราการ จำกัด •การติดตามการรวม •การบันทึกการตรวจสอบ | •ปรับปรุงความน่าเชื่อถือ •การป้องกัน API •การตรวจสอบที่ดีขึ้น •การติดตามขั้นสูง |
| คุณสมบัติขั้นสูง | •สเปรดชีต •แชทเป็นกลุ่ม • Agent Registry •ส่วนผสมของตัวแทน | •การจัดการตัวแทนมวลชน • AI การทำงานร่วมกัน •การควบคุมส่วนกลาง •โซลูชั่นที่ซับซ้อน |
| - การสนับสนุนผู้ให้บริการ | • openai •มานุษยวิทยา • Chromadb •ผู้ให้บริการที่กำหนดเอง | •ความยืดหยุ่นของผู้ให้บริการ •ตัวเลือกการจัดเก็บข้อมูล •การรวมที่กำหนดเอง •ความเป็นอิสระของผู้ขาย |
| - คุณสมบัติการผลิต | •การลองใหม่โดยอัตโนมัติ •สนับสนุน Async •การจัดการสิ่งแวดล้อม •พิมพ์ความปลอดภัย | •ความน่าเชื่อถือที่ดีขึ้น •ปรับปรุงประสิทธิภาพ •การกำหนดค่าที่ง่าย •รหัสปลอดภัยยิ่งขึ้น |
| ใช้การสนับสนุนเคส | •ตัวแทนเฉพาะงาน •เวิร์กโฟลว์ที่กำหนดเอง •โซลูชั่นอุตสาหกรรม •เฟรมเวิร์กที่ขยายได้ | •การปรับใช้อย่างรวดเร็ว •โซลูชั่นที่ยืดหยุ่น •ความพร้อมของอุตสาหกรรม •ปรับแต่งได้ง่าย |
python3.10 ขึ้นไป!$ pip install -U swarms และอย่าลืมติดตั้งฝูง!.env พร้อมคีย์ API จากผู้ให้บริการของคุณเช่น OPENAI_API_KEY , ANTHROPIC_API_KEY.env ด้วยพื้นที่ทำงานที่คุณต้องการ: WORKSPACE_DIR="agent_workspace" หรือทำในเทอร์มินัลของคุณด้วย export WORKSPACE_DIR="agent_workspace"swarms onboarding เพื่อให้คุณเริ่มต้น อ้างถึงเอกสารของเราสำหรับรายละเอียดการใช้งานเกรดการผลิต
| ส่วน | ลิงค์ |
|---|---|
| การติดตั้ง | การติดตั้ง |
| เร็ว | เริ่มต้นใช้งาน |
| กลไกภายในตัวแทน | สถาปัตยกรรมตัวแทน |
| ตัวแทน API | ตัวแทน API |
| การบูรณาการตัวแทนภายนอก griptape, autogen ฯลฯ | การรวม API ภายนอก |
| การสร้างตัวแทนจาก Yaml | การสร้างตัวแทนจาก Yaml |
| ทำไมคุณต้องมีฝูง | เหตุใดจึงจำเป็นต้องมีการทำงานร่วมกันแบบหลายหน่วย |
| การวิเคราะห์สถาปัตยกรรมฝูง | สถาปัตยกรรมฝูง |
| การเลือกฝูงที่เหมาะสมสำหรับปัญหาทางธุรกิจของคุณ " | คลิกที่นี่ |
| เอกสาร AgentRearRange | คลิกที่นี่ |
$ pip3 install -U swarms ตอนนี้คุณได้ดาวน์โหลดฝูงด้วย pip3 install -U swarms แล้วเราสามารถเข้าถึง 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 ที่ออกแบบมาเพื่อดำเนินการงานอย่างอิสระ มันหลอมรวม LLMS เครื่องมือและความสามารถของหน่วยความจำระยะยาวเพื่อสร้างเอเจนต์สแต็กเต็มรูปแบบ คลาส Agent สามารถปรับแต่งได้สูงช่วยให้สามารถควบคุมพฤติกรรมและการโต้ตอบได้อย่างละเอียด
run วิธี run เป็นจุดเริ่มต้นหลักสำหรับการดำเนินงานด้วย Agent เอเจนต์ มันยอมรับสตริงงานเป็นงานอินพุตหลักและประมวลผลตามการกำหนดค่าของตัวแทน และยังสามารถยอมรับพารามิเตอร์ img เช่น img="image_filepath.png เพื่อประมวลผลภาพหากคุณมี VLM
คลาส 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"
) Agent ที่ติดตั้งหน่วยความจำระยะยาวเสมือนที่ไม่ จำกัด โดยใช้ RAG (กราฟตัวแทนเชิงสัมพันธ์) สำหรับการทำความเข้าใจเอกสารขั้นสูงการวิเคราะห์และความสามารถในการดึงข้อมูล
Mermaid Diagram สำหรับการรวมผ้าขี้ริ้ว
กราฟ TD
A [เริ่มต้นตัวแทนด้วย RAG] -> B [รับงาน]
B-> C [Query Memory ระยะยาว]
C -> D [งานกระบวนการที่มีบริบท]
d -> e [สร้างการตอบสนอง]
E-> F [อัปเดตหน่วยความจำระยะยาว]
f -> g [ส่งกลับออก]
ขั้นตอนที่ 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() | ดึงเอกสารทั้งหมดจากโฟลเดอร์ DOC |
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 เป็นประเภทเอาท์พุทต่อไปนี้เป็นตัวอย่างของเอเจนต์ที่ใส่ 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 )ToolAgentToolagent เป็นตัวแทนที่สามารถใช้เครื่องมือผ่านการเรียกใช้ฟังก์ชัน 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
นี่คือวิธีที่คุณสามารถสร้างเอเจนต์ กริปเป้ แบบกำหนดเองที่รวมเข้ากับเฟรมเวิร์ก Swarms โดยการสืบทอดจากคลาส Agent ใน ฝูง และเอาชนะ 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 และรวมตัวแทน Griptape เข้าด้วยกันWebScraperTool , PromptSummaryTool , FileManagerTool ) อนุญาตให้มีการขูดเว็บการสรุปและการจัดการไฟล์ตอนนี้คุณสามารถเสียบตัวแทนกริปเป้แบบกำหนดเองนี้เข้ากับ เฟรมเวิร์ก Swarms ได้อย่างง่ายดายและใช้งานเพื่อเรียกใช้งาน!
ฝูงหมายถึงกลุ่มตัวแทนมากกว่าสองคนที่ทำงานร่วมกันเพื่อให้บรรลุเป้าหมายร่วมกัน ตัวแทนเหล่านี้สามารถเป็นหน่วยงานซอฟต์แวร์เช่น LLM ที่มีปฏิสัมพันธ์ซึ่งกันและกันเพื่อทำงานที่ซับซ้อน แนวคิดของฝูงได้รับแรงบันดาลใจจากระบบธรรมชาติเช่นอาณานิคมมดหรือฝูงนกซึ่งพฤติกรรมของแต่ละบุคคลอย่างง่ายนำไปสู่การเปลี่ยนแปลงของกลุ่มที่ซับซ้อนและความสามารถในการแก้ปัญหา
สถาปัตยกรรม Swarm ได้รับการออกแบบมาเพื่อสร้างและจัดการการสื่อสารระหว่างตัวแทนภายในฝูง สถาปัตยกรรมเหล่านี้กำหนดวิธีที่ตัวแทนโต้ตอบแบ่งปันข้อมูลและประสานงานการกระทำของพวกเขาเพื่อให้บรรลุผลลัพธ์ที่ต้องการ นี่คือประเด็นสำคัญบางประการของสถาปัตยกรรมฝูง:
การสื่อสารแบบลำดับชั้น : ในฝูงลำดับชั้นการสื่อสารกระแสจากตัวแทนระดับสูงไปจนถึงตัวแทนระดับล่าง ตัวแทนระดับสูงทำหน้าที่เป็นผู้ประสานงานการแจกจ่ายงานและผลการรวบรวม โครงสร้างนี้มีประสิทธิภาพสำหรับงานที่ต้องมีการควบคุมและการตัดสินใจจากบนลงล่าง
การสื่อสารแบบขนาน : ในฝูงคู่ขนานตัวแทนทำงานอย่างอิสระและสื่อสารซึ่งกันและกันตามความจำเป็น สถาปัตยกรรมนี้เหมาะสำหรับงานที่สามารถประมวลผลได้พร้อมกันโดยไม่ต้องพึ่งพาทำให้สามารถดำเนินการได้เร็วขึ้นและปรับขนาดได้
การสื่อสารแบบต่อเนื่อง : การจัดทำแผนการตามลำดับตามลำดับเชิงเส้นซึ่งเอาต์พุตของเอเจนต์แต่ละตัวจะกลายเป็นอินพุตสำหรับเอเจนต์ถัดไป สิ่งนี้ทำให้มั่นใจได้ว่างานที่มีการพึ่งพาจะได้รับการจัดการในลำดับที่ถูกต้องรักษาความสมบูรณ์ของเวิร์กโฟลว์
การสื่อสารด้วยตาข่าย : ในฝูงตาข่ายตัวแทนมีการเชื่อมต่ออย่างเต็มที่ทำให้ตัวแทนสามารถสื่อสารกับตัวแทนอื่น ๆ ได้ การตั้งค่านี้ให้ความยืดหยุ่นและความซ้ำซ้อนสูงทำให้เหมาะสำหรับระบบที่ซับซ้อนที่ต้องการการโต้ตอบแบบไดนามิก
การสื่อสารแบบสหพันธรัฐ : ฝูงที่รวมกันเกี่ยวข้องกับฝูงอิสระหลายตัวที่ทำงานร่วมกันโดยการแบ่งปันข้อมูลและผลลัพธ์ ฝูงแต่ละตัวทำงานอย่างอิสระ แต่สามารถนำไปสู่งานที่มีขนาดใหญ่ขึ้นทำให้การแก้ปัญหาแบบกระจายอยู่ในโหนดที่แตกต่างกัน
สถาปัตยกรรม Swarm ใช้ประโยชน์จากรูปแบบการสื่อสารเหล่านี้เพื่อให้แน่ใจว่าตัวแทนทำงานร่วมกันอย่างมีประสิทธิภาพปรับให้เข้ากับข้อกำหนดเฉพาะของงานที่อยู่ในมือ ด้วยการกำหนดโปรโตคอลการสื่อสารที่ชัดเจนและแบบจำลองการโต้ตอบสถาปัตยกรรม Swarm ช่วยให้การประสานงานที่ไร้รอยต่อของตัวแทนหลายตัวนำไปสู่ประสิทธิภาพที่เพิ่มขึ้นและความสามารถในการแก้ปัญหา
| ชื่อ | คำอธิบาย | ลิงค์รหัส | ใช้เคส |
|---|---|---|---|
| ฝูง | ระบบที่มีการจัดระเบียบตัวแทนในลำดับชั้นโดยมีตัวแทนระดับสูงกว่าประสานงานตัวแทนระดับล่างเพื่อให้ได้งานที่ซับซ้อน | ลิงค์รหัส | การเพิ่มประสิทธิภาพกระบวนการผลิตการจัดการการขายหลายระดับการประสานงานด้านการดูแลสุขภาพ |
| ตัวแทนจัดเรียงใหม่ | การตั้งค่าที่ตัวแทนจัดเรียงตัวเองใหม่ตามข้อกำหนดของงานและสภาพแวดล้อม | ลิงค์รหัส | สายการผลิตที่ปรับตัวได้การปรับเปลี่ยนพื้นที่ขายแบบไดนามิกการดูแลสุขภาพที่ยืดหยุ่น |
| เวิร์กโฟลว์พร้อมกัน | ตัวแทนดำเนินงานที่แตกต่างกันพร้อมกันประสานงานเพื่อบรรลุเป้าหมายที่ใหญ่ขึ้น | ลิงค์รหัส | สายการผลิตพร้อมกันการดำเนินการขายแบบขนานกระบวนการดูแลผู้ป่วยพร้อมกัน |
| การประสานงานตามลำดับ | ตัวแทนดำเนินงานตามลำดับที่เฉพาะเจาะจงซึ่งความสำเร็จของงานหนึ่งจะทำให้เริ่มต้นของการเริ่มต้นถัดไป | ลิงค์รหัส | สายการประกอบแบบทีละขั้นตอนกระบวนการขายตามลำดับเวิร์กโฟลว์การรักษาผู้ป่วยแบบขั้นตอน |
| การประมวลผลแบบขนาน | ตัวแทนทำงานในส่วนต่าง ๆ ของงานพร้อมกันเพื่อเร่งกระบวนการโดยรวม | ลิงค์รหัส | การประมวลผลข้อมูลแบบขนานในการผลิตการวิเคราะห์การขายพร้อมกันการทดสอบทางการแพทย์พร้อมกัน |
| ส่วนผสมของตัวแทน | ฝูงที่แตกต่างกันซึ่งตัวแทนที่มีความสามารถต่างกันถูกรวมเข้าด้วยกันเพื่อแก้ปัญหาที่ซับซ้อน | ลิงค์รหัส | การพยากรณ์ทางการเงินการแก้ปัญหาที่ซับซ้อนต้องใช้ทักษะที่หลากหลาย |
| เวิร์กโฟลว์กราฟ | ตัวแทนทำงานร่วมกันในรูปแบบกราฟ Acyclic (DAG) โดยตรงเพื่อจัดการการพึ่งพาและงานขนาน | ลิงค์รหัส | ท่อพัฒนาซอฟต์แวร์ที่ขับเคลื่อนด้วย AI การจัดการโครงการที่ซับซ้อน |
| การแชทเป็นกลุ่ม | ตัวแทนมีส่วนร่วมในการโต้ตอบเหมือนแชทเพื่อให้ได้การตัดสินใจร่วมกัน | ลิงค์รหัส | การตัดสินใจร่วมกันแบบเรียลไทม์การเจรจาสัญญา |
| เอเจนต์รีจิสทรี | รีจิสทรีส่วนกลางที่ตัวแทนจะถูกจัดเก็บเรียกคืนและเรียกใช้แบบไดนามิก | ลิงค์รหัส | การจัดการตัวแทนแบบไดนามิก, เครื่องมือแนะนำการพัฒนา |
| สเปรดชีต | จัดการงานที่สเกลการติดตามเอเจนต์ในรูปแบบที่มีโครงสร้างเช่นไฟล์ CSV | ลิงค์รหัส | การวิเคราะห์การตลาดขนาดใหญ่การตรวจสอบทางการเงิน |
| ฝูงป่า | โครงสร้างฝูงที่จัดระเบียบตัวแทนในลำดับชั้นเหมือนต้นไม้สำหรับกระบวนการตัดสินใจที่ซับซ้อน | ลิงค์รหัส | เวิร์กโฟลว์หลายขั้นตอนการเรียนรู้การเสริมแรงแบบลำดับชั้น |
| เราเตอร์ฝูง | เส้นทางและเลือกสถาปัตยกรรมฝูงตามข้อกำหนดของงานและตัวแทนที่มีอยู่ | ลิงค์รหัส | การกำหนดเส้นทางงานแบบไดนามิก, การเลือกสถาปัตยกรรม Swarm แบบปรับตัว, การจัดสรรตัวแทนที่ดีที่สุด |
SequentialWorkflow เวิร์กโฟลว์แบบต่อเนื่องช่วยให้คุณสามารถดำเนินการตามลำดับกับ Agent แล้วส่งเอาต์พุตไปยังเอเจนต์ถัดไปและต่อไปจนกว่าคุณจะระบุลูปสูงสุดของคุณ
กราฟ LR
A [Agent 1] -> B [Agent 2]
b -> c [ตัวแทน 3]
C -> D [Agent 4]
D -> E [Max Loops]
e -> f [end]
| วิธี | คำอธิบาย | พารามิเตอร์ | ค่าส่งคืน |
|---|---|---|---|
__init__ | เริ่มต้น SequentialWorkFlow | agents : รายการวัตถุตัวแทนmax_loops : จำนวนสูงสุดของการวนซ้ำverbose : บูลีนสำหรับเอาต์พุต 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 เทคนิคการประสาน AgentRearrange ซึ่งได้รับแรงบันดาลใจจาก Einops และ Einsum ช่วยให้คุณสามารถกำหนดและทำแผนที่ความสัมพันธ์ระหว่างตัวแทนต่าง ๆ มันเป็นเครื่องมือที่ทรงพลังสำหรับการจัดเวิร์กโฟลว์ที่ซับซ้อนทำให้คุณสามารถระบุความสัมพันธ์เชิงเส้นและลำดับเช่น 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 เป็นระบบการจัดการเวิร์กโฟลว์ที่ออกแบบมาเพื่อจัดทำงานที่ซับซ้อนโดยใช้ประโยชน์จากพลังของทฤษฎีกราฟ มันช่วยให้การสร้างกราฟ acyclic โดยตรง (DAG) เพื่อจำลองการพึ่งพาระหว่างงานและตัวแทน สิ่งนี้ช่วยให้การกำหนดงานการดำเนินการและการตรวจสอบที่มีประสิทธิภาพ
นี่คือรายละเอียดของวิธีการทำงานของ GraphSwarm :
GraphSwarm ประกอบด้วยโหนดซึ่งสามารถเป็นตัวแทนหรืองานได้ ตัวแทนมีหน้าที่รับผิดชอบในการดำเนินงานและงานแสดงถึงการดำเนินการเฉพาะที่ต้องดำเนินการ ในตัวอย่างมีการสร้างเอเจนต์สองตัว ( agent1 และ agent2 ) และหนึ่งงาน ( task1 )agent1 และ agent2 ไปยัง task1 ซึ่งบ่งชี้ว่าตัวแทนทั้งสองมีความสามารถในการดำเนินการ task1GraphSwarm ต้องการคำจำกัดความของจุดเข้า (ที่เวิร์กโฟลว์เริ่มต้น) และจุดสิ้นสุด (ที่เวิร์กโฟลว์สิ้นสุดลง) ในตัวอย่างนี้ agent1 และ agent2 ถูกตั้งค่าเป็นจุดเข้าและ task1 ถูกตั้งค่าเป็นจุดสิ้นสุดGraphSwarm มีคุณสมบัติการสร้างภาพเพื่อแสดงถึงเวิร์กโฟลว์แบบกราฟิก สิ่งนี้ช่วยให้เข้าใจและดีบักโครงสร้างเวิร์กโฟลว์ได้ง่ายGraphSwarm ดำเนินการโดยการสำรวจกราฟจากจุดเข้าสู่จุดสิ้นสุด ในกรณีนี้ทั้ง agent1 และ agent2 จะดำเนินการ task1 พร้อมกันและรวบรวมผลลัพธ์task1 คือ "งานเสร็จ" GraphSwarm มีประโยชน์หลายประการรวมถึง:
ด้วยการใช้ประโยชน์จาก GraphSwarm เวิร์กโฟลว์ที่ซับซ้อนสามารถจัดการได้อย่างมีประสิทธิภาพและงานสามารถดำเนินการในลักษณะที่ประสานงานและปรับขนาดได้
| วิธี | คำอธิบาย | พารามิเตอร์ | ค่าส่งคืน |
|---|---|---|---|
add_node | เพิ่มโหนดลงในกราฟ | node : วัตถุโหนด | ไม่มี |
add_edge | เพิ่มขอบลงในกราฟ | edge : วัตถุขอบ | ไม่มี |
set_entry_points | ตั้งค่าจุดเข้าของกราฟ | entry_points : รายการรหัสโหนด | ไม่มี |
set_end_points | ตั้งค่าจุดสิ้นสุดของกราฟ | end_points : รายการรหัสโหนด | ไม่มี |
visualize | สร้างการแสดงภาพของกราฟ | ไม่มี | การแสดงสตริงของกราฟ |
run | ดำเนินการเวิร์กโฟลว์ | ไม่มี | พจนานุกรมผลการดำเนินการ |
| ป้อนข้อมูล | พิมพ์ | คำอธิบาย |
|---|---|---|
Node | วัตถุ | แสดงถึงโหนดในกราฟ (เอเจนต์หรืองาน) |
Edge | วัตถุ | แสดงถึงขอบที่เชื่อมต่อสองโหนด |
entry_points | รายการ [STR] | รายการรหัสโหนดที่เวิร์กโฟลว์เริ่มต้นขึ้น |
end_points | รายการ [STR] | รายการรหัสโหนดที่เวิร์กโฟลว์สิ้นสุดลง |
วิธี 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นี่คือการใช้งานตามกระดาษ: "ส่วนผสมของตัวแทนช่วยเพิ่มความสามารถของโมเดลภาษาขนาดใหญ่" โดยร่วมกัน. โดย https://arxiv.org/abs/2406.04692 มันบรรลุผลที่ทันสมัย (SOTA) ใน Alpacaeval 2.0, Mt-bench และ Flask, เหนือกว่า GPT-4 Omni สถาปัตยกรรมนี้เหมาะอย่างยิ่งสำหรับงานที่ต้องใช้การขนานตามด้วยการประมวลผลตามลำดับในลูปอื่น
| วิธี | คำอธิบาย | พารามิเตอร์ | ค่าส่งคืน |
|---|---|---|---|
__init__ | เริ่มต้นส่วนผสม | name : ชื่อของฝูงagents : รายการวัตถุตัวแทนlayers : จำนวนเลเยอร์การประมวลผลfinal_agent : 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__ | เริ่มต้นสเปรดชีต | name : ชื่อของฝูงdescription : คำอธิบายของฝูงagents : รายการวัตถุตัวแทนautosave_on : บูลีนเพื่อเปิดใช้งาน autosavesave_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 | รายการ [ต้นไม้] | รายการวัตถุต้นไม้แต่ละรายการมีวัตถุ treeacent |
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 เป็นระบบการกำหนดเส้นทางที่ยืดหยุ่นซึ่งออกแบบมาเพื่อจัดการประเภทของฝูงสำหรับการปฏิบัติงาน มันมีอินเทอร์เฟซแบบครบวงจรเพื่อโต้ตอบกับประเภทฝูงหลากหลายรวมถึง AgentRearrange , MixtureOfAgents , SpreadSheetSwarm , SequentialWorkflow และ ConcurrentWorkflow เราจะเพิ่มสถาปัตยกรรมฝูงมากขึ้นเรื่อย ๆ ที่นี่เมื่อเราดำเนินการกับสถาปัตยกรรมใหม่
name (str): ชื่อของอินสแตนซ์ swarmrouterdescription (str): คำอธิบายของอินสแตนซ์ swarmroutermax_loops (int): จำนวนลูปสูงสุดที่จะดำเนินการagents (รายการ [Agent]): รายการวัตถุตัวแทนที่จะใช้ในฝูงswarm_type (swarmtype): ประเภทของฝูงที่จะใช้swarm (Union [AgentRearRange, Mixtureofagents, Spreadsheetswarm, Sequentialworkflow, พร้อมกัน WorkFlow]): วัตถุฝูงอินสแตนซ์logs (รายการ [swarmlog]): รายการบันทึกรายการที่บันทึกระหว่างการดำเนินการ __init__(self, name: str, description: str, max_loops: int, agents: List[Agent], swarm_type: SwarmType, *args, **kwargs) : เริ่มต้น swarmrouter_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." )ได้รับ onboarded ตอนนี้กับผู้สร้างและผู้ดูแลนำของ Swarms, Kye Gomez ซึ่งจะแสดงวิธีเริ่มต้นด้วยการติดตั้งตัวอย่างการใช้งานและเริ่มสร้างกรณีการใช้งานที่กำหนดเองของคุณ! คลิกที่นี่
เอกสารอยู่ที่นี่ที่: docs.swarms.world
แพ็คเกจ Swarms ได้รับการออกแบบมาอย่างน่าดึงดูดสำหรับความสามารถในการใช้งานและความเข้าใจอย่างมากแพ็คเกจ Swarms จะถูกแบ่งออกเป็นโมดูลต่าง ๆ เช่น swarms.agents swarms.structs มี Agent ที่สร้างไว้ล่วงหน้า โครงสร้างตัวแทน 3 ที่สำคัญที่สุดคือ structs models และ agents
├── __init__.py
├── agents
├── artifacts
├── memory
├── schemas
├── models - > swarm_models
├── prompts
├── structs
├── telemetry
├── tools
├── utils
└── workers วิธีที่ง่ายที่สุดในการมีส่วนร่วมคือการเลือกปัญหาใด ๆ กับแท็ก good first issue ? อ่านแนวทางการสนับสนุนที่นี่ รายงานข้อผิดพลาด? ไฟล์ที่นี่ | คำขอคุณสมบัติ? ไฟล์ที่นี่
Swarms เป็นโครงการโอเพ่นซอร์สและยินดีต้อนรับการมีส่วนร่วม หากคุณต้องการมีส่วนร่วมคุณสามารถสร้างคุณสมบัติใหม่แก้ไขข้อบกพร่องหรือปรับปรุงโครงสร้างพื้นฐาน โปรดดูที่การสนับสนุน MD และคณะกรรมการที่มีส่วนร่วมของเราเพื่อเข้าร่วมในการอภิปรายแผนงาน!
เร่งบั๊กคุณสมบัติและการสาธิตที่จะนำไปใช้โดยสนับสนุนเราที่นี่:
เข้าร่วมชุมชนที่กำลังเติบโตของเราทั่วโลกเพื่อการสนับสนุนแบบเรียลไทม์ความคิดและการอภิปรายเกี่ยวกับฝูง?
ใบอนุญาตสาธารณะ GNU Affero ทั่วไป