[FEAT][Extensive Error handling]

pull/245/head
Kye 1 year ago
parent d295cc44fd
commit 4097a9b703

@ -267,9 +267,17 @@ class Agent:
def _check_stopping_condition(self, response: str) -> bool: def _check_stopping_condition(self, response: str) -> bool:
"""Check if the stopping condition is met.""" """Check if the stopping condition is met."""
try:
if self.stopping_condition: if self.stopping_condition:
return self.stopping_condition(response) return self.stopping_condition(response)
return False return False
except Exception as error:
print(
colored(
f"Error checking stopping condition: {error}",
"red",
)
)
def dynamic_temperature(self): def dynamic_temperature(self):
""" """
@ -278,12 +286,19 @@ class Agent:
3. If the temperature is present, then dynamically change the temperature 3. If the temperature is present, then dynamically change the temperature
4. for every loop you can randomly change the temperature on a scale from 0.0 to 1.0 4. for every loop you can randomly change the temperature on a scale from 0.0 to 1.0
""" """
try:
if hasattr(self.llm, "temperature"): if hasattr(self.llm, "temperature"):
# Randomly change the temperature attribute of self.llm object # Randomly change the temperature attribute of self.llm object
self.llm.temperature = random.uniform(0.0, 1.0) self.llm.temperature = random.uniform(0.0, 1.0)
else: else:
# Use a default temperature # Use a default temperature
self.llm.temperature = 0.7 self.llm.temperature = 0.7
except Exception as error:
print(
colored(
f"Error dynamically changing temperature: {error}"
)
)
def format_prompt(self, template, **kwargs: Any) -> str: def format_prompt(self, template, **kwargs: Any) -> str:
"""Format the template with the provided kwargs using f-string interpolation.""" """Format the template with the provided kwargs using f-string interpolation."""
@ -407,11 +422,25 @@ class Agent:
def add_task_to_memory(self, task: str): def add_task_to_memory(self, task: str):
"""Add the task to the memory""" """Add the task to the memory"""
try:
self.short_memory.append([f"{self.user_name}: {task}"]) self.short_memory.append([f"{self.user_name}: {task}"])
except Exception as error:
print(
colored(
f"Error adding task to memory: {error}", "red"
)
)
def add_message_to_memory(self, message: str): def add_message_to_memory(self, message: str):
"""Add the message to the memory""" """Add the message to the memory"""
try:
self.short_memory[-1].append(message) self.short_memory[-1].append(message)
except Exception as error:
print(
colored(
f"Error adding message to memory: {error}", "red"
)
)
def add_message_to_memory_and_truncate(self, message: str): def add_message_to_memory_and_truncate(self, message: str):
"""Add the message to the memory and truncate""" """Add the message to the memory and truncate"""
@ -466,8 +495,15 @@ class Agent:
message (Dict[str, Any]): _description_ message (Dict[str, Any]): _description_
metadata (Dict[str, Any]): _description_ metadata (Dict[str, Any]): _description_
""" """
try:
if self.memory is not None: if self.memory is not None:
self.memory.add(message, metadata) self.memory.add(message, metadata)
except Exception as error:
print(
colored(
f"Error adding message to memory: {error}", "red"
)
)
def query_memorydb( def query_memorydb(
self, self,
@ -715,6 +751,7 @@ class Agent:
5. Repeat until stopping condition is met or max_loops is reached 5. Repeat until stopping condition is met or max_loops is reached
""" """
try:
# Activate Autonomous agent message # Activate Autonomous agent message
self.activate_autonomous_agent() self.activate_autonomous_agent()
@ -727,11 +764,15 @@ class Agent:
loop_count = 0 loop_count = 0
# for i in range(self.max_loops): # for i in range(self.max_loops):
while self.max_loops == "auto" or loop_count < self.max_loops: while (
self.max_loops == "auto"
or loop_count < self.max_loops
):
loop_count += 1 loop_count += 1
print( print(
colored( colored(
f"\nLoop {loop_count} of {self.max_loops}", "blue" f"\nLoop {loop_count} of {self.max_loops}",
"blue",
) )
) )
print("\n") print("\n")
@ -767,7 +808,9 @@ class Agent:
print(response) print(response)
break break
except Exception as e: except Exception as e:
logging.error(f"Error generating response: {e}") logging.error(
f"Error generating response: {e}"
)
attempt += 1 attempt += 1
time.sleep(self.retry_interval) time.sleep(self.retry_interval)
history.append(response) history.append(response)
@ -790,13 +833,23 @@ class Agent:
return response, history return response, history
return response return response
except Exception as error:
print(
colored(
f"Error asynchronous running agent: {error}",
"red",
)
)
def _run(self, **kwargs: Any) -> str: def _run(self, **kwargs: Any) -> str:
"""Generate a result using the provided keyword args.""" """Generate a result using the provided keyword args."""
try:
task = self.format_prompt(**kwargs) task = self.format_prompt(**kwargs)
response, history = self._generate(task, task) response, history = self._generate(task, task)
logging.info(f"Message history: {history}") logging.info(f"Message history: {history}")
return response return response
except Exception as error:
print(colored(f"Error running agent: {error}", "red"))
def agent_history_prompt( def agent_history_prompt(
self, self,
@ -844,15 +897,29 @@ class Agent:
Args: Args:
tasks (List[str]): A list of tasks to run. tasks (List[str]): A list of tasks to run.
""" """
try:
task_coroutines = [ task_coroutines = [
self.run_async(task, **kwargs) for task in tasks self.run_async(task, **kwargs) for task in tasks
] ]
completed_tasks = await asyncio.gather(*task_coroutines) completed_tasks = await asyncio.gather(*task_coroutines)
return completed_tasks return completed_tasks
except Exception as error:
print(
colored(
(
f"Error running agent: {error} while running"
" concurrently"
),
"red",
)
)
def bulk_run(self, inputs: List[Dict[str, Any]]) -> List[str]: def bulk_run(self, inputs: List[Dict[str, Any]]) -> List[str]:
try:
"""Generate responses for multiple input sets.""" """Generate responses for multiple input sets."""
return [self.run(**input_data) for input_data in inputs] return [self.run(**input_data) for input_data in inputs]
except Exception as error:
print(colored(f"Error running bulk run: {error}", "red"))
@staticmethod @staticmethod
def from_llm_and_template(llm: Any, template: str) -> "Agent": def from_llm_and_template(llm: Any, template: str) -> "Agent":
@ -874,9 +941,14 @@ class Agent:
Args: Args:
file_path (_type_): _description_ file_path (_type_): _description_
""" """
try:
with open(file_path, "w") as f: with open(file_path, "w") as f:
json.dump(self.short_memory, f) json.dump(self.short_memory, f)
print(f"Saved agent history to {file_path}") print(f"Saved agent history to {file_path}")
except Exception as error:
print(
colored(f"Error saving agent history: {error}", "red")
)
def load(self, file_path: str): def load(self, file_path: str):
""" """
@ -1127,6 +1199,7 @@ class Agent:
Example: Example:
>>> agent.save_state('saved_flow.json') >>> agent.save_state('saved_flow.json')
""" """
try:
state = { state = {
"agent_id": str(self.id), "agent_id": str(self.id),
"agent_name": self.agent_name, "agent_name": self.agent_name,
@ -1139,7 +1212,9 @@ class Agent:
"retry_interval": self.retry_interval, "retry_interval": self.retry_interval,
"interactive": self.interactive, "interactive": self.interactive,
"dashboard": self.dashboard, "dashboard": self.dashboard,
"dynamic_temperature": self.dynamic_temperature_enabled, "dynamic_temperature": (
self.dynamic_temperature_enabled
),
"autosave": self.autosave, "autosave": self.autosave,
"saved_state_path": self.saved_state_path, "saved_state_path": self.saved_state_path,
"max_loops": self.max_loops, "max_loops": self.max_loops,
@ -1148,11 +1223,18 @@ class Agent:
with open(file_path, "w") as f: with open(file_path, "w") as f:
json.dump(state, f, indent=4) json.dump(state, f, indent=4)
saved = colored(f"Saved agent state to: {file_path}", "green") saved = colored(
f"Saved agent state to: {file_path}", "green"
)
print(saved) print(saved)
except Exception as error:
print(
colored(f"Error saving agent state: {error}", "red")
)
def state_to_str(self): def state_to_str(self):
"""Transform the JSON into a string""" """Transform the JSON into a string"""
try:
state = { state = {
"agent_id": str(self.id), "agent_id": str(self.id),
"agent_name": self.agent_name, "agent_name": self.agent_name,
@ -1165,13 +1247,22 @@ class Agent:
"retry_interval": self.retry_interval, "retry_interval": self.retry_interval,
"interactive": self.interactive, "interactive": self.interactive,
"dashboard": self.dashboard, "dashboard": self.dashboard,
"dynamic_temperature": self.dynamic_temperature_enabled, "dynamic_temperature": (
self.dynamic_temperature_enabled
),
"autosave": self.autosave, "autosave": self.autosave,
"saved_state_path": self.saved_state_path, "saved_state_path": self.saved_state_path,
"max_loops": self.max_loops, "max_loops": self.max_loops,
} }
out = str(state) out = str(state)
return out return out
except Exception as error:
print(
colored(
f"Error transforming state to string: {error}",
"red",
)
)
def load_state(self, file_path: str): def load_state(self, file_path: str):
""" """
@ -1358,6 +1449,7 @@ class Agent:
# Response # Response
""" """
return PROMPT
def self_healing(self, **kwargs): def self_healing(self, **kwargs):
""" """

@ -2,7 +2,7 @@ import concurrent.futures
import json import json
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Union from typing import Any, Callable, Dict, List, Optional, Union
import logging
from termcolor import colored from termcolor import colored
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
@ -43,6 +43,7 @@ class Task:
kwargs: Dict[str, Any] = field(default_factory=dict) kwargs: Dict[str, Any] = field(default_factory=dict)
result: Any = None result: Any = None
history: List[Any] = field(default_factory=list) history: List[Any] = field(default_factory=list)
# logger = logging.getLogger(__name__)
def execute(self): def execute(self):
""" """
@ -158,14 +159,11 @@ class SequentialWorkflow:
def reset_workflow(self) -> None: def reset_workflow(self) -> None:
"""Resets the workflow by clearing the results of each task.""" """Resets the workflow by clearing the results of each task."""
try: try:
for task in self.tasks: for task in self.tasks:
task.result = None task.result = None
except Exception as error: except Exception as error:
print( print(
colored( colored(f"Error resetting workflow: {error}", "red"),
f"Error resetting workflow: {error}", "red"
),
) )
def get_task_results(self) -> Dict[str, Any]: def get_task_results(self) -> Dict[str, Any]:
@ -190,12 +188,15 @@ class SequentialWorkflow:
"""Remove tasks from sequential workflow""" """Remove tasks from sequential workflow"""
try: try:
self.tasks = [ self.tasks = [
task for task in self.tasks if task.description != task task
for task in self.tasks
if task.description != task
] ]
except Exception as error: except Exception as error:
print( print(
colored( colored(
f"Error removing task from workflow: {error}", "red" f"Error removing task from workflow: {error}",
"red",
), ),
) )
@ -238,6 +239,44 @@ class SequentialWorkflow:
), ),
) )
def delete_task(self, task: str) -> None:
"""
Delete a task from the workflow.
Args:
task (str): The description of the task to delete.
Raises:
ValueError: If the task is not found in the workflow.
Examples:
>>> from swarms.models import OpenAIChat
>>> from swarms.structs import SequentialWorkflow
>>> llm = OpenAIChat(openai_api_key="")
>>> workflow = SequentialWorkflow(max_loops=1)
>>> workflow.add("What's the weather in miami", llm)
>>> workflow.add("Create a report on these metrics", llm)
>>> workflow.delete_task("What's the weather in miami")
>>> workflow.tasks
[Task(description='Create a report on these metrics', agent=Agent(llm=OpenAIChat(openai_api_key=''), max_loops=1, dashboard=False), args=[], kwargs={}, result=None, history=[])]
"""
try:
for task in self.tasks:
if task.description == task:
self.tasks.remove(task)
break
else:
raise ValueError(
f"Task {task} not found in workflow."
)
except Exception as error:
print(
colored(
f"Error deleting task from workflow: {error}",
"red",
),
)
def concurrent_run(self): def concurrent_run(self):
""" """
Concurrently run the workflow using a pool of workers. Concurrently run the workflow using a pool of workers.
@ -384,7 +423,6 @@ class SequentialWorkflow:
def add_objective_to_workflow(self, task: str, **kwargs) -> None: def add_objective_to_workflow(self, task: str, **kwargs) -> None:
"""Adds an objective to the workflow.""" """Adds an objective to the workflow."""
try: try:
print( print(
colored( colored(
""" """
@ -430,7 +468,6 @@ class SequentialWorkflow:
""" """
try: try:
filepath = filepath or self.restore_state_filepath filepath = filepath or self.restore_state_filepath
with open(filepath, "r") as f: with open(filepath, "r") as f:
@ -538,14 +575,16 @@ class SequentialWorkflow:
# Ensure that 'task' is provided in the kwargs # Ensure that 'task' is provided in the kwargs
if "task" not in task.kwargs: if "task" not in task.kwargs:
raise ValueError( raise ValueError(
"The 'task' argument is required for" "The 'task' argument is required"
" the Agent agent execution in" " for the Agent agent execution"
f" '{task.description}'" f" in '{task.description}'"
) )
# Separate the 'task' argument from other kwargs # Separate the 'task' argument from other kwargs
flow_task_arg = task.kwargs.pop("task") flow_task_arg = task.kwargs.pop("task")
task.result = await task.agent.arun( task.result = await task.agent.arun(
flow_task_arg, *task.args, **task.kwargs flow_task_arg,
*task.args,
**task.kwargs,
) )
else: else:
# If it's not a Agent instance, call the agent directly # If it's not a Agent instance, call the agent directly

Loading…
Cancel
Save