Merge pull request #824 from ascender1729/fix/remove-swarm-models-dependency

fix: Remove swarm_models dependency and simplify Agent initialization
pull/814/merge
Kye Gomez 2 months ago committed by GitHub
commit 685c573179
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -1271,24 +1271,28 @@ The `run` method returns a dictionary containing the execution results of all no
```python ```python
import os
from dotenv import load_dotenv
from swarms import Agent, Edge, GraphWorkflow, Node, NodeType from swarms import Agent, Edge, GraphWorkflow, Node, NodeType
from swarm_models import OpenAIChat # Initialize agents with model_name parameter
agent1 = Agent(
load_dotenv() agent_name="Agent1",
model_name="openai/gpt-4o-mini", # Using provider prefix
api_key = os.environ.get("OPENAI_API_KEY") temperature=0.5,
max_tokens=4000,
max_loops=1,
autosave=True,
dashboard=True,
)
llm = OpenAIChat( agent2 = Agent(
temperature=0.5, openai_api_key=api_key, max_tokens=4000 agent_name="Agent2",
model_name="openai/gpt-4o-mini", # Using provider prefix
temperature=0.5,
max_tokens=4000,
max_loops=1,
autosave=True,
dashboard=True,
) )
agent1 = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True)
agent2 = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True)
def sample_task(): def sample_task():
print("Running sample task") print("Running sample task")
@ -1297,9 +1301,8 @@ def sample_task():
wf_graph = GraphWorkflow() wf_graph = GraphWorkflow()
wf_graph.add_node(Node(id="agent1", type=NodeType.AGENT, agent=agent1)) wf_graph.add_node(Node(id="agent1", type=NodeType.AGENT, agent=agent1))
wf_graph.add_node(Node(id="agent2", type=NodeType.AGENT, agent=agent2)) wf_graph.add_node(Node(id="agent2", type=NodeType.AGENT, agent=agent2))
wf_graph.add_node( wf_graph.add_node(Node(id="task1", type=NodeType.TASK, callable=sample_task))
Node(id="task1", type=NodeType.TASK, callable=sample_task)
)
wf_graph.add_edge(Edge(source="agent1", target="task1")) wf_graph.add_edge(Edge(source="agent1", target="task1"))
wf_graph.add_edge(Edge(source="agent2", target="task1")) wf_graph.add_edge(Edge(source="agent2", target="task1"))
@ -1308,10 +1311,8 @@ wf_graph.set_end_points(["task1"])
print(wf_graph.visualize()) print(wf_graph.visualize())
# Run the workflow
results = wf_graph.run() results = wf_graph.run()
print("Execution results:", results) print("Execution results:", results)
``` ```
## `MixtureOfAgents` ## `MixtureOfAgents`
@ -2216,21 +2217,20 @@ Documentation is located here at: [docs.swarms.world](https://docs.swarms.world)
----- -----
## Folder Structure ## 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`. The swarms package has been meticulously crafted for extreme usability 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 package is split into various modules, with the most important being `structs`, `tools`, and `agents`.
```sh ```sh
├── __init__.py ├── __init__.py
├── agents ├── agents/
├── artifacts ├── artifacts/
├── memory ├── client/
├── schemas ├── cli/
├── models -> swarm_models ├── prompts/
├── prompts ├── schemas/
├── structs ├── structs/
├── telemetry ├── telemetry/
├── tools ├── tools/
├── utils └── utils/
└── workers
``` ```
---- ----

@ -20,35 +20,27 @@ $ pip install -U swarms
### **Usage Example: Single Agent** ### **Usage Example: Single Agent**
Heres a simple example of creating a financial analysis agent powered by OpenAIs GPT-4 model. This agent will analyze financial queries like how to set up a ROTH IRA. Here's a simple example of creating a financial analysis agent powered by OpenAI's GPT-4o-mini model. This agent will analyze financial queries like how to set up a ROTH IRA.
```python ```python
import os from swarms.structs.agent import Agent
from swarms import Agent
from swarm_models import OpenAIChat
from dotenv import load_dotenv
load_dotenv()
# Initialize OpenAI model # Initialize the agent with GPT-4o-mini model
model = OpenAIChat(
openai_api_key=os.getenv("OPENAI_API_KEY"), model_name="gpt-4o-mini", temperature=0.1
)
# Initialize the agent
agent = Agent( agent = Agent(
agent_name="Financial-Analysis-Agent", agent_name="Financial-Analysis-Agent",
system_prompt="Analyze financial situations and provide advice...", system_prompt="Analyze financial situations and provide advice...",
llm=model,
max_loops=1, max_loops=1,
autosave=True, autosave=True,
dashboard=False, dashboard=False,
verbose=True, verbose=True,
saved_state_path="finance_agent.json" saved_state_path="finance_agent.json",
model_name="gpt-4o-mini",
) )
# Run the agent on a financial query # Run your query
out = agent.run("How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria?") out = agent.run(
"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria?"
)
print(out) print(out)
``` ```
@ -57,13 +49,13 @@ print(out)
- **Attributes:** - **Attributes:**
- `agent_name`: Name of the agent. - `agent_name`: Name of the agent.
- `system_prompt`: System-level instruction guiding the agent's behavior. - `system_prompt`: System-level instruction guiding the agent's behavior.
- `llm`: Language model used by the agent (e.g., GPT, Anthropic). - `model_name`: Name of the model to use (e.g., "gpt-4o-mini").
- `max_loops`: Max iterations for a task. - `max_loops`: Max iterations for a task.
- `autosave`: Auto-saves the state after each iteration. - `autosave`: Auto-saves the state after each iteration.
- **Methods:** - **Methods:**
- `run(task: str)`: Executes the agents task. - `run(task: str)`: Executes the agent's task.
- `ingest_docs(doc_path: str)`: Ingests documents into the agents knowledge base. - `ingest_docs(doc_path: str)`: Ingests documents into the agent's knowledge base.
- `filtered_run(task: str)`: Runs agent with a filtered system prompt. - `filtered_run(task: str)`: Runs agent with a filtered system prompt.
----- -----
@ -121,7 +113,7 @@ agents:
### Key Configuration Fields: ### Key Configuration Fields:
- **agent_name**: Name of the agent. - **agent_name**: Name of the agent.
- **model**: Defines the language model settings (e.g., API key, model name, temperature, and max tokens). - **model**: Defines the language model settings (e.g., API key, model name, temperature, and max tokens).
- **system_prompt**: The system prompt used to guide the agents behavior. - **system_prompt**: The system prompt used to guide the agent's behavior.
- **task**: (Optional) Task for the agent to execute once created. - **task**: (Optional) Task for the agent to execute once created.
--- ---
@ -248,7 +240,7 @@ Steps:
For example, here's an example on how to create an agent from griptape. For example, here's an example on how to create an agent from griptape.
Heres how you can create a custom **Griptape** agent that integrates with the **Swarms** framework by inheriting from the `Agent` class in **Swarms** and overriding the `run(task: str) -> str` method. Here's how you can create a custom **Griptape** agent that integrates with the **Swarms** framework by inheriting from the `Agent` class in **Swarms** and overriding the `run(task: str) -> str` method.
```python ```python
@ -420,7 +412,7 @@ print(output)
### 5. **Spreadsheet Swarm** ### 5. **Spreadsheet Swarm**
**Overview**: `SpreadSheetSwarm` enables the management of thousands of agents simultaneously, where each agent operates on its own thread. Its ideal for overseeing large-scale agent outputs. **Overview**: `SpreadSheetSwarm` enables the management of thousands of agents simultaneously, where each agent operates on its own thread. It's ideal for overseeing large-scale agent outputs.
#### Mermaid Graph: #### Mermaid Graph:
@ -466,7 +458,7 @@ These are the key swarm architectures available in the **Swarms Framework**. Eac
#### **Workflow Classes** #### **Workflow Classes**
- **SequentialWorkflow:** - **SequentialWorkflow:**
- Chains agents, where one agent's output becomes the next agents input. - Chains agents, where one agent's output becomes the next agent's input.
- **AgentRearrange:** - **AgentRearrange:**
- Dynamically rearranges agent tasks either in parallel or sequentially based on defined flow. - Dynamically rearranges agent tasks either in parallel or sequentially based on defined flow.

@ -2,19 +2,17 @@ from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import ( from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT, FINANCIAL_AGENT_SYS_PROMPT,
) )
from swarm_models import OpenAIChat
model = OpenAIChat(model_name="gpt-4o") # Initialize the agent (no swarm_models import needed)
# Initialize the agent
agent = Agent( agent = Agent(
agent_name="Financial-Analysis-Agent", agent_name="Financial-Analysis-Agent",
agent_description="Personal finance advisor agent", agent_description="Personal finance advisor agent",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT system_prompt=(
+ "Output the <DONE> token when you're done creating a portfolio of etfs, index, funds, and more for AI", FINANCIAL_AGENT_SYS_PROMPT
+ " Output the <DONE> token when you're done creating a portfolio"
),
max_loops=1, max_loops=1,
llm=model, model_name="gpt-4o",
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
user_name="Kye", user_name="Kye",
retry_attempts=3, retry_attempts=3,
@ -33,7 +31,8 @@ agent = Agent(
async def run_agent(): async def run_agent():
await agent.arun( await agent.arun(
"Create a table of super high growth opportunities for AI. I have $40k to invest in ETFs, index funds, and more. Please create a table in markdown.", "Create a table of super high-growth AI investment opportunities "
"with $40k in ETFs, index funds, etc., and output it in Markdown.",
all_cores=True, all_cores=True,
) )

@ -1,30 +1,14 @@
import os
import asyncio import asyncio
from swarms import Agent
from swarm_models import OpenAIChat
import time import time
import psutil import psutil
from swarms.prompts.finance_agent_sys_prompt import ( from swarms.structs.agent import Agent
FINANCIAL_AGENT_SYS_PROMPT, from swarms.prompts.finance_agent_sys_prompt import FINANCIAL_AGENT_SYS_PROMPT
)
from dotenv import load_dotenv
load_dotenv()
# Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")
# Create an instance of the OpenAIChat class # Initialize the agent (no external imports or env lookups needed here)
model = OpenAIChat(
openai_api_key=api_key, model_name="gpt-4o-mini", temperature=0.1
)
# Initialize the agent
agent = Agent( agent = Agent(
agent_name="Financial-Analysis-Agent", agent_name="Financial-Analysis-Agent",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT, system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
llm=model,
max_loops=1, max_loops=1,
autosave=True, autosave=True,
dashboard=False, dashboard=False,
@ -37,39 +21,35 @@ agent = Agent(
return_step_meta=False, return_step_meta=False,
output_type="string", output_type="string",
streaming_on=False, streaming_on=False,
model_name="gpt-4o-mini",
) )
# Helper decorator to measure time and memory usage
# Function to measure time and memory usage
def measure_time_and_memory(func): def measure_time_and_memory(func):
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
start_time = time.time() start = time.time()
result = func(*args, **kwargs) result = func(*args, **kwargs)
end_time = time.time() elapsed = time.time() - start
memory_usage = psutil.Process().memory_info().rss / 1024**2 mem_mb = psutil.Process().memory_info().rss / 1024**2
print(f"Time taken: {end_time - start_time} seconds") print(f"[{func.__name__}] Time: {elapsed:.2f}s | Memory: {mem_mb:.2f} MB")
print(f"Memory used: {memory_usage} MB")
return result return result
return wrapper return wrapper
# Async wrapper using asyncio.to_thread for the blocking call
# Function to run the agent asynchronously
@measure_time_and_memory @measure_time_and_memory
async def run_agent_async(): async def run_agent_async():
await asyncio.gather( return await asyncio.to_thread(
agent.run( agent.run,
"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria" "How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria?"
)
) )
# Threaded wrapper simply runs the async version in the event loop again
# Function to run the agent on another thread
@measure_time_and_memory @measure_time_and_memory
def run_agent_thread(): def run_agent_in_thread():
asyncio.run(run_agent_async()) asyncio.run(run_agent_async())
if __name__ == "__main__":
# Run the agent asynchronously and on another thread to test the speed # 1) Run asynchronously
asyncio.run(run_agent_async()) asyncio.run(run_agent_async())
run_agent_thread() # 2) Then run again via the threaded wrapper
run_agent_in_thread()

Loading…
Cancel
Save