Skip to content

Commit

Permalink
removed unrelated changes to PR
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickbdevaney committed Jan 3, 2025
1 parent 51a7c7e commit 0b21b32
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 37 deletions.
13 changes: 5 additions & 8 deletions swarms/structs/concurrent_workflow.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,30 @@

import asyncio
import os
import uuid
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from typing import Any, Dict, List, Optional, Union
import concurrent

from pydantic import BaseModel, Field
from tenacity import retry, stop_after_attempt, wait_exponential

from swarms.structs.agent import Agent
from swarms.structs.base_swarm import BaseSwarm
from swarms.utils.file_processing import create_file_in_folder
import concurrent
from clusterops import (
execute_on_gpu,
execute_with_cpu_cores,
execute_on_multiple_gpus,
list_available_gpus,
)

from swarms.structs.agent import Agent
from swarms.structs.base_swarm import BaseSwarm
from swarms.utils.file_processing import create_file_in_folder

from swarms.utils.loguru_logger import initialize_logger
from swarms.structs.swarm_id_generator import generate_swarm_id

logger = initialize_logger(log_folder="concurrent_workflow")




class AgentOutputSchema(BaseModel):
run_id: Optional[str] = Field(
..., description="Unique ID for the run"
Expand Down
5 changes: 3 additions & 2 deletions swarms/tools/func_calling_utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

import json
from typing import List, Union, Dict

Expand Down Expand Up @@ -122,9 +123,9 @@ def prepare_output_for_output_model(
"""
if output_type == BaseModel:
return str_to_pydantic_model(output, output_type)
elif output_type is dict:
elif output_type == dict:
return dict_to_json_str(output)
elif output_type is str:
elif output_type == str:
return output
else:
return output
69 changes: 44 additions & 25 deletions tests/agent_evals/auto_test_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from swarms.structs.agent import Agent


@dataclass
class SwarmSystemInfo:
"""System information for Swarms issue reports."""
Expand Down Expand Up @@ -110,14 +111,7 @@ def _get_gpu_info(self) -> Tuple[bool, Optional[str]]:
gpu_info = torch.cuda.get_device_name(0)
return cuda_available, gpu_info
return False, None
except ModuleNotFoundError as e:
print(f"Error: {e}")
return False, None
except RuntimeError as e:
print(f"Error: {e}")
return False, None
except Exception as e:
print(f"Unexpected error: {e}")
except:
return False, None

def _get_system_info(self) -> SwarmSystemInfo:
Expand All @@ -136,15 +130,23 @@ def _get_system_info(self) -> SwarmSystemInfo:
gpu_info=gpu_info,
)

def _categorize_error(self, error: Exception, context: Dict) -> List[str]:
def _categorize_error(
self, error: Exception, context: Dict
) -> List[str]:
"""Categorize the error and return appropriate labels."""
error_str = str(error).lower()
type(error).__name__

labels = ["bug", "automated"]

# Check error message and context for category keywords
for category, category_labels in self.ISSUE_CATEGORIES.items():
if any(keyword in error_str for keyword in category_labels):
for (
category,
category_labels,
) in self.ISSUE_CATEGORIES.items():
if any(
keyword in error_str for keyword in category_labels
):
labels.extend(category_labels)
break

Expand All @@ -159,7 +161,10 @@ def _categorize_error(self, error: Exception, context: Dict) -> List[str]:
return list(set(labels)) # Remove duplicates

def _format_swarms_issue_body(
self, error: Exception, system_info: SwarmSystemInfo, context: Dict
self,
error: Exception,
system_info: SwarmSystemInfo,
context: Dict,
) -> str:
"""Format the issue body with Swarms-specific information."""
return f"""
Expand Down Expand Up @@ -202,25 +207,27 @@ def _get_dependencies_info(self) -> str:
for dist in pkg_resources.working_set:
deps.append(f"- {dist.key} {dist.version}")
return "\n".join(deps)
except ImportError as e:
print(f"Error: {e}")
return "Unable to fetch dependency information"
except Exception as e:
print(f"Unexpected error: {e}")
except:
return "Unable to fetch dependency information"

# First, add this method to your SwarmsIssueReporter class
def _check_rate_limit(self) -> bool:
"""Check if we're within rate limits."""
now = datetime.now()
time_diff = (now - self.last_issue_time).total_seconds()

if len(self.issues_created) >= self.rate_limit and time_diff < self.rate_period:
if (
len(self.issues_created) >= self.rate_limit
and time_diff < self.rate_period
):
logger.warning("Rate limit exceeded for issue creation")
return False

# Clean up old issues from tracking
self.issues_created = [
time for time in self.issues_created if (now - time).total_seconds() < self.rate_period
time
for time in self.issues_created
if (now - time).total_seconds() < self.rate_period
]

return True
Expand All @@ -246,7 +253,9 @@ def report_swarms_issue(
"""
try:
if not self._check_rate_limit():
logger.warning("Skipping issue creation due to rate limit")
logger.warning(
"Skipping issue creation due to rate limit"
)
return None

# Collect system information
Expand Down Expand Up @@ -277,19 +286,25 @@ def report_swarms_issue(
url = f"https://api.github.com/repos/{self.REPO_OWNER}/{self.REPO_NAME}/issues"
data = {
"title": title,
"body": self._format_swarms_issue_body(error, system_info, full_context),
"body": self._format_swarms_issue_body(
error, system_info, full_context
),
"labels": labels,
}

response = requests.post(
url,
headers={"Authorization": f"token {self.github_token}"},
headers={
"Authorization": f"token {self.github_token}"
},
json=data,
)
response.raise_for_status()

issue_number = response.json()["number"]
logger.info(f"Successfully created Swarms issue #{issue_number}")
logger.info(
f"Successfully created Swarms issue #{issue_number}"
)

return issue_number

Expand All @@ -299,11 +314,15 @@ def report_swarms_issue(


# Setup the reporter with your GitHub token
reporter = SwarmsIssueReporter(github_token=os.getenv("GITHUB_API_KEY"))
reporter = SwarmsIssueReporter(
github_token=os.getenv("GITHUB_API_KEY")
)


# Force an error to test the reporter
try:
# This will raise an error since the input isn't valid
# Create an agent that might have issues
model = OpenAIChat(model_name="gpt-4o")
agent = Agent(agent_name="Test-Agent", max_loops=1)

Expand All @@ -318,4 +337,4 @@ def report_swarms_issue(
context={"task": "test_run"},
priority="high",
)
print(f"Created issue number: {issue_number}")
print(f"Created issue number: {issue_number}")
7 changes: 5 additions & 2 deletions tests/profiling_agent.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import time

start_time = time.time()

import os
import uuid
from swarms import Agent
from swarm_models import OpenAIChat
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
start_time = time.time()


# Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")
Expand Down Expand Up @@ -41,4 +44,4 @@
end_time = time.time()

print(f"Execution time: {end_time - start_time} seconds")
# Execution time: 9.922541856765747 seconds for the whole script
# Execution time: 9.922541856765747 seconds for the whole script

0 comments on commit 0b21b32

Please sign in to comment.