undo a couple changes

pull/443/head
Wyatt Stanke 1 year ago
parent 42ee4ba39c
commit 7cec78fdc1
No known key found for this signature in database
GPG Key ID: CE6BA5FFF135536D

@ -1,19 +1,18 @@
---
repos: repos:
- repo: https://github.com/ambv/black - repo: https://github.com/ambv/black
rev: 22.3.0 rev: 22.3.0
hooks: hooks:
- id: black - id: black
- repo: https://github.com/charliermarsh/ruff-pre-commit - repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.0.255' rev: 'v0.0.255'
hooks: hooks:
- id: ruff - id: ruff
args: ['----unsafe-fixes'] args: [----unsafe-fixes]
- repo: https://github.com/nbQA-dev/nbQA - repo: https://github.com/nbQA-dev/nbQA
rev: 1.6.3 rev: 1.6.3
hooks: hooks:
- id: nbqa-black - id: nbqa-black
additional_dependencies: [ipython==8.12, black] additional_dependencies: [ipython==8.12, black]
- id: nbqa-ruff - id: nbqa-ruff
args: ["--ignore=I001"] args: ["--ignore=I001"]
additional_dependencies: [ipython==8.12, ruff] additional_dependencies: [ipython==8.12, ruff]

@ -1,11 +1,13 @@
---
version: 2 version: 2
build: build:
os: ubuntu-22.04 os: ubuntu-22.04
tools: tools:
python: "3.11" python: "3.11"
mkdocs: mkdocs:
configuration: mkdocs.yml configuration: mkdocs.yml
python: python:
install: install:
- requirements: requirements.txt - requirements: requirements.txt

@ -1,5 +0,0 @@
---
formatter:
type: basic
include_document_start: true
max_line_length: 80

@ -1,3 +0,0 @@
rules:
line-length:
max: 127

@ -1,6 +1,7 @@
from swarms import Agent, Anthropic from swarms import Agent, Anthropic
# Initialize the workflow
## Initialize the workflow
agent = Agent( agent = Agent(
agent_name="Transcript Generator", agent_name="Transcript Generator",
agent_description=( agent_description=(

@ -1,4 +1,3 @@
---
site_name: Swarms Docs site_name: Swarms Docs
plugins: plugins:
- glightbox - glightbox
@ -17,11 +16,11 @@ extra:
- icon: fontawesome/brands/python - icon: fontawesome/brands/python
link: https://pypi.org/project/Swarms/ link: https://pypi.org/project/Swarms/
theme: theme:
name: material name: material
custom_dir: docs/overrides custom_dir: docs/overrides
logo: assets/img/SwarmsLogoIcon.png logo: assets/img/SwarmsLogoIcon.png
palette: palette:
# Palette toggle for light mode # Palette toggle for light mode
- scheme: default - scheme: default
primary: black primary: black
toggle: toggle:
@ -33,14 +32,14 @@ theme:
toggle: toggle:
icon: material/brightness-4 icon: material/brightness-4
name: Switch to light mode name: Switch to light mode
features: features:
- content.code.copy - content.code.copy
- content.code.annotate - content.code.annotate
- navigation.tabs - navigation.tabs
- navigation.sections - navigation.sections
- navigation.expand - navigation.expand
- navigation.top - navigation.top
- announce.dismiss - announce.dismiss
markdown_extensions: markdown_extensions:
- pymdownx.highlight: - pymdownx.highlight:
anchor_linenums: true anchor_linenums: true
@ -56,127 +55,131 @@ markdown_extensions:
- def_list - def_list
- footnotes - footnotes
nav: nav:
- Home: - Home:
- Overview: "index.md" - Overview: "index.md"
- Contributing: "contributing.md" - Contributing: "contributing.md"
- Limitations of Individual Agents: "limits_of_individual_agents.md" - Limitations of Individual Agents: "limits_of_individual_agents.md"
- Why Swarms: "why_swarms.md" - Why Swarms: "why_swarms.md"
- The Swarms Bounty System: "swarms_bounty_system.md" - The Swarms Bounty System: "swarms_bounty_system.md"
- Swarms Cloud API: - Swarms Cloud API:
- Overview: "swarms_cloud/main.md" - Overview: "swarms_cloud/main.md"
- Migrate from OpenAI to Swarms in 3 lines of code: "swarms_cloud/migrate_openai.md" - Migrate from OpenAI to Swarms in 3 lines of code: "swarms_cloud/migrate_openai.md"
- Swarms Framework [PY]: - Swarms Framework [PY]:
- Overview: "swarms/index.md" - Overview: "swarms/index.md"
- DIY Build Your Own Agent: "diy_your_own_agent.md" - DIY Build Your Own Agent: "diy_your_own_agent.md"
- swarms.agents: - swarms.agents:
- Agents: - Agents:
- WorkerAgent: "swarms/agents/workeragent.md" - WorkerAgent: "swarms/agents/workeragent.md"
- OmniAgent: "swarms/agents/omni_agent.md" - OmniAgent: "swarms/agents/omni_agent.md"
- AbstractAgent: "swarms/agents/abstractagent.md" - AbstractAgent: "swarms/agents/abstractagent.md"
- ToolAgent: "swarms/agents/toolagent.md" - ToolAgent: "swarms/agents/toolagent.md"
- swarms.models: - swarms.models:
- How to Create A Custom Language Model: "swarms/models/custom_model.md" - How to Create A Custom Language Model: "swarms/models/custom_model.md"
- "Deploying Azure OpenAI in Production: A Comprehensive Guide": "swarms/models/azure_openai.md" - Deploying Azure OpenAI in Production: A Comprehensive Guide: "swarms/models/azure_openai.md"
- Language: - Language:
- BaseLLM: "swarms/models/base_llm.md" - BaseLLM: "swarms/models/base_llm.md"
- Overview: "swarms/models/index.md" - Overview: "swarms/models/index.md"
- HuggingFaceLLM: "swarms/models/huggingface.md" - HuggingFaceLLM: "swarms/models/huggingface.md"
- Anthropic: "swarms/models/anthropic.md" - Anthropic: "swarms/models/anthropic.md"
- OpenAI: "swarms/models/openai.md" - OpenAI: "swarms/models/openai.md"
- vLLM: "swarms/models/vllm.md" - vLLM: "swarms/models/vllm.md"
- MPT7B: "swarms/models/mpt.md" - MPT7B: "swarms/models/mpt.md"
- Mistral: "swarms/models/mistral.md" - Mistral: "swarms/models/mistral.md"
- Mixtral: "swarms/models/mixtral.md" - Mixtral: "swarms/models/mixtral.md"
- MultiModal: - MultiModal:
- BaseMultiModalModel: "swarms/models/base_multimodal_model.md" - BaseMultiModalModel: "swarms/models/base_multimodal_model.md"
- Fuyu: "swarms/models/fuyu.md" - Fuyu: "swarms/models/fuyu.md"
- Vilt: "swarms/models/vilt.md" - Vilt: "swarms/models/vilt.md"
- Idefics: "swarms/models/idefics.md" - Idefics: "swarms/models/idefics.md"
- Kosmos: "swarms/models/kosmos.md" - Kosmos: "swarms/models/kosmos.md"
- Nougat: "swarms/models/nougat.md" - Nougat: "swarms/models/nougat.md"
- Dalle3: "swarms/models/dalle3.md" - Dalle3: "swarms/models/dalle3.md"
- GPT4V: "swarms/models/gpt4v.md" - GPT4V: "swarms/models/gpt4v.md"
- DistilWhisperModel: "swarms/models/distilled_whisperx.md" - DistilWhisperModel: "swarms/models/distilled_whisperx.md"
- swarms.structs: - swarms.structs:
- Foundational Structures: - Foundational Structures:
- agent: "swarms/structs/agent.md" - agent: "swarms/structs/agent.md"
- basestructure: "swarms/structs/basestructure.md" - basestructure: "swarms/structs/basestructure.md"
- artifactupload: "swarms/structs/artifactupload.md" - artifactupload: "swarms/structs/artifactupload.md"
- taskinput: "swarms/structs/taskinput.md" - taskinput: "swarms/structs/taskinput.md"
- stepinput: "swarms/structs/stepinput.md" - stepinput: "swarms/structs/stepinput.md"
- artifact: "swarms/structs/artifact.md" - artifact: "swarms/structs/artifact.md"
- task: "swarms/structs/task.md" - task: "swarms/structs/task.md"
- Task Queue Base: "swarms/structs/taskqueuebase.md" - Task Queue Base: "swarms/structs/taskqueuebase.md"
- Workflows: - Workflows:
- recursiveworkflow: "swarms/structs/recursiveworkflow.md" - recursiveworkflow: "swarms/structs/recursiveworkflow.md"
- concurrentworkflow: "swarms/structs/concurrentworkflow.md" - concurrentworkflow: "swarms/structs/concurrentworkflow.md"
- nonlinearworkflow: "swarms/structs/nonlinearworkflow.md" - nonlinearworkflow: "swarms/structs/nonlinearworkflow.md"
- sequential_workflow: "swarms/structs/sequential_workflow.md" - sequential_workflow: "swarms/structs/sequential_workflow.md"
- workflow: "swarms/structs/workflow.md" - workflow: "swarms/structs/workflow.md"
- baseworkflow: "swarms/structs/baseworkflow.md" - baseworkflow: "swarms/structs/baseworkflow.md"
- Multi Agent Architectures: - Multi Agent Architectures:
- conversation: "swarms/structs/conversation.md" - conversation: "swarms/structs/conversation.md"
- groupchat: "swarms/structs/groupchat.md" - groupchat: "swarms/structs/groupchat.md"
- swarmnetwork: "swarms/structs/swarmnetwork.md" - swarmnetwork: "swarms/structs/swarmnetwork.md"
- groupchatmanager: "swarms/structs/groupchatmanager.md" - groupchatmanager: "swarms/structs/groupchatmanager.md"
- MajorityVoting: "swarms/structs/majorityvoting.md" - MajorityVoting: "swarms/structs/majorityvoting.md"
- swarms.memory: - swarms.memory:
- Building Custom Vector Memory Databases with the AbstractVectorDatabase Class: "swarms/memory/diy_memory.md" - Building Custom Vector Memory Databases with the AbstractVectorDatabase Class: "swarms/memory/diy_memory.md"
- Vector Databases: - Vector Databases:
- Weaviate: "swarms/memory/weaviate.md" - Weaviate: "swarms/memory/weaviate.md"
- PineconeDB: "swarms/memory/pinecone.md" - PineconeDB: "swarms/memory/pinecone.md"
- PGVectorStore: "swarms/memory/pg.md" - PGVectorStore: "swarms/memory/pg.md"
- ShortTermMemory: "swarms/memory/short_term_memory.md" - ShortTermMemory: "swarms/memory/short_term_memory.md"
- swarms.utils: - swarms.utils:
- Misc: - Misc:
- pdf_to_text: "swarms/utils/pdf_to_text.md" - pdf_to_text: "swarms/utils/pdf_to_text.md"
- load_model_torch: "swarms/utils/load_model_torch.md" - load_model_torch: "swarms/utils/load_model_torch.md"
- metrics_decorator: "swarms/utils/metrics_decorator.md" - metrics_decorator: "swarms/utils/metrics_decorator.md"
- prep_torch_inference: "swarms/utils/prep_torch_inference.md" - prep_torch_inference: "swarms/utils/prep_torch_inference.md"
- find_image_path: "swarms/utils/find_image_path.md" - find_image_path: "swarms/utils/find_image_path.md"
- print_class_parameters: "swarms/utils/print_class_parameters.md" - print_class_parameters: "swarms/utils/print_class_parameters.md"
- extract_code_from_markdown: "swarms/utils/extract_code_from_markdown.md" - extract_code_from_markdown: "swarms/utils/extract_code_from_markdown.md"
- check_device: "swarms/utils/check_device.md" - check_device: "swarms/utils/check_device.md"
- display_markdown_message: "swarms/utils/display_markdown_message.md" - display_markdown_message: "swarms/utils/display_markdown_message.md"
- phoenix_tracer: "swarms/utils/phoenix_tracer.md" - phoenix_tracer: "swarms/utils/phoenix_tracer.md"
- limit_tokens_from_string: "swarms/utils/limit_tokens_from_string.md" - limit_tokens_from_string: "swarms/utils/limit_tokens_from_string.md"
- math_eval: "swarms/utils/math_eval.md" - math_eval: "swarms/utils/math_eval.md"
- Guides: - Guides:
- Building Custom Vector Memory Databases with the AbstractVectorDatabase Class: "swarms/memory/diy_memory.md" - Building Custom Vector Memory Databases with the AbstractVectorDatabase Class: "swarms/memory/diy_memory.md"
- How to Create A Custom Language Model: "swarms/models/custom_model.md" - How to Create A Custom Language Model: "swarms/models/custom_model.md"
- "Deploying Azure OpenAI in Production: A Comprehensive Guide": "swarms/models/azure_openai.md" - Deploying Azure OpenAI in Production: A Comprehensive Guide: "swarms/models/azure_openai.md"
- DIY Build Your Own Agent: "diy_your_own_agent.md" - DIY Build Your Own Agent: "diy_your_own_agent.md"
- Overview: "examples/index.md" - Overview: "examples/index.md"
- Agents: - Agents:
- Agent: "examples/flow.md" - Agent: "examples/flow.md"
- OmniAgent: "examples/omni_agent.md" - OmniAgent: "examples/omni_agent.md"
- Swarms: - Swarms:
- SequentialWorkflow: "examples/reliable_autonomous_agents.md" - SequentialWorkflow: "examples/reliable_autonomous_agents.md"
- 2O+ Autonomous Agent Blogs: "examples/ideas.md" - 2O+ Autonomous Agent Blogs: "examples/ideas.md"
- Applications: - Applications:
- CustomerSupport: - CustomerSupport:
- Overview: "applications/customer_support.md" - Overview: "applications/customer_support.md"
- Marketing: - Marketing:
- Overview: "applications/marketing_agencies.md" - Overview: "applications/marketing_agencies.md"
- Corporate: - Corporate:
- Corporate Documents: - Corporate Documents:
- Data Room: "corporate/data_room.md" - Data Room: "corporate/data_room.md"
- SwarmMemo: "corporate/swarm_memo.md" - SwarmMemo: "corporate/swarm_memo.md"
- Corporate Architecture: "corporate/architecture.md" - Corporate Architecture: "corporate/architecture.md"
- Flywheel: "corporate/flywheel.md" - Flywheel: "corporate/flywheel.md"
- Bounties: "corporate/bounties.md" - Bounties: "corporate/bounties.md"
- Purpose: "corporate/purpose.md" - Purpose: "corporate/purpose.md"
- Roadmap: "corporate/roadmap.md" - Roadmap: "corporate/roadmap.md"
- Sales: - Sales:
- FAQ: "corporate/faq.md" - FAQ: "corporate/faq.md"
- Distribution: "corporate/distribution" - Distribution: "corporate/distribution"
- Product: - Product:
- SwarmCloud: "corporate/swarm_cloud.md" - SwarmCloud: "corporate/swarm_cloud.md"
- Weaknesses: "corporate/failures.md" - Weaknesses: "corporate/failures.md"
- Design: "corporate/design.md" - Design: "corporate/design.md"
- Metric: "corporate/metric.md" - Metric: "corporate/metric.md"
- Research: "corporate/research.md" - Research: "corporate/research.md"
- Demos: "corporate/demos.md" - Demos: "corporate/demos.md"
- Checklist: "corporate/checklist.md" - Checklist: "corporate/checklist.md"
- Organization:
- FrontEnd Member Onboarding: "corporate/front_end_contributors.md" - Organization:
- FrontEnd Member Onboarding: "corporate/front_end_contributors.md"

@ -1,6 +1,6 @@
from swarms import Agent, OpenAIChat from swarms import Agent, OpenAIChat
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=OpenAIChat(), llm=OpenAIChat(),
max_loops="auto", max_loops="auto",

@ -1,6 +1,5 @@
import subprocess
from swarms import Agent, Anthropic, tool from swarms import Agent, Anthropic, tool
import subprocess
# Model # Model
llm = Anthropic( llm = Anthropic(

@ -10,7 +10,7 @@ def search_api(query: str, max_results: int = 10):
return f"Search API: {query} -> {max_results} results" return f"Search API: {query} -> {max_results} results"
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
agent_name="Youtube Transcript Generator", agent_name="Youtube Transcript Generator",
agent_description=( agent_description=(

@ -21,7 +21,7 @@ llm = GPT4VisionAPI(
task = "What is the color of the object?" task = "What is the color of the object?"
img = "images/swarms.jpeg" img = "images/swarms.jpeg"
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=llm, llm=llm,
max_loops="auto", max_loops="auto",

@ -0,0 +1,82 @@
from swarms import Agent, Anthropic, tool
# Model
llm = Anthropic(
temperature=0.1,
)
# Tools
@tool
def text_to_video(task: str):
"""
Converts a given text task into an animated video.
Args:
task (str): The text task to be converted into a video.
Returns:
str: The path to the exported GIF file.
"""
import torch
from diffusers import (
AnimateDiffPipeline,
MotionAdapter,
EulerDiscreteScheduler,
)
from diffusers.utils import export_to_gif
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file
device = "cuda"
dtype = torch.float16
step = 4 # Options: [1,2,4,8]
repo = "ByteDance/AnimateDiff-Lightning"
ckpt = f"animatediff_lightning_{step}step_diffusers.safetensors"
base = ( # Choose to your favorite base model.
"emilianJR/epiCRealism"
)
adapter = MotionAdapter().to(device, dtype)
adapter.load_state_dict(
load_file(hf_hub_download(repo, ckpt), device=device)
)
pipe = AnimateDiffPipeline.from_pretrained(
base, motion_adapter=adapter, torch_dtype=dtype
).to(device)
pipe.scheduler = EulerDiscreteScheduler.from_config(
pipe.scheduler.config,
timestep_spacing="trailing",
beta_schedule="linear",
)
output = pipe(
prompt=task, guidance_scale=1.0, num_inference_steps=step
)
out = export_to_gif(output.frames[0], "animation.gif")
return out
# Agent
agent = Agent(
agent_name="Devin",
system_prompt=(
"Autonomous agent that can interact with humans and other"
" agents. Be Helpful and Kind. Use the tools provided to"
" assist the user. Return all code in markdown format."
),
llm=llm,
max_loops="auto",
autosave=True,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
interactive=True,
tools=[text_to_video],
)
# Run the agent
out = agent("Create a vide of a girl coding AI wearing hijab")
print(out)

@ -68,7 +68,6 @@ class ProductAdConceptGenerator:
def generate_concept(self): def generate_concept(self):
theme = random.choice(self.themes) theme = random.choice(self.themes)
context = random.choice(self.contexts) context = random.choice(self.contexts)
style = random.choice(["medival", "modern", "futuristic", "retro"])
return ( return (
f"{theme} inside a {style} {self.product_name}, {context}" f"{theme} inside a {style} {self.product_name}, {context}"
) )
@ -89,7 +88,6 @@ image_paths = sd_api.run(creative_concept)
# Generate ad copy # Generate ad copy
ad_copy_agent = Agent(llm=llm, max_loops=1) ad_copy_agent = Agent(llm=llm, max_loops=1)
social_media_platform = "Instagram"
ad_copy_prompt = ( ad_copy_prompt = (
f"Write a compelling {social_media_platform} ad copy for a" f"Write a compelling {social_media_platform} ad copy for a"
f" product photo showing {product_name} {creative_concept}." f" product photo showing {product_name} {creative_concept}."
@ -97,7 +95,9 @@ ad_copy_prompt = (
ad_copy = ad_copy_agent.run(task=ad_copy_prompt) ad_copy = ad_copy_agent.run(task=ad_copy_prompt)
# Output the results # Output the results
print("Ad Copy:", ad_copy) print("Creative Concept:", concept_result)
print("Design Ideas:", design_result)
print("Ad Copy:", copywriting_result)
print( print(
"Image Path:", "Image Path:",
image_paths[0] if image_paths else "No image generated", image_paths[0] if image_paths else "No image generated",

@ -4,8 +4,8 @@ Building an Autonomous Agent in 5 minutes with:
- Tools: Search, Browser, ETC - Tools: Search, Browser, ETC
- Long Term Mmeory: ChromaDB, Weaviate, Pinecone, ETC - Long Term Mmeory: ChromaDB, Weaviate, Pinecone, ETC
""" """
from playground.demos.agent_in_5.chroma_db import ChromaDB
from swarms import Agent, OpenAIChat, tool from swarms import Agent, OpenAIChat, tool
from playground.demos.agent_in_5.chroma_db import ChromaDB
# Initialize the memory # Initialize the memory
chroma = ChromaDB( chroma = ChromaDB(

@ -0,0 +1,59 @@
def test_create_graph():
"""
Tests that a graph can be created.
"""
graph = create_graph()
assert isinstance(graph, dict)
def test_weight_edges():
"""
Tests that the edges of a graph can be weighted.
"""
graph = create_graph()
weight_edges(graph)
for edge in graph.edges:
assert isinstance(edge.weight, int)
def test_create_user_list():
"""
Tests that a list of all the podcasts that the user has listened to can be created.
"""
user_list = create_user_list()
assert isinstance(user_list, list)
def test_find_most_similar_podcasts():
"""
Tests that the most similar podcasts to a given podcast can be found.
"""
graph = create_graph()
weight_edges(graph)
user_list = create_user_list()
most_similar_podcasts = find_most_similar_podcasts(
graph, user_list
)
assert isinstance(most_similar_podcasts, list)
def test_add_most_similar_podcasts():
"""
Tests that the most similar podcasts to a given podcast can be added to the user's list.
"""
graph = create_graph()
weight_edges(graph)
user_list = create_user_list()
add_most_similar_podcasts(graph, user_list)
assert len(user_list) > 0
def test_repeat_steps():
"""
Tests that steps 5-6 can be repeated until the user's list contains the desired number of podcasts.
"""
graph = create_graph()
weight_edges(graph)
user_list = create_user_list()
repeat_steps(graph, user_list)
assert len(user_list) == 10

@ -1,13 +1,12 @@
import concurrent import concurrent
import csv import csv
from dotenv import load_dotenv
from swarms import Agent, OpenAIChat from swarms import Agent, OpenAIChat
from swarms.memory import ChromaDB from swarms.memory import ChromaDB
from dotenv import load_dotenv
from swarms.utils.parse_code import extract_code_from_markdown
from swarms.utils.file_processing import create_file from swarms.utils.file_processing import create_file
from swarms.utils.loguru_logger import logger from swarms.utils.loguru_logger import logger
from swarms.utils.parse_code import extract_code_from_markdown
# Load ENV # Load ENV
load_dotenv() load_dotenv()
@ -70,7 +69,7 @@ def extract_and_create_agents(
""" """
try: try:
agents = [] agents = []
with open(csv_file_path, encoding="utf-8") as file: with open(csv_file_path, mode="r", encoding="utf-8") as file:
reader = csv.DictReader(file) reader = csv.DictReader(file)
for row in reader: for row in reader:
project_name = row[target_columns[0]] project_name = row[target_columns[0]]

@ -11,7 +11,7 @@ task = (
) )
img = "assembly_line.jpg" img = "assembly_line.jpg"
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=llm, llm=llm,
max_loops=1, max_loops=1,

@ -1,10 +1,8 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
import swarms.prompts.autoswarm as sdsp
from swarms.models import OpenAIChat from swarms.models import OpenAIChat
from swarms.structs import Agent from swarms.structs import Agent
import swarms.prompts.autoswarm as sdsp
# Load environment variables and initialize the OpenAI Chat model # Load environment variables and initialize the OpenAI Chat model
load_dotenv() load_dotenv()

@ -9,7 +9,7 @@ llm = GPT4VisionAPI()
task = "What is the color of the object?" task = "What is the color of the object?"
img = "images/swarms.jpeg" img = "images/swarms.jpeg"
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=llm, llm=llm,
sop=MULTI_MODAL_AUTO_AGENT_SYSTEM_PROMPT_1, sop=MULTI_MODAL_AUTO_AGENT_SYSTEM_PROMPT_1,

@ -6,7 +6,7 @@ llm = GPT4VisionAPI()
task = "What is the color of the object?" task = "What is the color of the object?"
img = "images/swarms.jpeg" img = "images/swarms.jpeg"
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=llm, llm=llm,
max_loops="auto", max_loops="auto",

@ -22,7 +22,7 @@ llm = GPT4VisionAPI(
task = "This is an eye test. What do you see?" task = "This is an eye test. What do you see?"
img = "playground/demos/multi_modal_chain_of_thought/eyetest.jpg" img = "playground/demos/multi_modal_chain_of_thought/eyetest.jpg"
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=llm, llm=llm,
max_loops=2, max_loops=2,

@ -171,7 +171,7 @@ if st.button("Generate Image"):
for i, (enriched_prompt, img_path, analysis) in enumerate( for i, (enriched_prompt, img_path, analysis) in enumerate(
results results
): ):
st.write(f"Iteration {i + 1}:") st.write(f"Iteration {i+1}:")
st.write("Enriched Prompt:", enriched_prompt) st.write("Enriched Prompt:", enriched_prompt)
if img_path: if img_path:
st.image(img_path, caption="Generated Image") st.image(img_path, caption="Generated Image")

@ -1,6 +1,5 @@
# Import the necessary libraries. # Import the necessary libraries.
import asyncio import asyncio
import websockets import websockets
# Create a list of public group chats. # Create a list of public group chats.

@ -1,5 +1,5 @@
import discord import discord
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
# Discord Bot Setup # Discord Bot Setup
client = discord.Client() client = discord.Client()

@ -1,10 +1,10 @@
# OpenMind.bot streamlines social interactions between personalized bots, representing users, media, and influencers, ensuring meaningful exchanges. It eliminates misunderstandings by using context-aware conversations, followed by summaries or audio recaps of these interactions for efficient communication. # OpenMind.bot streamlines social interactions between personalized bots, representing users, media, and influencers, ensuring meaningful exchanges. It eliminates misunderstandings by using context-aware conversations, followed by summaries or audio recaps of these interactions for efficient communication.
import datetime
import json import json
import datetime
import pytz import pytz
from flask import Flask, jsonify, request
from flask import Flask, request, jsonify
app = Flask(__name__) app = Flask(__name__)
@ -28,7 +28,7 @@ def create_conversation():
@app.route("/api/v1/conversations/<conversation_id>", methods=["GET"]) @app.route("/api/v1/conversations/<conversation_id>", methods=["GET"])
def get_conversation(conversation_id): def get_conversation(conversation_id):
# Get the conversation from the database # Get the conversation from the database
with open("conversations.json") as f: with open("conversations.json", "r") as f:
conversation = json.load(f) conversation = json.load(f)
# Return the conversation # Return the conversation
@ -49,7 +49,7 @@ def create_message(conversation_id):
} }
# Get the conversation from the database # Get the conversation from the database
with open("conversations.json") as f: with open("conversations.json", "r") as f:
conversation = json.load(f) conversation = json.load(f)
# Add the message to the conversation # Add the message to the conversation
@ -68,7 +68,7 @@ def create_message(conversation_id):
) )
def get_messages(conversation_id): def get_messages(conversation_id):
# Get the conversation from the database # Get the conversation from the database
with open("conversations.json") as f: with open("conversations.json", "r") as f:
conversation = json.load(f) conversation = json.load(f)
# Return the messages # Return the messages
@ -80,7 +80,7 @@ def get_messages(conversation_id):
) )
def get_summary(conversation_id): def get_summary(conversation_id):
# Get the conversation from the database # Get the conversation from the database
with open("conversations.json") as f: with open("conversations.json", "r") as f:
conversation = json.load(f) conversation = json.load(f)
# Create a summary of the conversation # Create a summary of the conversation
@ -98,7 +98,7 @@ def get_summary(conversation_id):
) )
def get_audio_recap(conversation_id): def get_audio_recap(conversation_id):
# Get the conversation from the database # Get the conversation from the database
with open("conversations.json") as f: with open("conversations.json", "r") as f:
conversation = json.load(f) conversation = json.load(f)
# Create an audio recap of the conversation # Create an audio recap of the conversation

@ -1,14 +1,12 @@
import concurrent import concurrent
import csv import csv
import os import os
from swarms import Gemini, Agent
from dotenv import load_dotenv
from swarms import Agent, Gemini
from swarms.memory import ChromaDB from swarms.memory import ChromaDB
from dotenv import load_dotenv
from swarms.utils.parse_code import extract_code_from_markdown
from swarms.utils.file_processing import create_file from swarms.utils.file_processing import create_file
from swarms.utils.loguru_logger import logger from swarms.utils.loguru_logger import logger
from swarms.utils.parse_code import extract_code_from_markdown
# Load ENV # Load ENV
load_dotenv() load_dotenv()
@ -73,7 +71,7 @@ def extract_and_create_agents(
- target_columns: A list of column names to extract values from. - target_columns: A list of column names to extract values from.
""" """
agents = [] agents = []
with open(csv_file_path, encoding="utf-8") as file: with open(csv_file_path, mode="r", encoding="utf-8") as file:
reader = csv.DictReader(file) reader = csv.DictReader(file)
for row in reader: for row in reader:
project_name = row[target_columns[0]] project_name = row[target_columns[0]]

@ -19,7 +19,7 @@ llm = HuggingfaceLLM(
temperature=0.5, temperature=0.5,
) )
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=llm, llm=llm,
max_loops="auto", max_loops="auto",

@ -4,7 +4,7 @@ import sys
from dotenv import load_dotenv from dotenv import load_dotenv
# Import the OpenAIChat model and the Agent struct # Import the OpenAIChat model and the Agent struct
from swarms import Agent, OpenAIChat from swarms import OpenAIChat, Agent
# Load the environment variables # Load the environment variables
load_dotenv() load_dotenv()
@ -26,7 +26,7 @@ print(
f" {sys.stderr}" f" {sys.stderr}"
) )
# Initialize the workflow ## Initialize the workflow
agent = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True) agent = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True)
# Run the workflow on a task # Run the workflow on a task

@ -1,8 +1,6 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import OpenAIChat, Task, ConcurrentWorkflow, Agent
from swarms import Agent, ConcurrentWorkflow, OpenAIChat, Task
# Load environment variables from .env file # Load environment variables from .env file
load_dotenv() load_dotenv()

@ -1,6 +1,5 @@
import torch
from swarms.models import HuggingfaceLLM from swarms.models import HuggingfaceLLM
import torch
try: try:
inference = HuggingfaceLLM( inference = HuggingfaceLLM(

@ -1,18 +1,16 @@
from swarms.structs import Agent
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms.models import GPT4VisionAPI from swarms.models import GPT4VisionAPI
from swarms.prompts.logistics import ( from swarms.prompts.logistics import (
Efficiency_Agent_Prompt,
Health_Security_Agent_Prompt, Health_Security_Agent_Prompt,
Productivity_Agent_Prompt,
Quality_Control_Agent_Prompt, Quality_Control_Agent_Prompt,
Productivity_Agent_Prompt,
Safety_Agent_Prompt, Safety_Agent_Prompt,
Security_Agent_Prompt, Security_Agent_Prompt,
Sustainability_Agent_Prompt, Sustainability_Agent_Prompt,
Efficiency_Agent_Prompt,
) )
from swarms.structs import Agent
# Load ENV # Load ENV
load_dotenv() load_dotenv()

@ -1,8 +1,6 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import OpenAIChat, Task, RecursiveWorkflow, Agent
from swarms import Agent, OpenAIChat, RecursiveWorkflow, Task
# Load environment variables from .env file # Load environment variables from .env file
load_dotenv() load_dotenv()

@ -1,9 +1,7 @@
import os import os
from swarms import OpenAIChat, Agent, SequentialWorkflow
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import Agent, OpenAIChat, SequentialWorkflow
load_dotenv() load_dotenv()
# Load the environment variables # Load the environment variables

@ -3,8 +3,8 @@ import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import ( from swarms import (
Conversation,
OpenAIChat, OpenAIChat,
Conversation,
) )
conv = Conversation( conv = Conversation(

@ -3,7 +3,7 @@ import os
from dotenv import load_dotenv from dotenv import load_dotenv
# Import the OpenAIChat model and the Agent struct # Import the OpenAIChat model and the Agent struct
from swarms import Agent, OpenAIChat, SwarmNetwork from swarms import OpenAIChat, Agent, SwarmNetwork
# Load the environment variables # Load the environment variables
load_dotenv() load_dotenv()
@ -17,7 +17,7 @@ llm = OpenAIChat(
openai_api_key=api_key, openai_api_key=api_key,
) )
# Initialize the workflow ## Initialize the workflow
agent = Agent(llm=llm, max_loops=1, agent_name="Social Media Manager") agent = Agent(llm=llm, max_loops=1, agent_name="Social Media Manager")
agent2 = Agent(llm=llm, max_loops=1, agent_name=" Product Manager") agent2 = Agent(llm=llm, max_loops=1, agent_name=" Product Manager")
agent3 = Agent(llm=llm, max_loops=1, agent_name="SEO Manager") agent3 = Agent(llm=llm, max_loops=1, agent_name="SEO Manager")

@ -1,6 +1,5 @@
# Import necessary libraries # Import necessary libraries
from transformers import AutoModelForCausalLM, AutoTokenizer from transformers import AutoModelForCausalLM, AutoTokenizer
from swarms import ToolAgent from swarms import ToolAgent
# Load the pre-trained model and tokenizer # Load the pre-trained model and tokenizer

@ -1,9 +1,7 @@
# Importing necessary modules # Importing necessary modules
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import Worker, OpenAIChat, tool
from swarms import OpenAIChat, Worker, tool
# Loading environment variables from .env file # Loading environment variables from .env file
load_dotenv() load_dotenv()

@ -1,7 +1,5 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import AzureOpenAI from swarms import AzureOpenAI
# Load the environment variables # Load the environment variables

@ -1,5 +1,4 @@
from vllm import LLM from vllm import LLM
from swarms import AbstractLLM, Agent, ChromaDB from swarms import AbstractLLM, Agent, ChromaDB

@ -11,7 +11,7 @@ llm = OpenAIChat(
# max_tokens=100, # max_tokens=100,
) )
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=llm, llm=llm,
max_loops=2, max_loops=2,

@ -26,7 +26,7 @@ llm = OpenAIChat(
max_tokens=1000, max_tokens=1000,
) )
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=llm, llm=llm,
max_loops=4, max_loops=4,

@ -66,7 +66,7 @@ llm = OpenAIChat(
) )
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
agent_name="Research Agent", agent_name="Research Agent",
llm=llm, llm=llm,

@ -20,7 +20,7 @@ llm = OpenAIChat(
) )
# Initialize the workflow ## Initialize the workflow
agent = Agent(llm=llm, max_loops=1, dashboard=True) agent = Agent(llm=llm, max_loops=1, dashboard=True)

@ -1,6 +1,6 @@
from swarms import Agent, AzureOpenAI from swarms import Agent, AzureOpenAI
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=AzureOpenAI(), llm=AzureOpenAI(),
max_loops="auto", max_loops="auto",

@ -10,7 +10,7 @@ class ExampleLLM(AbstractLLM):
pass pass
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=ExampleLLM(), llm=ExampleLLM(),
max_loops="auto", max_loops="auto",

@ -268,7 +268,7 @@ topic_specifier_prompt = [
Frame the debate topic as a problem to be solved. Frame the debate topic as a problem to be solved.
Be creative and imaginative. Be creative and imaginative.
Please reply with the specified topic in {word_limit} words or less. Please reply with the specified topic in {word_limit} words or less.
Speak directly to the presidential candidates: {*character_names, }. Speak directly to the presidential candidates: {*character_names,}.
Do not add anything else."""), Do not add anything else."""),
] ]
specified_topic = ChatOpenAI(temperature=1.0)( specified_topic = ChatOpenAI(temperature=1.0)(

@ -1,6 +1,6 @@
from swarms import Agent, OpenAIChat from swarms import Agent, OpenAIChat
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=OpenAIChat(), llm=OpenAIChat(),
max_loops=1, max_loops=1,

@ -1,8 +1,7 @@
import os import os
from swarms import OpenAIChat, Agent
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import Agent, OpenAIChat
# Load environment variables # Load environment variables
load_dotenv() load_dotenv()

@ -1,4 +1,4 @@
from swarms import Agent, Anthropic, ChromaDB, MajorityVoting from swarms import Agent, MajorityVoting, ChromaDB, Anthropic
# Initialize the llm # Initialize the llm
llm = Anthropic() llm = Anthropic()

@ -1,6 +1,7 @@
from swarms.structs.message_pool import MessagePool
from swarms import Agent, OpenAIChat from swarms import Agent, OpenAIChat
from swarms.memory.chroma_db import ChromaDB from swarms.memory.chroma_db import ChromaDB
from swarms.structs.message_pool import MessagePool
# Agents # Agents
agent1 = Agent( agent1 = Agent(

@ -1,9 +1,7 @@
import os import os
from swarms import Gemini, Agent
from dotenv import load_dotenv
from swarms import Agent, Gemini
from swarms.structs.multi_process_workflow import MultiProcessWorkflow from swarms.structs.multi_process_workflow import MultiProcessWorkflow
from dotenv import load_dotenv
# Load the environment variables # Load the environment variables
load_dotenv() load_dotenv()

@ -1,16 +1,14 @@
# Import the OpenAIChat model and the Agent struct # Import the OpenAIChat model and the Agent struct
import os import os
from dotenv import load_dotenv
from swarms import ( from swarms import (
Agent, Agent,
Anthropic,
OpenAIChat, OpenAIChat,
SwarmNetwork, SwarmNetwork,
Anthropic,
TogetherLLM, TogetherLLM,
) )
from swarms.memory import ChromaDB from swarms.memory import ChromaDB
from dotenv import load_dotenv
# load the environment variables # load the environment variables
load_dotenv() load_dotenv()
@ -31,7 +29,7 @@ together_llm = TogetherLLM(
together_api_key=os.getenv("TOGETHER_API_KEY"), max_tokens=3000 together_api_key=os.getenv("TOGETHER_API_KEY"), max_tokens=3000
) )
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=anthropic, llm=anthropic,
max_loops=1, max_loops=1,

@ -1,5 +1,4 @@
from transformers import AutoModelForCausalLM, AutoTokenizer from transformers import AutoModelForCausalLM, AutoTokenizer
from swarms import ToolAgent from swarms import ToolAgent
# Load the pre-trained model and tokenizer # Load the pre-trained model and tokenizer

@ -1,21 +1,21 @@
import concurrent
import inspect import inspect
import os import os
import threading import threading
from typing import Callable, List from typing import Callable, List
from swarms import Agent, OpenAIChat
from swarms.prompts.documentation import DOCUMENTATION_WRITER_SOP from swarms.prompts.documentation import DOCUMENTATION_WRITER_SOP
from swarms import Agent, OpenAIChat
from swarms.utils.loguru_logger import logger
import concurrent
######### #########
from swarms.utils.file_processing import ( from swarms.utils.file_processing import (
create_file_in_folder,
load_json, load_json,
sanitize_file_path, sanitize_file_path,
zip_folders,
zip_workspace, zip_workspace,
create_file_in_folder,
zip_folders,
) )
from swarms.utils.loguru_logger import logger
class PythonDocumentationSwarm: class PythonDocumentationSwarm:

@ -3,9 +3,7 @@ Boss selects what agent to use
B -> W1, W2, W3 B -> W1, W2, W3
""" """
from typing import List, Optional from typing import List, Optional
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from swarms.utils.json_utils import str_to_json from swarms.utils.json_utils import str_to_json

@ -26,7 +26,7 @@ def search_api(query: str) -> str:
print(f"Searching API for {query}") print(f"Searching API for {query}")
# Initialize the workflow ## Initialize the workflow
agent = Agent( agent = Agent(
llm=llm, llm=llm,
max_loops=5, max_loops=5,

@ -0,0 +1,57 @@
from swarms import Agent, Anthropic, tool
# Model
llm = Anthropic(
temperature=0.1,
)
"""
How to create tools:
1. Define a function that takes the required arguments with documentation and type hints.
2. Add the `@tool` decorator to the function.
3. Add the function to the `tools` list in the `Agent` class.
"""
# Tools
# Browser tools
@tool
def browser(query: str):
"""
Opens a web browser and searches for the given query on Google.
Args:
query (str): The search query.
Returns:
str: A message indicating that the search is being performed.
"""
import webbrowser
url = f"https://www.google.com/search?q={query}"
webbrowser.open(url)
return f"Searching for {query} in the browser."
# Agent
agent = Agent(
agent_name="Devin",
system_prompt=(
"Autonomous agent that can interact with humans and other"
" agents. Be Helpful and Kind. Use the tools provided to"
" assist the user. Return all code in markdown format."
),
llm=llm,
max_loops="auto",
autosave=True,
dashboard=False,
verbose=True,
stopping_token="<DONE>",
interactive=True,
tools=[browser],
)
# Run the agent
out = agent.run("what's the weather in Miami?")
print(out)

3133
poetry.lock generated

File diff suppressed because it is too large Load Diff

@ -1,4 +1,4 @@
# VERISON2 ###### VERISON2
import inspect import inspect
import os import os
import threading import threading

@ -2,8 +2,8 @@ import os
import shutil import shutil
# Create a new directory for the log files if it doesn't exist # Create a new directory for the log files if it doesn't exist
if not os.path.exists("artifacts"): if not os.path.exists("artifacts_two"):
os.makedirs("artifacts") os.makedirs("artifacts_two")
# Walk through the current directory # Walk through the current directory
for dirpath, dirnames, filenames in os.walk("."): for dirpath, dirnames, filenames in os.walk("."):
@ -12,10 +12,10 @@ for dirpath, dirnames, filenames in os.walk("."):
if filename.endswith(".log"): if filename.endswith(".log"):
# Construct the full file path # Construct the full file path
file_path = os.path.join(dirpath, filename) file_path = os.path.join(dirpath, filename)
# Move the log file to the 'artifacts' directory # Move the log file to the 'artifacts_two' directory
shutil.move(file_path, "artifacts") shutil.move(file_path, "artifacts_two")
print( print(
"Moved all log files into the 'artifacts' directory and deleted" "Moved all log files into the 'artifacts_two' directory and"
" their original location." " deleted their original location."
) )

@ -0,0 +1,10 @@
#!/bin/bash
# Create the new directory if it doesn't exist
sudo mkdir -p /artifacts_logs
# Find all .log files in the root directory and its subdirectories
find / -name "*.log" -print0 | while IFS= read -r -d '' file; do
# Use sudo to move the file to the new directory
sudo mv "$file" /artifacts_logs/
done

@ -9,10 +9,10 @@ for f in /swarms/playground/examples/example_*.py; do
echo "Skipping ${f} as it ran successfully in a previous run." echo "Skipping ${f} as it ran successfully in a previous run."
else else
# Run the script if not previously successful # Run the script if not previously successful
if python "$f" 2>>errors.txt; then if /home/kye/miniconda3/envs/swarms/bin/python "$f" 2>>errors.txt; then
echo "(${f}) ran successfully without errors." echo "(${f}) ran successfully without errors."
# Log the successful script execution # Log the successful script execution
echo "$f" >>"$SUCCESS_LOG" echo "$f" >> "$SUCCESS_LOG"
else else
echo "Error encountered in ${f}. Check errors.txt for details." echo "Error encountered in ${f}. Check errors.txt for details."
break break

@ -1,5 +1,5 @@
from abc import abstractmethod from abc import abstractmethod
from typing import Dict, List, Optional, Union from typing import Dict, List, Union, Optional
class AbstractAgent: class AbstractAgent:

@ -1,4 +1,4 @@
from typing import Any, Callable, Optional from typing import Any, Optional, Callable
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.tools.format_tools import Jsonformer from swarms.tools.format_tools import Jsonformer

@ -7,9 +7,9 @@ import chromadb
import numpy as np import numpy as np
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms.memory.base_vectordb import AbstractVectorDatabase
from swarms.utils.data_to_text import data_to_text from swarms.utils.data_to_text import data_to_text
from swarms.utils.markdown_message import display_markdown_message from swarms.utils.markdown_message import display_markdown_message
from swarms.memory.base_vectordb import AbstractVectorDatabase
# Load environment variables # Load environment variables
load_dotenv() load_dotenv()

@ -6,9 +6,8 @@ from langchain.chains.question_answering import load_qa_chain
from langchain.embeddings.openai import OpenAIEmbeddings from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import Chroma from langchain.vectorstores import Chroma
from swarms.memory.base_vectordb import AbstractVectorDatabase
from swarms.models.popular_llms import OpenAIChat from swarms.models.popular_llms import OpenAIChat
from swarms.memory.base_vectordb import AbstractVectorDatabase
def synchronized_mem(method): def synchronized_mem(method):

@ -5,7 +5,6 @@ from sqlalchemy import JSON, Column, String, create_engine
from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from swarms.memory.base_vectordb import AbstractVectorDatabase from swarms.memory.base_vectordb import AbstractVectorDatabase

@ -1,7 +1,6 @@
from typing import List from typing import List
from httpx import RequestError from httpx import RequestError
from swarms.memory.base_vectordb import AbstractVectorDatabase from swarms.memory.base_vectordb import AbstractVectorDatabase
try: try:

@ -23,7 +23,6 @@ from swarms.models.popular_llms import (
from swarms.models.popular_llms import ( from swarms.models.popular_llms import (
CohereChat as Cohere, CohereChat as Cohere,
) )
from swarms.models.popular_llms import OctoAIChat
from swarms.models.popular_llms import ( from swarms.models.popular_llms import (
OpenAIChatLLM as OpenAIChat, OpenAIChatLLM as OpenAIChat,
) )
@ -33,7 +32,9 @@ from swarms.models.popular_llms import (
from swarms.models.popular_llms import ( from swarms.models.popular_llms import (
ReplicateLLM as Replicate, ReplicateLLM as Replicate,
) )
from swarms.models.popular_llms import OctoAIChat
from swarms.models.qwen import QwenVLMultiModal # noqa: E402 from swarms.models.qwen import QwenVLMultiModal # noqa: E402
from swarms.models.sampling_params import SamplingParams, SamplingType from swarms.models.sampling_params import SamplingParams, SamplingType
from swarms.models.together import TogetherLLM # noqa: E402 from swarms.models.together import TogetherLLM # noqa: E402
from swarms.models.types import ( # noqa: E402 from swarms.models.types import ( # noqa: E402
@ -45,6 +46,7 @@ from swarms.models.types import ( # noqa: E402
) )
from swarms.models.vilt import Vilt # noqa: E402 from swarms.models.vilt import Vilt # noqa: E402
__all__ = [ __all__ = [
"AbstractLLM", "AbstractLLM",
"Anthropic", "Anthropic",

@ -2,10 +2,9 @@ from __future__ import annotations
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from dataclasses import dataclass from dataclasses import dataclass
from typing import Callable
import numpy as np import numpy as np
from typing import Callable
from swarms.artifacts.text_artifact import TextArtifact from swarms.artifacts.text_artifact import TextArtifact
from swarms.utils.exponential_backoff import ExponentialBackoffMixin from swarms.utils.exponential_backoff import ExponentialBackoffMixin

@ -175,7 +175,7 @@ class DistilWhisperModel:
# Print the chunk's transcription # Print the chunk's transcription
print( print(
colored( colored(
f"Chunk {i + 1}/{len(chunks)}: ", "yellow" f"Chunk {i+1}/{len(chunks)}: ", "yellow"
) )
+ transcription + transcription
) )

@ -0,0 +1,75 @@
from swarms.models.base_llm import AbstractLLM
from pydantic import BaseModel
from typing import List, Dict
import openai
class OpenRouterRequest(BaseModel):
model: str
messages: List[Dict[str, str]] = []
class OpenRouterChat(AbstractLLM):
"""
A class representing an OpenRouter chat model.
Args:
model_name (str): The name of the OpenRouter model.
base_url (str, optional): The base URL for the OpenRouter API. Defaults to "https://openrouter.ai/api/v1/chat/completions".
openrouter_api_key (str, optional): The API key for accessing the OpenRouter API. Defaults to None.
system_prompt (str, optional): The system prompt for the chat model. Defaults to None.
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
Attributes:
model_name (str): The name of the OpenRouter model.
base_url (str): The base URL for the OpenRouter API.
openrouter_api_key (str): The API key for accessing the OpenRouter API.
system_prompt (str): The system prompt for the chat model.
Methods:
run(task, *args, **kwargs): Runs the chat model with the given task.
"""
def __init__(
self,
model_name: str,
base_url: str = "https://openrouter.ai/api/v1/chat/completions",
openrouter_api_key: str = None,
system_prompt: str = None,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
self.model_name = model_name
self.base_url = base_url
self.openrouter_api_key = openrouter_api_key
self.system_prompt = system_prompt
openai.api_base = "https://openrouter.ai/api/v1"
openai.api_key = openrouter_api_key
def run(self, task: str, *args, **kwargs) -> str:
"""
Runs the chat model with the given task.
Args:
task (str): The user's task for the chat model.
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
Returns:
str: The response generated by the chat model.
"""
response = openai.ChatCompletion.create(
model=self.model_name,
messages=[
{"role": "system", "content": self.system_prompt},
{"role": "user", "content": task},
]
* args,
**kwargs,
)
return response.choices[0].message.text

@ -5,7 +5,7 @@ import warnings
from typing import Any, Callable, Literal, Sequence from typing import Any, Callable, Literal, Sequence
import numpy as np import numpy as np
from pydantic import BaseModel, ConfigDict, Field, model_validator from pydantic import model_validator, ConfigDict, BaseModel, Field
from tenacity import ( from tenacity import (
AsyncRetrying, AsyncRetrying,
before_sleep_log, before_sleep_log,

@ -8,7 +8,6 @@ from langchain.llms import BaseLLM
from langchain.pydantic_v1 import BaseModel from langchain.pydantic_v1 import BaseModel
from langchain.schema import Generation, LLMResult from langchain.schema import Generation, LLMResult
from langchain.utils import get_from_dict_or_env from langchain.utils import get_from_dict_or_env
from pydantic import model_validator
from tenacity import ( from tenacity import (
before_sleep_log, before_sleep_log,
retry, retry,
@ -16,6 +15,7 @@ from tenacity import (
stop_after_attempt, stop_after_attempt,
wait_exponential, wait_exponential,
) )
from pydantic import model_validator
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)

@ -31,7 +31,7 @@ def debate_monitor(game_description, word_limit, character_names):
Frame the debate topic as a problem to be solved. Frame the debate topic as a problem to be solved.
Be creative and imaginative. Be creative and imaginative.
Please reply with the specified topic in {word_limit} words or less. Please reply with the specified topic in {word_limit} words or less.
Speak directly to the presidential candidates: {*character_names, }. Speak directly to the presidential candidates: {*character_names,}.
Do not add anything else. Do not add anything else.
""" """

@ -123,7 +123,7 @@ class SchemaGenerator:
return "\n".join(command_strings + [finish_string]) return "\n".join(command_strings + [finish_string])
else: else:
return "\n".join( return "\n".join(
f"{i + 1}. {item}" for i, item in enumerate(items) f"{i+1}. {item}" for i, item in enumerate(items)
) )
def generate_prompt_string(self) -> str: def generate_prompt_string(self) -> str:

@ -34,7 +34,7 @@ commands: {
""" """
# FEW SHOT EXAMPLES ################ ########### FEW SHOT EXAMPLES ################
SCENARIOS = """ SCENARIOS = """
commands: { commands: {
"tools": { "tools": {

@ -1,6 +1,8 @@
import datetime import datetime
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from swarms.tools.tool import BaseTool
from swarms.tools.tool_utils import scrape_tool_func_docs
from typing import List
time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
@ -24,54 +26,202 @@ class ResponseFormat(BaseModel):
response_json = ResponseFormat.model_json_schema() response_json = ResponseFormat.model_json_schema()
def worker_tools_sop_promp(name: str, memory: str, time=time): tool_usage_browser = """
out = f"""
You are {name}, ```json
Your decisions must always be made independently without seeking user assistance. {
Play to your strengths as an LLM and pursue simple strategies with no legal complications. "thoughts": {
If you have completed all your tasks, make sure to use the 'finish' command. "text": "To check the weather in Miami, I will use the browser tool to search for 'Miami weather'.",
"reasoning": "The browser tool allows me to search the web, so I can look up the current weather conditions in Miami.",
GOALS: "plan": "Use the browser tool to search Google for 'Miami weather'. Parse the result to get the current temperature, conditions, etc. and format that into a readable weather report."
},
1. Hello, how are you? Create an image of how you are doing! "command": {
"name": "browser",
Constraints: "args": {
"query": "Miami weather"
1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files. }
2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember. }
3. No user assistance }
4. Exclusively use the commands listed in double quotes e.g. 'command name' ```
Commands: """
1. finish: use this to signal that you have finished all your objectives, args: 'response': 'final response to let people know you have finished your objectives' tool_usage_terminal = """
Resources: ```json
{
1. Internet access for searches and information gathering. "thoughts": {
2. Long Term memory management. "text": "To check the weather in Miami, I will use the browser tool to search for 'Miami weather'.",
3. Agents for delegation of simple tasks. "reasoning": "The browser tool allows me to search the web, so I can look up the current weather conditions in Miami.",
4. File output. "plan": "Use the browser tool to search Google for 'Miami weather'. Parse the result to get the current temperature, conditions, etc. and format that into a readable weather report."
},
Performance Evaluation: "command": {
"name": "terminal",
1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities. "args": {
2. Constructively self-criticize your big-picture behavior constantly. "code": "uptime"
3. Reflect on past decisions and strategies to refine your approach. }
4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps. }
}
You should only respond in JSON format as described below Response Format, you will respond only in markdown format within 6 backticks. The JSON will be in markdown format. ```
``` """
{response_json}
```
browser_and_terminal_tool = """
Ensure the response can be parsed by Python json.loads ```
System: The current time and date is {time} {
System: This reminds you of these events from your past: "thoughts": {
[{memory}] "text": "To analyze the latest stock market trends, I need to fetch current stock data and then process it using a script.",
"reasoning": "Using the browser tool to retrieve stock data ensures I have the most recent information. Following this, the terminal tool can run a script that analyzes this data to identify trends.",
Human: Determine which next command to use, and respond using the format specified above: "plan": "First, use the browser to get the latest stock prices. Then, use the terminal to execute a data analysis script on the fetched data."
},
"commands": [
{
"name": "browser",
"args": {
"query": "download latest stock data for NASDAQ"
}
},
{
"name": "terminal",
"args": {
"cmd": "python analyze_stocks.py"
}
}
]
}
```
"""
browser_and_terminal_tool_two = """
```
{
"thoughts": {
"text": "To prepare a monthly budget report, I need current expenditure data, process it, and calculate the totals and averages.",
"reasoning": "The browser will fetch the latest expenditure data. The terminal will run a processing script to organize the data, and the calculator will be used to sum up expenses and compute averages.",
"plan": "Download the data using the browser, process it with a terminal command, and then calculate totals and averages using the calculator."
},
"commands": [
{
"name": "browser",
"args": {
"query": "download monthly expenditure data"
}
},
{
"name": "terminal",
"args": {
"cmd": "python process_expenditures.py"
}
},
{
"name": "calculator",
"args": {
"operation": "sum",
"numbers": "[output_from_process_expenditures]"
}
}
]
}
```
"""
# Function to parse tools and get their documentation
def parse_tools(tools: List[BaseTool] = []):
tool_docs = []
for tool in tools:
tool_doc = scrape_tool_func_docs(tool)
tool_docs.append(tool_doc)
return tool_docs
# Function to generate the worker prompt
def tool_usage_worker_prompt(
current_time=time, tools: List[BaseTool] = []
):
tool_docs = parse_tools(tools)
prompt = f"""
**Date and Time**: {current_time}
### Constraints
- Only use the tools as specified in the instructions.
- Follow the command format strictly to avoid errors and ensure consistency.
- Only use the tools for the intended purpose as described in the SOP.
- Document your thoughts, reasoning, and plan before executing the command.
- Provide the output in JSON format within markdown code blocks.
- Review the output to ensure it matches the expected outcome.
- Only follow the instructions provided in the SOP and do not deviate from the specified tasks unless tool usage is not required.
### Performance Evaluation
- **Efficiency**: Use tools to complete tasks with minimal steps.
- **Accuracy**: Ensure that commands are executed correctly to achieve the desired outcome.
- **Adaptability**: Be ready to adjust the use of tools based on task requirements and feedback.
### Tool Commands
1. **Browser**
- **Purpose**: To retrieve information from the internet.
- **Usage**:
- `{{"name": "browser", "args": {{"query": "search query here"}}}}`
- Example: Fetch current weather in London.
- Command: `{{"name": "browser", "args": {{"query": "London weather"}}}}`
2. **Terminal**
- **Purpose**: To execute system commands.
- **Usage**:
- `{{"name": "terminal", "args": {{"cmd": "system command here"}}}}`
- Example: Check disk usage on a server.
- Command: `{{"name": "terminal", "args": {{"cmd": "df -h"}}}}`
3. **Custom Tool** (if applicable)
- **Purpose**: Describe specific functionality.
- **Usage**:
- `{{"name": "custom_tool", "args": {{"parameter": "value"}}}}`
- Example: Custom analytics tool.
- Command: `{{"name": "custom_tool", "args": {{"data": "analyze this data"}}}}`
### Usage Examples
- **Example 1**: Retrieving Weather Information
```json
{tool_usage_browser}
```
- **Example 2**: System Check via Terminal
```json
{tool_usage_terminal}
```
- **Example 3**: Combined Browser and Terminal Usage
```json
{browser_and_terminal_tool}
```
- **Example 4**: Combined Browser, Terminal, and Calculator Usage
```json
{browser_and_terminal_tool_two}
```
### Next Steps
- Determine the appropriate tool for the task at hand.
- Format your command according to the examples provided.
- Execute the command and evaluate the results based on the expected outcome.
- Document any issues or challenges faced during the tool usage.
- Always output the results in the specified format: JSON in markdown code blocks.
###### Tools Available
{tool_docs}
This SOP is designed to guide you through the structured and effective use of tools. By adhering to this protocol, you will enhance your productivity and accuracy in task execution.
""" """
return str(out) return prompt

@ -4,7 +4,6 @@ from swarms.structs.agent_process import (
AgentProcess, AgentProcess,
AgentProcessQueue, AgentProcessQueue,
) )
from swarms.structs.agent_rearrange import AgentRearrange
from swarms.structs.auto_swarm import AutoSwarm, AutoSwarmRouter from swarms.structs.auto_swarm import AutoSwarm, AutoSwarmRouter
from swarms.structs.autoscaler import AutoScaler from swarms.structs.autoscaler import AutoScaler
from swarms.structs.base import BaseStructure from swarms.structs.base import BaseStructure
@ -79,6 +78,8 @@ from swarms.structs.utils import (
find_token_in_text, find_token_in_text,
parse_tasks, parse_tasks,
) )
from swarms.structs.agent_rearrange import AgentRearrange
__all__ = [ __all__ = [
"Agent", "Agent",

@ -6,7 +6,7 @@ import random
import sys import sys
import time import time
import uuid import uuid
from typing import Any, Callable, Dict, List, Optional, Tuple, Union from typing import Any, Callable, Dict, List, Optional, Tuple
import yaml import yaml
from loguru import logger from loguru import logger
@ -17,16 +17,15 @@ from swarms.prompts.agent_system_prompts import AGENT_SYSTEM_PROMPT_3
from swarms.prompts.multi_modal_autonomous_instruction_prompt import ( from swarms.prompts.multi_modal_autonomous_instruction_prompt import (
MULTI_MODAL_AUTO_AGENT_SYSTEM_PROMPT_1, MULTI_MODAL_AUTO_AGENT_SYSTEM_PROMPT_1,
) )
from swarms.prompts.worker_prompt import worker_tools_sop_promp
from swarms.structs.conversation import Conversation from swarms.structs.conversation import Conversation
from swarms.tools.code_executor import CodeExecutor
from swarms.tools.exec_tool import execute_tool_by_name
from swarms.tools.function_util import process_tool_docs
from swarms.tools.tool import BaseTool from swarms.tools.tool import BaseTool
from swarms.utils.code_interpreter import SubprocessCodeInterpreter from swarms.utils.code_interpreter import SubprocessCodeInterpreter
from swarms.utils.data_to_text import data_to_text from swarms.utils.data_to_text import data_to_text
from swarms.utils.parse_code import extract_code_from_markdown from swarms.utils.parse_code import extract_code_from_markdown
from swarms.utils.pdf_to_text import pdf_to_text from swarms.utils.pdf_to_text import pdf_to_text
from swarms.tools.exec_tool import execute_tool_by_name
from swarms.tools.code_executor import CodeExecutor
from swarms.prompts.worker_prompt import tool_usage_worker_prompt
# Utils # Utils
@ -172,7 +171,7 @@ class Agent:
agent_name: str = "swarm-worker-01", agent_name: str = "swarm-worker-01",
agent_description: str = None, agent_description: str = None,
system_prompt: str = AGENT_SYSTEM_PROMPT_3, system_prompt: str = AGENT_SYSTEM_PROMPT_3,
tools: Union[List[BaseTool]] = None, tools: List[BaseTool] = [],
dynamic_temperature_enabled: Optional[bool] = False, dynamic_temperature_enabled: Optional[bool] = False,
sop: Optional[str] = None, sop: Optional[str] = None,
sop_list: Optional[List[str]] = None, sop_list: Optional[List[str]] = None,
@ -210,6 +209,7 @@ class Agent:
custom_exit_command: Optional[str] = "exit", custom_exit_command: Optional[str] = "exit",
sentiment_analyzer: Optional[Callable] = None, sentiment_analyzer: Optional[Callable] = None,
limit_tokens_from_string: Optional[Callable] = None, limit_tokens_from_string: Optional[Callable] = None,
custom_tools_prompt: Optional[Callable] = None,
*args, *args,
**kwargs, **kwargs,
): ):
@ -318,21 +318,21 @@ class Agent:
# If tools are provided then set the tool prompt by adding to sop # If tools are provided then set the tool prompt by adding to sop
if self.tools: if self.tools:
tools_prompt = worker_tools_sop_promp( if custom_tools_prompt is not None:
name=self.agent_name, tools_prompt = custom_tools_prompt(tools=self.tools)
memory=self.short_memory.return_history_as_string(),
)
# Append the tools prompt to the short_term_memory self.short_memory.add(
self.short_memory.add( role=self.agent_name, content=tools_prompt
role=self.agent_name, content=tools_prompt )
)
else:
tools_prompt = tool_usage_worker_prompt(
tools=self.tools
)
# And, add the tool documentation to the memory # Append the tools prompt to the short_term_memory
for tool in self.tools:
tool_docs = process_tool_docs(tool)
self.short_memory.add( self.short_memory.add(
role=self.agent_name, content=tool_docs role=self.agent_name, content=tools_prompt
) )
# If the long term memory is provided then set the long term memory prompt # If the long term memory is provided then set the long term memory prompt
@ -614,7 +614,7 @@ class Agent:
else (task_prompt, img, *args) else (task_prompt, img, *args)
) )
response = self.llm(*response_args, **kwargs) response = self.llm(*response_args, **kwargs)
print(response) # print(response)
self.short_memory.add( self.short_memory.add(
role=self.agent_name, content=response role=self.agent_name, content=response
) )
@ -696,11 +696,16 @@ class Agent:
content=sentiment, content=sentiment,
) )
if self.streaming:
self.streaming(response)
else:
print(response)
success = True # Mark as successful to exit the retry loop success = True # Mark as successful to exit the retry loop
except Exception as e: except Exception as e:
logger.error( logger.error(
f"Attempt {attempt + 1}: Error generating" f"Attempt {attempt+1}: Error generating"
f" response: {e}" f" response: {e}"
) )
attempt += 1 attempt += 1
@ -713,10 +718,11 @@ class Agent:
break # Exit the loop if all retry attempts fail break # Exit the loop if all retry attempts fail
# Check stopping conditions # Check stopping conditions
if self.stopping_token in response: if self.stopping_token is not None:
break if self.stopping_token in response:
break
elif ( elif (
self.stopping_condition self.stopping_condition is not None
and self._check_stopping_condition(response) and self._check_stopping_condition(response)
): ):
break break

@ -1,10 +1,10 @@
from datetime import datetime from datetime import datetime
from typing import Callable
from pydantic import BaseModel from pydantic import BaseModel
from swarms.structs.omni_agent_types import agents from swarms.structs.omni_agent_types import agents
from swarms.utils.loguru_logger import logger from swarms.utils.loguru_logger import logger
from typing import Callable
class AgentProcess(BaseModel): class AgentProcess(BaseModel):

@ -1,7 +1,6 @@
import logging import logging
from collections import defaultdict from collections import defaultdict
from typing import Callable, Sequence from typing import Callable, Sequence
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.base_swarm import BaseSwarm from swarms.structs.base_swarm import BaseSwarm

@ -15,8 +15,8 @@ import yaml
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.conversation import Conversation from swarms.structs.conversation import Conversation
from swarms.structs.omni_agent_types import agent
from swarms.utils.loguru_logger import logger from swarms.utils.loguru_logger import logger
from swarms.structs.omni_agent_types import agent
class BaseSwarm(ABC): class BaseSwarm(ABC):
@ -102,8 +102,8 @@ class BaseSwarm(ABC):
# Handle the case where the agents are not provided # Handle the case where the agents are not provided
# Handle agents # Handle agents
for agent_instance in self.agents: for agent in self.agents:
if not isinstance(agent_instance, Agent): if not isinstance(agent, Agent):
raise TypeError("Agents must be of type Agent.") raise TypeError("Agents must be of type Agent.")
if self.agents is None: if self.agents is None:
@ -392,26 +392,26 @@ class BaseSwarm(ABC):
Returns: Returns:
""" """
for agent_instance in self.agents: for agent in self.agents:
agent_instance.reset() agent.reset()
def select_agent(self, agent_id: str): def select_agent(self, agent_id: str):
""" """
Select an agent through their id Select an agent through their id
""" """
# Find agent with id # Find agent with id
for agent_instance in self.agents: for agent in self.agents:
if agent_instance.id == agent_id: if agent.id == agent_id:
return agent_instance return agent
def select_agent_by_name(self, agent_name: str): def select_agent_by_name(self, agent_name: str):
""" """
Select an agent through their name Select an agent through their name
""" """
# Find agent with id # Find agent with id
for agent_instance in self.agents: for agent in self.agents:
if agent_instance.name == agent_name: if agent.name == agent_name:
return agent_instance return agent
def task_assignment_by_id( def task_assignment_by_id(
self, task: str, agent_id: str, *args, **kwargs self, task: str, agent_id: str, *args, **kwargs
@ -471,8 +471,8 @@ class BaseSwarm(ABC):
_type_: _description_ _type_: _description_
""" """
responses = [] responses = []
for agent_instance in self.agents: for agent in self.agents:
responses.append(agent_instance(task, *args, **kwargs)) responses.append(agent(task, *args, **kwargs))
return responses return responses
def run_on_all_agents(self, task: str = None, *args, **kwargs): def run_on_all_agents(self, task: str = None, *args, **kwargs):

@ -1,11 +1,12 @@
import datetime import datetime
import json import json
from typing import Any, Optional from typing import Optional
from termcolor import colored from termcolor import colored
from swarms.memory.base_db import AbstractDatabase from swarms.memory.base_db import AbstractDatabase
from swarms.structs.base import BaseStructure from swarms.structs.base import BaseStructure
from typing import Any
class Conversation(BaseStructure): class Conversation(BaseStructure):

@ -237,7 +237,7 @@ class Debate:
if self.mod_ans["debate_translation"] != "": if self.mod_ans["debate_translation"] != "":
break break
else: else:
print(f"===== Debate Round-{round + 2} =====\n") print(f"===== Debate Round-{round+2} =====\n")
self.affirmative.add_message_to_memory( self.affirmative.add_message_to_memory(
self.save_file["debate_prompt"].replace( self.save_file["debate_prompt"].replace(
"##oppo_ans##", self.neg_ans "##oppo_ans##", self.neg_ans

@ -17,8 +17,7 @@ class GraphWorkflow(BaseStructure):
connect(from_node, to_node): Connects two nodes in the graph. connect(from_node, to_node): Connects two nodes in the graph.
set_entry_point(node_name): Sets the entry point node for the workflow. set_entry_point(node_name): Sets the entry point node for the workflow.
add_edge(from_node, to_node): Adds an edge between two nodes in the graph. add_edge(from_node, to_node): Adds an edge between two nodes in the graph.
add_conditional_edges(from_node, condition, edge_dict): add_conditional_edges(from_node, condition, edge_dict): Adds conditional edges from a node to multiple nodes based on a condition.
Adds conditional edges from a node to multiple nodes based on a condition.
run(): Runs the workflow and returns the graph. run(): Runs the workflow and returns the graph.
Examples: Examples:
@ -127,11 +126,15 @@ class GraphWorkflow(BaseStructure):
if from_node in self.graph: if from_node in self.graph:
for condition_value, to_node in edge_dict.items(): for condition_value, to_node in edge_dict.items():
if to_node in self.graph: if to_node in self.graph:
self.graph[from_node]["edges"][to_node] = condition self.graph[from_node]["edges"][
to_node
] = condition
else: else:
raise ValueError("Node does not exist in graph") raise ValueError("Node does not exist in graph")
else: else:
raise ValueError(f"Node {from_node} does not exist in graph") raise ValueError(
f"Node {from_node} does not exist in graph"
)
def run(self): def run(self):
""" """
@ -157,7 +160,9 @@ class GraphWorkflow(BaseStructure):
ValueError: _description_ ValueError: _description_
""" """
if node_name not in self.graph: if node_name not in self.graph:
raise ValueError(f"Node {node_name} does not exist in graph") raise ValueError(
f"Node {node_name} does not exist in graph"
)
def _check_nodes_exist(self, from_node, to_node): def _check_nodes_exist(self, from_node, to_node):
""" """

@ -20,7 +20,9 @@ def _hash(input: str):
return hex_dig return hex_dig
def msg_hash(agent: Agent, content: str, turn: int, msg_type: str = "text"): def msg_hash(
agent: Agent, content: str, turn: int, msg_type: str = "text"
):
""" """
Generate a hash value for a message. Generate a hash value for a message.
@ -35,7 +37,8 @@ def msg_hash(agent: Agent, content: str, turn: int, msg_type: str = "text"):
""" """
time = time_ns() time = time_ns()
return _hash( return _hash(
f"agent: {agent.agent_name}\ncontent: {content}\ntimestamp:" f" {str(time)}\nturn: {turn}\nmsg_type: {msg_type}" f"agent: {agent.agent_name}\ncontent: {content}\ntimestamp:"
f" {str(time)}\nturn: {turn}\nmsg_type: {msg_type}"
) )
@ -64,17 +67,11 @@ class MessagePool:
>>> message_pool.add(agent=agent2, content="Hello, agent1!", turn=1) >>> message_pool.add(agent=agent2, content="Hello, agent1!", turn=1)
>>> message_pool.add(agent=agent3, content="Hello, agent1!", turn=1) >>> message_pool.add(agent=agent3, content="Hello, agent1!", turn=1)
>>> message_pool.get_all_messages() >>> message_pool.get_all_messages()
[{'agent': Agent(agent_name='agent1'), 'content': 'Hello, agent2!', 'turn': 1, 'visible_to': 'all', 'logged': True}, [{'agent': Agent(agent_name='agent1'), 'content': 'Hello, agent2!', 'turn': 1, 'visible_to': 'all', 'logged': True}, {'agent': Agent(agent_name='agent2'), 'content': 'Hello, agent1!', 'turn': 1, 'visible_to': 'all', 'logged': True}, {'agent': Agent(agent_name='agent3'), 'content': 'Hello, agent1!', 'turn': 1, 'visible_to': 'all', 'logged': True}]
{'agent': Agent(agent_name='agent2'), 'content': 'Hello, agent1!', 'turn': 1, 'visible_to': 'all', 'logged': True},
{'agent': Agent(agent_name='agent3'), 'content': 'Hello, agent1!', 'turn': 1, 'visible_to': 'all', 'logged': True}]
>>> message_pool.get_visible_messages(agent=agent1, turn=1) >>> message_pool.get_visible_messages(agent=agent1, turn=1)
[{'agent': Agent(agent_name='agent1'), 'content': 'Hello, agent2!', 'turn': 1, 'visible_to': 'all', 'logged': True}, [{'agent': Agent(agent_name='agent1'), 'content': 'Hello, agent2!', 'turn': 1, 'visible_to': 'all', 'logged': True}, {'agent': Agent(agent_name='agent2'), 'content': 'Hello, agent1!', 'turn': 1, 'visible_to': 'all', 'logged': True}, {'agent': Agent(agent_name='agent3'), 'content': 'Hello, agent1!', 'turn': 1, 'visible_to': 'all', 'logged': True}]
{'agent': Agent(agent_name='agent2'), 'content': 'Hello, agent1!', 'turn': 1, 'visible_to': 'all', 'logged': True},
{'agent': Agent(agent_name='agent3'), 'content': 'Hello, agent1!', 'turn': 1, 'visible_to': 'all', 'logged': True}]
>>> message_pool.get_visible_messages(agent=agent2, turn=1) >>> message_pool.get_visible_messages(agent=agent2, turn=1)
[{'agent': Agent(agent_name='agent1'), 'content': 'Hello, agent2!', 'turn': 1, 'visible_to': 'all', 'logged': True}, [{'agent': Agent(agent_name='agent1'), 'content': 'Hello, agent2!', 'turn': 1, 'visible_to': 'all', 'logged': True}, {'agent': Agent(agent_name='agent2'), 'content': 'Hello, agent1!', 'turn': 1, 'visible_to': 'all', 'logged': True}, {'agent': Agent(agent_name='agent3'), 'content': 'Hello, agent1!', 'turn': 1, 'visible_to': 'all', 'logged': True}]
{'agent': Agent(agent_name='agent2'), 'content': 'Hello, agent1!', 'turn': 1, 'visible_to': 'all', 'logged': True},
{'agent': Agent(agent_name='agent3'), 'content': 'Hello, agent1!', 'turn': 1, 'visible_to': 'all', 'logged': True}]
""" """
def __init__( def __init__(
@ -101,7 +98,9 @@ class MessagePool:
logger.info("MessagePool initialized") logger.info("MessagePool initialized")
logger.info(f"Number of agents: {len(agents)}") logger.info(f"Number of agents: {len(agents)}")
logger.info(f"Agents: {[agent.agent_name for agent in agents]}") logger.info(
f"Agents: {[agent.agent_name for agent in agents]}"
)
logger.info(f"moderator: {moderator.agent_name} is available") logger.info(f"moderator: {moderator.agent_name} is available")
logger.info(f"Number of turns: {turns}") logger.info(f"Number of turns: {turns}")
@ -188,11 +187,18 @@ class MessagePool:
List[Dict]: The list of visible messages. List[Dict]: The list of visible messages.
""" """
# Get the messages before the current turn # Get the messages before the current turn
prev_messages = [message for message in self.messages if message["turn"] < turn] prev_messages = [
message
for message in self.messages
if message["turn"] < turn
]
visible_messages = [] visible_messages = []
for message in prev_messages: for message in prev_messages:
if message["visible_to"] == "all" or agent.agent_name in message["visible_to"]: if (
message["visible_to"] == "all"
or agent.agent_name in message["visible_to"]
):
visible_messages.append(message) visible_messages.append(message)
return visible_messages return visible_messages

@ -1,24 +1,25 @@
from swarms.structs.agent import Agent
from typing import Union from typing import Union
from swarms.models.base_llm import AbstractLLM
from swarms.models.popular_llms import OpenAIChat from swarms.models.popular_llms import OpenAIChat
from swarms.models.base_llm import AbstractLLM
from swarms.prompts.meta_system_prompt import ( from swarms.prompts.meta_system_prompt import (
meta_system_prompt_generator, meta_system_prompt_generator,
) )
from swarms.structs.agent import Agent
meta_prompter_llm = OpenAIChat(system_prompt=str(meta_system_prompt_generator)) meta_prompter_llm = OpenAIChat(
system_prompt=str(meta_system_prompt_generator)
)
def meta_system_prompt(agent: Union[Agent, AbstractLLM], system_prompt: str) -> str: def meta_system_prompt(
agent: Union[Agent, AbstractLLM], system_prompt: str
) -> str:
""" """
Generates a meta system prompt for the given agent using the provided system prompt. Generates a meta system prompt for the given agent using the provided system prompt.
Args: Args:
agent (Union[Agent, AbstractLLM]): agent (Union[Agent, AbstractLLM]): The agent or LLM (Language Learning Model) for which the meta system prompt is generated.
The agent or LLM (Language Learning Model) for which the meta system prompt is generated. system_prompt (str): The system prompt used to generate the meta system prompt.
system_prompt (str):
The system prompt used to generate the meta system prompt.
Returns: Returns:
str: The generated meta system prompt. str: The generated meta system prompt.

@ -88,7 +88,7 @@ class ModelParallelizer:
"""Save responses to file""" """Save responses to file"""
with open(filename, "w") as file: with open(filename, "w") as file:
table = [ table = [
[f"LLM {i + 1}", response] [f"LLM {i+1}", response]
for i, response in enumerate(self.last_responses) for i, response in enumerate(self.last_responses)
] ]
file.write(table) file.write(table)
@ -111,7 +111,7 @@ class ModelParallelizer:
print(f"{i + 1}. {task}") print(f"{i + 1}. {task}")
print("\nLast Responses:") print("\nLast Responses:")
table = [ table = [
[f"LLM {i + 1}", response] [f"LLM {i+1}", response]
for i, response in enumerate(self.last_responses) for i, response in enumerate(self.last_responses)
] ]
print( print(

@ -120,7 +120,7 @@ class MultiThreadedWorkflow(BaseWorkflow):
except Exception as e: except Exception as e:
logging.error( logging.error(
( (
f"Attempt {attempt + 1} failed for task" f"Attempt {attempt+1} failed for task"
f" {task}: {str(e)}" f" {task}: {str(e)}"
), ),
exc_info=True, exc_info=True,

@ -4,7 +4,6 @@ from typing import (
Sequence, Sequence,
Union, Union,
) )
from swarms.models.base_llm import AbstractLLM from swarms.models.base_llm import AbstractLLM
from swarms.models.base_multimodal_model import BaseMultiModalModel from swarms.models.base_multimodal_model import BaseMultiModalModel
from swarms.structs.agent import Agent from swarms.structs.agent import Agent

@ -1,9 +1,8 @@
import logging import logging
from collections import defaultdict from collections import defaultdict
from typing import Callable, Sequence
from swarms.structs.agent import Agent
from swarms.utils.loguru_logger import logger from swarms.utils.loguru_logger import logger
from swarms.structs.agent import Agent
from typing import Sequence, Callable
class AgentRearrange: class AgentRearrange:

@ -186,7 +186,7 @@ class SequentialWorkflow:
loops = 0 loops = 0
while loops < self.max_loops: while loops < self.max_loops:
for i, agent in enumerate(self.agents): for i, agent in enumerate(self.agents):
logger.info(f"Agent {i + 1} is executing the task.") logger.info(f"Agent {i+1} is executing the task.")
out = agent(self.description) out = agent(self.description)
self.conversation.add(agent.agent_name, str(out)) self.conversation.add(agent.agent_name, str(out))
prompt = self.conversation.return_history_as_string() prompt = self.conversation.return_history_as_string()

@ -1,5 +1,4 @@
from typing import Callable, List, Sequence, Union from typing import Union, Sequence, List, Callable
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.base_swarm import BaseSwarm from swarms.structs.base_swarm import BaseSwarm

@ -1,8 +1,7 @@
from typing import Dict, List, Sequence from typing import Dict, List, Sequence
from pydantic import BaseModel
from swarms.tools.tool import BaseTool from swarms.tools.tool import BaseTool
from pydantic import BaseModel
class Step(BaseModel): class Step(BaseModel):

@ -5,6 +5,7 @@ import threading
from typing import List, Optional from typing import List, Optional
# from fastapi import FastAPI # from fastapi import FastAPI
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.base import BaseStructure from swarms.structs.base import BaseStructure
from swarms.utils.logger import logger # noqa: F401 from swarms.utils.logger import logger # noqa: F401

@ -1,7 +1,7 @@
import json import json
from typing import List, Optional from typing import List, Optional
from pydantic import BaseModel, Field, Json, model_validator from pydantic import model_validator, BaseModel, Field, Json
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.task import Task from swarms.structs.task import Task

@ -1,5 +1,4 @@
from swarms.telemetry.log_all import log_all_calls, log_calls from swarms.telemetry.log_all import log_all_calls, log_calls
from swarms.telemetry.sentry_active import activate_sentry
from swarms.telemetry.sys_info import ( from swarms.telemetry.sys_info import (
get_cpu_info, get_cpu_info,
get_os_version, get_os_version,
@ -17,6 +16,7 @@ from swarms.telemetry.user_utils import (
get_system_info, get_system_info,
get_user_device_data, get_user_device_data,
) )
from swarms.telemetry.sentry_active import activate_sentry
__all__ = [ __all__ = [
"log_all_calls", "log_all_calls",

@ -1,8 +1,7 @@
import subprocess import subprocess
from termcolor import colored
from swarms.telemetry.check_update import check_for_update from swarms.telemetry.check_update import check_for_update
from termcolor import colored
def auto_update(): def auto_update():

@ -1,5 +1,5 @@
import logging
import os import os
import logging
import warnings import warnings
from swarms.telemetry.auto_upgrade_swarms import auto_update from swarms.telemetry.auto_upgrade_swarms import auto_update

@ -1,7 +1,6 @@
import os import os
import sentry_sdk
from dotenv import load_dotenv from dotenv import load_dotenv
import sentry_sdk
load_dotenv() load_dotenv()

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save