pull/435/head
Kye 10 months ago
parent 4e1100e15a
commit 6e96027704

@ -54,14 +54,8 @@ agent = Agent(
# dynamic_temperature=False, # Set to 'True' for dynamic temperature handling.
)
# out = agent.load_state("flow_state.json")
# temp = agent.dynamic_temperature()
# filter = agent.add_response_filter("Trump")
# Load the agent with a task
out = agent.run("Generate a 10,000 word blog on health and wellness.")
# out = agent.validate_response(out)
# out = agent.analyze_feedback(out)
# out = agent.print_history_and_memory()
# # out = agent.save_state("flow_state.json")
# print(out)
```

@ -24,12 +24,6 @@ agent = Agent(
# dynamic_temperature=False, # Set to 'True' for dynamic temperature handling.
)
# out = agent.load_state("flow_state.json")
# temp = agent.dynamic_temperature()
# filter = agent.add_response_filter("Trump")
# Run the workflow on a task
out = agent.run("Generate a 10,000 word blog on health and wellness.")
# out = agent.validate_response(out)
# out = agent.analyze_feedback(out)
# out = agent.print_history_and_memory()
# # out = agent.save_state("flow_state.json")
# print(out)
print(out)

@ -16,9 +16,7 @@ class MySwarm(BaseSwarm):
# Add your custom swarm to the AutoSwarmRouter
router = AutoSwarmRouter(
swarms=[MySwarm]
)
router = AutoSwarmRouter(swarms=[MySwarm])
# Create an AutoSwarm instance

@ -1,21 +1,4 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"private_outputs": true,
"provenance": [],
"gpuType": "T4"
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"accelerator": "GPU"
},
"cells": [
{
"cell_type": "code",
@ -30,16 +13,21 @@
},
{
"cell_type": "markdown",
"metadata": {
"id": "-d9k3egzgp2_"
},
"source": [
"Copied from the repo, example.py\n",
"Enter your OpenAI API key here."
],
"metadata": {
"id": "-d9k3egzgp2_"
}
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "K1Sbq4UkgVjk"
},
"outputs": [],
"source": [
"from swarms.models import OpenAIChat\n",
"from swarms.structs import Agent\n",
@ -76,37 +64,45 @@
" \"Generate a 10,000 word blog on mental clarity and the benefits\"\n",
" \" of meditation.\"\n",
")\n",
"# out = agent.validate_response(out)\n",
"# out = agent.analyze_feedback(out)\n",
"# out = agent.print_history_and_memory()\n",
"# # out = agent.save_state(\"flow_state.json\")\n",
"# print(out)"
],
"metadata": {
"id": "K1Sbq4UkgVjk"
},
"execution_count": null,
"outputs": []
"print(out)"
]
},
{
"cell_type": "markdown",
"source": [
"Look at the log, which may be empty."
],
"metadata": {
"id": "6VtgQ0F4BNc-"
}
},
"source": [
"Look at the log, which may be empty."
]
},
{
"cell_type": "code",
"source": [
"!cat errors.txt"
],
"execution_count": null,
"metadata": {
"id": "RqL5LL3xBLWR"
},
"execution_count": null,
"outputs": []
"outputs": [],
"source": [
"!cat errors.txt"
]
}
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"gpuType": "T4",
"private_outputs": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

@ -0,0 +1,140 @@
import logging
from collections import defaultdict
from swarms.utils.loguru_logger import logger
from swarms.structs.agent import Agent
from typing import Sequence, Callable, List, Dict, Union
class AgentRearrange:
def __init__(
self,
agents: Sequence[Agent] = None,
verbose: bool = False,
custom_prompt: str = None,
callbacks: Sequence[Callable] = None,
*args,
**kwargs,
):
"""
Initialize with a dictionary of Agent objects keyed by their names.
"""
if not all(isinstance(agent, Agent) for agent in agents):
raise ValueError(
"All elements must be instances of the Agent class."
)
self.agents = agents
self.verbose = verbose
self.custom_prompt = custom_prompt
self.callbacks = callbacks
self.flows = defaultdict(list)
def parse_pattern(self, pattern: str):
"""
Parse the interaction pattern and setup task flows.
Pattern format: "a -> b, c -> d, e -> f"
"""
try:
for flow in pattern.split(","):
parts = [part.strip() for part in flow.split("->")]
if len(parts) != 2:
logging.error(
f"Invalid flow pattern: {flow}. Each flow"
" must have exactly one '->'."
)
return False
source_name, destinations_str = parts
source = self.find_agent_by_name(source_name)
if source is None:
logging.error(
f"Source agent {source_name} not found."
)
return False
destinations_names = destinations_str.split()
for dest_name in destinations_names:
dest = self.find_agent_by_name(dest_name)
if dest is None:
logging.error(
f"Destination agent {dest_name} not"
" found."
)
return False
self.flows[source.agent_name].append(
dest.agent_name
)
return True
except Exception as e:
logger.error(f"Error: {e}")
raise e
def self_find_agen_by_name(self, name: str):
for agent in self.agents:
if agent.agent_name == name:
return agent
return None
def __call__(
self,
agents: Sequence[Agent] = None,
pattern: str = None,
task: str = None,
*args,
**kwargs,
):
"""
Execute the task based on the specified pattern.
"""
try:
if agents:
self.flows.clear() # Reset previous flows
if not self.parse_pattern(pattern):
return # Pattern parsing failed
for source, destinations in self.flows.items():
for dest in destinations:
# agents[dest].runt(f"{task} (from {source})")
dest_agent = self.self_find_agen_by_name(dest)
if self.custom_prompt:
dest_agent.run(
f"{task} {self.custom_prompt}"
)
else:
dest_agent.run(f"{task} (from {source})")
else:
self.flows.clear() # Reset previous flows
if not self.parse_pattern(pattern):
return # Pattern parsing failed
for source, destinations in self.flows.items():
for dest in destinations:
dest_agent = self.self_find_agen_by_name(dest)
if self.custom_prompt:
dest_agent.run(
f"{task} {self.custom_prompt}"
)
else:
dest_agent.run(f"{task} (from {source})")
except Exception as e:
logger.error(
f"Error: {e} try again by providing agents and"
" pattern"
)
raise e
# # Example usage
# try:
# agents = [
# Agent(name=f"b{i}") for i in range(1, 4)
# ] # Creating agents b1, b2, b3
# agents.append(Agent(name="d")) # Adding agent d
# rearranger = Rearrange(agents)
# # Specifying a complex pattern for task execution
# rearranger.execute("d -> b1 b2 b3, b2 -> b3", "Analyze data")
# except ValueError as e:
# logging.error(e)
Loading…
Cancel
Save