pull/522/head
Kye Gomez 7 months ago
parent 4d963fa901
commit 71da285dc1

@ -2,6 +2,8 @@
The Swarms API provides endpoints to interact with various language models, manage agent configurations, and handle token counting. This documentation covers the available endpoints, input and output models, and detailed examples for each endpoint. The Swarms API provides endpoints to interact with various language models, manage agent configurations, and handle token counting. This documentation covers the available endpoints, input and output models, and detailed examples for each endpoint.
URL: `https://api.swarms.world`
## Endpoints ## Endpoints
### `/v1/models` ### `/v1/models`

@ -39,7 +39,9 @@ class ConcurrentWorkflow(BaseWorkflow):
return_results: bool = False return_results: bool = False
stopping_condition: Optional[Callable] = None stopping_condition: Optional[Callable] = None
def run(self, task: Optional[str] = None, *args, **kwargs) -> Optional[List[Any]]: def run(
self, task: Optional[str] = None, *args, **kwargs
) -> Optional[List[Any]]:
""" """
Executes the tasks in parallel using multiple threads. Executes the tasks in parallel using multiple threads.
@ -59,7 +61,12 @@ class ConcurrentWorkflow(BaseWorkflow):
logger.warning("No agents found in the workflow.") logger.warning("No agents found in the workflow.")
break break
threads = [threading.Thread(target=self.execute_agent, args=(agent, task)) for agent in self.agents] threads = [
threading.Thread(
target=self.execute_agent, args=(agent, task)
)
for agent in self.agents
]
for thread in threads: for thread in threads:
thread.start() thread.start()
@ -68,11 +75,19 @@ class ConcurrentWorkflow(BaseWorkflow):
thread.join() thread.join()
if self.return_results: if self.return_results:
results.extend([thread.result for thread in threads if hasattr(thread, 'result')]) results.extend(
[
thread.result
for thread in threads
if hasattr(thread, "result")
]
)
loop += 1 loop += 1
if self.stopping_condition and self.stopping_condition(results): if self.stopping_condition and self.stopping_condition(
results
):
break break
return results if self.return_results else None return results if self.return_results else None
@ -85,8 +100,10 @@ class ConcurrentWorkflow(BaseWorkflow):
def save(self): def save(self):
"""Saves the state of the workflow to a file.""" """Saves the state of the workflow to a file."""
self.save_state(self.saved_state_filepath) self.save_state(self.saved_state_filepath)
def execute_agent(self, agent: Agent, task: Optional[str] = None, *args, **kwargs): def execute_agent(
self, agent: Agent, task: Optional[str] = None, *args, **kwargs
):
try: try:
result = agent.run(task, *args, **kwargs) result = agent.run(task, *args, **kwargs)
if self.print_results: if self.print_results:
@ -95,16 +112,26 @@ class ConcurrentWorkflow(BaseWorkflow):
return result return result
except Exception as e: except Exception as e:
logger.error(f"Agent {agent} generated an exception: {e}") logger.error(f"Agent {agent} generated an exception: {e}")
api_key = os.environ["OPENAI_API_KEY"] api_key = os.environ["OPENAI_API_KEY"]
# Model # Model
swarm = ConcurrentWorkflow( swarm = ConcurrentWorkflow(
agents = [Agent(llm=OpenAIChat(openai_api_key=api_key, max_tokens=4000,), max_loops=4, dashboard=False)], agents=[
Agent(
llm=OpenAIChat(
openai_api_key=api_key,
max_tokens=4000,
),
max_loops=4,
dashboard=False,
)
],
) )
# Run the workflow # Run the workflow
swarm.run("Generate a report on the top 3 biggest expenses for small businesses and how businesses can save 20%") swarm.run(
"Generate a report on the top 3 biggest expenses for small businesses and how businesses can save 20%"
)

@ -1,4 +1,3 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
@ -9,16 +8,16 @@ load_dotenv()
api_key = os.environ.get("OPENAI_API_KEY") api_key = os.environ.get("OPENAI_API_KEY")
llm = OpenAIChat( llm = OpenAIChat(temperature=0.5, openai_api_key=api_key, max_tokens=4000)
temperature=0.5, openai_api_key=api_key, max_tokens=4000
)
agent1 = Agent(llm=llm, 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) 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")
return "Task completed" return "Task completed"
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))

@ -25,7 +25,6 @@ Always prioritize accuracy, depth of analysis, and clarity in your responses. Us
""" """
# Initialize the agent # Initialize the agent
agent = Agent( agent = Agent(
agent_name="Geo Expert AI", agent_name="Geo Expert AI",
@ -57,7 +56,6 @@ agent = Agent(
) )
# Initialize the agent # Initialize the agent
forecaster_agent = Agent( forecaster_agent = Agent(
agent_name="Forecaster Agent", agent_name="Forecaster Agent",
@ -91,11 +89,13 @@ forecaster_agent = Agent(
# Initialize the swarm # Initialize the swarm
swarm = MixtureOfAgents( swarm = MixtureOfAgents(
agents = [agent, forecaster_agent], agents=[agent, forecaster_agent],
final_agent = forecaster_agent, final_agent=forecaster_agent,
layers = 1, layers=1,
) )
# Run the swarm # Run the swarm
out = swarm.run("what is the economic impact of China from technology decoupling, and how is that impact measured? What is the forecast or economic, give some numbers") out = swarm.run(
print(out) "what is the economic impact of China from technology decoupling, and how is that impact measured? What is the forecast or economic, give some numbers"
)
print(out)

@ -2,6 +2,7 @@ import os
import shutil import shutil
from loguru import logger from loguru import logger
def cleanup_json_logs(name: str = None): def cleanup_json_logs(name: str = None):
# Define the root directory and the target directory # Define the root directory and the target directory
root_dir = os.getcwd() root_dir = os.getcwd()
@ -46,8 +47,10 @@ def cleanup_json_logs(name: str = None):
shutil.rmtree(chroma_folder) shutil.rmtree(chroma_folder)
logger.info(f"Deleted Chroma folder at {chroma_folder}") logger.info(f"Deleted Chroma folder at {chroma_folder}")
logger.info(f"All JSON, LOG and TXT files have been moved to {target_dir}") logger.info(
f"All JSON, LOG and TXT files have been moved to {target_dir}"
)
# Call the function # Call the function
cleanup_json_logs("heinz_swarm") cleanup_json_logs("heinz_swarm")

@ -89,7 +89,12 @@ from swarms.structs.yaml_model import (
pydantic_type_to_yaml_schema, pydantic_type_to_yaml_schema,
) )
from swarms.structs.mixture_of_agents import MixtureOfAgents from swarms.structs.mixture_of_agents import MixtureOfAgents
from swarms.structs.graph_workflow import GraphWorkflow, Node, NodeType, Edge from swarms.structs.graph_workflow import (
GraphWorkflow,
Node,
NodeType,
Edge,
)
__all__ = [ __all__ = [

@ -38,6 +38,7 @@ class BaseWorkflow(BaseStructure):
add_objective_to_workflow: Adds an objective to the workflow. add_objective_to_workflow: Adds an objective to the workflow.
load_workflow_state: Loads the workflow state from a json file and restores the workflow state. load_workflow_state: Loads the workflow state from a json file and restores the workflow state.
""" """
def __init__( def __init__(
self, self,
agents: List[Agent] = None, agents: List[Agent] = None,

Loading…
Cancel
Save