[PLAYGROUND][CLEANUP][FEAT][FireWorksAI]

pull/529/head
Kye Gomez 6 months ago
parent 38ac047711
commit 19c31e99a2

@ -153,7 +153,3 @@ Please replace `/path/to/directory` with the actual path where the `code-quality
If you're asking for a specific content or functionality inside `code-quality.sh` related to YAPF or other code quality tools, you would need to edit the `code-quality.sh` script to include the desired commands, such as running YAPF on a directory. The contents of `code-quality.sh` would dictate exactly what happens when you run it.
## 📄 license
By contributing, you agree that your contributions will be licensed under an [MIT license](https://github.com/kyegomez/swarms/blob/develop/LICENSE.md).

@ -26,7 +26,7 @@
[![GitHub issues](https://img.shields.io/github/issues/kyegomez/swarms)](https://github.com/kyegomez/swarms/issues) [![GitHub forks](https://img.shields.io/github/forks/kyegomez/swarms)](https://github.com/kyegomez/swarms/network) [![GitHub stars](https://img.shields.io/github/stars/kyegomez/swarms)](https://github.com/kyegomez/swarms/stargazers) [![GitHub license](https://img.shields.io/github/license/kyegomez/swarms)](https://github.com/kyegomez/swarms/blob/main/LICENSE)[![GitHub star chart](https://img.shields.io/github/stars/kyegomez/swarms?style=social)](https://star-history.com/#kyegomez/swarms)[![Dependency Status](https://img.shields.io/librariesio/github/kyegomez/swarms)](https://libraries.io/github/kyegomez/swarms) [![Downloads](https://static.pepy.tech/badge/swarms/month)](https://pepy.tech/project/swarms)
[![Join the Agora discord](https://img.shields.io/discord/1110910277110743103?label=Discord&logo=discord&logoColor=white&style=plastic&color=d7b023)![Share on Twitter](https://img.shields.io/twitter/url/https/twitter.com/cloudposse.svg?style=social&label=Share%20%40kyegomez/swarms)](https://twitter.com/intent/tweet?text=Check%20out%20this%20amazing%20AI%20project:%20&url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms) [![Share on Facebook](https://img.shields.io/badge/Share-%20facebook-blue)](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms) [![Share on LinkedIn](https://img.shields.io/badge/Share-%20linkedin-blue)](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&title=&summary=&source=)
![Share on Twitter](https://img.shields.io/twitter/url/https/twitter.com/cloudposse.svg?style=social&label=Share%20%40kyegomez/swarms)](https://twitter.com/intent/tweet?text=Check%20out%20this%20amazing%20AI%20project:%20&url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms) [![Share on Facebook](https://img.shields.io/badge/Share-%20facebook-blue)](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms) [![Share on LinkedIn](https://img.shields.io/badge/Share-%20linkedin-blue)](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&title=&summary=&source=)
[![Share on Reddit](https://img.shields.io/badge/-Share%20on%20Reddit-orange)](https://www.reddit.com/submit?url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&title=Swarms%20-%20the%20future%20of%20AI) [![Share on Hacker News](https://img.shields.io/badge/-Share%20on%20Hacker%20News-orange)](https://news.ycombinator.com/submitlink?u=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&t=Swarms%20-%20the%20future%20of%20AI) [![Share on Pinterest](https://img.shields.io/badge/-Share%20on%20Pinterest-red)](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&media=https%3A%2F%2Fexample.com%2Fimage.jpg&description=Swarms%20-%20the%20future%20of%20AI) [![Share on WhatsApp](https://img.shields.io/badge/-Share%20on%20WhatsApp-green)](https://api.whatsapp.com/send?text=Check%20out%20Swarms%20-%20the%20future%20of%20AI%20%23swarms%20%23AI%0A%0Ahttps%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms)
@ -39,21 +39,12 @@
Swarms is an enterprise grade and production ready multi-agent collaboration framework that enables you to orchestrate many agents to work collaboratively at scale to automate real-world activities.
| **Feature** | **Description** | **Performance Impact** | **Documentation Link** |
|------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------|-------------------------------|
| Models | Pre-trained models that can be utilized for various tasks within the swarm framework. | ⭐⭐⭐ | [Documentation](https://docs.swarms.world/en/latest/swarms/models/) |
| Models APIs | APIs to interact with and utilize the models effectively, providing interfaces for inference, training, and fine-tuning. | ⭐⭐⭐ | [Documentation](https://docs.swarms.world/en/latest/swarms/models/) |
| Agents with Tools | Agents equipped with specialized tools to perform specific tasks more efficiently, such as data processing, analysis, or interaction with external systems. | ⭐⭐⭐⭐ | [Documentation](https://medium.com/@kyeg/the-swarms-tool-system-functions-pydantic-basemodels-as-tools-and-radical-customization-c2a2e227b8ca) |
| Agents with Memory | Mechanisms for agents to store and recall past interactions, improving learning and adaptability over time. | ⭐⭐⭐⭐ | [Documentation](https://github.com/kyegomez/swarms/blob/master/playground/structs/agent/agent_with_longterm_memory.py) |
| Multi-Agent Orchestration | Coordination of multiple agents to work together seamlessly on complex tasks, leveraging their individual strengths to achieve higher overall performance. | ⭐⭐⭐⭐⭐ | [Documentation]() |
The performance impact is rated on a scale from one to five stars, with multi-agent orchestration being the highest due to its ability to combine the strengths of multiple agents and optimize task execution.
----
## Requirements
- `python3.10` or above!
- `.env` file with API keys from your providers like `OpenAI`, `Anthropic`
- `.env` file with API keys from your providers like `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`
- `$ pip install -U swarms` And, don't forget to install swarms!
## Install 💻
@ -65,7 +56,6 @@ $ pip3 install -U swarms
# Usage Examples 🤖
### Google Collab Example
Run example in Collab: <a target="_blank" href="https://colab.research.google.com/github/kyegomez/swarms/blob/master/playground/swarms_example.ipynb">
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
</a>
@ -630,14 +620,7 @@ In traditional swarm theory, there are many types of swarms usually for very spe
### `SequentialWorkflow`
Sequential Workflow enables you to sequentially execute tasks with `Agent` and then pass the output into the next agent and onwards until you have specified your max loops. `SequentialWorkflow` is wonderful for real-world business tasks like sending emails, summarizing documents, and analyzing data.
✅ Save and Restore Workflow states!
✅ Multi-Modal Support for Visual Chaining
✅ Utilizes Agent class
Sequential Workflow enables you to sequentially execute tasks with `Agent` and then pass the output into the next agent and onwards until you have specified your max loops.
```python
from swarms import Agent, SequentialWorkflow, Anthropic
@ -676,253 +659,7 @@ workflow.run(
```
### `ConcurrentWorkflow`
`ConcurrentWorkflow` runs all the tasks all at the same time with the inputs you give it!
```python
import os
from dotenv import load_dotenv
from swarms import Agent, ConcurrentWorkflow, OpenAIChat, Task
# Load environment variables from .env file
load_dotenv()
# Load environment variables
llm = OpenAIChat(openai_api_key=os.getenv("OPENAI_API_KEY"))
agent = Agent(llm=llm, max_loops=1)
# Create a workflow
workflow = ConcurrentWorkflow(max_workers=5)
# Create tasks
task1 = Task(agent, "What's the weather in miami")
task2 = Task(agent, "What's the weather in new york")
task3 = Task(agent, "What's the weather in london")
# Add tasks to the workflow
workflow.add(tasks=[task1, task2, task3])
# Run the workflow
workflow.run()
```
### `SwarmNetwork`
`SwarmNetwork` provides the infrasturcture for building extremely dense and complex multi-agent applications that span across various types of agents.
✅ Efficient Task Management: SwarmNetwork's intelligent agent pool and task queue management system ensures tasks are distributed evenly across agents. This leads to efficient use of resources and faster task completion.
✅ Scalability: SwarmNetwork can dynamically scale the number of agents based on the number of pending tasks. This means it can handle an increase in workload by adding more agents, and conserve resources when the workload is low by reducing the number of agents.
✅ Versatile Deployment Options: With SwarmNetwork, each agent can be run on its own thread, process, container, machine, or even cluster. This provides a high degree of flexibility and allows for deployment that best suits the user's needs and infrastructure.
```python
import os
from dotenv import load_dotenv
# Import the OpenAIChat model and the Agent struct
from swarms import Agent, OpenAIChat, SwarmNetwork
# Load the environment variables
load_dotenv()
# Get the API key from the environment
api_key = os.environ.get("OPENAI_API_KEY")
# Initialize the language model
llm = OpenAIChat(
temperature=0.5,
openai_api_key=api_key,
)
## 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")
# Load the swarmnet with the agents
swarmnet = SwarmNetwork(
agents=[agent, agent2, agent3],
)
# List the agents in the swarm network
out = swarmnet.list_agents()
print(out)
# Run the workflow on a task
out = swarmnet.run_single_agent(
agent2.id, "Generate a 10,000 word blog on health and wellness."
)
print(out)
# Run all the agents in the swarm network on a task
out = swarmnet.run_many_agents("Generate a 10,000 word blog on health and wellness.")
print(out)
```
### Majority Voting
Multiple-agents will evaluate an idea based off of an parsing or evaluation function. From papers like "[More agents is all you need](https://arxiv.org/pdf/2402.05120.pdf)
```python
from swarms import Agent, MajorityVoting, ChromaDB, Anthropic
# Initialize the llm
llm = Anthropic()
# Agents
agent1 = Agent(
llm = llm,
system_prompt="You are the leader of the Progressive Party. What is your stance on healthcare?",
agent_name="Progressive Leader",
agent_description="Leader of the Progressive Party",
long_term_memory=ChromaDB(),
max_steps=1,
)
agent2 = Agent(
llm=llm,
agent_name="Conservative Leader",
agent_description="Leader of the Conservative Party",
long_term_memory=ChromaDB(),
max_steps=1,
)
agent3 = Agent(
llm=llm,
agent_name="Libertarian Leader",
agent_description="Leader of the Libertarian Party",
long_term_memory=ChromaDB(),
max_steps=1,
)
# Initialize the majority voting
mv = MajorityVoting(
agents=[agent1, agent2, agent3],
output_parser=llm.majority_voting,
autosave=False,
verbose=True,
)
# Start the majority voting
mv.run("What is your stance on healthcare?")
```
## Build your own LLMs, Agents, and Swarms!
### Swarms Compliant Model Interface
```python
from swarms import BaseLLM
class vLLMLM(BaseLLM):
def __init__(self, model_name='default_model', tensor_parallel_size=1, *args, **kwargs):
super().__init__(*args, **kwargs)
self.model_name = model_name
self.tensor_parallel_size = tensor_parallel_size
# Add any additional initialization here
def run(self, task: str):
pass
# Example
model = vLLMLM("mistral")
# Run the model
out = model("Analyze these financial documents and summarize of them")
print(out)
```
### Swarms Compliant Agent Interface
```python
from swarms import Agent
class MyCustomAgent(Agent):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Custom initialization logic
    def custom_method(self, *args, **kwargs):
        # Implement custom logic here
        pass
    def run(self, task, *args, **kwargs):
        # Customize the run method
        response = super().run(task, *args, **kwargs)
        # Additional custom logic
        return response`
# Model
agent = MyCustomAgent()
# Run the agent
out = agent("Analyze and summarize these financial documents: ")
print(out)
```
### Compliant Interface for Multi-Agent Collaboration
```python
from swarms import AutoSwarm, AutoSwarmRouter, BaseSwarm
# Build your own Swarm
class MySwarm(BaseSwarm):
def __init__(self, name="kyegomez/myswarm", *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = name
def run(self, task: str, *args, **kwargs):
# Add your multi-agent logic here
# agent 1
# agent 2
# agent 3
return "output of the swarm"
# Add your custom swarm to the AutoSwarmRouter
router = AutoSwarmRouter(
swarms=[MySwarm]
)
# Create an AutoSwarm instance
autoswarm = AutoSwarm(
name="kyegomez/myswarm",
description="A simple API to build and run swarms",
verbose=True,
router=router,
)
# Run the AutoSwarm
autoswarm.run("Analyze these financial data and give me a summary")
```
------
## `AgentRearrange`
Inspired by Einops and einsum, this orchestration techniques enables you to map out the relationships between various agents. For example you specify linear and sequential relationships like `a -> a1 -> a2 -> a3` or concurrent relationships where the first agent will send a message to 3 agents all at once: `a -> a1, a2, a3`. You can customize your workflow to mix sequential and concurrent relationships. [Docs Available:](https://swarms.apac.ai/en/latest/swarms/structs/agent_rearrange/)
@ -1070,12 +807,12 @@ out = swarm.run("Prepare financial statements and audit financial records")
print(out)
```
----------
## Onboarding Session
Get onboarded now with the creator and lead maintainer of Swarms, Kye Gomez, who will show you how to get started with the installation, usage examples, and starting to build your custom use case! [CLICK HERE](https://cal.com/swarms/swarms-onboarding-session)
---
## Documentation
@ -1083,6 +820,13 @@ Documentation is located here at: [docs.swarms.world](https://docs.swarms.world)
----
## Docker Instructions
- [Learn More Here About Deployments In Docker](https://swarms.apac.ai/en/latest/docker_setup/)
-----
## Folder Structure
The swarms package has been meticlously crafted for extreme use-ability and understanding, the swarms package is split up into various modules such as `swarms.agents` that holds pre-built agents, `swarms.structs` that holds a vast array of structures like `Agent` and multi agent structures. The 3 most important are `structs`, `models`, and `agents`.
@ -1115,19 +859,12 @@ Swarms is an open-source project, and contributions are VERY welcome. If you wan
----
## Community
Join our growing community around the world, for real-time support, ideas, and discussions on Swarms 😊
- View our official [Blog](https://swarms.apac.ai)
- Chat live with us on [Discord](https://discord.gg/kS3rwKs3ZC)
- Follow us on [Twitter](https://twitter.com/kyegomez)
- Connect with us on [LinkedIn](https://www.linkedin.com/company/the-swarm-corporation)
- Visit us on [YouTube](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ)
- [Join the Swarms community on Discord!](https://discord.gg/AJazBmhKnr)
- Join our Swarms Community Gathering every Thursday at 1pm NYC Time to unlock the potential of autonomous agents in automating your daily tasks [Sign up here](https://lu.ma/5p2jnc2v)
## Swarm Newsletter 🤖 🤖 🤖 📧
Sign up to the Swarm newsletter to receive updates on the latest Autonomous agent research papers, step by step guides on creating multi-agent app, and much more Swarmie goodiness 😊
---
[CLICK HERE TO SIGNUP](https://docs.google.com/forms/d/e/1FAIpQLSfqxI2ktPR9jkcIwzvHL0VY6tEIuVPd-P2fOWKnd6skT9j1EQ/viewform?usp=sf_link)
## Discovery Call
Book a discovery call to learn how Swarms can lower your operating costs by 40% with swarms of autonomous agents in lightspeed. [Click here to book a time that works for you!](https://calendly.com/swarm-corp/30min?month=2023-11)
@ -1138,15 +875,19 @@ Accelerate Bugs, Features, and Demos to implement by supporting us here:
<a href="https://polar.sh/kyegomez"><img src="https://polar.sh/embed/fund-our-backlog.svg?org=kyegomez" /></a>
## Community
## Docker Instructions
- [Learn More Here About Deployments In Docker](https://swarms.apac.ai/en/latest/docker_setup/)
Join our growing community around the world, for real-time support, ideas, and discussions on Swarms 😊
## Swarm Newsletter 🤖 🤖 🤖 📧
Sign up to the Swarm newsletter to receive updates on the latest Autonomous agent research papers, step by step guides on creating multi-agent app, and much more Swarmie goodiness 😊
- View our official [Blog](https://swarms.apac.ai)
- Chat live with us on [Discord](https://discord.gg/kS3rwKs3ZC)
- Follow us on [Twitter](https://twitter.com/kyegomez)
- Connect with us on [LinkedIn](https://www.linkedin.com/company/the-swarm-corporation)
- Visit us on [YouTube](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ)
- [Join the Swarms community on Discord!](https://discord.gg/AJazBmhKnr)
- Join our Swarms Community Gathering every Thursday at 1pm NYC Time to unlock the potential of autonomous agents in automating your daily tasks [Sign up here](https://lu.ma/5p2jnc2v)
[CLICK HERE TO SIGNUP](https://docs.google.com/forms/d/e/1FAIpQLSfqxI2ktPR9jkcIwzvHL0VY6tEIuVPd-P2fOWKnd6skT9j1EQ/viewform?usp=sf_link)
---
# License
Apache License

@ -1,6 +1,6 @@
## Building Analyst Agents with Swarms to write Business Reports
> Jupyter Notebook accompanying this post is accessible at: [Business Analyst Agent Notebook](https://github.com/kyegomez/swarms/blob/master/playground/business-analyst-agent.ipynb)
> Jupyter Notebook accompanying this post is accessible at: [Business Analyst Agent Notebook](https://github.com/kyegomez/swarms/blob/master/playground/demos/business_analysis_swarm/business-analyst-agent.ipynb)
Solving a business problem often involves preparing a Business Case Report. This report comprehensively analyzes the problem, evaluates potential solutions, and provides evidence-based recommendations and an implementation plan to effectively address the issue and drive business value. While the process of preparing one requires an experienced business analyst, the workflow can be augmented using AI agents. Two candidates stick out as areas to work on:

@ -172,9 +172,9 @@ nav:
- Memory Systems:
- ChromaDB: "swarms_memory/chromadb.md"
- Pinecone: "swarms_memory/pinecone.md"
- Redis: "swarms_memory/redis.md"
# - Redis: "swarms_memory/redis.md"
- Faiss: "swarms_memory/faiss.md"
- HNSW: "swarms_memory/hnsw.md"
# - HNSW: "swarms_memory/hnsw.md"
- References:
- Agent Glossary: "swarms/glossary.md"
- List of The Best Multi-Agent Papers: "swarms/papers.md"

@ -1,5 +1,6 @@
from swarms import Agent, Anthropic
def calculate_profit(revenue: float, expenses: float):
"""
Calculates the profit by subtracting expenses from revenue.

@ -2,7 +2,7 @@ import os
from dotenv import load_dotenv
from swarms.structs import Agent, OpenAIChat, Task
from swarms import Agent, Task, OpenAIChat
# Load the environment variables
load_dotenv()

@ -1,80 +0,0 @@
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 = "emilianJR/epiCRealism" # Choose to your favorite base model.
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)

@ -30,7 +30,7 @@ llm2 = Anthropic(
# Agents
paper_summarizer_agent = Agent(
agent_name = "paper_summarizer_agent",
agent_name="paper_summarizer_agent",
llm=llm2,
sop=PAPER_SUMMARY_ANALYZER,
max_loops=1,
@ -39,7 +39,7 @@ paper_summarizer_agent = Agent(
)
paper_implementor_agent = Agent(
agent_name = "paper_implementor_agent",
agent_name="paper_implementor_agent",
llm=llm1,
sop=PAPER_IMPLEMENTOR_AGENT_PROMPT,
max_loops=1,
@ -49,7 +49,7 @@ paper_implementor_agent = Agent(
)
pytorch_pseudocode_agent = Agent(
agent_name = "pytorch_pseudocode_agent",
agent_name="pytorch_pseudocode_agent",
llm=llm1,
sop=PAPER_IMPLEMENTOR_AGENT_PROMPT,
max_loops=1,
@ -66,10 +66,13 @@ task = f"""
"""
agents = [paper_summarizer_agent, paper_implementor_agent, pytorch_pseudocode_agent]
agents = [
paper_summarizer_agent,
paper_implementor_agent,
pytorch_pseudocode_agent,
]
flow = "paper_summarizer_agent -> paper_implementor_agent -> pytorch_pseudocode_agent"
swarm = rearrange(agents, flow, task)
print(swarm)

@ -1,12 +1,10 @@
import os
from dotenv import load_dotenv
from pydantic import BaseModel, Field
from swarms import Agent
from swarms.models import OpenAIChat
from swarms.models.gpt4_vision_api import GPT4VisionAPI
from swarms.structs.rearrange import AgentRearrange
from typing import Optional, List, Dict, Any
# Load the environment variables
load_dotenv()
@ -74,69 +72,6 @@ def TREATMENT_PLAN_SYSTEM_PROMPT() -> str:
"""
class LLMConfig(BaseModel):
model_name: str
max_tokens: int
class AgentConfig(BaseModel):
agent_name: str
system_prompt: str
llm: LLMConfig
max_loops: int
autosave: bool
dashboard: bool
class AgentRearrangeConfig(BaseModel):
agents: List[AgentConfig]
flow: str
max_loops: int
verbose: bool
class AgentRunResult(BaseModel):
agent_name: str
output: Dict[str, Any]
tokens_generated: int
class RunAgentsResponse(BaseModel):
results: List[AgentRunResult]
total_tokens_generated: int
class AgentRearrangeResponse(BaseModel):
results: List[AgentRunResult]
total_tokens_generated: int
class RunConfig(BaseModel):
task: str = Field(..., title="The task to run")
flow: str = "D -> T"
image: Optional[str] = None # Optional image path as a string
max_loops: Optional[int] = 1
# @app.get("/v1/health")
# async def health_check():
# return JSONResponse(content={"status": "healthy"})
# @app.get("/v1/models_available")
# async def models_available():
# available_models = {
# "models": [
# {"name": "gpt-4-1106-vision-preview", "type": "vision"},
# {"name": "openai-chat", "type": "text"},
# ]
# }
# return JSONResponse(content=available_models)
# @app.get("/v1/swarm/completions")
# async def run_agents(run_config: RunConfig):
# Diagnoser agent
diagnoser = Agent(
# agent_name="Medical Image Diagnostic Agent",
agent_name="D",
@ -167,4 +102,6 @@ rearranger = AgentRearrange(
)
# Run the agents
results = rearranger.run("")
results = rearranger.run(
"Analyze the medical image and provide a treatment plan."
)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 113 KiB

@ -1,14 +0,0 @@
"""from swarms.models import Dalle3
# Create an instance of the Dalle3 class with high quality
dalle3 = Dalle3(quality="high")
# Define a text prompt
task = "A high-quality image of a sunset"
# Generate a high-quality image from the text prompt
image_url = dalle3(task)
# Print the generated image URL
print(image_url)
"""

@ -1,36 +0,0 @@
from swarms.models import HuggingfaceLLM
import torch
try:
inference = HuggingfaceLLM(
model_id="gpt2",
quantize=False,
verbose=True,
)
device = "cuda" if torch.cuda.is_available() else "cpu"
inference.model.to(device)
prompt_text = (
"Create a list of known biggest risks of structural collapse"
" with references"
)
inputs = inference.tokenizer(prompt_text, return_tensors="pt").to(
device
)
generated_ids = inference.model.generate(
**inputs,
max_new_tokens=1000, # Adjust the length of the generation
temperature=0.7, # Adjust creativity
top_k=50, # Limits the vocabulary considered at each step
pad_token_id=inference.tokenizer.eos_token_id,
do_sample=True, # Enable sampling to utilize temperature
)
generated_text = inference.tokenizer.decode(
generated_ids[0], skip_special_tokens=True
)
print(generated_text)
except Exception as e:
print(f"An error occurred: {e}")

@ -1,10 +0,0 @@
from swarms.models import Mixtral
# Initialize the Mixtral model with 4 bit and flash attention!
mixtral = Mixtral(load_in_4bit=True, use_flash_attention_2=True)
# Generate text for a simple task
generated_text = mixtral.run("Generate a creative story.")
# Print the generated text
print(generated_text)

@ -1,45 +0,0 @@
import os
from dotenv import load_dotenv
from swarms import (
OpenAIChat,
Conversation,
)
conv = Conversation(
time_enabled=True,
)
# Load the environment variables
load_dotenv()
# Get the API key from the environment
api_key = os.environ.get("OPENAI_API_KEY")
# Initialize the language model
llm = OpenAIChat(openai_api_key=api_key, model_name="gpt-4")
# Run the language model in a loop
def interactive_conversation(llm):
conv = Conversation()
while True:
user_input = input("User: ")
conv.add("user", user_input)
if user_input.lower() == "quit":
break
task = (
conv.return_history_as_string()
) # Get the conversation history
out = llm(task)
conv.add("assistant", out)
print(
f"Assistant: {out}",
)
conv.display_conversation()
conv.export_conversation("conversation.txt")
# Replace with your LLM instance
interactive_conversation(llm)

@ -1,35 +0,0 @@
# Importing necessary modules
import os
from dotenv import load_dotenv
from swarms import Worker, OpenAIChat, tool
# Loading environment variables from .env file
load_dotenv()
# Retrieving the OpenAI API key from environment variables
api_key = os.getenv("OPENAI_API_KEY")
# Create a tool
@tool
def search_api(query: str):
pass
# Creating a Worker instance
worker = Worker(
name="My Worker",
role="Worker",
human_in_the_loop=False,
tools=[search_api],
temperature=0.5,
llm=OpenAIChat(openai_api_key=api_key),
)
# Running the worker with a prompt
out = worker.run(
"Hello, how are you? Create an image of how your are doing!"
)
# Printing the output
print(out)

@ -1,12 +0,0 @@
# Import the model
from swarms import ZeroscopeTTV
# Initialize the model
zeroscope = ZeroscopeTTV()
# Specify the task
task = "A person is walking on the street."
# Generate the video!
video_path = zeroscope(task)
print(video_path)

@ -1,186 +0,0 @@
import logging
import os
import uuid
from typing import Optional
import chromadb
from dotenv import load_dotenv
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 BaseVectorDatabase
# Load environment variables
load_dotenv()
# Results storage using local ChromaDB
class ChromaDB(BaseVectorDatabase):
"""
ChromaDB database
Args:
metric (str): The similarity metric to use.
output (str): The name of the collection to store the results in.
limit_tokens (int, optional): The maximum number of tokens to use for the query. Defaults to 1000.
n_results (int, optional): The number of results to retrieve. Defaults to 2.
Methods:
add: _description_
query: _description_
Examples:
>>> chromadb = ChromaDB(
>>> metric="cosine",
>>> output="results",
>>> llm="gpt3",
>>> openai_api_key=OPENAI_API_KEY,
>>> )
>>> chromadb.add(task, result, result_id)
"""
def __init__(
self,
metric: str = "cosine",
output_dir: str = "swarms",
limit_tokens: Optional[int] = 1000,
n_results: int = 1,
docs_folder: str = None,
verbose: bool = False,
*args,
**kwargs,
):
self.metric = metric
self.output_dir = output_dir
self.limit_tokens = limit_tokens
self.n_results = n_results
self.docs_folder = docs_folder
self.verbose = verbose
# Disable ChromaDB logging
if verbose:
logging.getLogger("chromadb").setLevel(logging.INFO)
# Create Chroma collection
chroma_persist_dir = "chroma"
chroma_client = chromadb.PersistentClient(
settings=chromadb.config.Settings(
persist_directory=chroma_persist_dir,
),
*args,
**kwargs,
)
# Create ChromaDB client
self.client = chromadb.Client()
# Create Chroma collection
self.collection = chroma_client.get_or_create_collection(
name=output_dir,
metadata={"hnsw:space": metric},
*args,
**kwargs,
)
display_markdown_message(
"ChromaDB collection created:"
f" {self.collection.name} with metric: {self.metric} and"
f" output directory: {self.output_dir}"
)
# If docs
if docs_folder:
display_markdown_message(
f"Traversing directory: {docs_folder}"
)
self.traverse_directory()
def add(
self,
document: str,
*args,
**kwargs,
):
"""
Add a document to the ChromaDB collection.
Args:
document (str): The document to be added.
condition (bool, optional): The condition to check before adding the document. Defaults to True.
Returns:
str: The ID of the added document.
"""
try:
doc_id = str(uuid.uuid4())
self.collection.add(
ids=[doc_id],
documents=[document],
*args,
**kwargs,
)
print("-----------------")
print("Document added successfully")
print("-----------------")
return doc_id
except Exception as e:
raise Exception(f"Failed to add document: {str(e)}")
def query(
self,
query_text: str,
*args,
**kwargs,
) -> str:
"""
Query documents from the ChromaDB collection.
Args:
query (str): The query string.
n_docs (int, optional): The number of documents to retrieve. Defaults to 1.
Returns:
dict: The retrieved documents.
"""
try:
logging.info(f"Querying documents for: {query_text}")
docs = self.collection.query(
query_texts=[query_text],
n_results=self.n_results,
*args,
**kwargs,
)["documents"]
# Convert into a string
out = ""
for doc in docs:
out += f"{doc}\n"
# Display the retrieved document
display_markdown_message(f"Query: {query_text}")
display_markdown_message(f"Retrieved Document: {out}")
return out
except Exception as e:
raise Exception(f"Failed to query documents: {str(e)}")
def traverse_directory(self):
"""
Traverse through every file in the given directory and its subdirectories,
and return the paths of all files.
Parameters:
- directory_name (str): The name of the directory to traverse.
Returns:
- list: A list of paths to each file in the directory and its subdirectories.
"""
added_to_db = False
for root, dirs, files in os.walk(self.docs_folder):
for file in files:
file_path = os.path.join(root, file) # Change this line
_, ext = os.path.splitext(file_path)
data = data_to_text(file_path)
added_to_db = self.add(str(data))
print(f"{file_path} added to Database")
return added_to_db

@ -1,14 +0,0 @@
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
uri = "mongodb+srv://kye:Kgx7d2FeLN7AyGNh@cluster0.ndu3b6d.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
# Create a new client and connect to the server
client = MongoClient(uri, server_api=ServerApi("1"))
# Send a ping to confirm a successful connection
try:
client.admin.command("ping")
print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
print(e)

@ -4,7 +4,7 @@ import pinecone
from attr import define, field
from swarms.memory.base_vectordb import BaseVectorDatabase
from swarms.utils.hash import str_to_hash
from swarms.utils import str_to_hash
@define

@ -1,25 +0,0 @@
from langchain.document_loaders import CSVLoader
from swarms.memory import qdrant
loader = CSVLoader(
file_path="../document_parsing/aipg/aipg.csv",
encoding="utf-8-sig",
)
docs = loader.load()
# Initialize the Qdrant instance
# See qdrant documentation on how to run locally
qdrant_client = qdrant.Qdrant(
host="https://697ea26c-2881-4e17-8af4-817fcb5862e8.europe-west3-0.gcp.cloud.qdrant.io",
collection_name="qdrant",
)
qdrant_client.add_vectors(docs)
# Perform a search
search_query = "Who is jojo"
search_results = qdrant_client.search_vectors(search_query)
print("Search Results:")
for result in search_results:
print(result)

@ -1,180 +0,0 @@
"""
Weaviate API Client
"""
from typing import Any, Dict, List, Optional
from swarms.memory.base_vectordb import BaseVectorDatabase
try:
import weaviate
except ImportError:
print("pip install weaviate-client")
class WeaviateDB(BaseVectorDatabase):
"""
Weaviate API Client
Interface to Weaviate, a vector database with a GraphQL API.
Args:
http_host (str): The HTTP host of the Weaviate server.
http_port (str): The HTTP port of the Weaviate server.
http_secure (bool): Whether to use HTTPS.
grpc_host (Optional[str]): The gRPC host of the Weaviate server.
grpc_port (Optional[str]): The gRPC port of the Weaviate server.
grpc_secure (Optional[bool]): Whether to use gRPC over TLS.
auth_client_secret (Optional[Any]): The authentication client secret.
additional_headers (Optional[Dict[str, str]]): Additional headers to send with requests.
additional_config (Optional[weaviate.AdditionalConfig]): Additional configuration for the client.
Methods:
create_collection: Create a new collection in Weaviate.
add: Add an object to a specified collection.
query: Query objects from a specified collection.
update: Update an object in a specified collection.
delete: Delete an object from a specified collection.
Examples:
>>> from swarms.memory import WeaviateDB
"""
def __init__(
self,
http_host: str,
http_port: str,
http_secure: bool,
grpc_host: Optional[str] = None,
grpc_port: Optional[str] = None,
grpc_secure: Optional[bool] = None,
auth_client_secret: Optional[Any] = None,
additional_headers: Optional[Dict[str, str]] = None,
additional_config: Optional[Any] = None,
connection_params: Dict[str, Any] = None,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
self.http_host = http_host
self.http_port = http_port
self.http_secure = http_secure
self.grpc_host = grpc_host
self.grpc_port = grpc_port
self.grpc_secure = grpc_secure
self.auth_client_secret = auth_client_secret
self.additional_headers = additional_headers
self.additional_config = additional_config
self.connection_params = connection_params
# If connection_params are provided, use them to initialize the client.
connection_params = weaviate.ConnectionParams.from_params(
http_host=http_host,
http_port=http_port,
http_secure=http_secure,
grpc_host=grpc_host,
grpc_port=grpc_port,
grpc_secure=grpc_secure,
)
# If additional headers are provided, add them to the connection params.
self.client = weaviate.WeaviateDB(
connection_params=connection_params,
auth_client_secret=auth_client_secret,
additional_headers=additional_headers,
additional_config=additional_config,
)
def create_collection(
self,
name: str,
properties: List[Dict[str, Any]],
vectorizer_config: Any = None,
):
"""Create a new collection in Weaviate.
Args:
name (str): _description_
properties (List[Dict[str, Any]]): _description_
vectorizer_config (Any, optional): _description_. Defaults to None.
"""
try:
out = self.client.collections.create(
name=name,
vectorizer_config=vectorizer_config,
properties=properties,
)
print(out)
except Exception as error:
print(f"Error creating collection: {error}")
raise
def add(self, collection_name: str, properties: Dict[str, Any]):
"""Add an object to a specified collection.
Args:
collection_name (str): _description_
properties (Dict[str, Any]): _description_
Returns:
_type_: _description_
"""
try:
collection = self.client.collections.get(collection_name)
return collection.data.insert(properties)
except Exception as error:
print(f"Error adding object: {error}")
raise
def query(self, collection_name: str, query: str, limit: int = 10):
"""Query objects from a specified collection.
Args:
collection_name (str): _description_
query (str): _description_
limit (int, optional): _description_. Defaults to 10.
Returns:
_type_: _description_
"""
try:
collection = self.client.collections.get(collection_name)
response = collection.query.bm25(query=query, limit=limit)
return [o.properties for o in response.objects]
except Exception as error:
print(f"Error querying objects: {error}")
raise
def update(
self,
collection_name: str,
object_id: str,
properties: Dict[str, Any],
):
"""UPdate an object in a specified collection.
Args:
collection_name (str): _description_
object_id (str): _description_
properties (Dict[str, Any]): _description_
"""
try:
collection = self.client.collections.get(collection_name)
collection.data.update(object_id, properties)
except Exception as error:
print(f"Error updating object: {error}")
raise
def delete(self, collection_name: str, object_id: str):
"""Delete an object from a specified collection.
Args:
collection_name (str): _description_
object_id (str): _description_
"""
try:
collection = self.client.collections.get(collection_name)
collection.data.delete_by_id(object_id)
except Exception as error:
print(f"Error deleting object: {error}")
raise

@ -1,6 +1,8 @@
import os
from swarms.models import Anthropic
model = Anthropic(anthropic_api_key="")
model = Anthropic(anthropic_api_key=os.getenv("ANTHROPIC_API_KEY"))
task = "What is quantum field theory? What are 3 books on the field?"

@ -1,13 +0,0 @@
import asyncio
from swarms.models.distilled_whisperx import DistilWhisperModel
model_wrapper = DistilWhisperModel()
# Download mp3 of voice and place the path here
transcription = model_wrapper("path/to/audio.mp3")
# For async usage
transcription = asyncio.run(
model_wrapper.async_transcribe("path/to/audio.mp3")
)

@ -1,12 +0,0 @@
from swarms import Mistral
# Initialize the model
model = Mistral(
model_name="miqudev/miqu-1-70b",
max_length=500,
use_flash_attention=True,
load_in_4bit=True,
)
# Run the model
result = model.run("What is the meaning of life?")

@ -1,7 +0,0 @@
from swarms.models import Mistral
model = Mistral(device="cuda", use_flash_attention=True)
prompt = "My favourite condiment is"
result = model.run(prompt)
print(result)

@ -1,9 +0,0 @@
from swarms.models.mpt import MPT
mpt_instance = MPT(
"mosaicml/mpt-7b-storywriter",
"EleutherAI/gpt-neox-20b",
max_tokens=150,
)
mpt_instance.generate("Once upon a time in a land far, far away...")

@ -1,7 +0,0 @@
from swarms.models.openai_chat import OpenAIChat
model = OpenAIChat()
out = model("Hello, how are you?")
print(out)

@ -1,6 +1,10 @@
from swarms.models.openai_models import OpenAIChat
import os
from swarms.models import OpenAIChat
openai = OpenAIChat(openai_api_key="", verbose=False)
# Load doten
openai = OpenAIChat(
openai_api_key=os.getenv("OPENAI_API_KEY"), verbose=False
)
chat = openai("What are quantum fields?")
print(chat)

@ -1,45 +0,0 @@
import os
from dotenv import load_dotenv
# Import the OpenAIChat model and the Agent struct
from swarms.models import OpenAIChat
from swarms.structs import Agent
from swarms.structs.autoscaler import AutoScaler
# Load the environment variables
load_dotenv()
# Get the API key from the environment
api_key = os.environ.get("OPENAI_API_KEY")
# Initialize the language model
llm = OpenAIChat(
temperature=0.5,
openai_api_key=api_key,
)
## Initialize the workflow
agent = Agent(llm=llm, max_loops=1, dashboard=True)
# Load the autoscaler
autoscaler = AutoScaler(
initial_agents=2,
scale_up_factor=1,
idle_threshold=0.2,
busy_threshold=0.7,
agents=[agent],
autoscale=True,
min_agents=1,
max_agents=5,
custom_scale_strategy=None,
)
print(autoscaler)
# Run the workflow on a task
out = autoscaler.run(
agent.id, "Generate a 10,000 word blog on health and wellness."
)
print(out)

@ -142,7 +142,9 @@
"metadata": {},
"outputs": [],
"source": [
"from swarms import Agent, ChromaDB, OpenAIChat, tool\n",
"# !pip install swarms-memory\n",
"from swarms import Agent, OpenAIChat, tool\n",
"from swarms_memory import ChromaDB\n",
"\n",
"# Making an instance of the ChromaDB class\n",
"memory = ChromaDB(\n",

@ -1,14 +0,0 @@
import pandas as pd
from swarms import dataframe_to_text
# # Example usage:
df = pd.DataFrame(
{
"A": [1, 2, 3],
"B": [4, 5, 6],
"C": [7, 8, 9],
}
)
print(dataframe_to_text(df))

@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api"
[tool.poetry]
name = "swarms"
version = "5.3.3"
version = "5.3.4"
description = "Swarms - Pytorch"
license = "MIT"
authors = ["Kye Gomez <kye@apac.ai>"]
@ -20,6 +20,11 @@ keywords = [
"Prompt Engineering",
"swarms",
"agents",
"llms",
"transformers",
"multi-agent",
"swarms of agents",
"chicken nuggets",
]
classifiers = [
"Development Status :: 4 - Beta",

@ -0,0 +1,7 @@
"""
A script that runs ruff, black, autopep8, and all other formatters in one python script on a cron job.
- Perhaps make a github workflow as well
"""

@ -40,6 +40,7 @@ from swarms.models.types import ( # noqa: E402
VideoModality,
)
from swarms.models.vilt import Vilt # noqa: E402
from swarms.models.popular_llms import FireWorksAI
__all__ = [
"BaseEmbeddingModel",
@ -75,4 +76,5 @@ __all__ = [
"OpenAIEmbeddings",
"llama3Hosted",
"GPT4o",
"FireWorksAI",
]

@ -80,3 +80,11 @@ class OctoAIChat(OctoAIEndpoint):
def run(self, *args, **kwargs):
return self.invoke(*args, **kwargs)
class FireWorksAI(Fireworks):
def __call__(self, *args, **kwargs):
return self.invoke(*args, **kwargs)
def run(self, *args, **kwargs):
return self.invoke(*args, **kwargs)

@ -236,7 +236,7 @@ boss_agent_creator = Agent(
def run_jamba_swarm(task: str = None):
logger.info(f"Making plan for the task: {task}")
out = planning_agent.run(task)
planning_agent.run(task)
memory = planning_agent.short_memory.return_history_as_string()

@ -4,7 +4,7 @@ from unittest.mock import Mock, patch
import pytest
from dotenv import load_dotenv
from swarms.models import BaseCohere, Cohere
from swarms import Cohere
# Load the environment variables
load_dotenv()
@ -154,7 +154,7 @@ def test_base_cohere_validate_environment():
"cohere_api_key": "my-api-key",
"user_agent": "langchain",
}
validated_values = BaseCohere.validate_environment(values)
validated_values = Cohere.validate_environment(values)
assert "client" in validated_values
assert "async_client" in validated_values
@ -166,7 +166,7 @@ def test_base_cohere_validate_environment_without_cohere():
}
with patch.dict("sys.modules", {"cohere": None}):
with pytest.raises(ImportError):
BaseCohere.validate_environment(values)
Cohere.validate_environment(values)
# Test cases for benchmarking generations with various models

Loading…
Cancel
Save