Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Py best pratices flakes and pyupgrade #734

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion csvagent_example.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# Example usage
from pathlib import Path
from swarms.structs.csv_to_agent import AgentLoader, AgentValidationError

from swarms.structs.csv_to_agent import (
AgentLoader,
AgentValidationError,
)

if __name__ == "__main__":
# Example agent configurations
Expand Down
3 changes: 2 additions & 1 deletion example.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import os

from dotenv import load_dotenv
from swarm_models import OpenAIChat

from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
from dotenv import load_dotenv

load_dotenv()

Expand Down
2 changes: 1 addition & 1 deletion graph_swarm_example.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from loguru import logger

from swarms.structs.agent import Agent
from swarms.structs.graph_swarm import GraphSwarm


if __name__ == "__main__":
try:
# Create agents
Expand Down
2 changes: 1 addition & 1 deletion multi_agent_router_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,4 @@
print(result_execute)

except Exception as e:
print(f"Error occurred: {str(e)}")
print(f"Error occurred: {e!s}")
4 changes: 2 additions & 2 deletions new_features_examples/agent_showcase_example.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import os

from swarms import Agent

from swarm_models import OpenAIChat

from swarms import Agent
from swarms.structs.agents_available import showcase_available_agents

# Get the OpenAI API key from the environment variable
Expand Down
12 changes: 6 additions & 6 deletions new_features_examples/agent_with_fluidapi.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import os

from swarm_models import OpenAIChat
from swarms import Agent
from fluid_api_agent.main import fluid_api_request
from dotenv import load_dotenv
from fluid_api_agent.main import fluid_api_request
from swarm_models import OpenAIChat

from swarms import Agent

load_dotenv()

Expand Down Expand Up @@ -82,9 +82,9 @@ def omni_api(task: str) -> str:

# Define the system prompt tailored for the API expert
API_AGENT_SYS_PROMPT = """
You are a highly specialized financial API expert.
Your expertise lies in analyzing financial data, making investment recommendations, and
interacting with APIs to retrieve, process, and present data effectively.
You are a highly specialized financial API expert.
Your expertise lies in analyzing financial data, making investment recommendations, and
interacting with APIs to retrieve, process, and present data effectively.
You use tools like 'omni_api' to fetch data dynamically, ensuring accuracy and up-to-date results.

Instructions:
Expand Down
3 changes: 2 additions & 1 deletion new_features_examples/async_agent.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from swarm_models import OpenAIChat

from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
from swarm_models import OpenAIChat

model = OpenAIChat(model_name="gpt-4o")

Expand Down
2 changes: 1 addition & 1 deletion new_features_examples/async_agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
from dotenv import load_dotenv
from swarm_models import OpenAIChat

from new_features_examples.async_executor import HighSpeedExecutor
from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
from new_features_examples.async_executor import HighSpeedExecutor

load_dotenv()

Expand Down
6 changes: 3 additions & 3 deletions new_features_examples/async_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
import multiprocessing as mp
import time
from functools import partial
from typing import Any, Dict, Union
from typing import Any, Optional, Union


class HighSpeedExecutor:
def __init__(self, num_processes: int = None):
def __init__(self, num_processes: Optional[int] = None):
"""
Initialize the executor with configurable number of processes.
If num_processes is None, it uses CPU count.
Expand Down Expand Up @@ -45,7 +45,7 @@ async def execute_batch(
num_executions: int,
*args: Any,
**kwargs: Any,
) -> Dict[str, Union[int, float]]:
) -> dict[str, Union[int, float]]:
"""
Execute the given function multiple times concurrently.

Expand Down
13 changes: 6 additions & 7 deletions new_features_examples/async_workflow_example.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import asyncio
from typing import List

from swarm_models import OpenAIChat

from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
from swarms.structs.agent import Agent
from swarms.structs.async_workflow import (
SpeakerConfig,
SpeakerRole,
create_default_workflow,
run_workflow_with_retry,
)
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
from swarms.structs.agent import Agent


async def create_specialized_agents() -> List[Agent]:
async def create_specialized_agents() -> list[Agent]:
"""Create a set of specialized agents for financial analysis"""

# Base model configuration
Expand Down Expand Up @@ -165,7 +164,7 @@ async def main():
print(value)

except Exception as e:
print(f"Workflow failed: {str(e)}")
print(f"Workflow failed: {e!s}")

finally:
await workflow.cleanup()
Expand Down
22 changes: 11 additions & 11 deletions new_features_examples/auto_agent.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import json
import os
from contextlib import suppress
from typing import Any, Callable, Dict, Optional, Type, Union
from typing import Any, Callable, Optional, Union

from dotenv import load_dotenv
from pydantic import BaseModel, Field, ValidationError, create_model
Expand All @@ -10,7 +10,7 @@

class DynamicParser:
@staticmethod
def extract_fields(model: Type[BaseModel]) -> Dict[str, Any]:
def extract_fields(model: type[BaseModel]) -> dict[str, Any]:
return {
field_name: (
field.annotation,
Expand All @@ -21,8 +21,8 @@ def extract_fields(model: Type[BaseModel]) -> Dict[str, Any]:

@staticmethod
def create_partial_model(
model: Type[BaseModel], data: Dict[str, Any]
) -> Type[BaseModel]:
model: type[BaseModel], data: dict[str, Any]
) -> type[BaseModel]:
fields = {
field_name: (
field.annotation,
Expand All @@ -35,7 +35,7 @@ def create_partial_model(

@classmethod
def parse(
cls, data: Union[str, Dict[str, Any]], model: Type[BaseModel]
cls, data: Union[str, dict[str, Any]], model: type[BaseModel]
) -> Optional[BaseModel]:
if isinstance(data, str):
try:
Expand Down Expand Up @@ -88,7 +88,7 @@ class Command(BaseModel):
...,
description="Command name to execute from the provided list of commands.",
)
args: Dict[str, Any] = Field(
args: dict[str, Any] = Field(
..., description="Arguments required to execute the command."
)

Expand Down Expand Up @@ -134,9 +134,9 @@ def task_complete_command(reason: str):


# Dynamic command execution
def execute_command(name: str, args: Dict[str, Any]):
def execute_command(name: str, args: dict[str, Any]):
"""Dynamically execute a command based on its name and arguments."""
command_map: Dict[str, Callable] = {
command_map: dict[str, Callable] = {
"fluid_api": lambda **kwargs: fluid_api_command(
task=kwargs.get("task")
),
Expand All @@ -157,8 +157,8 @@ def execute_command(name: str, args: Dict[str, Any]):


def parse_and_execute_command(
response: Union[str, Dict[str, Any]],
base_model: Type[BaseModel] = AgentResponse,
response: Union[str, dict[str, Any]],
base_model: type[BaseModel] = AgentResponse,
) -> Any:
"""Enhanced command parser with flexible input handling"""
parsed = DynamicParser.parse(response, base_model)
Expand Down Expand Up @@ -197,7 +197,7 @@ def parse_and_execute_command(
### COMMANDS:
1. Fluid API: "fluid_api", args: "method": "<GET/POST/...>", "url": "<url>", "headers": "<headers>", "body": "<payload>"
18. Send Tweet: "send_tweet", args: "text": "<text>"
19. Do Nothing: "do_nothing", args:
19. Do Nothing: "do_nothing", args:
20. Task Complete (Shutdown): "task_complete", args: "reason": "<reason>"

### RESOURCES:
Expand Down
4 changes: 3 additions & 1 deletion new_features_examples/auto_swarm_router.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import os

from dotenv import load_dotenv
from swarms import Agent
from swarm_models import OpenAIChat

from swarms import Agent
from swarms.structs.swarm_router import SwarmRouter

load_dotenv()
Expand Down
60 changes: 30 additions & 30 deletions new_features_examples/concurrent_examples/concurrent_mix 2.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@
delaware_ccorp_agent = Agent(
agent_name="Delaware-CCorp-Hiring-Agent",
system_prompt="""
Create a comprehensive hiring description for a Delaware C Corporation,
including all relevant laws and regulations, such as the Delaware General
Corporation Law (DGCL) and the Delaware Corporate Law. Ensure the description
covers the requirements for hiring employees, contractors, and officers,
including the necessary paperwork, tax obligations, and benefits. Also,
outline the procedures for compliance with Delaware's employment laws,
including anti-discrimination laws, workers' compensation, and unemployment
insurance. Provide guidance on how to navigate the complexities of Delaware's
corporate law and ensure that all hiring practices are in compliance with
Create a comprehensive hiring description for a Delaware C Corporation,
including all relevant laws and regulations, such as the Delaware General
Corporation Law (DGCL) and the Delaware Corporate Law. Ensure the description
covers the requirements for hiring employees, contractors, and officers,
including the necessary paperwork, tax obligations, and benefits. Also,
outline the procedures for compliance with Delaware's employment laws,
including anti-discrimination laws, workers' compensation, and unemployment
insurance. Provide guidance on how to navigate the complexities of Delaware's
corporate law and ensure that all hiring practices are in compliance with
state and federal regulations.
""",
llm=model,
Expand All @@ -41,17 +41,17 @@
indian_foreign_agent = Agent(
agent_name="Indian-Foreign-Hiring-Agent",
system_prompt="""
Create a comprehensive hiring description for an Indian or foreign country,
including all relevant laws and regulations, such as the Indian Contract Act,
the Indian Labour Laws, and the Foreign Exchange Management Act (FEMA).
Ensure the description covers the requirements for hiring employees,
contractors, and officers, including the necessary paperwork, tax obligations,
and benefits. Also, outline the procedures for compliance with Indian and
foreign employment laws, including anti-discrimination laws, workers'
compensation, and unemployment insurance. Provide guidance on how to navigate
the complexities of Indian and foreign corporate law and ensure that all hiring
practices are in compliance with state and federal regulations. Consider the
implications of hiring foreign nationals and the requirements for obtaining
Create a comprehensive hiring description for an Indian or foreign country,
including all relevant laws and regulations, such as the Indian Contract Act,
the Indian Labour Laws, and the Foreign Exchange Management Act (FEMA).
Ensure the description covers the requirements for hiring employees,
contractors, and officers, including the necessary paperwork, tax obligations,
and benefits. Also, outline the procedures for compliance with Indian and
foreign employment laws, including anti-discrimination laws, workers'
compensation, and unemployment insurance. Provide guidance on how to navigate
the complexities of Indian and foreign corporate law and ensure that all hiring
practices are in compliance with state and federal regulations. Consider the
implications of hiring foreign nationals and the requirements for obtaining
necessary visas and work permits.
""",
llm=model,
Expand All @@ -69,19 +69,19 @@
agents = [delaware_ccorp_agent, indian_foreign_agent]
tasks = [
"""
Create a comprehensive hiring description for an Agent Engineer, including
required skills and responsibilities. Ensure the description covers the
necessary technical expertise, such as proficiency in AI/ML frameworks,
programming languages, and data structures. Outline the key responsibilities,
including designing and developing AI agents, integrating with existing systems,
Create a comprehensive hiring description for an Agent Engineer, including
required skills and responsibilities. Ensure the description covers the
necessary technical expertise, such as proficiency in AI/ML frameworks,
programming languages, and data structures. Outline the key responsibilities,
including designing and developing AI agents, integrating with existing systems,
and ensuring scalability and performance.
""",
"""
Generate a detailed job description for a Prompt Engineer, including
required skills and responsibilities. Ensure the description covers the
necessary technical expertise, such as proficiency in natural language processing,
machine learning, and software development. Outline the key responsibilities,
including designing and optimizing prompts for AI systems, ensuring prompt
Generate a detailed job description for a Prompt Engineer, including
required skills and responsibilities. Ensure the description covers the
necessary technical expertise, such as proficiency in natural language processing,
machine learning, and software development. Outline the key responsibilities,
including designing and optimizing prompts for AI systems, ensuring prompt
quality and consistency, and collaborating with cross-functional teams.
""",
]
Expand Down
Loading
Loading