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,4 +1,3 @@
---
repos:
- repo: https://github.com/ambv/black
rev: 22.3.0
@ -8,7 +7,7 @@ repos:
rev: 'v0.0.255'
hooks:
- id: ruff
args: ['----unsafe-fixes']
args: [----unsafe-fixes]
- repo: https://github.com/nbQA-dev/nbQA
rev: 1.6.3
hooks:

@ -1,11 +1,13 @@
---
version: 2
build:
os: ubuntu-22.04
tools:
python: "3.11"
mkdocs:
configuration: mkdocs.yml
python:
install:
- 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
# Initialize the workflow
## Initialize the workflow
agent = Agent(
agent_name="Transcript Generator",
agent_description=(

@ -1,4 +1,3 @@
---
site_name: Swarms Docs
plugins:
- glightbox
@ -76,7 +75,7 @@ nav:
- ToolAgent: "swarms/agents/toolagent.md"
- swarms.models:
- 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:
- BaseLLM: "swarms/models/base_llm.md"
- Overview: "swarms/models/index.md"
@ -144,7 +143,7 @@ nav:
- Guides:
- 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"
- "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"
- Overview: "examples/index.md"
- Agents:
@ -178,5 +177,9 @@ nav:
- Research: "corporate/research.md"
- Demos: "corporate/demos.md"
- Checklist: "corporate/checklist.md"
- Organization:
- FrontEnd Member Onboarding: "corporate/front_end_contributors.md"

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

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

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

@ -21,7 +21,7 @@ llm = GPT4VisionAPI(
task = "What is the color of the object?"
img = "images/swarms.jpeg"
# Initialize the workflow
## Initialize the workflow
agent = Agent(
llm=llm,
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):
theme = random.choice(self.themes)
context = random.choice(self.contexts)
style = random.choice(["medival", "modern", "futuristic", "retro"])
return (
f"{theme} inside a {style} {self.product_name}, {context}"
)
@ -89,7 +88,6 @@ image_paths = sd_api.run(creative_concept)
# Generate ad copy
ad_copy_agent = Agent(llm=llm, max_loops=1)
social_media_platform = "Instagram"
ad_copy_prompt = (
f"Write a compelling {social_media_platform} ad copy for a"
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)
# Output the results
print("Ad Copy:", ad_copy)
print("Creative Concept:", concept_result)
print("Design Ideas:", design_result)
print("Ad Copy:", copywriting_result)
print(
"Image Path:",
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
- Long Term Mmeory: ChromaDB, Weaviate, Pinecone, ETC
"""
from playground.demos.agent_in_5.chroma_db import ChromaDB
from swarms import Agent, OpenAIChat, tool
from playground.demos.agent_in_5.chroma_db import ChromaDB
# Initialize the memory
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 csv
from dotenv import load_dotenv
from swarms import Agent, OpenAIChat
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.loguru_logger import logger
from swarms.utils.parse_code import extract_code_from_markdown
# Load ENV
load_dotenv()
@ -70,7 +69,7 @@ def extract_and_create_agents(
"""
try:
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)
for row in reader:
project_name = row[target_columns[0]]

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

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

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

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

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

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

@ -1,5 +1,5 @@
import discord
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
# Discord Bot Setup
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.
import datetime
import json
import datetime
import pytz
from flask import Flask, jsonify, request
from flask import Flask, request, jsonify
app = Flask(__name__)
@ -28,7 +28,7 @@ def create_conversation():
@app.route("/api/v1/conversations/<conversation_id>", methods=["GET"])
def get_conversation(conversation_id):
# Get the conversation from the database
with open("conversations.json") as f:
with open("conversations.json", "r") as f:
conversation = json.load(f)
# Return the conversation
@ -49,7 +49,7 @@ def create_message(conversation_id):
}
# Get the conversation from the database
with open("conversations.json") as f:
with open("conversations.json", "r") as f:
conversation = json.load(f)
# Add the message to the conversation
@ -68,7 +68,7 @@ def create_message(conversation_id):
)
def get_messages(conversation_id):
# Get the conversation from the database
with open("conversations.json") as f:
with open("conversations.json", "r") as f:
conversation = json.load(f)
# Return the messages
@ -80,7 +80,7 @@ def get_messages(conversation_id):
)
def get_summary(conversation_id):
# Get the conversation from the database
with open("conversations.json") as f:
with open("conversations.json", "r") as f:
conversation = json.load(f)
# Create a summary of the conversation
@ -98,7 +98,7 @@ def get_summary(conversation_id):
)
def get_audio_recap(conversation_id):
# Get the conversation from the database
with open("conversations.json") as f:
with open("conversations.json", "r") as f:
conversation = json.load(f)
# Create an audio recap of the conversation

@ -1,14 +1,12 @@
import concurrent
import csv
import os
from dotenv import load_dotenv
from swarms import Agent, Gemini
from swarms import Gemini, Agent
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.loguru_logger import logger
from swarms.utils.parse_code import extract_code_from_markdown
# Load ENV
load_dotenv()
@ -73,7 +71,7 @@ def extract_and_create_agents(
- target_columns: A list of column names to extract values from.
"""
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)
for row in reader:
project_name = row[target_columns[0]]

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

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

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

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

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

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

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

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

@ -3,7 +3,7 @@ import os
from dotenv import load_dotenv
# 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_dotenv()
@ -17,7 +17,7 @@ llm = OpenAIChat(
openai_api_key=api_key,
)
# Initialize the workflow
## Initialize the workflow
agent = Agent(llm=llm, max_loops=1, agent_name="Social Media Manager")
agent2 = Agent(llm=llm, max_loops=1, agent_name=" Product Manager")
agent3 = Agent(llm=llm, max_loops=1, agent_name="SEO Manager")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -1,21 +1,21 @@
import concurrent
import inspect
import os
import threading
from typing import Callable, List
from swarms import Agent, OpenAIChat
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 (
create_file_in_folder,
load_json,
sanitize_file_path,
zip_folders,
zip_workspace,
create_file_in_folder,
zip_folders,
)
from swarms.utils.loguru_logger import logger
class PythonDocumentationSwarm:

@ -3,9 +3,7 @@ Boss selects what agent to use
B -> W1, W2, W3
"""
from typing import List, Optional
from pydantic import BaseModel, Field
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}")
# Initialize the workflow
## Initialize the workflow
agent = Agent(
llm=llm,
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 os
import threading

@ -2,8 +2,8 @@ import os
import shutil
# Create a new directory for the log files if it doesn't exist
if not os.path.exists("artifacts"):
os.makedirs("artifacts")
if not os.path.exists("artifacts_two"):
os.makedirs("artifacts_two")
# Walk through the current directory
for dirpath, dirnames, filenames in os.walk("."):
@ -12,10 +12,10 @@ for dirpath, dirnames, filenames in os.walk("."):
if filename.endswith(".log"):
# Construct the full file path
file_path = os.path.join(dirpath, filename)
# Move the log file to the 'artifacts' directory
shutil.move(file_path, "artifacts")
# Move the log file to the 'artifacts_two' directory
shutil.move(file_path, "artifacts_two")
print(
"Moved all log files into the 'artifacts' directory and deleted"
" their original location."
"Moved all log files into the 'artifacts_two' directory and"
" 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,7 +9,7 @@ for f in /swarms/playground/examples/example_*.py; do
echo "Skipping ${f} as it ran successfully in a previous run."
else
# 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."
# Log the successful script execution
echo "$f" >> "$SUCCESS_LOG"

@ -1,5 +1,5 @@
from abc import abstractmethod
from typing import Dict, List, Optional, Union
from typing import Dict, List, Union, Optional
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.tools.format_tools import Jsonformer

@ -7,9 +7,9 @@ import chromadb
import numpy as np
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.markdown_message import display_markdown_message
from swarms.memory.base_vectordb import AbstractVectorDatabase
# Load environment variables
load_dotenv()

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

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

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

@ -23,7 +23,6 @@ from swarms.models.popular_llms import (
from swarms.models.popular_llms import (
CohereChat as Cohere,
)
from swarms.models.popular_llms import OctoAIChat
from swarms.models.popular_llms import (
OpenAIChatLLM as OpenAIChat,
)
@ -33,7 +32,9 @@ from swarms.models.popular_llms import (
from swarms.models.popular_llms import (
ReplicateLLM as Replicate,
)
from swarms.models.popular_llms import OctoAIChat
from swarms.models.qwen import QwenVLMultiModal # noqa: E402
from swarms.models.sampling_params import SamplingParams, SamplingType
from swarms.models.together import TogetherLLM # 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
__all__ = [
"AbstractLLM",
"Anthropic",

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

@ -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
import numpy as np
from pydantic import BaseModel, ConfigDict, Field, model_validator
from pydantic import model_validator, ConfigDict, BaseModel, Field
from tenacity import (
AsyncRetrying,
before_sleep_log,

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

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

@ -1,6 +1,8 @@
import datetime
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")
@ -24,54 +26,202 @@ class ResponseFormat(BaseModel):
response_json = ResponseFormat.model_json_schema()
def worker_tools_sop_promp(name: str, memory: str, time=time):
out = f"""
You are {name},
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.
If you have completed all your tasks, make sure to use the 'finish' command.
tool_usage_browser = """
```json
{
"thoughts": {
"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.",
"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."
},
"command": {
"name": "browser",
"args": {
"query": "Miami weather"
}
}
}
```
GOALS:
"""
1. Hello, how are you? Create an image of how you are doing!
tool_usage_terminal = """
```json
{
"thoughts": {
"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.",
"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."
},
"command": {
"name": "terminal",
"args": {
"code": "uptime"
}
}
}
```
Constraints:
"""
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:
browser_and_terminal_tool = """
```
{
"thoughts": {
"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.",
"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"
}
}
]
}
```
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'
"""
Resources:
1. Internet access for searches and information gathering.
2. Long Term memory management.
3. Agents for delegation of simple tasks.
4. File output.
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]"
}
}
]
}
Performance Evaluation:
```
1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.
2. Constructively self-criticize your big-picture behavior constantly.
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.
# 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}
```
{response_json}
- **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}
```
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:
[{memory}]
Human: Determine which next command to use, and respond using the format specified above:
### 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,
AgentProcessQueue,
)
from swarms.structs.agent_rearrange import AgentRearrange
from swarms.structs.auto_swarm import AutoSwarm, AutoSwarmRouter
from swarms.structs.autoscaler import AutoScaler
from swarms.structs.base import BaseStructure
@ -79,6 +78,8 @@ from swarms.structs.utils import (
find_token_in_text,
parse_tasks,
)
from swarms.structs.agent_rearrange import AgentRearrange
__all__ = [
"Agent",

@ -6,7 +6,7 @@ import random
import sys
import time
import uuid
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from typing import Any, Callable, Dict, List, Optional, Tuple
import yaml
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 (
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.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.utils.code_interpreter import SubprocessCodeInterpreter
from swarms.utils.data_to_text import data_to_text
from swarms.utils.parse_code import extract_code_from_markdown
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
@ -172,7 +171,7 @@ class Agent:
agent_name: str = "swarm-worker-01",
agent_description: str = None,
system_prompt: str = AGENT_SYSTEM_PROMPT_3,
tools: Union[List[BaseTool]] = None,
tools: List[BaseTool] = [],
dynamic_temperature_enabled: Optional[bool] = False,
sop: Optional[str] = None,
sop_list: Optional[List[str]] = None,
@ -210,6 +209,7 @@ class Agent:
custom_exit_command: Optional[str] = "exit",
sentiment_analyzer: Optional[Callable] = None,
limit_tokens_from_string: Optional[Callable] = None,
custom_tools_prompt: Optional[Callable] = None,
*args,
**kwargs,
):
@ -318,21 +318,21 @@ class Agent:
# If tools are provided then set the tool prompt by adding to sop
if self.tools:
tools_prompt = worker_tools_sop_promp(
name=self.agent_name,
memory=self.short_memory.return_history_as_string(),
)
if custom_tools_prompt is not None:
tools_prompt = custom_tools_prompt(tools=self.tools)
# Append the tools prompt to the short_term_memory
self.short_memory.add(
role=self.agent_name, content=tools_prompt
)
# And, add the tool documentation to the memory
for tool in self.tools:
tool_docs = process_tool_docs(tool)
else:
tools_prompt = tool_usage_worker_prompt(
tools=self.tools
)
# Append the tools prompt to the short_term_memory
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
@ -614,7 +614,7 @@ class Agent:
else (task_prompt, img, *args)
)
response = self.llm(*response_args, **kwargs)
print(response)
# print(response)
self.short_memory.add(
role=self.agent_name, content=response
)
@ -696,6 +696,11 @@ class Agent:
content=sentiment,
)
if self.streaming:
self.streaming(response)
else:
print(response)
success = True # Mark as successful to exit the retry loop
except Exception as e:
@ -713,10 +718,11 @@ class Agent:
break # Exit the loop if all retry attempts fail
# Check stopping conditions
if self.stopping_token is not None:
if self.stopping_token in response:
break
elif (
self.stopping_condition
self.stopping_condition is not None
and self._check_stopping_condition(response)
):
break

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

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

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

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

@ -17,8 +17,7 @@ class GraphWorkflow(BaseStructure):
connect(from_node, to_node): Connects two nodes in the graph.
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_conditional_edges(from_node, condition, edge_dict):
Adds conditional edges from a node to multiple nodes based on a condition.
add_conditional_edges(from_node, condition, edge_dict): Adds conditional edges from a node to multiple nodes based on a condition.
run(): Runs the workflow and returns the graph.
Examples:
@ -127,11 +126,15 @@ class GraphWorkflow(BaseStructure):
if from_node in self.graph:
for condition_value, to_node in edge_dict.items():
if to_node in self.graph:
self.graph[from_node]["edges"][to_node] = condition
self.graph[from_node]["edges"][
to_node
] = condition
else:
raise ValueError("Node does not exist in graph")
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):
"""
@ -157,7 +160,9 @@ class GraphWorkflow(BaseStructure):
ValueError: _description_
"""
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):
"""

@ -20,7 +20,9 @@ def _hash(input: str):
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.
@ -35,7 +37,8 @@ def msg_hash(agent: Agent, content: str, turn: int, msg_type: str = "text"):
"""
time = time_ns()
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=agent3, content="Hello, agent1!", turn=1)
>>> message_pool.get_all_messages()
[{'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='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}]
>>> 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='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='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}]
>>> 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='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='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}]
"""
def __init__(
@ -101,7 +98,9 @@ class MessagePool:
logger.info("MessagePool initialized")
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"Number of turns: {turns}")
@ -188,11 +187,18 @@ class MessagePool:
List[Dict]: The list of visible messages.
"""
# 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 = []
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)
return visible_messages

@ -1,24 +1,25 @@
from swarms.structs.agent import Agent
from typing import Union
from swarms.models.base_llm import AbstractLLM
from swarms.models.popular_llms import OpenAIChat
from swarms.models.base_llm import AbstractLLM
from swarms.prompts.meta_system_prompt import (
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.
Args:
agent (Union[Agent, AbstractLLM]):
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.
agent (Union[Agent, AbstractLLM]): 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.
Returns:
str: The generated meta system prompt.

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

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

@ -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.base_swarm import BaseSwarm

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

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

@ -1,7 +1,7 @@
import json
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.task import Task

@ -1,5 +1,4 @@
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 (
get_cpu_info,
get_os_version,
@ -17,6 +16,7 @@ from swarms.telemetry.user_utils import (
get_system_info,
get_user_device_data,
)
from swarms.telemetry.sentry_active import activate_sentry
__all__ = [
"log_all_calls",

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

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

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

@ -1,3 +1,4 @@
from swarms.tools.tool import BaseTool, Tool, StructuredTool, tool
from swarms.tools.code_executor import CodeExecutor
from swarms.tools.exec_tool import (
AgentAction,
@ -6,7 +7,6 @@ from swarms.tools.exec_tool import (
execute_tool_by_name,
preprocess_json_input,
)
from swarms.tools.tool import BaseTool, StructuredTool, Tool, tool
from swarms.tools.tool_utils import (
execute_tools,
extract_tool_commands,

@ -1,5 +1,5 @@
import concurrent.futures
import json
import concurrent.futures
import re
from abc import abstractmethod
from typing import Dict, List, NamedTuple
@ -9,6 +9,8 @@ from pydantic import ValidationError
from swarms.tools.tool import BaseTool
from swarms.utils.loguru_logger import logger
class AgentAction(NamedTuple):
"""Action returned by AgentOutputParser."""
@ -97,6 +99,9 @@ def execute_tool_by_name(
# Get command name and arguments
action = output_parser.parse(text)
tools = {t.name: t for t in tools}
logger.info(f"Tools available: {tools}")
if action.name == stop_token:
return action.args["response"]
if action.name in tools:
@ -109,6 +114,7 @@ def execute_tool_by_name(
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = []
for tool_name in tool_names:
logger.info(f"Executing tool: {tool_name}")
futures.append(
executor.submit(
tools[tool_name].run, action.args

@ -1,16 +1,15 @@
import json
from typing import Any, Dict, List, Union
from pydantic import BaseModel
from termcolor import cprint
from transformers import PreTrainedModel, PreTrainedTokenizer
from swarms.models.base_llm import AbstractLLM
from pydantic import BaseModel
from swarms.tools.logits_processor import (
NumberStoppingCriteria,
OutputNumbersTokens,
StringStoppingCriteria,
)
from swarms.models.base_llm import AbstractLLM
GENERATION_MARKER = "|GENERATION|"

@ -1,8 +1,8 @@
from langchain.tools import (
BaseTool,
StructuredTool,
Tool,
StructuredTool,
tool,
)
) # noqa F401
__all__ = ["BaseTool", "Tool", "StructuredTool", "tool"]

@ -1,12 +1,13 @@
import inspect
import json
import re
from typing import Any, Callable, List
from termcolor import colored
from typing import Any, List
from swarms.prompts.tools import SCENARIOS
from swarms.tools.tool import BaseTool
import inspect
from typing import Callable
from termcolor import colored
def scrape_tool_func_docs(fn: Callable) -> str:
@ -17,8 +18,7 @@ def scrape_tool_func_docs(fn: Callable) -> str:
fn (Callable): The function to scrape.
Returns:
str: A string containing the function's name, documentation string, and a list of its parameters.
Each parameter is represented as a line containing the parameter's name, default value, and annotation.
str: A string containing the function's name, documentation string, and a list of its parameters. Each parameter is represented as a line containing the parameter's name, default value, and annotation.
"""
try:
# If the function is a tool, get the original function
@ -35,7 +35,10 @@ def scrape_tool_func_docs(fn: Callable) -> str:
f" {param.annotation if param.annotation is not param.empty else 'None'}"
)
parameters_str = "\n".join(parameters)
return f"Function: {fn.__name__}\nDocstring:" f" {inspect.getdoc(fn)}\nParameters:\n{parameters_str}"
return (
f"Function: {fn.__name__}\nDocstring:"
f" {inspect.getdoc(fn)}\nParameters:\n{parameters_str}"
)
except Exception as error:
print(
colored(

@ -1,6 +1,5 @@
from swarms.utils.class_args_wrapper import print_class_parameters
from swarms.utils.code_interpreter import SubprocessCodeInterpreter
from swarms.utils.concurrent_utils import execute_concurrently
from swarms.utils.csv_and_pandas import (
csv_to_dataframe,
dataframe_to_strings,
@ -18,11 +17,11 @@ from swarms.utils.download_weights_from_url import (
)
from swarms.utils.exponential_backoff import ExponentialBackoffMixin
from swarms.utils.file_processing import (
create_file_in_folder,
load_json,
sanitize_file_path,
zip_folders,
zip_workspace,
create_file_in_folder,
zip_folders,
)
from swarms.utils.find_img_path import find_image_path
from swarms.utils.json_output_parser import JsonOutputParser
@ -45,6 +44,8 @@ from swarms.utils.save_logs import parse_log_file
# from swarms.utils.supervision_visualizer import MarkVisualizer
from swarms.utils.try_except_wrapper import try_except_wrapper
from swarms.utils.yaml_output_parser import YamlOutputParser
from swarms.utils.concurrent_utils import execute_concurrently
__all__ = [
"print_class_parameters",

@ -108,7 +108,7 @@ class Action:
def to_json(self):
try:
tool_output = json.loads(self.tool_output)
except json.JSONDecodeError:
except:
tool_output = self.tool_output
return {
"thought": self.thought,

@ -1,7 +1,7 @@
import asyncio
import concurrent.futures
from inspect import iscoroutinefunction
from typing import Any, Callable, Dict, List
from inspect import iscoroutinefunction
import asyncio
# Helper function to run an asynchronous function in a synchronous way

@ -18,8 +18,7 @@ def load_model_torch(
model_path (str): Path to the saved model file.
device (torch.device): Device to move the model to.
model (nn.Module): The model architecture, if the model file only contains the state dictionary.
strict (bool): Whether to strictly enforce that the keys in the state dictionary match
the keys returned by the model's `state_dict()` function.
strict (bool): Whether to strictly enforce that the keys in the state dictionary match the keys returned by the model's `state_dict()` function.
map_location (callable): A function to remap the storage locations of the loaded model.
*args: Additional arguments to pass to `torch.load`.
**kwargs: Additional keyword arguments to pass to `torch.load`.
@ -32,11 +31,15 @@ def load_model_torch(
RuntimeError: If there is an error while loading the model.
"""
if device is None:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device = torch.device(
"cuda" if torch.cuda.is_available() else "cpu"
)
try:
if model is None:
model = torch.load(model_path, map_location=map_location, *args, **kwargs)
model = torch.load(
model_path, map_location=map_location, *args, **kwargs
)
else:
model.load_state_dict(
torch.load(

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

Loading…
Cancel
Save