diff --git a/docs/llm.txt b/docs/llm.txt index 4f86dbdf..145c3b1e 100644 --- a/docs/llm.txt +++ b/docs/llm.txt @@ -10676,7 +10676,7 @@ from swarms import OpenAIAssistant assistant = OpenAIAssistant( name="Math Tutor", instructions="You are a helpful math tutor.", - model="gpt-4o", + model="gpt-4.1", tools=[{"type": "code_interpreter"}] ) @@ -10728,7 +10728,7 @@ assistant.add_function( OpenAIAssistant( name: str, instructions: Optional[str] = None, - model: str = "gpt-4o", + model: str = "gpt-4.1", tools: Optional[List[Dict[str, Any]]] = None, file_ids: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, @@ -11602,7 +11602,7 @@ consistency_agent = SelfConsistencyAgent( # Reasoning Duo for collaborative analysis workflows duo_agent = ReasoningDuo( - model_names=["gpt-4o-mini", "gpt-4o"] + model_names=["gpt-4o-mini", "gpt-4.1"] ) # Reflexion Agent for adaptive learning scenarios @@ -11667,7 +11667,7 @@ The ReasoningDuo class implements a dual-agent reasoning system that combines a |-----------|------|---------|-------------| | model_name | str | "reasoning-agent-01" | Name identifier for the reasoning agent | | description | str | "A highly intelligent..." | Description of the reasoning agent's capabilities | -| model_names | list[str] | ["gpt-4o-mini", "gpt-4o"] | Model names for reasoning and main agents | +| model_names | list[str] | ["gpt-4o-mini", "gpt-4.1"] | Model names for reasoning and main agents | | system_prompt | str | "You are a helpful..." | System prompt for the main agent | ### Methods @@ -11687,7 +11687,7 @@ from swarms.agents.reasoning_duo import ReasoningDuo # Initialize the ReasoningDuo duo = ReasoningDuo( model_name="reasoning-agent-01", - model_names=["gpt-4o-mini", "gpt-4o"] + model_names=["gpt-4o-mini", "gpt-4.1"] ) # Run a single task @@ -11753,7 +11753,7 @@ You can customize both agents by modifying their initialization parameters: duo = ReasoningDuo( model_name="custom-reasoning-agent", description="Specialized financial analysis agent", - model_names=["gpt-4o-mini", "gpt-4o"], + model_names=["gpt-4o-mini", "gpt-4.1"], system_prompt="You are a financial expert AI assistant..." ) ``` @@ -21096,7 +21096,7 @@ market_research_agent = Agent( - Industry report generation - Market opportunity identification - Risk assessment and mitigation strategies""", - model_name="gpt-4o", + model_name="gpt-4.1", ) financial_analyst_agent = Agent( @@ -21109,7 +21109,7 @@ financial_analyst_agent = Agent( - Financial modeling and forecasting - Risk assessment and portfolio analysis - ESG (Environmental, Social, Governance) analysis""", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the hierarchical swarm @@ -21144,7 +21144,7 @@ frontend_developer_agent = Agent( - State management (Redux, Zustand, Context API) - Web performance optimization - Accessibility (WCAG) and SEO best practices""", - model_name="gpt-4o", + model_name="gpt-4.1", ) backend_developer_agent = Agent( @@ -21157,7 +21157,7 @@ backend_developer_agent = Agent( - API design and REST/GraphQL implementation - Authentication and authorization systems - Microservices architecture and containerization""", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the development swarm @@ -21185,13 +21185,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm market_agent = Agent( agent_name="Market-Analyst", agent_description="Expert in market analysis and trends", - model_name="gpt-4o", + model_name="gpt-4.1", ) technical_agent = Agent( agent_name="Technical-Analyst", agent_description="Specialist in technical analysis and patterns", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the swarm @@ -21219,13 +21219,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm market_agent = Agent( agent_name="Market-Analyst", agent_description="Expert in market analysis and trends", - model_name="gpt-4o", + model_name="gpt-4.1", ) technical_agent = Agent( agent_name="Technical-Analyst", agent_description="Specialist in technical analysis and patterns", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the swarm @@ -21260,21 +21260,21 @@ research_manager = Agent( agent_name="Research-Manager", agent_description="Manages research operations and coordinates research tasks", system_prompt="You are a research manager responsible for overseeing research projects and coordinating research efforts.", - model_name="gpt-4o", + model_name="gpt-4.1", ) data_analyst = Agent( agent_name="Data-Analyst", agent_description="Analyzes data and generates insights", system_prompt="You are a data analyst specializing in processing and analyzing data to extract meaningful insights.", - model_name="gpt-4o", + model_name="gpt-4.1", ) research_assistant = Agent( agent_name="Research-Assistant", agent_description="Assists with research tasks and data collection", system_prompt="You are a research assistant who helps gather information and support research activities.", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the research swarm @@ -21875,7 +21875,7 @@ legal_expert = Agent( 3. Ensuring regulatory compliance 4. Providing legal recommendations 5. Drafting and reviewing legal documents""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -21887,7 +21887,7 @@ financial_expert = Agent( 3. Assessing financial risks 4. Providing financial projections 5. Recommending financial strategies""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -21899,7 +21899,7 @@ business_expert = Agent( 3. Assessing competitive advantages 4. Providing strategic recommendations 5. Planning business development""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -21912,7 +21912,7 @@ aggregator = Agent( 3. Prioritizing recommendations 4. Providing coherent final decisions 5. Ensuring comprehensive coverage of all aspects""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) ``` @@ -22020,7 +22020,7 @@ market_analyst = Agent( 3. Customer segments 4. Market trends 5. Entry barriers""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -22032,7 +22032,7 @@ financial_analyst = Agent( 3. Cash flow analysis 4. Investment requirements 5. ROI projections""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -22044,7 +22044,7 @@ risk_analyst = Agent( 3. Financial risks 4. Regulatory risks 5. Strategic risks""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -22057,7 +22057,7 @@ aggregator = Agent( 3. Evaluating trade-offs 4. Making recommendations 5. Providing action plans""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -22367,7 +22367,7 @@ research_agent = Agent( # Creative agent using GPT-4o for content generation creative_agent = Agent( agent_name="Creative-Agent", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="You are a creative content expert." ) @@ -22389,7 +22389,7 @@ from swarms import Agent, ModelRouter model_router = ModelRouter( models={ "analysis": "claude-3-sonnet-20240229", - "creative": "gpt-4o", + "creative": "gpt-4.1", "fast": "gpt-4o-mini", "local": "ollama/llama2" } @@ -22726,7 +22726,7 @@ agent = Agent( agent_description="Expert cryptocurrency financial analyst and market researcher", system_prompt=CRYPTO_ANALYST_SYSTEM_PROMPT, max_loops="auto", - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="crypto_analyst", output_type="str", @@ -22969,21 +22969,21 @@ from swarms.structs.swarm_router import SwarmRouter, SwarmType data_extractor_agent = Agent( agent_name="Data-Extractor", system_prompt="You are a data extraction specialist...", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) summarizer_agent = Agent( agent_name="Document-Summarizer", system_prompt="You are a document summarization expert...", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) financial_analyst_agent = Agent( agent_name="Financial-Analyst", system_prompt="You are a financial analysis specialist...", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) ``` @@ -23127,21 +23127,21 @@ from swarms.structs.swarm_router import SwarmRouter, SwarmType research_agent = Agent( agent_name="ResearchAgent", system_prompt="You are a research specialist...", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1 ) analysis_agent = Agent( agent_name="AnalysisAgent", system_prompt="You are an analysis expert...", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1 ) summary_agent = Agent( agent_name="SummaryAgent", system_prompt="You are a summarization specialist...", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1 ) @@ -23866,7 +23866,7 @@ class BrowserAgent: async def browser_agent_test(self, task: str): agent = Agent( task=task, - llm=ChatOpenAI(model="gpt-4o"), + llm=ChatOpenAI(model="gpt-4.1"), ) result = await agent.run() return result @@ -23920,7 +23920,7 @@ agent = Agent( agent_description="Personal finance advisor agent", system_prompt=FINANCIAL_AGENT_SYS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="swarms_corp", return_step_meta=False, @@ -23967,7 +23967,7 @@ agent = Agent( agent_description="Personal finance advisor agent", system_prompt=FINANCIAL_AGENT_SYS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="swarms_corp", retry_attempts=3, @@ -25696,7 +25696,7 @@ agent = Agent( agent_description="Personal finance advisor agent", system_prompt=FINANCIAL_AGENT_SYS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="swarms_corp", retry_attempts=3, @@ -27504,7 +27504,7 @@ A Pydantic model representing a delta update for messages in chat applications. A Pydantic model representing a request for chat completion. **Attributes**: -- `model` (`str`): The model to use for completing the chat (default is "gpt-4o"). +- `model` (`str`): The model to use for completing the chat (default is "gpt-4.1"). - `messages` (`List[ChatMessageInput]`): A list of input messages for the chat. @@ -30798,13 +30798,13 @@ board_members = [ research_agent = Agent( agent_name="Research-Specialist", agent_description="Expert in market research and analysis", - model_name="gpt-4o", + model_name="gpt-4.1", ) financial_agent = Agent( agent_name="Financial-Analyst", agent_description="Specialist in financial analysis and valuation", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the Board of Directors swarm @@ -30834,7 +30834,7 @@ print(result) market_research_agent = Agent( agent_name="Market-Research-Specialist", agent_description="Expert in market research, competitive analysis, and industry trends", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are a Market Research Specialist. Your responsibilities include: 1. Conducting comprehensive market research and analysis 2. Identifying market trends, opportunities, and risks @@ -30848,7 +30848,7 @@ You should be thorough, analytical, and objective in your research.""" financial_analyst_agent = Agent( agent_name="Financial-Analyst", agent_description="Specialist in financial analysis, valuation, and investment assessment", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are a Financial Analyst. Your responsibilities include: 1. Conducting financial analysis and valuation 2. Assessing investment opportunities and risks @@ -30862,7 +30862,7 @@ You should be financially astute, analytical, and focused on value creation.""" technical_assessor_agent = Agent( agent_name="Technical-Assessor", agent_description="Expert in technical feasibility and implementation assessment", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are a Technical Assessor. Your responsibilities include: 1. Evaluating technical feasibility and requirements 2. Assessing implementation challenges and risks @@ -30946,7 +30946,7 @@ print(json.dumps(result, indent=2)) tech_strategy_agent = Agent( agent_name="Tech-Strategy-Specialist", agent_description="Expert in technology strategy and digital transformation", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are a Technology Strategy Specialist. Your responsibilities include: 1. Developing technology roadmaps and strategies 2. Assessing digital transformation opportunities @@ -30960,7 +30960,7 @@ You should be strategic, forward-thinking, and technology-savvy.""" implementation_planner_agent = Agent( agent_name="Implementation-Planner", agent_description="Expert in implementation planning and project management", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are an Implementation Planner. Your responsibilities include: 1. Creating detailed implementation plans 2. Assessing resource requirements and timelines @@ -31010,7 +31010,7 @@ print(json.dumps(result, indent=2)) crisis_coordinator_agent = Agent( agent_name="Crisis-Coordinator", agent_description="Expert in crisis management and emergency response", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are a Crisis Coordinator. Your responsibilities include: 1. Coordinating crisis response efforts 2. Assessing crisis severity and impact @@ -31024,7 +31024,7 @@ You should be calm, decisive, and action-oriented.""" communications_specialist_agent = Agent( agent_name="Communications-Specialist", agent_description="Expert in crisis communications and stakeholder management", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are a Communications Specialist. Your responsibilities include: 1. Developing crisis communication strategies 2. Managing stakeholder communications @@ -32847,7 +32847,7 @@ agent = Agent( output_type="json", # LLM Configuration - model_name="gpt-4o", + model_name="gpt-4.1", temperature=0.3, max_tokens=8000, top_p=0.95, @@ -35440,7 +35440,7 @@ graph TD | description | str | "This is a swarm that creates swarms" | A description of the swarm's purpose | | verbose | bool | True | Whether to output detailed logs | | max_loops | int | 1 | Maximum number of execution loops | -| model_name | str | "gpt-4o" | The model to use for agent creation | +| model_name | str | "gpt-4.1" | The model to use for agent creation | | return_dictionary | bool | True | Whether to return results as a dictionary | | system_prompt | str | BOSS_SYSTEM_PROMPT | The system prompt for the boss agent | @@ -35450,7 +35450,7 @@ graph TD |--------|-------------|------------|---------| | run | Run the swarm on a given task | task: str, image_url: str = None, *args, **kwargs | Tuple[List[Agent], int] | | _create_agents | Create necessary agents for a task | task: str, *args, **kwargs | List[Agent] | -| build_agent | Build a single agent with specifications | agent_name: str, agent_description: str, agent_system_prompt: str, max_loops: int = 1, model_name: str = "gpt-4o", dynamic_temperature_enabled: bool = True, auto_generate_prompt: bool = False, role: str = "worker", max_tokens: int = 8192, temperature: float = 0.5 | Agent | +| build_agent | Build a single agent with specifications | agent_name: str, agent_description: str, agent_system_prompt: str, max_loops: int = 1, model_name: str = "gpt-4.1", dynamic_temperature_enabled: bool = True, auto_generate_prompt: bool = False, role: str = "worker", max_tokens: int = 8192, temperature: float = 0.5 | Agent | ## Enterprise Use Cases @@ -41114,7 +41114,7 @@ result = swarm.run("Develop a go-to-market strategy for a new SaaS product") # Market Analysis swarm = HeavySwarm( name="FinanceSwarm", - worker_model_name="gpt-4o", + worker_model_name="gpt-4.1", show_dashboard=True ) @@ -41147,7 +41147,7 @@ Analyze the impact of recent Federal Reserve policy changes on: # Clinical Research Analysis swarm = HeavySwarm( name="HealthcareSwarm", - worker_model_name="gpt-4o", + worker_model_name="gpt-4.1", timeout=600, loops_per_agent=2 ) @@ -41182,7 +41182,7 @@ Evaluate the potential of AI-driven personalized medicine: # Tech Strategy Analysis swarm = HeavySwarm( name="TechSwarm", - worker_model_name="gpt-4o", + worker_model_name="gpt-4.1", show_dashboard=True, verbose=True ) @@ -41212,7 +41212,7 @@ Assess the strategic implications of quantum computing adoption: # Supply Chain Optimization swarm = HeavySwarm( name="ManufacturingSwarm", - worker_model_name="gpt-4o", + worker_model_name="gpt-4.1", max_workers=8 ) @@ -41243,8 +41243,8 @@ Optimize global supply chain resilience: # High-performance configuration swarm = HeavySwarm( name="HighPerformanceSwarm", - question_agent_model_name="gpt-4o", - worker_model_name="gpt-4o", + question_agent_model_name="gpt-4.1", + worker_model_name="gpt-4.1", timeout=900, loops_per_agent=3, max_workers=12, @@ -41794,13 +41794,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm research_agent = Agent( agent_name="Research-Specialist", agent_description="Expert in market research and analysis", - model_name="gpt-4o", + model_name="gpt-4.1", ) financial_agent = Agent( agent_name="Financial-Analyst", agent_description="Specialist in financial analysis and valuation", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the hierarchical swarm @@ -41847,13 +41847,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm frontend_agent = Agent( agent_name="Frontend-Developer", agent_description="Expert in React and modern web development", - model_name="gpt-4o", + model_name="gpt-4.1", ) backend_agent = Agent( agent_name="Backend-Developer", agent_description="Specialist in Node.js and API development", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the swarm @@ -41900,13 +41900,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm market_agent = Agent( agent_name="Market-Analyst", agent_description="Expert in market analysis and trends", - model_name="gpt-4o", + model_name="gpt-4.1", ) technical_agent = Agent( agent_name="Technical-Analyst", agent_description="Specialist in technical analysis and patterns", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the swarm @@ -42398,12 +42398,12 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm research_agent = Agent( agent_name="Research-Specialist", agent_description="Expert in market research and analysis", - model_name="gpt-4o", + model_name="gpt-4.1", ) financial_agent = Agent( agent_name="Financial-Analyst", agent_description="Specialist in financial analysis and valuation", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the hierarchical swarm @@ -43722,21 +43722,21 @@ agents = [ agent_description="Personal finance advisor focused on market analysis", system_prompt="You are a financial advisor specializing in market analysis and investment opportunities.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="Risk-Assessment-Agent", agent_description="Risk analysis and portfolio management expert", system_prompt="You are a risk assessment expert focused on evaluating investment risks and portfolio diversification.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="Tech-Investment-Agent", agent_description="Technology sector investment specialist", system_prompt="You are a technology investment specialist focused on AI, emerging tech, and growth opportunities.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ) ] @@ -43746,7 +43746,7 @@ consensus_agent = Agent( agent_description="Consensus agent focused on analyzing investment advice", system_prompt="You are a consensus agent focused on analyzing investment advice and providing a final answer.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ) # Create majority voting system @@ -43780,21 +43780,21 @@ agents = [ agent_description="Personal finance advisor focused on market analysis", system_prompt="You are a financial advisor specializing in market analysis and investment opportunities.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="Risk-Assessment-Agent", agent_description="Risk analysis and portfolio management expert", system_prompt="You are a risk assessment expert focused on evaluating investment risks and portfolio diversification.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="Tech-Investment-Agent", agent_description="Technology sector investment specialist", system_prompt="You are a technology investment specialist focused on AI, emerging tech, and growth opportunities.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ) ] @@ -43804,7 +43804,7 @@ consensus_agent = Agent( agent_description="Consensus agent focused on analyzing investment advice", system_prompt="You are a consensus agent focused on analyzing investment advice and providing a final answer.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ) # Create majority voting system @@ -45551,7 +45551,7 @@ healthcare_router = MultiAgentRouter( name="Healthcare-Router", description="Routes medical and healthcare-related tasks to specialized agents", agents=agents, - model="gpt-4o", + model="gpt-4.1", temperature=0.1 ) @@ -46954,19 +46954,19 @@ from swarms import Agent, SequentialWorkflow agent1 = Agent( agent_name="ICD-10 Code Analyzer", system_prompt="Analyze medical data and provide relevant ICD-10 codes.", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) agent2 = Agent( agent_name="ICD-10 Code Summarizer", system_prompt="Summarize the findings and suggest ICD-10 codes.", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) agent3 = Agent( agent_name="ICD-10 Code Validator", system_prompt="Validate and finalize the ICD-10 code recommendations.", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -49643,8 +49643,8 @@ Runs the swarm by having agents pick up tasks from the queue. # Initialize agents - agent1 = Agent(agent_name="Agent1", model_name="gpt-4o") - agent2 = Agent(agent_name="Agent2", model_name="gpt-4o") + agent1 = Agent(agent_name="Agent1", model_name="gpt-4.1") + agent2 = Agent(agent_name="Agent2", model_name="gpt-4.1") # Create the TaskQueueSwarm swarm = TaskQueueSwarm(agents=[agent1, agent2], max_loops=5) @@ -51630,7 +51630,7 @@ agent = Agent( "clear, accurate financial insights and recommendations. Always format " "responses in markdown for better readability." ), - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=3, autosave=True, dashboard=False, @@ -51815,7 +51815,7 @@ agent = Agent( "data and provide comprehensive financial insights. Always present data " "in a clear, professional format with actionable recommendations." ), - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=3, autosave=True, dashboard=False, @@ -54542,7 +54542,7 @@ agent_config = { "and present findings in a clear, structured format. " "Focus on accuracy, clarity, and actionable recommendations." ), - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 2, "max_tokens": 8192, @@ -54623,7 +54623,7 @@ batch_completions = [ "agent_name": "Research Analyst", "description": "An expert in analyzing research data", "system_prompt": "You are a Research Analyst...", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 2 }, "task": "Analyze the impact of AI on healthcare delivery." @@ -54633,7 +54633,7 @@ batch_completions = [ "agent_name": "Market Analyst", "description": "An expert in market analysis", "system_prompt": "You are a Market Analyst...", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1 }, "task": "Analyze the AI startup landscape in 2025." @@ -55086,7 +55086,7 @@ Key features: "agent_name": "Document Analyzer", "description": "Analyzes document content and structure", "system_prompt": "You are an expert document analyst. Extract key information, themes, and insights from documents.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -55094,7 +55094,7 @@ Key features: "agent_name": "Legal Expert", "description": "Provides legal context and interpretation", "system_prompt": "You are a legal expert. Analyze documents for legal implications, risks, and compliance issues.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.2 }, @@ -55102,7 +55102,7 @@ Key features: "agent_name": "Summarizer", "description": "Creates concise summaries and action items", "system_prompt": "You are an expert at creating clear, actionable summaries from complex information.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.4 } @@ -55135,7 +55135,7 @@ Key features: "agent_name": "Document Analyzer", "description": "Analyzes document content and structure", "system_prompt": "You are an expert document analyst. Extract key information, themes, and insights from documents.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -55143,7 +55143,7 @@ Key features: "agent_name": "Legal Expert", "description": "Provides legal context and interpretation", "system_prompt": "You are a legal expert. Analyze documents for legal implications, risks, and compliance issues.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.2 }, @@ -55151,7 +55151,7 @@ Key features: "agent_name": "Summarizer", "description": "Creates concise summaries and action items", "system_prompt": "You are an expert at creating clear, actionable summaries from complex information.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.4 } @@ -56776,7 +56776,7 @@ Key features: "agent_name": "AI Market Analyst", "description": "Analyzes AI market trends and opportunities", "system_prompt": "You are an AI market analyst. Focus on artificial intelligence market trends, opportunities, key players, and growth projections.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -56784,7 +56784,7 @@ Key features: "agent_name": "Healthcare Market Analyst", "description": "Analyzes healthcare market trends", "system_prompt": "You are a healthcare market analyst. Focus on healthcare market trends, digital health opportunities, regulatory landscape, and growth areas.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -56792,7 +56792,7 @@ Key features: "agent_name": "Fintech Market Analyst", "description": "Analyzes fintech market opportunities", "system_prompt": "You are a fintech market analyst. Focus on financial technology trends, digital payment systems, blockchain opportunities, and regulatory developments.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -56800,7 +56800,7 @@ Key features: "agent_name": "E-commerce Market Analyst", "description": "Analyzes e-commerce market trends", "system_prompt": "You are an e-commerce market analyst. Focus on online retail trends, marketplace opportunities, consumer behavior, and emerging platforms.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 } @@ -56832,7 +56832,7 @@ Key features: "agent_name": "AI Market Analyst", "description": "Analyzes AI market trends and opportunities", "system_prompt": "You are an AI market analyst. Focus on artificial intelligence market trends, opportunities, key players, and growth projections.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -56840,7 +56840,7 @@ Key features: "agent_name": "Healthcare Market Analyst", "description": "Analyzes healthcare market trends", "system_prompt": "You are a healthcare market analyst. Focus on healthcare market trends, digital health opportunities, regulatory landscape, and growth areas.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -56848,7 +56848,7 @@ Key features: "agent_name": "Fintech Market Analyst", "description": "Analyzes fintech market opportunities", "system_prompt": "You are a fintech market analyst. Focus on financial technology trends, digital payment systems, blockchain opportunities, and regulatory developments.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -56856,7 +56856,7 @@ Key features: "agent_name": "E-commerce Market Analyst", "description": "Analyzes e-commerce market trends", "system_prompt": "You are an e-commerce market analyst. Focus on online retail trends, marketplace opportunities, consumer behavior, and emerging platforms.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 } @@ -56995,28 +56995,28 @@ Key features: "agent_name": "Product Manager", "description": "Leads product strategy and development", "system_prompt": "You are a senior product manager. Focus on product positioning, features, user needs, and market fit. Ask probing questions and build on others ideas.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 3, }, { "agent_name": "Marketing Strategist", "description": "Develops marketing and positioning strategy", "system_prompt": "You are a marketing strategist. Focus on target audience, messaging, channels, and competitive positioning. Contribute marketing insights to the discussion.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 3, }, { "agent_name": "Sales Director", "description": "Provides sales and customer perspective", "system_prompt": "You are a sales director with small business experience. Focus on pricing, sales process, customer objections, and market adoption. Share practical sales insights.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 3, }, { "agent_name": "UX Researcher", "description": "Represents user experience and research insights", "system_prompt": "You are a UX researcher specializing in small business tools. Focus on user behavior, usability, adoption barriers, and design considerations.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 3, } ], @@ -57047,28 +57047,28 @@ Key features: "agent_name": "Product Manager", "description": "Leads product strategy and development", "system_prompt": "You are a senior product manager. Focus on product positioning, features, user needs, and market fit. Ask probing questions and build on others ideas.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 3, }, { "agent_name": "Marketing Strategist", "description": "Develops marketing and positioning strategy", "system_prompt": "You are a marketing strategist. Focus on target audience, messaging, channels, and competitive positioning. Contribute marketing insights to the discussion.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 3, }, { "agent_name": "Sales Director", "description": "Provides sales and customer perspective", "system_prompt": "You are a sales director with small business experience. Focus on pricing, sales process, customer objections, and market adoption. Share practical sales insights.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 3, }, { "agent_name": "UX Researcher", "description": "Represents user experience and research insights", "system_prompt": "You are a UX researcher specializing in small business tools. Focus on user behavior, usability, adoption barriers, and design considerations.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 3, } ], @@ -57189,7 +57189,7 @@ Key features: "agent_name": "AI Market Analyst", "description": "Analyzes AI market trends and opportunities", "system_prompt": "You are an AI market analyst. Focus on artificial intelligence market trends, opportunities, key players, and growth projections.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -57197,7 +57197,7 @@ Key features: "agent_name": "Healthcare Market Analyst", "description": "Analyzes healthcare market trends", "system_prompt": "You are a healthcare market analyst. Focus on healthcare market trends, digital health opportunities, regulatory landscape, and growth areas.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -57205,7 +57205,7 @@ Key features: "agent_name": "Fintech Market Analyst", "description": "Analyzes fintech market opportunities", "system_prompt": "You are a fintech market analyst. Focus on financial technology trends, digital payment systems, blockchain opportunities, and regulatory developments.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -57213,7 +57213,7 @@ Key features: "agent_name": "E-commerce Market Analyst", "description": "Analyzes e-commerce market trends", "system_prompt": "You are an e-commerce market analyst. Focus on online retail trends, marketplace opportunities, consumer behavior, and emerging platforms.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 } @@ -57245,7 +57245,7 @@ Key features: "agent_name": "AI Market Analyst", "description": "Analyzes AI market trends and opportunities", "system_prompt": "You are an AI market analyst. Focus on artificial intelligence market trends, opportunities, key players, and growth projections.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -57253,7 +57253,7 @@ Key features: "agent_name": "Healthcare Market Analyst", "description": "Analyzes healthcare market trends", "system_prompt": "You are a healthcare market analyst. Focus on healthcare market trends, digital health opportunities, regulatory landscape, and growth areas.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -57261,7 +57261,7 @@ Key features: "agent_name": "Fintech Market Analyst", "description": "Analyzes fintech market opportunities", "system_prompt": "You are a fintech market analyst. Focus on financial technology trends, digital payment systems, blockchain opportunities, and regulatory developments.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -57269,7 +57269,7 @@ Key features: "agent_name": "E-commerce Market Analyst", "description": "Analyzes e-commerce market trends", "system_prompt": "You are an e-commerce market analyst. Focus on online retail trends, marketplace opportunities, consumer behavior, and emerging platforms.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 } @@ -57826,7 +57826,7 @@ Key features: "agent_name": "Growth Investor", "description": "Focuses on growth potential and market opportunity", "system_prompt": "You are a growth-focused venture capitalist. Evaluate investments based on market size, scalability, and growth potential. Provide a recommendation with confidence score.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -57834,7 +57834,7 @@ Key features: "agent_name": "Financial Analyst", "description": "Analyzes financial metrics and projections", "system_prompt": "You are a financial analyst specializing in startups. Evaluate financial projections, revenue models, and unit economics. Provide a recommendation with confidence score.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.2 }, @@ -57842,7 +57842,7 @@ Key features: "agent_name": "Technical Due Diligence", "description": "Evaluates technology and product viability", "system_prompt": "You are a technical due diligence expert. Assess technology viability, intellectual property, product-market fit, and technical risks. Provide a recommendation with confidence score.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -57850,7 +57850,7 @@ Key features: "agent_name": "Market Analyst", "description": "Analyzes market conditions and competition", "system_prompt": "You are a market research analyst. Evaluate market dynamics, competitive landscape, regulatory environment, and market timing. Provide a recommendation with confidence score.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -57858,7 +57858,7 @@ Key features: "agent_name": "Risk Assessor", "description": "Identifies and evaluates investment risks", "system_prompt": "You are a risk assessment specialist. Identify potential risks, evaluate mitigation strategies, and assess overall risk profile. Provide a recommendation with confidence score.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.2 } @@ -57890,7 +57890,7 @@ Key features: "agent_name": "Growth Investor", "description": "Focuses on growth potential and market opportunity", "system_prompt": "You are a growth-focused venture capitalist. Evaluate investments based on market size, scalability, and growth potential. Provide a recommendation with confidence score.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -57898,7 +57898,7 @@ Key features: "agent_name": "Financial Analyst", "description": "Analyzes financial metrics and projections", "system_prompt": "You are a financial analyst specializing in startups. Evaluate financial projections, revenue models, and unit economics. Provide a recommendation with confidence score.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.2 }, @@ -57906,7 +57906,7 @@ Key features: "agent_name": "Technical Due Diligence", "description": "Evaluates technology and product viability", "system_prompt": "You are a technical due diligence expert. Assess technology viability, intellectual property, product-market fit, and technical risks. Provide a recommendation with confidence score.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -57914,7 +57914,7 @@ Key features: "agent_name": "Market Analyst", "description": "Analyzes market conditions and competition", "system_prompt": "You are a market research analyst. Evaluate market dynamics, competitive landscape, regulatory environment, and market timing. Provide a recommendation with confidence score.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -57922,7 +57922,7 @@ Key features: "agent_name": "Risk Assessor", "description": "Identifies and evaluates investment risks", "system_prompt": "You are a risk assessment specialist. Identify potential risks, evaluate mitigation strategies, and assess overall risk profile. Provide a recommendation with confidence score.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.2 } @@ -58322,7 +58322,7 @@ swarm_config = { "agent_name": "Data Analyzer", "description": "Looks at financial data", "system_prompt": "Analyze the data.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 1000, @@ -58333,7 +58333,7 @@ swarm_config = { "agent_name": "Risk Analyst", "description": "Checks risk levels", "system_prompt": "Evaluate the risks.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 1000, @@ -58344,7 +58344,7 @@ swarm_config = { "agent_name": "Strategy Checker", "description": "Validates strategies", "system_prompt": "Review the strategy.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 1000, @@ -59187,7 +59187,7 @@ Key features: "agent_name": "Market Research Analyst", "description": "Analyzes market trends and opportunities", "system_prompt": "You are a market research expert specializing in healthcare technology. Analyze market size, trends, and competitive landscape.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -59195,7 +59195,7 @@ Key features: "agent_name": "Financial Analyst", "description": "Evaluates financial viability and projections", "system_prompt": "You are a financial analyst expert. Assess financial implications, ROI, and cost structures for business strategies.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.2 }, @@ -59203,7 +59203,7 @@ Key features: "agent_name": "Regulatory Expert", "description": "Analyzes compliance and regulatory requirements", "system_prompt": "You are a healthcare regulatory expert. Analyze compliance requirements, regulatory pathways, and potential barriers.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.1 }, @@ -59211,7 +59211,7 @@ Key features: "agent_name": "Technology Strategist", "description": "Evaluates technical feasibility and strategy", "system_prompt": "You are a technology strategy expert. Assess technical requirements, implementation challenges, and scalability.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 } @@ -59243,7 +59243,7 @@ Key features: "agent_name": "Market Research Analyst", "description": "Analyzes market trends and opportunities", "system_prompt": "You are a market research expert specializing in healthcare technology. Analyze market size, trends, and competitive landscape.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -59251,7 +59251,7 @@ Key features: "agent_name": "Financial Analyst", "description": "Evaluates financial viability and projections", "system_prompt": "You are a financial analyst expert. Assess financial implications, ROI, and cost structures for business strategies.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.2 }, @@ -59259,7 +59259,7 @@ Key features: "agent_name": "Regulatory Expert", "description": "Analyzes compliance and regulatory requirements", "system_prompt": "You are a healthcare regulatory expert. Analyze compliance requirements, regulatory pathways, and potential barriers.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.1 }, @@ -59267,7 +59267,7 @@ Key features: "agent_name": "Technology Strategist", "description": "Evaluates technical feasibility and strategy", "system_prompt": "You are a technology strategy expert. Assess technical requirements, implementation challenges, and scalability.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 } @@ -59414,7 +59414,7 @@ Key features: "agent_name": "Billing Specialist", "description": "Handles billing, payments, and account issues", "system_prompt": "You are a billing specialist. Handle all billing inquiries, payment issues, refunds, and account-related questions with empathy and accuracy.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -59422,7 +59422,7 @@ Key features: "agent_name": "Technical Support", "description": "Resolves technical issues and troubleshooting", "system_prompt": "You are a technical support specialist. Diagnose and resolve technical issues, provide step-by-step troubleshooting, and escalate complex problems.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.2 }, @@ -59430,7 +59430,7 @@ Key features: "agent_name": "Sales Consultant", "description": "Provides product recommendations and sales support", "system_prompt": "You are a sales consultant. Provide product recommendations, explain features and benefits, and help customers find the right solutions.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.4 }, @@ -59438,7 +59438,7 @@ Key features: "agent_name": "Policy Advisor", "description": "Explains company policies and procedures", "system_prompt": "You are a policy advisor. Explain company policies, terms of service, return procedures, and compliance requirements clearly.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.1 } @@ -59470,7 +59470,7 @@ Key features: "agent_name": "Billing Specialist", "description": "Handles billing, payments, and account issues", "system_prompt": "You are a billing specialist. Handle all billing inquiries, payment issues, refunds, and account-related questions with empathy and accuracy.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -59478,7 +59478,7 @@ Key features: "agent_name": "Technical Support", "description": "Resolves technical issues and troubleshooting", "system_prompt": "You are a technical support specialist. Diagnose and resolve technical issues, provide step-by-step troubleshooting, and escalate complex problems.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.2 }, @@ -59486,7 +59486,7 @@ Key features: "agent_name": "Sales Consultant", "description": "Provides product recommendations and sales support", "system_prompt": "You are a sales consultant. Provide product recommendations, explain features and benefits, and help customers find the right solutions.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.4 }, @@ -59494,7 +59494,7 @@ Key features: "agent_name": "Policy Advisor", "description": "Explains company policies and procedures", "system_prompt": "You are a policy advisor. Explain company policies, terms of service, return procedures, and compliance requirements clearly.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.1 } @@ -60082,7 +60082,7 @@ response = client.agent.create( agent_config={ "agent_name": "Researcher", "description": "Conducts in-depth research on topics", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "temperature": 0.7 }, task="Research the latest advancements in quantum computing and summarize the key findings" @@ -60146,7 +60146,7 @@ responses = client.agent.create_batch([ { "agent_config": { "agent_name": "Writer", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "temperature": 0.7 }, "task": "Write a blog post about AI safety" @@ -60186,7 +60186,7 @@ async def main(): agent_config={ "agent_name": "Researcher", "description": "Conducts in-depth research", - "model_name": "gpt-4o" + "model_name": "gpt-4.1" }, task="Research the impact of quantum computing on cryptography" ) @@ -60227,7 +60227,7 @@ async def main(): { "agent_config": { "agent_name": "Writer", - "model_name": "gpt-4o" + "model_name": "gpt-4.1" }, "task": "Write a blog post about AI safety" } @@ -60268,7 +60268,7 @@ response = client.swarm.create( { "agent_name": "Researcher", "description": "Conducts in-depth research", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "temperature": 0.5 }, { @@ -60332,7 +60332,7 @@ responses = client.swarm.create_batch([ "swarm_type": "auto", "task": "Research quantum computing advances", "agents": [ - {"agent_name": "Researcher", "model_name": "gpt-4o"} + {"agent_name": "Researcher", "model_name": "gpt-4.1"} ] }, { @@ -60340,7 +60340,7 @@ responses = client.swarm.create_batch([ "swarm_type": "SequentialWorkflow", "task": "Write a blog post about AI safety", "agents": [ - {"agent_name": "Writer", "model_name": "gpt-4o"}, + {"agent_name": "Writer", "model_name": "gpt-4.1"}, {"agent_name": "Editor", "model_name": "gpt-4o-mini"} ] } @@ -60428,7 +60428,7 @@ async def main(): { "agent_name": "Researcher", "description": "Conducts in-depth research", - "model_name": "gpt-4o" + "model_name": "gpt-4.1" }, { "agent_name": "Critic", @@ -60470,7 +60470,7 @@ async def main(): "swarm_type": "auto", "task": "Research quantum computing", "agents": [ - {"agent_name": "Researcher", "model_name": "gpt-4o"} + {"agent_name": "Researcher", "model_name": "gpt-4.1"} ] }, { @@ -60478,7 +60478,7 @@ async def main(): "swarm_type": "SequentialWorkflow", "task": "Write a blog post about AI safety", "agents": [ - {"agent_name": "Writer", "model_name": "gpt-4o"} + {"agent_name": "Writer", "model_name": "gpt-4.1"} ] } ]) @@ -60617,7 +60617,7 @@ from swarms_client import SwarmsClient, SwarmsError, AuthenticationError, RateLi try: client = SwarmsClient(api_key="invalid-api-key") response = client.agent.create( - agent_config={"agent_name": "Researcher", "model_name": "gpt-4o"}, + agent_config={"agent_name": "Researcher", "model_name": "gpt-4.1"}, task="Research quantum computing" ) except AuthenticationError as e: @@ -60706,7 +60706,7 @@ try: researcher = { "agent_name": "Researcher", "description": "Conducts thorough research on specified topics", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "temperature": 0.5, "system_prompt": "You are a diligent researcher focused on finding accurate and comprehensive information." } @@ -60714,7 +60714,7 @@ try: analyst = { "agent_name": "Analyst", "description": "Analyzes research findings and identifies key insights", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "temperature": 0.3, "system_prompt": "You are an insightful analyst who can identify patterns and extract meaningful insights from research data." } @@ -61187,7 +61187,7 @@ The API is accessible through two base URLs: "agent_name": "Market Analyst", # (1) "description": "Analyzes market trends", "system_prompt": "You are a financial analyst expert.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, @@ -61198,7 +61198,7 @@ The API is accessible through two base URLs: "agent_name": "Economic Forecaster", # (2) "description": "Predicts economic trends", "system_prompt": "You are an expert in economic forecasting.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, @@ -61237,7 +61237,7 @@ The API is accessible through two base URLs: "agent_name": "Market Analyst", "description": "Analyzes market trends", "system_prompt": "You are a financial analyst expert.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, @@ -61248,7 +61248,7 @@ The API is accessible through two base URLs: "agent_name": "Economic Forecaster", "description": "Predicts economic trends", "system_prompt": "You are an expert in economic forecasting.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, @@ -61295,7 +61295,7 @@ The API is accessible through two base URLs: agent_name: "Market Analyst", description: "Analyzes market trends", system_prompt: "You are a financial analyst expert.", - model_name: "gpt-4o", + model_name: "gpt-4.1", role: "worker", max_loops: 1, max_tokens: 8192, @@ -61306,7 +61306,7 @@ The API is accessible through two base URLs: agent_name: "Economic Forecaster", description: "Predicts economic trends", system_prompt: "You are an expert in economic forecasting.", - model_name: "gpt-4o", + model_name: "gpt-4.1", role: "worker", max_loops: 1, max_tokens: 8192, @@ -62193,7 +62193,7 @@ async fn main() -> Result<(), Box> { agent .name("Researcher") .description("Conducts in-depth research") - .model("gpt-4o") + .model("gpt-4.1") }) .send() .await?; @@ -62395,7 +62395,7 @@ async fn main() -> Result<(), Box> { .completion() .agent_name("Content Writer") .task("Write a blog post about sustainable technology") - .model("gpt-4o") + .model("gpt-4.1") .temperature(0.7) .max_tokens(2000) .description("An expert content writer specializing in technology topics") @@ -62435,7 +62435,7 @@ async fn main() -> Result<(), Box> { agent .name("Data Collector") .description("Gathers comprehensive data and recent developments") - .model("gpt-4o") + .model("gpt-4.1") .system_prompt("You are a research data collector specializing in AI and healthcare. Your job is to gather the most recent and relevant information about AI applications in healthcare, including clinical trials, FDA approvals, and industry developments.") .temperature(0.3) .max_tokens(3000) @@ -62446,7 +62446,7 @@ async fn main() -> Result<(), Box> { agent .name("Technical Analyst") .description("Analyzes technical aspects and implementation details") - .model("gpt-4o") + .model("gpt-4.1") .system_prompt("You are a technical analyst with deep expertise in AI/ML technologies. Analyze the technical feasibility, implementation challenges, and technological requirements of AI solutions in healthcare.") .temperature(0.4) .max_tokens(3000) @@ -62457,7 +62457,7 @@ async fn main() -> Result<(), Box> { agent .name("Market Analyst") .description("Analyzes market trends, adoption rates, and economic factors") - .model("gpt-4o") + .model("gpt-4.1") .system_prompt("You are a market research analyst specializing in healthcare technology markets. Analyze market size, growth projections, key players, investment trends, and economic factors affecting AI adoption in healthcare.") .temperature(0.5) .max_tokens(3000) @@ -62468,7 +62468,7 @@ async fn main() -> Result<(), Box> { agent .name("Regulatory Expert") .description("Analyzes regulatory landscape and compliance requirements") - .model("gpt-4o") + .model("gpt-4.1") .system_prompt("You are a regulatory affairs expert with deep knowledge of healthcare regulations and AI governance. Analyze regulatory challenges, compliance requirements, ethical considerations, and policy developments affecting AI in healthcare.") .temperature(0.3) .max_tokens(3000) @@ -62479,7 +62479,7 @@ async fn main() -> Result<(), Box> { agent .name("Report Synthesizer") .description("Synthesizes all analyses into a comprehensive report") - .model("gpt-4o") + .model("gpt-4.1") .system_prompt("You are an expert report writer and strategic analyst. Synthesize all the previous analyses into a comprehensive, well-structured executive report with clear insights, recommendations, and future outlook.") .temperature(0.6) .max_tokens(4000) @@ -62524,7 +62524,7 @@ async fn main() -> Result<(), Box> { agent .name("Financial Data Collector") .description("Specializes in gathering and organizing financial data from various sources") - .model("gpt-4o") + .model("gpt-4.1") .system_prompt("You are a financial data collection specialist. Your role is to gather and organize relevant financial data, including revenue, expenses, profit margins, and key financial ratios. Present the data in a clear, structured format.") .temperature(0.7) .max_tokens(2000) @@ -62535,7 +62535,7 @@ async fn main() -> Result<(), Box> { agent .name("Ratio Analyzer") .description("Analyzes key financial ratios and metrics") - .model("gpt-4o") + .model("gpt-4.1") .system_prompt("You are a financial ratio analysis expert. Your role is to calculate and interpret key financial ratios such as P/E ratio, debt-to-equity, current ratio, and return on equity. Provide insights on what these ratios indicate about the company's financial health.") .temperature(0.7) .max_tokens(2000) @@ -62546,7 +62546,7 @@ async fn main() -> Result<(), Box> { agent .name("Investment Advisor") .description("Provides investment recommendations based on analysis") - .model("gpt-4o") + .model("gpt-4.1") .system_prompt("You are an investment advisory specialist. Your role is to synthesize the analysis from previous agents and provide clear, actionable investment recommendations. Consider both short-term and long-term investment perspectives.") .temperature(0.7) .max_tokens(2000) @@ -62651,7 +62651,7 @@ async fn main() -> Result<(), Box> { .agent(|agent| { agent .name("Market Analyst") - .model("gpt-4o") + .model("gpt-4.1") .temperature(0.5) }) .send() @@ -62920,7 +62920,7 @@ Key features: "agent_name": "Research Specialist", "description": "Conducts thorough research on the topic", "system_prompt": "You are a research specialist. Gather comprehensive, accurate information on the given topic from reliable sources.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -62928,7 +62928,7 @@ Key features: "agent_name": "Content Writer", "description": "Creates engaging written content", "system_prompt": "You are a skilled content writer. Transform research into engaging, well-structured articles that are informative and readable.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.6 }, @@ -62936,7 +62936,7 @@ Key features: "agent_name": "Editor", "description": "Reviews and polishes the content", "system_prompt": "You are a professional editor. Review content for clarity, grammar, flow, and overall quality. Make improvements while maintaining the author's voice.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.4 }, @@ -62944,7 +62944,7 @@ Key features: "agent_name": "SEO Optimizer", "description": "Optimizes content for search engines", "system_prompt": "You are an SEO expert. Optimize content for search engines while maintaining readability and quality.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.2 } @@ -62976,7 +62976,7 @@ Key features: "agent_name": "Research Specialist", "description": "Conducts thorough research on the topic", "system_prompt": "You are a research specialist. Gather comprehensive, accurate information on the given topic from reliable sources.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.3 }, @@ -62984,7 +62984,7 @@ Key features: "agent_name": "Content Writer", "description": "Creates engaging written content", "system_prompt": "You are a skilled content writer. Transform research into engaging, well-structured articles that are informative and readable.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.6 }, @@ -62992,7 +62992,7 @@ Key features: "agent_name": "Editor", "description": "Reviews and polishes the content", "system_prompt": "You are a professional editor. Review content for clarity, grammar, flow, and overall quality. Make improvements while maintaining the author's voice.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.4 }, @@ -63000,7 +63000,7 @@ Key features: "agent_name": "SEO Optimizer", "description": "Optimizes content for search engines", "system_prompt": "You are an SEO expert. Optimize content for search engines while maintaining readability and quality.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "temperature": 0.2 } @@ -63369,7 +63369,7 @@ The `AgentSpec` model defines the configuration of an individual agent. | agent_name | string | Unique name for the agent | Yes* | | description | string | Description of the agent's purpose | No | | system_prompt | string | Instructions for the agent | No | -| model_name | string | AI model to use (e.g., "gpt-4o") | Yes* | +| model_name | string | AI model to use (e.g., "gpt-4.1") | Yes* | | auto_generate_prompt | boolean | Whether to auto-generate prompts | No | | max_tokens | integer | Maximum tokens in response | No | | temperature | float | Randomness of responses (0-1) | No | @@ -63496,7 +63496,7 @@ Run a swarm with the specified configuration to complete a task. "agent_name": "Economic Forecaster", "description": "Predicts economic trends", "system_prompt": "You are an expert in economic forecasting.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, @@ -63543,7 +63543,7 @@ Run a swarm with the specified configuration to complete a task. "agent_name": "Economic Forecaster", "description": "Predicts economic trends", "system_prompt": "You are an expert in economic forecasting.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, @@ -63619,7 +63619,7 @@ Run a swarm with the specified configuration to complete a task. agent_name: "Economic Forecaster", description: "Predicts economic trends", system_prompt: "You are an expert in economic forecasting.", - model_name: "gpt-4o", + model_name: "gpt-4.1", role: "worker", max_loops: 1, max_tokens: 8192, @@ -63727,7 +63727,7 @@ Run multiple swarms as a batch operation. "agent_name": "Research Agent", "description": "Conducts research", "system_prompt": "You are a research assistant.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1 }, @@ -63735,7 +63735,7 @@ Run multiple swarms as a batch operation. "agent_name": "Analysis Agent", "description": "Analyzes data", "system_prompt": "You are a data analyst.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1 } @@ -63752,7 +63752,7 @@ Run multiple swarms as a batch operation. "agent_name": "Writing Agent", "description": "Writes content", "system_prompt": "You are a content writer.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1 }, @@ -63760,7 +63760,7 @@ Run multiple swarms as a batch operation. "agent_name": "Editing Agent", "description": "Edits content", "system_prompt": "You are an editor.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1 } @@ -63794,7 +63794,7 @@ Run multiple swarms as a batch operation. "agent_name": "Research Agent", "description": "Conducts research", "system_prompt": "You are a research assistant.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1 }, @@ -63802,7 +63802,7 @@ Run multiple swarms as a batch operation. "agent_name": "Analysis Agent", "description": "Analyzes data", "system_prompt": "You are a data analyst.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1 } @@ -63819,7 +63819,7 @@ Run multiple swarms as a batch operation. "agent_name": "Writing Agent", "description": "Writes content", "system_prompt": "You are a content writer.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1 }, @@ -63827,7 +63827,7 @@ Run multiple swarms as a batch operation. "agent_name": "Editing Agent", "description": "Edits content", "system_prompt": "You are an editor.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1 } @@ -63886,7 +63886,7 @@ Run multiple swarms as a batch operation. agent_name: "Research Agent", description: "Conducts research", system_prompt: "You are a research assistant.", - model_name: "gpt-4o", + model_name: "gpt-4.1", role: "worker", max_loops: 1 }, @@ -63894,7 +63894,7 @@ Run multiple swarms as a batch operation. agent_name: "Analysis Agent", description: "Analyzes data", system_prompt: "You are a data analyst.", - model_name: "gpt-4o", + model_name: "gpt-4.1", role: "worker", max_loops: 1 } @@ -63911,7 +63911,7 @@ Run multiple swarms as a batch operation. agent_name: "Writing Agent", description: "Writes content", system_prompt: "You are a content writer.", - model_name: "gpt-4o", + model_name: "gpt-4.1", role: "worker", max_loops: 1 }, @@ -63919,7 +63919,7 @@ Run multiple swarms as a batch operation. agent_name: "Editing Agent", description: "Edits content", system_prompt: "You are an editor.", - model_name: "gpt-4o", + model_name: "gpt-4.1", role: "worker", max_loops: 1 } @@ -64004,7 +64004,7 @@ Run a single agent with the specified configuration. "agent_name": "Research Assistant", "description": "Helps with research tasks", "system_prompt": "You are a research assistant expert.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "max_tokens": 8192, "temperature": 0.5 @@ -64031,7 +64031,7 @@ Run a single agent with the specified configuration. "agent_name": "Research Assistant", "description": "Helps with research tasks", "system_prompt": "You are a research assistant expert.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "max_loops": 1, "max_tokens": 8192, "temperature": 0.5 @@ -64080,7 +64080,7 @@ Run a single agent with the specified configuration. agent_name: "Research Assistant", description: "Helps with research tasks", system_prompt: "You are a research assistant expert.", - model_name: "gpt-4o", + model_name: "gpt-4.1", max_loops: 1, max_tokens: 8192, temperature: 0.5 @@ -64175,7 +64175,7 @@ Execute a task using a single agent with specified configuration. "agent_name": "Research Assistant", "description": "Specialized in research and analysis", "system_prompt": "You are an expert research assistant.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "auto_generate_prompt": false, "max_tokens": 8192, "temperature": 0.5, @@ -64245,7 +64245,7 @@ Execute multiple agent tasks in parallel. "agent_name": "Market Analyst", "description": "Expert in market analysis", "system_prompt": "You are a financial market analyst.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "temperature": 0.3 }, "task": "Analyze the current market trends in AI technology sector" @@ -64255,7 +64255,7 @@ Execute multiple agent tasks in parallel. "agent_name": "Technical Writer", "description": "Specialized in technical documentation", "system_prompt": "You are a technical documentation expert.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "temperature": 0.7 }, "task": "Create a technical guide for implementing OAuth2 authentication" @@ -64282,7 +64282,7 @@ Execute multiple agent tasks in parallel. "agent_name": "Market Analyst", "description": "Expert in market analysis", "system_prompt": "You are a financial market analyst.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "temperature": 0.3 }, "task": "Analyze the current market trends in AI technology sector" @@ -64292,7 +64292,7 @@ Execute multiple agent tasks in parallel. "agent_name": "Technical Writer", "description": "Specialized in technical documentation", "system_prompt": "You are a technical documentation expert.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "temperature": 0.7 }, "task": "Create a technical guide for implementing OAuth2 authentication" @@ -64341,7 +64341,7 @@ Execute multiple agent tasks in parallel. agent_name: "Market Analyst", description: "Expert in market analysis", system_prompt: "You are a financial market analyst.", - model_name: "gpt-4o", + model_name: "gpt-4.1", temperature: 0.3 }, task: "Analyze the current market trends in AI technology sector" @@ -64351,7 +64351,7 @@ Execute multiple agent tasks in parallel. agent_name: "Technical Writer", description: "Specialized in technical documentation", system_prompt: "You are a technical documentation expert.", - model_name: "gpt-4o", + model_name: "gpt-4.1", temperature: 0.7 }, task: "Create a technical guide for implementing OAuth2 authentication" @@ -64862,7 +64862,7 @@ def run_single_swarm(): "agent_name": "Economic Forecaster", "description": "Predicts economic trends", "system_prompt": "You are an expert in economic forecasting.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index c88f709d..7d5a508c 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -301,6 +301,9 @@ nav: - MultiAgentRouter: "swarms/structs/multi_agent_router.md" - ModelRouter: "swarms/structs/model_router.md" + - Agent Orchestration Protocol (AOP): + - AOP Overview: "swarms/structs/aop.md" + - Rearrangers: - SwarmRearrange: "swarms/structs/swarm_rearrange.md" - AgentRearrange: "swarms/structs/agent_rearrange.md" @@ -327,6 +330,7 @@ nav: - BaseTool Reference: "swarms/tools/base_tool.md" - MCP Client Utils: "swarms/tools/mcp_client_call.md" - MCP Agent Tool: "swarms/tools/mcp_agent_tool.md" + - Agent Orchestration Protocol (AOP): "swarms/structs/aop.md" - Vertical Tools: - Finance: "swarms_tools/finance.md" @@ -344,6 +348,9 @@ nav: - Deploy on Google Cloud Run: "swarms_cloud/cloud_run.md" - Deploy on Phala: "swarms_cloud/phala_deploy.md" - Deploy on Cloudflare Workers: "swarms_cloud/cloudflare_workers.md" + - Agent Orchestration Protocol (AOP): + - AOP Server Setup: "swarms/examples/aop_server_example.md" + - AOP Cluster Example: "swarms/examples/aop_cluster_example.md" - Examples: diff --git a/docs/swarms/RAG/qdrant_rag.md b/docs/swarms/RAG/qdrant_rag.md index c0553379..699427bd 100644 --- a/docs/swarms/RAG/qdrant_rag.md +++ b/docs/swarms/RAG/qdrant_rag.md @@ -110,7 +110,7 @@ for doc in documents: agent = Agent( agent_name="RAG-Agent", agent_description="Agent with Qdrant-powered RAG for enhanced knowledge retrieval", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, dynamic_temperature_enabled=True, long_term_memory=rag_db @@ -186,7 +186,7 @@ for i, result in enumerate(results_with_metadata): agent = Agent( agent_name="Advanced-RAG-Agent", agent_description="Advanced agent with metadata-enhanced RAG capabilities", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, dynamic_temperature_enabled=True, long_term_memory=rag_db @@ -330,7 +330,7 @@ for doc in company_documents: agent = Agent( agent_name="Company-DocQA-Agent", agent_description="Intelligent document Q&A system for company information", - model_name="gpt-4o", + model_name="gpt-4.1", long_term_memory=rag_db ) @@ -355,7 +355,7 @@ class KnowledgeBaseAgent: self.agent = Agent( agent_name="KB-Management-Agent", agent_description="Knowledge base management and retrieval system", - model_name="gpt-4o", + model_name="gpt-4.1", long_term_memory=self.rag_db ) diff --git a/docs/swarms/agents/openai_assistant.md b/docs/swarms/agents/openai_assistant.md index d5f3b8bf..11016a2b 100644 --- a/docs/swarms/agents/openai_assistant.md +++ b/docs/swarms/agents/openai_assistant.md @@ -27,7 +27,7 @@ from swarms import OpenAIAssistant assistant = OpenAIAssistant( name="Math Tutor", instructions="You are a helpful math tutor.", - model="gpt-4o", + model="gpt-4.1", tools=[{"type": "code_interpreter"}] ) @@ -79,7 +79,7 @@ assistant.add_function( OpenAIAssistant( name: str, instructions: Optional[str] = None, - model: str = "gpt-4o", + model: str = "gpt-4.1", tools: Optional[List[Dict[str, Any]]] = None, file_ids: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, diff --git a/docs/swarms/agents/reasoning_agents_overview.md b/docs/swarms/agents/reasoning_agents_overview.md index 634f88eb..8d41c08e 100644 --- a/docs/swarms/agents/reasoning_agents_overview.md +++ b/docs/swarms/agents/reasoning_agents_overview.md @@ -377,7 +377,7 @@ consistency_agent = SelfConsistencyAgent( # Reasoning Duo for collaborative analysis workflows duo_agent = ReasoningDuo( - model_names=["gpt-4o-mini", "gpt-4o"] + model_names=["gpt-4o-mini", "gpt-4.1"] ) # Reflexion Agent for adaptive learning scenarios diff --git a/docs/swarms/agents/reasoning_duo.md b/docs/swarms/agents/reasoning_duo.md index a964fff9..669dc64e 100644 --- a/docs/swarms/agents/reasoning_duo.md +++ b/docs/swarms/agents/reasoning_duo.md @@ -11,7 +11,7 @@ The ReasoningDuo class implements a dual-agent reasoning system that combines a |-----------|------|---------|-------------| | model_name | str | "reasoning-agent-01" | Name identifier for the reasoning agent | | description | str | "A highly intelligent..." | Description of the reasoning agent's capabilities | -| model_names | list[str] | ["gpt-4o-mini", "gpt-4o"] | Model names for reasoning and main agents | +| model_names | list[str] | ["gpt-4o-mini", "gpt-4.1"] | Model names for reasoning and main agents | | system_prompt | str | "You are a helpful..." | System prompt for the main agent | ### Methods @@ -31,7 +31,7 @@ from swarms.agents.reasoning_duo import ReasoningDuo # Initialize the ReasoningDuo duo = ReasoningDuo( model_name="reasoning-agent-01", - model_names=["gpt-4o-mini", "gpt-4o"] + model_names=["gpt-4o-mini", "gpt-4.1"] ) # Run a single task @@ -97,7 +97,7 @@ You can customize both agents by modifying their initialization parameters: duo = ReasoningDuo( model_name="custom-reasoning-agent", description="Specialized financial analysis agent", - model_names=["gpt-4o-mini", "gpt-4o"], + model_names=["gpt-4o-mini", "gpt-4.1"], system_prompt="You are a financial expert AI assistant..." ) ``` diff --git a/docs/swarms/examples/hierarchical_swarm_example.md b/docs/swarms/examples/hierarchical_swarm_example.md index a3a9cf1e..86a5b85f 100644 --- a/docs/swarms/examples/hierarchical_swarm_example.md +++ b/docs/swarms/examples/hierarchical_swarm_example.md @@ -19,7 +19,7 @@ market_research_agent = Agent( - Industry report generation - Market opportunity identification - Risk assessment and mitigation strategies""", - model_name="gpt-4o", + model_name="gpt-4.1", ) financial_analyst_agent = Agent( @@ -32,7 +32,7 @@ financial_analyst_agent = Agent( - Financial modeling and forecasting - Risk assessment and portfolio analysis - ESG (Environmental, Social, Governance) analysis""", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the hierarchical swarm @@ -67,7 +67,7 @@ frontend_developer_agent = Agent( - State management (Redux, Zustand, Context API) - Web performance optimization - Accessibility (WCAG) and SEO best practices""", - model_name="gpt-4o", + model_name="gpt-4.1", ) backend_developer_agent = Agent( @@ -80,7 +80,7 @@ backend_developer_agent = Agent( - API design and REST/GraphQL implementation - Authentication and authorization systems - Microservices architecture and containerization""", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the development swarm @@ -108,13 +108,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm market_agent = Agent( agent_name="Market-Analyst", agent_description="Expert in market analysis and trends", - model_name="gpt-4o", + model_name="gpt-4.1", ) technical_agent = Agent( agent_name="Technical-Analyst", agent_description="Specialist in technical analysis and patterns", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the swarm @@ -142,13 +142,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm market_agent = Agent( agent_name="Market-Analyst", agent_description="Expert in market analysis and trends", - model_name="gpt-4o", + model_name="gpt-4.1", ) technical_agent = Agent( agent_name="Technical-Analyst", agent_description="Specialist in technical analysis and patterns", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the swarm @@ -183,21 +183,21 @@ research_manager = Agent( agent_name="Research-Manager", agent_description="Manages research operations and coordinates research tasks", system_prompt="You are a research manager responsible for overseeing research projects and coordinating research efforts.", - model_name="gpt-4o", + model_name="gpt-4.1", ) data_analyst = Agent( agent_name="Data-Analyst", agent_description="Analyzes data and generates insights", system_prompt="You are a data analyst specializing in processing and analyzing data to extract meaningful insights.", - model_name="gpt-4o", + model_name="gpt-4.1", ) research_assistant = Agent( agent_name="Research-Assistant", agent_description="Assists with research tasks and data collection", system_prompt="You are a research assistant who helps gather information and support research activities.", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the research swarm diff --git a/docs/swarms/examples/mixture_of_agents.md b/docs/swarms/examples/mixture_of_agents.md index 3041ca92..2be96f15 100644 --- a/docs/swarms/examples/mixture_of_agents.md +++ b/docs/swarms/examples/mixture_of_agents.md @@ -39,7 +39,7 @@ legal_expert = Agent( 3. Ensuring regulatory compliance 4. Providing legal recommendations 5. Drafting and reviewing legal documents""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -51,7 +51,7 @@ financial_expert = Agent( 3. Assessing financial risks 4. Providing financial projections 5. Recommending financial strategies""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -63,7 +63,7 @@ business_expert = Agent( 3. Assessing competitive advantages 4. Providing strategic recommendations 5. Planning business development""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -76,7 +76,7 @@ aggregator = Agent( 3. Prioritizing recommendations 4. Providing coherent final decisions 5. Ensuring comprehensive coverage of all aspects""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) ``` @@ -184,7 +184,7 @@ market_analyst = Agent( 3. Customer segments 4. Market trends 5. Entry barriers""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -196,7 +196,7 @@ financial_analyst = Agent( 3. Cash flow analysis 4. Investment requirements 5. ROI projections""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -208,7 +208,7 @@ risk_analyst = Agent( 3. Financial risks 4. Regulatory risks 5. Strategic risks""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -221,7 +221,7 @@ aggregator = Agent( 3. Evaluating trade-offs 4. Making recommendations 5. Providing action plans""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) diff --git a/docs/swarms/examples/model_providers.md b/docs/swarms/examples/model_providers.md index e9396728..c3b64fdb 100644 --- a/docs/swarms/examples/model_providers.md +++ b/docs/swarms/examples/model_providers.md @@ -127,7 +127,7 @@ research_agent = Agent( # Creative agent using GPT-4o for content generation creative_agent = Agent( agent_name="Creative-Agent", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="You are a creative content expert." ) @@ -149,7 +149,7 @@ from swarms import Agent, ModelRouter model_router = ModelRouter( models={ "analysis": "claude-3-sonnet-20240229", - "creative": "gpt-4o", + "creative": "gpt-4.1", "fast": "gpt-4o-mini", "local": "ollama/llama2" } diff --git a/docs/swarms/examples/quant_crypto_agent.md b/docs/swarms/examples/quant_crypto_agent.md index 74cb339a..549e5c24 100644 --- a/docs/swarms/examples/quant_crypto_agent.md +++ b/docs/swarms/examples/quant_crypto_agent.md @@ -100,7 +100,7 @@ agent = Agent( agent_description="Expert cryptocurrency financial analyst and market researcher", system_prompt=CRYPTO_ANALYST_SYSTEM_PROMPT, max_loops="auto", - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="crypto_analyst", output_type="str", diff --git a/docs/swarms/examples/swarm_router.md b/docs/swarms/examples/swarm_router.md index 50787621..7caa875c 100644 --- a/docs/swarms/examples/swarm_router.md +++ b/docs/swarms/examples/swarm_router.md @@ -35,21 +35,21 @@ from swarms.structs.swarm_router import SwarmRouter, SwarmType data_extractor_agent = Agent( agent_name="Data-Extractor", system_prompt="You are a data extraction specialist...", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) summarizer_agent = Agent( agent_name="Document-Summarizer", system_prompt="You are a document summarization expert...", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) financial_analyst_agent = Agent( agent_name="Financial-Analyst", system_prompt="You are a financial analysis specialist...", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) ``` @@ -193,21 +193,21 @@ from swarms.structs.swarm_router import SwarmRouter, SwarmType research_agent = Agent( agent_name="ResearchAgent", system_prompt="You are a research specialist...", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1 ) analysis_agent = Agent( agent_name="AnalysisAgent", system_prompt="You are an analysis expert...", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1 ) summary_agent = Agent( agent_name="SummaryAgent", system_prompt="You are a summarization specialist...", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1 ) diff --git a/docs/swarms/examples/swarms_of_browser_agents.md b/docs/swarms/examples/swarms_of_browser_agents.md index 6ef35e97..26307569 100644 --- a/docs/swarms/examples/swarms_of_browser_agents.md +++ b/docs/swarms/examples/swarms_of_browser_agents.md @@ -36,7 +36,7 @@ class BrowserAgent: async def browser_agent_test(self, task: str): agent = Agent( task=task, - llm=ChatOpenAI(model="gpt-4o"), + llm=ChatOpenAI(model="gpt-4.1"), ) result = await agent.run() return result diff --git a/docs/swarms/examples/swarms_tools_htx.md b/docs/swarms/examples/swarms_tools_htx.md index ab4333dd..90e51f39 100644 --- a/docs/swarms/examples/swarms_tools_htx.md +++ b/docs/swarms/examples/swarms_tools_htx.md @@ -20,7 +20,7 @@ agent = Agent( agent_description="Personal finance advisor agent", system_prompt=FINANCIAL_AGENT_SYS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="swarms_corp", return_step_meta=False, diff --git a/docs/swarms/examples/swarms_tools_htx_gecko.md b/docs/swarms/examples/swarms_tools_htx_gecko.md index 9f554c53..f7b7c270 100644 --- a/docs/swarms/examples/swarms_tools_htx_gecko.md +++ b/docs/swarms/examples/swarms_tools_htx_gecko.md @@ -25,7 +25,7 @@ agent = Agent( agent_description="Personal finance advisor agent", system_prompt=FINANCIAL_AGENT_SYS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="swarms_corp", retry_attempts=3, diff --git a/docs/swarms/examples/yahoo_finance.md b/docs/swarms/examples/yahoo_finance.md index fd6ca089..3ebace9b 100644 --- a/docs/swarms/examples/yahoo_finance.md +++ b/docs/swarms/examples/yahoo_finance.md @@ -42,7 +42,7 @@ agent = Agent( agent_description="Personal finance advisor agent", system_prompt=FINANCIAL_AGENT_SYS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", tools=[yahoo_finance_api], ) diff --git a/docs/swarms/framework/reference.md b/docs/swarms/framework/reference.md index 8c7db8f7..c3473f55 100644 --- a/docs/swarms/framework/reference.md +++ b/docs/swarms/framework/reference.md @@ -1043,7 +1043,7 @@ A Pydantic model representing a delta update for messages in chat applications. A Pydantic model representing a request for chat completion. **Attributes**: -- `model` (`str`): The model to use for completing the chat (default is "gpt-4o"). +- `model` (`str`): The model to use for completing the chat (default is "gpt-4.1"). - `messages` (`List[ChatMessageInput]`): A list of input messages for the chat. diff --git a/docs/swarms/structs/BoardOfDirectors.md b/docs/swarms/structs/BoardOfDirectors.md index be0205ec..0896fd47 100644 --- a/docs/swarms/structs/BoardOfDirectors.md +++ b/docs/swarms/structs/BoardOfDirectors.md @@ -179,13 +179,13 @@ board_members = [ research_agent = Agent( agent_name="Research-Specialist", agent_description="Expert in market research and analysis", - model_name="gpt-4o", + model_name="gpt-4.1", ) financial_agent = Agent( agent_name="Financial-Analyst", agent_description="Specialist in financial analysis and valuation", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the Board of Directors swarm @@ -215,7 +215,7 @@ print(result) market_research_agent = Agent( agent_name="Market-Research-Specialist", agent_description="Expert in market research, competitive analysis, and industry trends", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are a Market Research Specialist. Your responsibilities include: 1. Conducting comprehensive market research and analysis 2. Identifying market trends, opportunities, and risks @@ -229,7 +229,7 @@ You should be thorough, analytical, and objective in your research.""" financial_analyst_agent = Agent( agent_name="Financial-Analyst", agent_description="Specialist in financial analysis, valuation, and investment assessment", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are a Financial Analyst. Your responsibilities include: 1. Conducting financial analysis and valuation 2. Assessing investment opportunities and risks @@ -243,7 +243,7 @@ You should be financially astute, analytical, and focused on value creation.""" technical_assessor_agent = Agent( agent_name="Technical-Assessor", agent_description="Expert in technical feasibility and implementation assessment", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are a Technical Assessor. Your responsibilities include: 1. Evaluating technical feasibility and requirements 2. Assessing implementation challenges and risks @@ -327,7 +327,7 @@ print(json.dumps(result, indent=2)) tech_strategy_agent = Agent( agent_name="Tech-Strategy-Specialist", agent_description="Expert in technology strategy and digital transformation", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are a Technology Strategy Specialist. Your responsibilities include: 1. Developing technology roadmaps and strategies 2. Assessing digital transformation opportunities @@ -341,7 +341,7 @@ You should be strategic, forward-thinking, and technology-savvy.""" implementation_planner_agent = Agent( agent_name="Implementation-Planner", agent_description="Expert in implementation planning and project management", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are an Implementation Planner. Your responsibilities include: 1. Creating detailed implementation plans 2. Assessing resource requirements and timelines @@ -391,7 +391,7 @@ print(json.dumps(result, indent=2)) crisis_coordinator_agent = Agent( agent_name="Crisis-Coordinator", agent_description="Expert in crisis management and emergency response", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are a Crisis Coordinator. Your responsibilities include: 1. Coordinating crisis response efforts 2. Assessing crisis severity and impact @@ -405,7 +405,7 @@ You should be calm, decisive, and action-oriented.""" communications_specialist_agent = Agent( agent_name="Communications-Specialist", agent_description="Expert in crisis communications and stakeholder management", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt="""You are a Communications Specialist. Your responsibilities include: 1. Developing crisis communication strategies 2. Managing stakeholder communications diff --git a/docs/swarms/structs/agent.md b/docs/swarms/structs/agent.md index 063cf11f..8947374a 100644 --- a/docs/swarms/structs/agent.md +++ b/docs/swarms/structs/agent.md @@ -894,7 +894,7 @@ agent = Agent( output_type="json", # LLM Configuration - model_name="gpt-4o", + model_name="gpt-4.1", temperature=0.3, max_tokens=8000, top_p=0.95, diff --git a/docs/swarms/structs/aop.md b/docs/swarms/structs/aop.md new file mode 100644 index 00000000..f1d51f67 --- /dev/null +++ b/docs/swarms/structs/aop.md @@ -0,0 +1,475 @@ +# AOP (Agent Orchestration Protocol) + +The Agent Orchestration Protocol (AOP) is a powerful framework for deploying multiple Swarms agents as tools in an MCP (Model Context Protocol) server. This enables you to create a distributed system where agents can be accessed as individual tools, making them available for use by other systems, applications, or clients. + +AOP provides two main classes: + +- **AOP**: Deploy agents as tools in a single MCP server +- **AOPCluster**: Connect to and manage multiple MCP servers + +## Core Classes + +### AgentToolConfig + +Configuration dataclass for converting an agent to an MCP tool. + +| Attribute | Type | Default | Description | +|-----------|------|---------|-------------| +| `tool_name` | `str` | Required | The name of the tool in the MCP server | +| `tool_description` | `str` | Required | Description of what the tool does | +| `input_schema` | `Dict[str, Any]` | Required | JSON schema for the tool's input parameters | +| `output_schema` | `Dict[str, Any]` | Required | JSON schema for the tool's output | +| `timeout` | `int` | `30` | Maximum time to wait for agent execution (seconds) | +| `max_retries` | `int` | `3` | Number of retries if agent execution fails | +| `verbose` | `bool` | `False` | Enable verbose logging for this tool | +| `traceback_enabled` | `bool` | `True` | Enable traceback logging for errors | + +### AOP Class + +Main class for deploying agents as tools in an MCP server. + +#### Constructor Parameters + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `server_name` | `str` | `"AOP Cluster"` | Name for the MCP server | +| `description` | `str` | `"A cluster that enables you to deploy multiple agents as tools in an MCP server."` | Server description | +| `agents` | `List[Agent]` | `None` | Optional list of agents to add initially | +| `port` | `int` | `8000` | Port for the MCP server | +| `transport` | `str` | `"streamable-http"` | Transport type for the MCP server | +| `verbose` | `bool` | `False` | Enable verbose logging | +| `traceback_enabled` | `bool` | `True` | Enable traceback logging for errors | +| `host` | `str` | `"localhost"` | Host to bind the server to | +| `log_level` | `str` | `"INFO"` | Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL) | + +#### Methods + +##### add_agent() + +Add an agent to the MCP server as a tool. + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `agent` | `AgentType` | Required | The swarms Agent instance to deploy | +| `tool_name` | `str` | `None` | Name for the tool (defaults to agent.agent_name) | +| `tool_description` | `str` | `None` | Description of the tool (defaults to agent.agent_description) | +| `input_schema` | `Dict[str, Any]` | `None` | JSON schema for input parameters | +| `output_schema` | `Dict[str, Any]` | `None` | JSON schema for output | +| `timeout` | `int` | `30` | Maximum execution time in seconds | +| `max_retries` | `int` | `3` | Number of retries on failure | +| `verbose` | `bool` | `None` | Enable verbose logging for this tool | +| `traceback_enabled` | `bool` | `None` | Enable traceback logging for this tool | + +**Returns:** `str` - The tool name that was registered + +##### add_agents_batch() + +Add multiple agents to the MCP server as tools in batch. + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `agents` | `List[Agent]` | Required | List of swarms Agent instances | +| `tool_names` | `List[str]` | `None` | Optional list of tool names | +| `tool_descriptions` | `List[str]` | `None` | Optional list of tool descriptions | +| `input_schemas` | `List[Dict[str, Any]]` | `None` | Optional list of input schemas | +| `output_schemas` | `List[Dict[str, Any]]` | `None` | Optional list of output schemas | +| `timeouts` | `List[int]` | `None` | Optional list of timeout values | +| `max_retries_list` | `List[int]` | `None` | Optional list of max retry values | +| `verbose_list` | `List[bool]` | `None` | Optional list of verbose settings | +| `traceback_enabled_list` | `List[bool]` | `None` | Optional list of traceback settings | + +**Returns:** `List[str]` - List of tool names that were registered + +##### remove_agent() + +Remove an agent from the MCP server. + +| Parameter | Type | Description | +|-----------|------|-------------| +| `tool_name` | `str` | Name of the tool to remove | + +**Returns:** `bool` - True if agent was removed, False if not found + +##### list_agents() + +Get a list of all registered agent tool names. + +**Returns:** `List[str]` - List of tool names + +##### get_agent_info() + +Get information about a specific agent tool. + +| Parameter | Type | Description | +|-----------|------|-------------| +| `tool_name` | `str` | Name of the tool | + +**Returns:** `Dict[str, Any]` - Agent information, or None if not found + +##### start_server() + +Start the MCP server. + +##### run() + +Run the MCP server (alias for start_server). + +##### get_server_info() + +Get information about the MCP server and registered tools. + +**Returns:** `Dict[str, Any]` - Server information + +### AOPCluster Class + +Class for connecting to and managing multiple MCP servers. + +#### AOPCluster Constructor Parameters + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `urls` | `List[str]` | Required | List of MCP server URLs to connect to | +| `transport` | `str` | `"streamable-http"` | Transport type for connections | + +#### AOPCluster Methods + +##### get_tools() + +Get tools from all connected MCP servers. + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `output_type` | `Literal["json", "dict", "str"]` | `"dict"` | Format of the output | + +**Returns:** `List[Dict[str, Any]]` - List of available tools + +##### find_tool_by_server_name() + +Find a tool by its server name (function name). + +| Parameter | Type | Description | +|-----------|------|-------------| +| `server_name` | `str` | The name of the tool/function to find | + +**Returns:** `Dict[str, Any]` - Tool information, or None if not found + +## Tool Parameters + +All agent tools accept the following parameters: + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `task` | `str` | Yes | The main task or prompt to execute | +| `img` | `str` | No | Single image to be processed by the agent | +| `imgs` | `List[str]` | No | Multiple images to be processed by the agent | +| `correct_answer` | `str` | No | Correct answer for validation or comparison | + +## Output Format + +All agent tools return a standardized response format: + +```json +{ + "result": "string", // The agent's response to the task + "success": "boolean", // Whether the task was executed successfully + "error": "string" // Error message if execution failed (null if successful) +} +``` + +## Complete Examples + +### Basic Server Setup + +```python +from swarms import Agent +from swarms.structs.aop import AOP + +# Create specialized agents +research_agent = Agent( + agent_name="Research-Agent", + agent_description="Expert in research, data collection, and information gathering", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + top_p=None, + dynamic_temperature_enabled=True, + system_prompt="""You are a research specialist. Your role is to: + 1. Gather comprehensive information on any given topic + 2. Analyze data from multiple sources + 3. Provide well-structured research findings + 4. Cite sources and maintain accuracy + 5. Present findings in a clear, organized manner + + Always provide detailed, factual information with proper context.""", +) + +analysis_agent = Agent( + agent_name="Analysis-Agent", + agent_description="Expert in data analysis, pattern recognition, and generating insights", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + top_p=None, + dynamic_temperature_enabled=True, + system_prompt="""You are an analysis specialist. Your role is to: + 1. Analyze data and identify patterns + 2. Generate actionable insights + 3. Create visualizations and summaries + 4. Provide statistical analysis + 5. Make data-driven recommendations + + Focus on extracting meaningful insights from information.""", +) + +# Create AOP instance +deployer = AOP( + server_name="MyAgentServer", + port=8000, + verbose=True, + log_level="INFO" +) + +# Add agents individually +deployer.add_agent(research_agent) +deployer.add_agent(analysis_agent) + +# Start the server +deployer.run() +``` + +### Batch Agent Addition + +```python +from swarms import Agent +from swarms.structs.aop import AOP + +# Create multiple agents +agents = [ + Agent( + agent_name="Research-Agent", + agent_description="Expert in research and data collection", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + ), + Agent( + agent_name="Writing-Agent", + agent_description="Expert in content creation and editing", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + ), + Agent( + agent_name="Code-Agent", + agent_description="Expert in programming and code review", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + ), +] + +# Create AOP instance +deployer = AOP("MyAgentServer", verbose=True) + +# Add all agents at once +tool_names = deployer.add_agents_batch(agents) + +print(f"Added {len(tool_names)} agents: {tool_names}") + +# Start the server +deployer.run() +``` + +### Advanced Configuration + +```python +from swarms import Agent +from swarms.structs.aop import AOP + +# Create agent with custom configuration +research_agent = Agent( + agent_name="Research-Agent", + agent_description="Expert in research and data collection", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, +) + +# Create AOP with custom settings +deployer = AOP( + server_name="AdvancedAgentServer", + port=8001, + host="0.0.0.0", # Allow external connections + verbose=True, + traceback_enabled=True, + log_level="DEBUG" +) + +# Add agent with custom tool configuration +deployer.add_agent( + agent=research_agent, + tool_name="custom_research_tool", + tool_description="Custom research tool with extended capabilities", + timeout=60, # 60 second timeout + max_retries=5, # 5 retries + verbose=True, + traceback_enabled=True +) + +# Add custom input/output schemas +custom_input_schema = { + "type": "object", + "properties": { + "task": { + "type": "string", + "description": "The research task to execute" + }, + "sources": { + "type": "array", + "items": {"type": "string"}, + "description": "Specific sources to research" + }, + "depth": { + "type": "string", + "enum": ["shallow", "medium", "deep"], + "description": "Research depth level" + } + }, + "required": ["task"] +} + +custom_output_schema = { + "type": "object", + "properties": { + "result": {"type": "string"}, + "sources": {"type": "array", "items": {"type": "string"}}, + "confidence": {"type": "number", "minimum": 0, "maximum": 1}, + "success": {"type": "boolean"}, + "error": {"type": "string"} + }, + "required": ["result", "success"] +} + +# Add another agent with custom schemas +analysis_agent = Agent( + agent_name="Analysis-Agent", + agent_description="Expert in data analysis", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, +) + +deployer.add_agent( + agent=analysis_agent, + tool_name="custom_analysis_tool", + tool_description="Custom analysis tool", + input_schema=custom_input_schema, + output_schema=custom_output_schema, + timeout=45, + max_retries=3 +) + +# List all registered agents +print("Registered agents:", deployer.list_agents()) + +# Get server information +server_info = deployer.get_server_info() +print("Server info:", server_info) + +# Start the server +deployer.run() +``` + +### AOPCluster Usage + +```python +import json +from swarms.structs.aop import AOPCluster + +# Connect to multiple MCP servers +cluster = AOPCluster( + urls=[ + "http://localhost:8000/mcp", + "http://localhost:8001/mcp", + "http://localhost:8002/mcp" + ], + transport="streamable-http" +) + +# Get all available tools from all servers +all_tools = cluster.get_tools(output_type="dict") +print(f"Found {len(all_tools)} tools across all servers") + +# Pretty print all tools +print(json.dumps(all_tools, indent=2)) + +# Find a specific tool by name +research_tool = cluster.find_tool_by_server_name("Research-Agent") +if research_tool: + print("Found Research-Agent tool:") + print(json.dumps(research_tool, indent=2)) +else: + print("Research-Agent tool not found") +``` + +### Tool Execution Examples + +Once your AOP server is running, you can call the tools using MCP clients. Here are examples of how the tools would be called: + +```python +# Example tool calls (these would be made by MCP clients) + +# Basic task execution +result = research_tool(task="Research the latest AI trends in 2024") + +# Task with single image +result = analysis_tool( + task="Analyze this chart and provide insights", + img="path/to/chart.png" +) + +# Task with multiple images +result = writing_tool( + task="Write a comprehensive report based on these images", + imgs=["image1.jpg", "image2.jpg", "image3.jpg"] +) + +# Task with validation +result = code_tool( + task="Debug this Python function", + correct_answer="Expected output: Hello World" +) + +# The response format for all calls: +# { +# "result": "The agent's response...", +# "success": true, +# "error": null +# } +``` + +## Error Handling + +AOP provides comprehensive error handling: + +- **Timeout Protection**: Each agent has configurable timeout limits +- **Retry Logic**: Automatic retries on failure with configurable retry counts +- **Detailed Logging**: Verbose logging with traceback information +- **Graceful Degradation**: Failed agents don't crash the entire server + +## Best Practices + +| Best Practice | Description | +|------------------------------|--------------------------------------------------------------------| +| **Use Descriptive Names** | Choose clear, descriptive tool names | +| **Set Appropriate Timeouts** | Configure timeouts based on expected task complexity | +| **Enable Logging** | Use verbose logging for debugging and monitoring | +| **Handle Errors** | Always check the `success` field in tool responses | +| **Resource Management** | Monitor server resources when running multiple agents | +| **Security** | Use appropriate host/port settings for your deployment environment | + +## Integration with Other Systems + +AOP servers can be integrated with: + +| Integration Target | Description | +|------------------------|--------------------------------------------------| +| **MCP Clients** | Any MCP-compatible client | +| **Web Applications** | Via HTTP transport | +| **Other Swarms** | As part of larger multi-agent systems | +| **External APIs** | Through MCP protocol | + +This makes AOP a powerful tool for creating distributed, scalable agent systems that can be easily integrated into existing workflows and applications. diff --git a/docs/swarms/structs/auto_swarm_builder.md b/docs/swarms/structs/auto_swarm_builder.md index 8bb9180e..516fb1c9 100644 --- a/docs/swarms/structs/auto_swarm_builder.md +++ b/docs/swarms/structs/auto_swarm_builder.md @@ -1,33 +1,37 @@ # AutoSwarmBuilder Documentation -The `AutoSwarmBuilder` is a powerful class that automatically builds and manages swarms of AI agents to accomplish complex tasks. It uses a sophisticated boss agent system to delegate work and create specialized agents as needed. - -## Overview +The `AutoSwarmBuilder` is a powerful class that automatically builds and manages swarms of AI agents to accomplish complex tasks. It uses a sophisticated boss agent system with comprehensive design principles to delegate work and create specialized agents as needed. The AutoSwarmBuilder is designed to: | Feature | Description | |---------|-------------| -| Automatic Agent Creation | Automatically create and coordinate multiple AI agents | -| Task Delegation | Delegate tasks to specialized agents based on task requirements | -| Agent Communication Management | Manage communication between agents through a swarm router | -| Complex Workflow Handling | Handle complex workflows with various execution types | -| Architecture Pattern Support | Support different multi-agent architecture patterns | -| Error Handling & Logging | Provide comprehensive error handling and logging | +| **Automatic Agent Creation** | Automatically create and coordinate multiple AI agents with distinct personalities and capabilities | +| **Intelligent Task Delegation** | Delegate tasks to specialized agents based on comprehensive task analysis and requirements | +| **Advanced Agent Communication** | Manage sophisticated communication protocols between agents through a swarm router | +| **Multiple Execution Types** | Support 6 different execution types for various use cases and workflows | +| **Comprehensive Architecture Support** | Support 13+ different multi-agent architecture patterns and coordination strategies | +| **Robust Error Handling** | Provide comprehensive error handling, logging, and recovery procedures | +| **Dynamic Agent Specification** | Create agents with detailed specifications including roles, personalities, and capabilities | +| **Flexible Configuration** | Support extensive configuration options for models, tokens, temperature, and behavior | +| **Batch Processing** | Handle multiple tasks efficiently with batch processing capabilities | +| **Interactive Mode** | Support real-time interactive collaboration and decision-making | ## Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| -| name | str | "auto-swarm-builder" | The name of the swarm | -| description | str | "Auto Swarm Builder" | A description of the swarm's purpose | -| verbose | bool | True | Whether to output detailed logs | -| max_loops | int | 1 | Maximum number of execution loops | -| model_name | str | "gpt-4.1" | The LLM model to use for the boss agent | -| generate_router_config | bool | False | Whether to generate router configuration | -| interactive | bool | False | Whether to enable interactive mode | -| max_tokens | int | 8000 | Maximum tokens for the LLM responses | -| execution_type | str | "return-agents" | Type of execution to perform | +| `name` | str | "auto-swarm-builder" | The name of the swarm | +| `description` | str | "Auto Swarm Builder" | A description of the swarm's purpose | +| `verbose` | bool | True | Whether to output detailed logs | +| `max_loops` | int | 1 | Maximum number of execution loops | +| `model_name` | str | "gpt-4.1" | The LLM model to use for the boss agent | +| `generate_router_config` | bool | False | Whether to generate router configuration | +| `interactive` | bool | False | Whether to enable interactive mode | +| `max_tokens` | int | 8000 | Maximum tokens for the LLM responses | +| `execution_type` | str | "return-agents" | Type of execution to perform (see Execution Types) | +| `return_dictionary` | bool | True | Whether to return dictionary format for agent specs | +| `system_prompt` | str | BOSS_SYSTEM_PROMPT | System prompt for the boss agent | ## Execution Types @@ -39,6 +43,8 @@ The `execution_type` parameter controls how the AutoSwarmBuilder operates: | **"execute-swarm-router"** | Executes the swarm router with the created agents | | **"return-swarm-router-config"** | Returns the swarm router configuration as a dictionary | | **"return-agent-configurations"**| Returns agent configurations as a dictionary | +| **"return-agent-specs"** | Returns agent specifications as a tuple (agents, count) | +| **"return-agent-dictionary"** | Returns agent configurations as a dictionary format | ## Core Methods @@ -156,6 +162,78 @@ Returns the available execution types. - `List[str]`: List of available execution types +### _create_agent_specs(task: str) + +Create agent specifications for a given task. + +**Parameters:** + +- `task` (str): The task to create agents for + +**Returns:** + +- `Tuple[List[Agent], int]`: List of created agents and count + +### _create_agent_dictionary(task: str) + +Create agent dictionary for a given task. + +**Parameters:** + +- `task` (str): The task to create agents for + +**Returns:** + +- `dict`: Dictionary containing agent configurations + +### _create_agents_from_specs(task: str, return_dict: bool = False) + +Create agents from specifications using the boss agent system. + +**Parameters:** + +- `task` (str): The task to create agents for +- `return_dict` (bool): Whether to return dictionary format + +**Returns:** + +- `List[Agent]` or `dict`: Created agents or dictionary + +### create_agents_from_specs(agents_dictionary: Any) + +Create agents from agent specifications. + +**Parameters:** + +- `agents_dictionary`: Dictionary containing agent specifications + +**Returns:** + +- `List[Agent]`: List of created agents + +### build_agent_from_spec(agent_name: str, agent_description: str, agent_system_prompt: str, max_loops: int = 1, model_name: str = "gpt-4.1", dynamic_temperature_enabled: bool = True, auto_generate_prompt: bool = False, role: str = "worker", max_tokens: int = 8192, temperature: float = 0.5) + +Build a single agent from agent specification with comprehensive configuration options. + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `agent_name` | str | - | Name of the agent | +| `agent_description` | str | - | Description of the agent's purpose | +| `agent_system_prompt` | str | - | The system prompt for the agent | +| `max_loops` | int | 1 | Maximum number of loops | +| `model_name` | str | "gpt-4.1" | Model name to use | +| `dynamic_temperature_enabled` | bool | True | Whether to enable dynamic temperature | +| `auto_generate_prompt` | bool | False | Whether to auto-generate prompts | +| `role` | str | "worker" | Role of the agent | +| `max_tokens` | int | 8192 | Maximum tokens | +| `temperature` | float | 0.5 | Temperature setting | + +**Returns:** + +- `Agent`: The constructed agent instance + ### dict_to_agent(output: dict) Converts a dictionary output to a list of Agent objects. @@ -190,6 +268,32 @@ Performs reliability checks on the AutoSwarmBuilder configuration. ## Configuration Classes +### AgentSpec + +Configuration for an individual agent specification with comprehensive options. + +**Fields:** + +| Field | Type | Description | +|----------------------|---------|-----------------------------------------------------------------------------------------------| +| `agent_name` | str | Unique name assigned to the agent, identifying its role and functionality | +| `description` | str | Detailed explanation of the agent's purpose, capabilities, and specific tasks | +| `system_prompt` | str | Initial instruction or context provided to guide agent behavior and responses | +| `model_name` | str | AI model name for processing tasks (e.g., 'gpt-4o', 'gpt-4o-mini', 'openai/o3-mini') | +| `auto_generate_prompt`| bool | Flag indicating whether the agent should automatically create prompts | +| `max_tokens` | int | Maximum number of tokens allowed in agent responses | +| `temperature` | float | Parameter controlling randomness of agent output (lower = more deterministic) | +| `role` | str | Designated role within the swarm influencing behavior and interactions | +| `max_loops` | int | Maximum number of times the agent can repeat its task for iterative processing | + +### Agents + +Configuration for a collection of agents that work together as a swarm. + +**Fields:** + +- `agents` (List[AgentSpec]): List containing specifications of each agent participating in the swarm + ### AgentConfig Configuration model for individual agents in a swarm. @@ -249,6 +353,67 @@ The AutoSwarmBuilder supports various multi-agent architecture patterns: | **InteractiveGroupChat** | Dynamic group interactions | | **HeavySwarm** | High-capacity processing with multiple agents | +## Boss System Prompt + +The AutoSwarmBuilder uses a comprehensive `BOSS_SYSTEM_PROMPT` that embodies sophisticated multi-agent architecture design principles. This system prompt guides the boss agent in creating highly effective agent teams. + +### Core Design Principles + +The boss system prompt includes six fundamental design principles: + +1. **Comprehensive Task Analysis** + - Thoroughly deconstruct tasks into fundamental components and sub-tasks + - Identify specific skills, knowledge domains, and personality traits required + - Analyze challenges, dependencies, and coordination requirements + - Map optimal workflows, information flow patterns, and decision-making hierarchies + +2. **Agent Design Excellence** + - Create agents with crystal-clear, specific purposes and domain expertise + - Design distinct, complementary personalities that enhance team dynamics + - Ensure agents are self-aware of limitations and know when to seek assistance + - Create agents that effectively communicate progress, challenges, and insights + +3. **Comprehensive Agent Framework** + - **Role & Purpose**: Precise description of responsibilities and authority + - **Personality Profile**: Distinct characteristics influencing thinking patterns + - **Expertise Matrix**: Specific knowledge domains, skill sets, and capabilities + - **Communication Protocol**: How agents present information and interact + - **Decision-Making Framework**: Systematic approach to problem-solving + - **Limitations & Boundaries**: Clear constraints and operational boundaries + - **Collaboration Strategy**: How agents work together and share knowledge + +4. **Advanced System Prompt Engineering** + - Detailed role and purpose explanations with context and scope + - Rich personality descriptions with behavioral guidelines + - Comprehensive capabilities, tools, and resource specifications + - Detailed communication protocols and reporting requirements + - Systematic problem-solving approaches with decision-making frameworks + - Collaboration guidelines and conflict resolution procedures + - Quality standards, success criteria, and performance metrics + - Error handling, recovery procedures, and escalation protocols + +5. **Multi-Agent Coordination Architecture** + - Design robust communication channels and protocols between agents + - Establish clear task handoff procedures and information sharing mechanisms + - Create feedback loops for continuous improvement and adaptation + - Implement comprehensive error handling and recovery procedures + - Define escalation paths for complex issues and decision-making hierarchies + +6. **Quality Assurance & Governance** + - Set measurable success criteria for each agent and the overall system + - Implement verification steps, validation procedures, and quality checks + - Create mechanisms for self-assessment, peer review, and continuous improvement + - Establish protocols for handling edge cases and unexpected situations + - Design governance structures for oversight, accountability, and performance management + +### Output Requirements + +The boss system prompt ensures that when creating multi-agent systems, the following are provided: + +1. **Agent Specifications**: Comprehensive role statements, personality profiles, capabilities, limitations, communication styles, and collaboration strategies +2. **System Prompts**: Complete, detailed prompts embodying each agent's identity and capabilities +3. **Architecture Design**: Team structure, communication flow patterns, task distribution strategies, quality control measures, and error handling procedures + ## Examples ### Example 1: Basic Content Creation Swarm @@ -278,7 +443,7 @@ from swarms.structs.auto_swarm_builder import AutoSwarmBuilder swarm = AutoSwarmBuilder( name="Data Analysis Swarm", description="A swarm specialized in data analysis and visualization", - model_name="gpt-4o", + model_name="gpt-4.1", max_tokens=12000, verbose=True, execution_type="return-agents" @@ -384,41 +549,204 @@ result = swarm.run( ) ``` +### Example 7: Getting Agent Specifications + +```python +from swarms.structs.auto_swarm_builder import AutoSwarmBuilder + +# Initialize to return agent specifications +swarm = AutoSwarmBuilder( + name="Specification Swarm", + description="A swarm for generating agent specifications", + execution_type="return-agent-specs" +) + +# Get agent specifications with count +agents, count = swarm.run( + "Create a team of agents for analyzing customer feedback and generating actionable insights" +) + +print(f"Created {count} agents:") +for agent in agents: + print(f"- {agent.agent_name}: {agent.description}") +``` + +### Example 8: Getting Agent Dictionary + +```python +from swarms.structs.auto_swarm_builder import AutoSwarmBuilder + +# Initialize to return agent dictionary +swarm = AutoSwarmBuilder( + name="Dictionary Swarm", + description="A swarm for generating agent dictionaries", + execution_type="return-agent-dictionary" +) + +# Get agent configurations as dictionary +agent_dict = swarm.run( + "Create a marketing team to develop a comprehensive social media strategy" +) + +print("Agent Dictionary:") +for agent in agent_dict["agents"]: + print(f"- {agent['agent_name']}: {agent['description']}") + print(f" Model: {agent['model_name']}") + print(f" Role: {agent['role']}") + print(f" Temperature: {agent['temperature']}") +``` + +### Example 9: Custom System Prompt + +```python +from swarms.structs.auto_swarm_builder import AutoSwarmBuilder + +# Custom system prompt for specialized domain +custom_prompt = """ +You are an expert in financial analysis and risk assessment. +Create specialized agents for financial modeling, risk analysis, +and investment strategy development. Focus on quantitative analysis, +regulatory compliance, and market research capabilities. +""" + +# Initialize with custom system prompt +swarm = AutoSwarmBuilder( + name="Financial Analysis Swarm", + description="A specialized swarm for financial analysis", + system_prompt=custom_prompt, + model_name="gpt-4.1", + max_tokens=12000 +) + +# Run with custom prompt +result = swarm.run( + "Analyze the financial health of a tech startup and provide investment recommendations" +) +``` + +### Example 10: Advanced Agent Configuration + +```python +from swarms.structs.auto_swarm_builder import AutoSwarmBuilder + +# Initialize with advanced configuration +swarm = AutoSwarmBuilder( + name="Advanced Swarm", + description="A highly configured swarm with advanced settings", + model_name="gpt-4.1", + max_tokens=16000, + temperature=0.3, + return_dictionary=True, + verbose=True, + interactive=False +) + +# Create agents with detailed specifications +agent_specs = swarm._create_agents_from_specs( + "Develop a comprehensive cybersecurity strategy for a mid-size company", + return_dict=True +) + +# Build agents from specifications +agents = swarm.create_agents_from_specs(agent_specs) + +# Use the agents directly +for agent in agents: + print(f"Agent: {agent.agent_name}") + print(f"Description: {agent.description}") + print(f"Model: {agent.model_name}") + print(f"Max Loops: {agent.max_loops}") + print("---") +``` + ## Best Practices !!! tip "Task Definition" - - Provide clear, specific task descriptions - - Include any relevant context or constraints - - Specify expected output format if needed + - Provide clear, specific task descriptions with context and constraints + - Include expected output format and success criteria - Break complex tasks into smaller, manageable components + - Consider task dependencies and coordination requirements + - Use domain-specific terminology for better agent specialization !!! note "Configuration" - - Set appropriate `max_loops` based on task complexity + - Set appropriate `max_loops` based on task complexity (typically 1) - Use `verbose=True` during development for debugging - Choose the right `execution_type` for your use case: - - Use `"return-agents"` for direct agent interaction - - Use `"return-agent-configurations"` for inspection - - Use `"return-swarm-router-config"` for configuration analysis + - Use `"return-agents"` for direct agent interaction and execution + - Use `"return-agent-configurations"` for inspecting agent setups + - Use `"return-swarm-router-config"` for analyzing swarm architecture + - Use `"return-agent-specs"` for getting agent specifications with counts + - Use `"return-agent-dictionary"` for dictionary-format configurations - Set `max_tokens` appropriately based on expected response length - Use `interactive=True` for real-time collaboration scenarios + - Set `return_dictionary=True` for easier data manipulation !!! note "Model Selection" - Choose appropriate `model_name` based on task requirements - - Consider model capabilities and token limits - - Use more powerful models for complex reasoning tasks + - Consider model capabilities, token limits, and cost + - Use more powerful models (GPT-4.1, Claude-3) for complex reasoning + - Use efficient models (GPT-4o-mini) for simple tasks - Balance performance with cost considerations + - Test different models for optimal results + +!!! note "Agent Design" + - Leverage the comprehensive BOSS_SYSTEM_PROMPT for optimal agent creation + - Use custom system prompts for domain-specific applications + - Consider agent personality and role diversity for better collaboration + - Set appropriate temperature values (0.1-0.7) for task requirements + - Use `auto_generate_prompt=True` for dynamic prompt generation + - Configure `max_tokens` based on expected response complexity + +!!! note "Swarm Architecture" + - Choose appropriate swarm types based on task requirements + - Use `AgentRearrange` for dynamic task allocation + - Use `MixtureOfAgents` for parallel processing + - Use `GroupChat` for collaborative decision-making + - Use `SequentialWorkflow` for linear task progression + - Consider `HeavySwarm` for high-capacity processing !!! warning "Error Handling" - - The class includes comprehensive error handling - - All methods include try-catch blocks with detailed logging - - Errors are propagated with full stack traces for debugging - - Always handle exceptions in your calling code + - Always wrap AutoSwarmBuilder calls in try-catch blocks + - Implement appropriate fallback strategies for failures + - Monitor error patterns and adjust configurations + - Use comprehensive logging for debugging + - Handle API rate limits and token limits gracefully !!! info "Performance Optimization" - Use `batch_run()` for processing multiple similar tasks - Consider using `generate_router_config=True` for complex workflows - Monitor token usage with `max_tokens` parameter - Use appropriate `swarm_type` for your specific use case + - Implement caching for repeated operations + - Use parallel processing where appropriate + +!!! info "Production Deployment" + - Implement proper logging and monitoring + - Use environment variables for sensitive configuration + - Set up health checks and circuit breakers + - Monitor resource usage and performance metrics + - Implement graceful shutdown procedures + - Use proper error reporting and alerting systems + +### Best Practices for Error Handling + +!!! warning "Always Handle Exceptions" + - Wrap AutoSwarmBuilder calls in try-catch blocks + - Log errors with appropriate detail levels + - Implement appropriate fallback strategies + - Monitor error patterns and adjust configurations + +!!! tip "Debugging Configuration Issues" + - Use `verbose=True` during development + - Test with simple tasks first + - Validate model names and API keys + - Check token limits and rate limits + +!!! note "Production Considerations" + - Implement circuit breakers for external API calls + - Use health checks to monitor system status + - Set up proper logging and monitoring + - Implement graceful shutdown procedures ## Notes diff --git a/docs/swarms/structs/heavy_swarm.md b/docs/swarms/structs/heavy_swarm.md index 5ad1f8ad..e0b76934 100644 --- a/docs/swarms/structs/heavy_swarm.md +++ b/docs/swarms/structs/heavy_swarm.md @@ -112,8 +112,8 @@ swarm = HeavySwarm( description="Comprehensive multi-agent analysis system", timeout=600, loops_per_agent=2, - question_agent_model_name="gpt-4o", - worker_model_name="gpt-4o", + question_agent_model_name="gpt-4.1", + worker_model_name="gpt-4.1", verbose=True, max_workers=8, show_dashboard=True, @@ -335,8 +335,8 @@ from swarms.structs.heavy_swarm import HeavySwarm swarm = HeavySwarm( name="AdvancedMarketAnalysis", description="Deep market analysis with multiple iterations", - worker_model_name="gpt-4o", - question_agent_model_name="gpt-4o", + worker_model_name="gpt-4.1", + question_agent_model_name="gpt-4.1", show_dashboard=True, loops_per_agent=3, # Multiple iterations for depth timeout=600, @@ -366,7 +366,7 @@ from swarms.structs.heavy_swarm import HeavySwarm # Configure for question generation swarm = HeavySwarm( name="QuestionGenerator", - question_agent_model_name="gpt-4o", + question_agent_model_name="gpt-4.1", worker_model_name="gpt-4o-mini", show_dashboard=False ) @@ -463,7 +463,7 @@ from swarms_tools import exa_search, calculator swarm = HeavySwarm( name="CustomToolsSwarm", description="HeavySwarm with enhanced tool capabilities", - worker_model_name="gpt-4o", + worker_model_name="gpt-4.1", worker_tools=[exa_search, calculator], show_dashboard=True, timeout=600 @@ -491,8 +491,8 @@ from swarms.structs.heavy_swarm import HeavySwarm swarm = HeavySwarm( name="EnterpriseAnalysis", description="High-performance enterprise analysis", - worker_model_name="gpt-4o", # Highest quality - question_agent_model_name="gpt-4o", + worker_model_name="gpt-4.1", # Highest quality + question_agent_model_name="gpt-4.1", show_dashboard=True, loops_per_agent=5, # Maximum depth timeout=1800, # 30 minutes @@ -523,7 +523,7 @@ from swarms.structs.heavy_swarm import HeavySwarm swarm = HeavySwarm( name="DiverseAnalysis", description="Analysis with random iteration depth", - worker_model_name="gpt-4o", + worker_model_name="gpt-4.1", question_agent_model_name="gpt-4o-mini", show_dashboard=True, loops_per_agent=1, # Base loops diff --git a/docs/swarms/structs/hierarchical_swarm.md b/docs/swarms/structs/hierarchical_swarm.md index 00967404..860efd30 100644 --- a/docs/swarms/structs/hierarchical_swarm.md +++ b/docs/swarms/structs/hierarchical_swarm.md @@ -94,13 +94,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm research_agent = Agent( agent_name="Research-Specialist", agent_description="Expert in market research and analysis", - model_name="gpt-4o", + model_name="gpt-4.1", ) financial_agent = Agent( agent_name="Financial-Analyst", agent_description="Specialist in financial analysis and valuation", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the hierarchical swarm @@ -196,13 +196,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm frontend_agent = Agent( agent_name="Frontend-Developer", agent_description="Expert in React and modern web development", - model_name="gpt-4o", + model_name="gpt-4.1", ) backend_agent = Agent( agent_name="Backend-Developer", agent_description="Specialist in Node.js and API development", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the swarm @@ -246,13 +246,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm market_agent = Agent( agent_name="Market-Analyst", agent_description="Expert in market analysis and trends", - model_name="gpt-4o", + model_name="gpt-4.1", ) technical_agent = Agent( agent_name="Technical-Analyst", agent_description="Specialist in technical analysis and patterns", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the swarm diff --git a/docs/swarms/structs/index.md b/docs/swarms/structs/index.md index 965f4457..310ee5de 100644 --- a/docs/swarms/structs/index.md +++ b/docs/swarms/structs/index.md @@ -51,12 +51,12 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm research_agent = Agent( agent_name="Research-Specialist", agent_description="Expert in market research and analysis", - model_name="gpt-4o", + model_name="gpt-4.1", ) financial_agent = Agent( agent_name="Financial-Analyst", agent_description="Specialist in financial analysis and valuation", - model_name="gpt-4o", + model_name="gpt-4.1", ) # Initialize the hierarchical swarm diff --git a/docs/swarms/structs/majorityvoting.md b/docs/swarms/structs/majorityvoting.md index c51067c5..5e62ffef 100644 --- a/docs/swarms/structs/majorityvoting.md +++ b/docs/swarms/structs/majorityvoting.md @@ -57,7 +57,7 @@ class MajorityVoting: consensus_agent_prompt: str = CONSENSUS_AGENT_PROMPT, consensus_agent_name: str = "Consensus-Agent", consensus_agent_description: str = "An agent that uses consensus to generate a final answer.", - consensus_agent_model_name: str = "gpt-4o", + consensus_agent_model_name: str = "gpt-4.1", additional_consensus_agent_kwargs: dict = {}, *args, **kwargs, @@ -79,7 +79,7 @@ class MajorityVoting: | `consensus_agent_prompt` | `str` | `CONSENSUS_AGENT_PROMPT` | System prompt for the consensus agent. | | `consensus_agent_name` | `str` | `"Consensus-Agent"` | Name for the automatically created consensus agent. | | `consensus_agent_description` | `str` | `"An agent that uses consensus to generate a final answer."` | Description for the consensus agent. | -| `consensus_agent_model_name` | `str` | `"gpt-4o"` | Model name for the consensus agent. | +| `consensus_agent_model_name` | `str` | `"gpt-4.1"` | Model name for the consensus agent. | | `additional_consensus_agent_kwargs` | `dict` | `{}` | Additional keyword arguments passed to the consensus agent. | | `*args` | `Any` | - | Variable length argument list passed to Conversation. | | `**kwargs` | `Any` | - | Arbitrary keyword arguments passed to Conversation. | @@ -619,7 +619,7 @@ technical_agent = Agent( agent_description="Specialized in technical analysis, chart patterns, and trading signals", system_prompt=TECHNICAL_ANALYSIS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", ) fundamental_agent = Agent( @@ -627,7 +627,7 @@ fundamental_agent = Agent( agent_description="Specialized in financial statement analysis and company valuation", system_prompt=FUNDAMENTAL_ANALYSIS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", ) risk_agent = Agent( @@ -635,7 +635,7 @@ risk_agent = Agent( agent_description="Specialized in portfolio optimization and risk management strategies", system_prompt=RISK_MANAGEMENT_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", ) # Create the majority voting swarm with the three specialized quant agents @@ -671,21 +671,21 @@ agents = [ agent_description="Market trend analyst", system_prompt="You are a market analyst specializing in identifying growth opportunities and market trends.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="Risk-Assessment-Agent", agent_description="Risk analysis expert", system_prompt="You are a risk assessment expert focused on evaluating investment risks and volatility.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="Portfolio-Strategy-Agent", agent_description="Portfolio optimization specialist", system_prompt="You are a portfolio strategist focused on diversification and long-term growth strategies.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ) ] @@ -726,28 +726,28 @@ content_agents = [ agent_description="Creative content specialist", system_prompt="You are a creative writer who produces engaging, story-driven content with vivid descriptions.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="Technical-Writer", agent_description="Technical content specialist", system_prompt="You are a technical writer who focuses on clarity, accuracy, and structured information.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="SEO-Optimized-Writer", agent_description="SEO content specialist", system_prompt="You are an SEO specialist who creates content optimized for search engines while maintaining quality.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="Conversational-Writer", agent_description="Conversational content specialist", system_prompt="You are a conversational writer who creates relatable, engaging content that connects with readers.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ) ] @@ -791,35 +791,35 @@ research_agents = [ agent_description="Quantitative research specialist", system_prompt="You are a quantitative researcher who analyzes data, statistics, and numerical evidence.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="Qualitative-Researcher", agent_description="Qualitative research specialist", system_prompt="You are a qualitative researcher who focuses on patterns, themes, and contextual understanding.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="Literature-Review-Specialist", agent_description="Literature review expert", system_prompt="You are a literature review specialist who synthesizes existing research and identifies knowledge gaps.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="Methodology-Expert", agent_description="Research methodology specialist", system_prompt="You are a methodology expert who evaluates research design, validity, and reliability.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ), Agent( agent_name="Ethics-Reviewer", agent_description="Research ethics specialist", system_prompt="You are an ethics reviewer who ensures research practices are responsible and unbiased.", max_loops=1, - model_name="gpt-4o" + model_name="gpt-4.1" ) ] diff --git a/docs/swarms/structs/multi_agent_router.md b/docs/swarms/structs/multi_agent_router.md index cebcd1ba..47ba2096 100644 --- a/docs/swarms/structs/multi_agent_router.md +++ b/docs/swarms/structs/multi_agent_router.md @@ -84,7 +84,7 @@ healthcare_router = MultiAgentRouter( name="Healthcare-Router", description="Routes medical and healthcare-related tasks to specialized agents", agents=agents, - model="gpt-4o", + model="gpt-4.1", temperature=0.1 ) diff --git a/docs/swarms/structs/sequential_workflow.md b/docs/swarms/structs/sequential_workflow.md index 25b93a93..b8a50e92 100644 --- a/docs/swarms/structs/sequential_workflow.md +++ b/docs/swarms/structs/sequential_workflow.md @@ -107,19 +107,19 @@ from swarms import Agent, SequentialWorkflow agent1 = Agent( agent_name="ICD-10 Code Analyzer", system_prompt="Analyze medical data and provide relevant ICD-10 codes.", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) agent2 = Agent( agent_name="ICD-10 Code Summarizer", system_prompt="Summarize the findings and suggest ICD-10 codes.", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) agent3 = Agent( agent_name="ICD-10 Code Validator", system_prompt="Validate and finalize the ICD-10 code recommendations.", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) diff --git a/docs/swarms/structs/transforms.md b/docs/swarms/structs/transforms.md index ae6fe418..bba4ab99 100644 --- a/docs/swarms/structs/transforms.md +++ b/docs/swarms/structs/transforms.md @@ -78,12 +78,12 @@ from swarms.structs.transforms import TransformConfig agent = Agent( agent_name="Trading-Agent", agent_description="Financial analysis agent", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, transforms=TransformConfig( enabled=True, method="middle-out", - model_name="gpt-4o", + model_name="gpt-4.1", preserve_system_messages=True, preserve_recent_messages=3, ), @@ -160,7 +160,7 @@ Built-in knowledge of popular models: # Supported models include: "gpt-4": 8192 tokens "gpt-4-turbo": 128000 tokens -"gpt-4o": 128000 tokens +"gpt-4.1": 128000 tokens "claude-3-opus": 200000 tokens "claude-3-sonnet": 200000 tokens # ... and many more @@ -213,7 +213,7 @@ from swarms.structs.transforms import apply_transforms_to_messages # Apply transforms to messages directly result = apply_transforms_to_messages( messages=my_messages, - model_name="gpt-4o" + model_name="gpt-4.1" ) ``` @@ -226,7 +226,7 @@ Transforms work seamlessly with conversation memory systems: def handle_transforms( transforms: MessageTransforms, short_memory: Conversation, - model_name: str = "gpt-4o" + model_name: str = "gpt-4.1" ) -> str: """Apply transforms to conversation memory.""" messages = short_memory.return_messages_as_dictionary() @@ -333,7 +333,7 @@ research_agent = Agent( # Support bot maintaining conversation history support_agent = Agent( agent_name="Support-Agent", - model_name="gpt-4o", + model_name="gpt-4.1", transforms=TransformConfig( enabled=True, preserve_system_messages=True, diff --git a/docs/swarms/tools/build_tool.md b/docs/swarms/tools/build_tool.md index f4bede71..8a186f99 100644 --- a/docs/swarms/tools/build_tool.md +++ b/docs/swarms/tools/build_tool.md @@ -334,7 +334,7 @@ agent = Agent( "clear, accurate financial insights and recommendations. Always format " "responses in markdown for better readability." ), - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=3, autosave=True, dashboard=False, @@ -519,7 +519,7 @@ agent = Agent( "data and provide comprehensive financial insights. Always present data " "in a clear, professional format with actionable recommendations." ), - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=3, autosave=True, dashboard=False, diff --git a/docs/swarms/utils/fallback_models.md b/docs/swarms/utils/fallback_models.md index 17a278b4..ef5efb20 100644 --- a/docs/swarms/utils/fallback_models.md +++ b/docs/swarms/utils/fallback_models.md @@ -20,7 +20,7 @@ from swarms import Agent # Configure a single fallback model agent = Agent( - model_name="gpt-4o", # Primary model + model_name="gpt-4.1", # Primary model fallback_model_name="gpt-4o-mini", # Fallback model max_loops=1 ) @@ -33,7 +33,7 @@ from swarms import Agent # Configure multiple fallback models using unified list agent = Agent( - fallback_models=["gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo", "claude-3-haiku"], # First is primary, rest are fallbacks + fallback_models=["gpt-4.1", "gpt-4o-mini", "gpt-3.5-turbo", "claude-3-haiku"], # First is primary, rest are fallbacks max_loops=1 ) ``` @@ -45,7 +45,7 @@ from swarms import Agent # You can use both single fallback and fallback list agent = Agent( - model_name="gpt-4o", # Primary model + model_name="gpt-4.1", # Primary model fallback_model_name="gpt-4o-mini", # Single fallback fallback_models=["gpt-3.5-turbo", "claude-3-haiku"], # Additional fallbacks max_loops=1 @@ -53,7 +53,7 @@ agent = Agent( # Or use the unified list approach (recommended) agent = Agent( - fallback_models=["gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo", "claude-3-haiku"], + fallback_models=["gpt-4.1", "gpt-4o-mini", "gpt-3.5-turbo", "claude-3-haiku"], max_loops=1 ) # Final order: gpt-4o -> gpt-4o-mini -> gpt-3.5-turbo -> claude-3-haiku @@ -128,7 +128,7 @@ from swarms import Agent # Create agent with fallback models agent = Agent( - model_name="gpt-4o", + model_name="gpt-4.1", fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"], max_loops=1 ) @@ -144,7 +144,7 @@ print(response) from swarms import Agent agent = Agent( - model_name="gpt-4o", + model_name="gpt-4.1", fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"], max_loops=1 ) @@ -156,7 +156,7 @@ print(f"Current model: {agent.get_current_model()}") response = agent.run("Analyze this data") # Check if fallback was used -if agent.get_current_model() != "gpt-4o": +if agent.get_current_model() != "gpt-4.1": print(f"Used fallback model: {agent.get_current_model()}") ``` @@ -166,7 +166,7 @@ if agent.get_current_model() != "gpt-4o": from swarms import Agent agent = Agent( - model_name="gpt-4o", + model_name="gpt-4.1", fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"], max_loops=1 ) @@ -247,7 +247,7 @@ Enable verbose logging to see detailed fallback information: ```python agent = Agent( - model_name="gpt-4o", + model_name="gpt-4.1", fallback_models=["gpt-4o-mini"], verbose=True # Enable detailed logging ) @@ -261,11 +261,11 @@ If you're upgrading from an agent without fallback support: ```python # Before -agent = Agent(model_name="gpt-4o") +agent = Agent(model_name="gpt-4.1") # After agent = Agent( - model_name="gpt-4o", + model_name="gpt-4.1", fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"] ) ``` diff --git a/examples/aop_examples/aop_cluster_example.md b/examples/aop_examples/aop_cluster_example.md new file mode 100644 index 00000000..9fb03de1 --- /dev/null +++ b/examples/aop_examples/aop_cluster_example.md @@ -0,0 +1,336 @@ +# AOP Cluster Example + +This example demonstrates how to use AOPCluster to connect to and manage multiple MCP servers running AOP agents. + +## Basic Cluster Setup + +```python +import json +from swarms.structs.aop import AOPCluster + +# Connect to multiple MCP servers +cluster = AOPCluster( + urls=[ + "http://localhost:8000/mcp", # Research and Analysis server + "http://localhost:8001/mcp", # Writing and Code server + "http://localhost:8002/mcp" # Financial server + ], + transport="streamable-http" +) + +# Get all available tools from all servers +all_tools = cluster.get_tools(output_type="dict") +print(f"Found {len(all_tools)} tools across all servers") + +# Pretty print all tools +print(json.dumps(all_tools, indent=2)) +``` + +## Finding Specific Tools + +```python +# Find a specific tool by name +research_tool = cluster.find_tool_by_server_name("Research-Agent") +if research_tool: + print("Found Research-Agent tool:") + print(json.dumps(research_tool, indent=2)) +else: + print("Research-Agent tool not found") + +# Find multiple tools +tool_names = ["Research-Agent", "Analysis-Agent", "Writing-Agent", "Code-Agent"] +found_tools = {} + +for tool_name in tool_names: + tool = cluster.find_tool_by_server_name(tool_name) + if tool: + found_tools[tool_name] = tool + print(f"✓ Found {tool_name}") + else: + print(f"✗ {tool_name} not found") + +print(f"Found {len(found_tools)} out of {len(tool_names)} tools") +``` + +## Tool Discovery and Management + +```python +# Get tools in different formats +json_tools = cluster.get_tools(output_type="json") +dict_tools = cluster.get_tools(output_type="dict") +str_tools = cluster.get_tools(output_type="str") + +print(f"JSON format: {len(json_tools)} tools") +print(f"Dict format: {len(dict_tools)} tools") +print(f"String format: {len(str_tools)} tools") + +# Analyze tool distribution across servers +server_tools = {} +for tool in dict_tools: + server_name = tool.get("server", "unknown") + if server_name not in server_tools: + server_tools[server_name] = [] + server_tools[server_name].append(tool.get("function", {}).get("name", "unknown")) + +print("\nTools by server:") +for server, tools in server_tools.items(): + print(f" {server}: {len(tools)} tools - {tools}") +``` + +## Advanced Cluster Management + +```python +class AOPClusterManager: + def __init__(self, urls, transport="streamable-http"): + self.cluster = AOPCluster(urls, transport) + self.tools_cache = {} + self.last_update = None + + def refresh_tools(self): + """Refresh the tools cache""" + self.tools_cache = {} + tools = self.cluster.get_tools(output_type="dict") + for tool in tools: + tool_name = tool.get("function", {}).get("name") + if tool_name: + self.tools_cache[tool_name] = tool + self.last_update = time.time() + return len(self.tools_cache) + + def get_tool(self, tool_name): + """Get a specific tool by name""" + if not self.tools_cache or time.time() - self.last_update > 300: # 5 min cache + self.refresh_tools() + return self.tools_cache.get(tool_name) + + def list_tools_by_category(self): + """Categorize tools by their names""" + categories = { + "research": [], + "analysis": [], + "writing": [], + "code": [], + "financial": [], + "other": [] + } + + for tool_name in self.tools_cache.keys(): + tool_name_lower = tool_name.lower() + if "research" in tool_name_lower: + categories["research"].append(tool_name) + elif "analysis" in tool_name_lower: + categories["analysis"].append(tool_name) + elif "writing" in tool_name_lower: + categories["writing"].append(tool_name) + elif "code" in tool_name_lower: + categories["code"].append(tool_name) + elif "financial" in tool_name_lower: + categories["financial"].append(tool_name) + else: + categories["other"].append(tool_name) + + return categories + + def get_available_servers(self): + """Get list of available servers""" + servers = set() + for tool in self.tools_cache.values(): + server = tool.get("server", "unknown") + servers.add(server) + return list(servers) + +# Usage example +import time + +manager = AOPClusterManager([ + "http://localhost:8000/mcp", + "http://localhost:8001/mcp", + "http://localhost:8002/mcp" +]) + +# Refresh and display tools +tool_count = manager.refresh_tools() +print(f"Loaded {tool_count} tools") + +# Categorize tools +categories = manager.list_tools_by_category() +for category, tools in categories.items(): + if tools: + print(f"{category.title()}: {tools}") + +# Get available servers +servers = manager.get_available_servers() +print(f"Available servers: {servers}") +``` + +## Error Handling and Resilience + +```python +class ResilientAOPCluster: + def __init__(self, urls, transport="streamable-http"): + self.urls = urls + self.transport = transport + self.cluster = AOPCluster(urls, transport) + self.failed_servers = set() + + def get_tools_with_fallback(self, output_type="dict"): + """Get tools with fallback for failed servers""" + try: + return self.cluster.get_tools(output_type=output_type) + except Exception as e: + print(f"Error getting tools: {e}") + # Try individual servers + all_tools = [] + for url in self.urls: + if url in self.failed_servers: + continue + try: + single_cluster = AOPCluster([url], self.transport) + tools = single_cluster.get_tools(output_type=output_type) + all_tools.extend(tools) + except Exception as server_error: + print(f"Server {url} failed: {server_error}") + self.failed_servers.add(url) + return all_tools + + def find_tool_with_retry(self, tool_name, max_retries=3): + """Find tool with retry logic""" + for attempt in range(max_retries): + try: + return self.cluster.find_tool_by_server_name(tool_name) + except Exception as e: + print(f"Attempt {attempt + 1} failed: {e}") + if attempt < max_retries - 1: + time.sleep(2 ** attempt) # Exponential backoff + return None + +# Usage +resilient_cluster = ResilientAOPCluster([ + "http://localhost:8000/mcp", + "http://localhost:8001/mcp", + "http://localhost:8002/mcp" +]) + +# Get tools with error handling +tools = resilient_cluster.get_tools_with_fallback() +print(f"Retrieved {len(tools)} tools") + +# Find tool with retry +research_tool = resilient_cluster.find_tool_with_retry("Research-Agent") +if research_tool: + print("Found Research-Agent tool") +else: + print("Research-Agent tool not found after retries") +``` + +## Monitoring and Health Checks + +```python +class AOPClusterMonitor: + def __init__(self, cluster_manager): + self.manager = cluster_manager + self.health_status = {} + + def check_server_health(self, url): + """Check if a server is healthy""" + try: + single_cluster = AOPCluster([url], self.manager.cluster.transport) + tools = single_cluster.get_tools(output_type="dict") + return { + "status": "healthy", + "tool_count": len(tools), + "timestamp": time.time() + } + except Exception as e: + return { + "status": "unhealthy", + "error": str(e), + "timestamp": time.time() + } + + def check_all_servers(self): + """Check health of all servers""" + for url in self.manager.cluster.urls: + health = self.check_server_health(url) + self.health_status[url] = health + status_icon = "✓" if health["status"] == "healthy" else "✗" + print(f"{status_icon} {url}: {health['status']}") + if health["status"] == "healthy": + print(f" Tools available: {health['tool_count']}") + else: + print(f" Error: {health['error']}") + + def get_health_summary(self): + """Get summary of server health""" + healthy_count = sum(1 for status in self.health_status.values() + if status["status"] == "healthy") + total_count = len(self.health_status) + return { + "healthy_servers": healthy_count, + "total_servers": total_count, + "health_percentage": (healthy_count / total_count) * 100 if total_count > 0 else 0 + } + +# Usage +monitor = AOPClusterMonitor(manager) +monitor.check_all_servers() + +summary = monitor.get_health_summary() +print(f"Health Summary: {summary['healthy_servers']}/{summary['total_servers']} servers healthy ({summary['health_percentage']:.1f}%)") +``` + +## Complete Example + +```python +import json +import time +from swarms.structs.aop import AOPCluster + +def main(): + # Initialize cluster + cluster = AOPCluster( + urls=[ + "http://localhost:8000/mcp", + "http://localhost:8001/mcp", + "http://localhost:8002/mcp" + ], + transport="streamable-http" + ) + + print("AOP Cluster Management System") + print("=" * 40) + + # Get all tools + print("\n1. Discovering tools...") + tools = cluster.get_tools(output_type="dict") + print(f"Found {len(tools)} tools across all servers") + + # List all tool names + tool_names = [tool.get("function", {}).get("name") for tool in tools] + print(f"Available tools: {tool_names}") + + # Find specific tools + print("\n2. Finding specific tools...") + target_tools = ["Research-Agent", "Analysis-Agent", "Writing-Agent", "Code-Agent", "Financial-Agent"] + + for tool_name in target_tools: + tool = cluster.find_tool_by_server_name(tool_name) + if tool: + print(f"✓ {tool_name}: Available") + else: + print(f"✗ {tool_name}: Not found") + + # Display tool details + print("\n3. Tool details:") + for tool in tools[:3]: # Show first 3 tools + print(f"\nTool: {tool.get('function', {}).get('name')}") + print(f"Description: {tool.get('function', {}).get('description')}") + print(f"Parameters: {list(tool.get('function', {}).get('parameters', {}).get('properties', {}).keys())}") + + print("\nAOP Cluster setup complete!") + +if __name__ == "__main__": + main() +``` + +This example demonstrates comprehensive AOP cluster management including tool discovery, error handling, health monitoring, and advanced cluster operations. diff --git a/examples/aop_examples/aop_cluster_example.py b/examples/aop_examples/aop_cluster_example.py new file mode 100644 index 00000000..a0a022e7 --- /dev/null +++ b/examples/aop_examples/aop_cluster_example.py @@ -0,0 +1,11 @@ +import json + +from swarms.structs.aop import AOPCluster + +aop_cluster = AOPCluster( + urls=["http://localhost:8000/mcp"], + transport="streamable-http", +) + +print(json.dumps(aop_cluster.get_tools(output_type="dict"), indent=4)) +print(aop_cluster.find_tool_by_server_name("Research-Agent")) diff --git a/examples/aop_examples/aop_server_example.md b/examples/aop_examples/aop_server_example.md new file mode 100644 index 00000000..22983128 --- /dev/null +++ b/examples/aop_examples/aop_server_example.md @@ -0,0 +1,318 @@ +# AOP Server Setup Example + +This example demonstrates how to set up an AOP (Agent Orchestration Protocol) server with multiple specialized agents. + +## Complete Server Setup + +```python +from swarms import Agent +from swarms.structs.aop import AOP + +# Create specialized agents +research_agent = Agent( + agent_name="Research-Agent", + agent_description="Expert in research, data collection, and information gathering", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + top_p=None, + dynamic_temperature_enabled=True, + system_prompt="""You are a research specialist. Your role is to: + 1. Gather comprehensive information on any given topic + 2. Analyze data from multiple sources + 3. Provide well-structured research findings + 4. Cite sources and maintain accuracy + 5. Present findings in a clear, organized manner + + Always provide detailed, factual information with proper context.""", +) + +analysis_agent = Agent( + agent_name="Analysis-Agent", + agent_description="Expert in data analysis, pattern recognition, and generating insights", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + top_p=None, + dynamic_temperature_enabled=True, + system_prompt="""You are an analysis specialist. Your role is to: + 1. Analyze data and identify patterns + 2. Generate actionable insights + 3. Create visualizations and summaries + 4. Provide statistical analysis + 5. Make data-driven recommendations + + Focus on extracting meaningful insights from information.""", +) + +writing_agent = Agent( + agent_name="Writing-Agent", + agent_description="Expert in content creation, editing, and communication", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + top_p=None, + dynamic_temperature_enabled=True, + system_prompt="""You are a writing specialist. Your role is to: + 1. Create engaging, well-structured content + 2. Edit and improve existing text + 3. Adapt tone and style for different audiences + 4. Ensure clarity and coherence + 5. Follow best practices in writing + + Always produce high-quality, professional content.""", +) + +code_agent = Agent( + agent_name="Code-Agent", + agent_description="Expert in programming, code review, and software development", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + top_p=None, + dynamic_temperature_enabled=True, + system_prompt="""You are a coding specialist. Your role is to: + 1. Write clean, efficient code + 2. Debug and fix issues + 3. Review and optimize code + 4. Explain programming concepts + 5. Follow best practices and standards + + Always provide working, well-documented code.""", +) + +financial_agent = Agent( + agent_name="Financial-Agent", + agent_description="Expert in financial analysis, market research, and investment insights", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + top_p=None, + dynamic_temperature_enabled=True, + system_prompt="""You are a financial specialist. Your role is to: + 1. Analyze financial data and markets + 2. Provide investment insights + 3. Assess risk and opportunities + 4. Create financial reports + 5. Explain complex financial concepts + + Always provide accurate, well-reasoned financial analysis.""", +) + +# Create AOP instance +deployer = AOP( + server_name="MyAgentServer", + port=8000, + verbose=True, + log_level="INFO" +) + +# Add all agents at once +agents = [ + research_agent, + analysis_agent, + writing_agent, + code_agent, + financial_agent, +] + +tool_names = deployer.add_agents_batch(agents) +print(f"Added {len(tool_names)} agents: {tool_names}") + +# Display server information +server_info = deployer.get_server_info() +print(f"Server: {server_info['server_name']}") +print(f"Total tools: {server_info['total_tools']}") +print(f"Available tools: {server_info['tools']}") + +# Start the server +print("Starting AOP server...") +deployer.run() +``` + +## Running the Server + +1. Save the code above to a file (e.g., `aop_server.py`) +2. Install required dependencies: + ```bash + pip install swarms + ``` +3. Run the server: + ```bash + python aop_server.py + ``` + +The server will start on `http://localhost:8000` and make all agents available as MCP tools. + +## Tool Usage Examples + +Once the server is running, you can call the tools using MCP clients: + +### Research Agent +```python +# Call the research agent +result = research_tool(task="Research the latest AI trends in 2024") +print(result) +``` + +### Analysis Agent with Image +```python +# Call the analysis agent with an image +result = analysis_tool( + task="Analyze this chart and provide insights", + img="path/to/chart.png" +) +print(result) +``` + +### Writing Agent with Multiple Images +```python +# Call the writing agent with multiple images +result = writing_tool( + task="Write a comprehensive report based on these images", + imgs=["image1.jpg", "image2.jpg", "image3.jpg"] +) +print(result) +``` + +### Code Agent with Validation +```python +# Call the code agent with expected output +result = code_tool( + task="Debug this Python function", + correct_answer="Expected output: Hello World" +) +print(result) +``` + +### Financial Agent +```python +# Call the financial agent +result = financial_tool(task="Analyze the current market trends for tech stocks") +print(result) +``` + +## Response Format + +All tools return a standardized response: + +```json +{ + "result": "The agent's response to the task", + "success": true, + "error": null +} +``` + +## Advanced Configuration + +### Custom Timeouts and Retries + +```python +# Add agent with custom configuration +deployer.add_agent( + agent=research_agent, + tool_name="custom_research_tool", + tool_description="Research tool with extended timeout", + timeout=120, # 2 minutes + max_retries=5, + verbose=True +) +``` + +### Custom Input/Output Schemas + +```python +# Define custom schemas +custom_input_schema = { + "type": "object", + "properties": { + "task": {"type": "string", "description": "The research task"}, + "sources": { + "type": "array", + "items": {"type": "string"}, + "description": "Specific sources to research" + }, + "depth": { + "type": "string", + "enum": ["shallow", "medium", "deep"], + "description": "Research depth level" + } + }, + "required": ["task"] +} + +# Add agent with custom schemas +deployer.add_agent( + agent=research_agent, + tool_name="advanced_research_tool", + input_schema=custom_input_schema, + timeout=60 +) +``` + +## Monitoring and Debugging + +### Enable Verbose Logging + +```python +deployer = AOP( + server_name="DebugServer", + verbose=True, + traceback_enabled=True, + log_level="DEBUG" +) +``` + +### Check Server Status + +```python +# List all registered agents +agents = deployer.list_agents() +print(f"Registered agents: {agents}") + +# Get detailed agent information +for agent_name in agents: + info = deployer.get_agent_info(agent_name) + print(f"Agent {agent_name}: {info}") + +# Get server information +server_info = deployer.get_server_info() +print(f"Server info: {server_info}") +``` + +## Production Deployment + +### External Access + +```python +deployer = AOP( + server_name="ProductionServer", + host="0.0.0.0", # Allow external connections + port=8000, + verbose=False, # Disable verbose logging in production + log_level="WARNING" +) +``` + +### Multiple Servers + +```python +# Server 1: Research and Analysis +research_deployer = AOP("ResearchServer", port=8000) +research_deployer.add_agent(research_agent) +research_deployer.add_agent(analysis_agent) + +# Server 2: Writing and Code +content_deployer = AOP("ContentServer", port=8001) +content_deployer.add_agent(writing_agent) +content_deployer.add_agent(code_agent) + +# Server 3: Financial +finance_deployer = AOP("FinanceServer", port=8002) +finance_deployer.add_agent(financial_agent) + +# Start all servers +import threading + +threading.Thread(target=research_deployer.run).start() +threading.Thread(target=content_deployer.run).start() +threading.Thread(target=finance_deployer.run).start() +``` + +This example demonstrates a complete AOP server setup with multiple specialized agents, proper configuration, and production-ready deployment options. diff --git a/examples/aop_examples/get_all_agents.py b/examples/aop_examples/get_all_agents.py new file mode 100644 index 00000000..2f369710 --- /dev/null +++ b/examples/aop_examples/get_all_agents.py @@ -0,0 +1,10 @@ +import json +from swarms.tools.mcp_client_tools import get_mcp_tools_sync + + +print( + json.dumps( + get_mcp_tools_sync(server_path="http://0.0.0.0:8000/mcp"), + indent=4, + ) +) diff --git a/examples/aop_examples/list_agents_and_call_them.py b/examples/aop_examples/list_agents_and_call_them.py new file mode 100644 index 00000000..d0c06503 --- /dev/null +++ b/examples/aop_examples/list_agents_and_call_them.py @@ -0,0 +1,105 @@ +import json +from swarms.tools.mcp_client_tools import ( + get_mcp_tools_sync, + execute_tool_call_simple, +) + + +def get_available_tools( + server_path: str = "http://localhost:8000/mcp", +) -> list: + """ + Get all available MCP tools from the server. + + Args: + server_path: URL of the MCP server + + Returns: + List of available tools + """ + tools = get_mcp_tools_sync(server_path=server_path) + return tools + + +def call_agent_tool( + tool_name: str, + task: str, + server_path: str = "http://localhost:8000/mcp", +) -> dict: + """ + Call a specific agent tool with a task. + + Args: + tool_name: Name of the agent tool to call + task: Task or prompt to send to the agent + server_path: URL of the MCP server + + Returns: + Response from the agent tool + """ + call = { + "function": { + "name": tool_name, + "arguments": {"task": task}, + } + } + + try: + import asyncio + + result = asyncio.run( + execute_tool_call_simple( + response=call, server_path=server_path + ) + ) + return result + except Exception as e: + return {"error": str(e)} + + +def main(): + """ + Main function to demonstrate MCP tool usage. + """ + server_path = "http://localhost:8000/mcp" + + # Step 1: Get available tools + tools = get_available_tools(server_path) + + if not tools: + return { + "error": "No tools available. Make sure the MCP server is running." + } + + # Step 2: Find an agent tool to call + agent_tools = [ + tool + for tool in tools + if "agent" in tool.get("function", {}).get("name", "").lower() + ] + + if not agent_tools: + return { + "error": "No agent tools found", + "available_tools": [ + tool.get("function", {}).get("name", "Unknown") + for tool in tools + ], + } + + # Step 3: Call the first available agent tool + agent_tool = agent_tools[0] + tool_name = agent_tool.get("function", {}).get("name") + + # Example task + task = "Hello! Can you help me understand what you do and what capabilities you have?" + + # Call the agent + result = call_agent_tool(tool_name, task, server_path) + + return result + + +if __name__ == "__main__": + result = main() + print(json.dumps(result, indent=4)) diff --git a/examples/aop_examples/server.py b/examples/aop_examples/server.py new file mode 100644 index 00000000..f9c14e8e --- /dev/null +++ b/examples/aop_examples/server.py @@ -0,0 +1,118 @@ +from swarms import Agent +from swarms.structs.aop import ( + AOP, +) + +# Create specialized agents +research_agent = Agent( + agent_name="Research-Agent", + agent_description="Expert in research, data collection, and information gathering", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + top_p=None, + dynamic_temperature_enabled=True, + system_prompt="""You are a research specialist. Your role is to: + 1. Gather comprehensive information on any given topic + 2. Analyze data from multiple sources + 3. Provide well-structured research findings + 4. Cite sources and maintain accuracy + 5. Present findings in a clear, organized manner + + Always provide detailed, factual information with proper context.""", +) + +analysis_agent = Agent( + agent_name="Analysis-Agent", + agent_description="Expert in data analysis, pattern recognition, and generating insights", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + top_p=None, + dynamic_temperature_enabled=True, + system_prompt="""You are an analysis specialist. Your role is to: + 1. Analyze data and identify patterns + 2. Generate actionable insights + 3. Create visualizations and summaries + 4. Provide statistical analysis + 5. Make data-driven recommendations + + Focus on extracting meaningful insights from information.""", +) + +writing_agent = Agent( + agent_name="Writing-Agent", + agent_description="Expert in content creation, editing, and communication", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + top_p=None, + dynamic_temperature_enabled=True, + system_prompt="""You are a writing specialist. Your role is to: + 1. Create engaging, well-structured content + 2. Edit and improve existing text + 3. Adapt tone and style for different audiences + 4. Ensure clarity and coherence + 5. Follow best practices in writing + + Always produce high-quality, professional content.""", +) + +code_agent = Agent( + agent_name="Code-Agent", + agent_description="Expert in programming, code review, and software development", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + top_p=None, + dynamic_temperature_enabled=True, + system_prompt="""You are a coding specialist. Your role is to: + 1. Write clean, efficient code + 2. Debug and fix issues + 3. Review and optimize code + 4. Explain programming concepts + 5. Follow best practices and standards + + Always provide working, well-documented code.""", +) + +financial_agent = Agent( + agent_name="Financial-Agent", + agent_description="Expert in financial analysis, market research, and investment insights", + model_name="anthropic/claude-sonnet-4-5", + max_loops=1, + top_p=None, + dynamic_temperature_enabled=True, + system_prompt="""You are a financial specialist. Your role is to: + 1. Analyze financial data and markets + 2. Provide investment insights + 3. Assess risk and opportunities + 4. Create financial reports + 5. Explain complex financial concepts + + Always provide accurate, well-reasoned financial analysis.""", +) + +# Basic usage - individual agent addition +deployer = AOP("MyAgentServer", verbose=True) + +agents = [ + research_agent, + analysis_agent, + writing_agent, + code_agent, + financial_agent, +] + +deployer.add_agents_batch(agents) + +# Example usage with different parameters +# The tools now accept: task, img, imgs, correct_answer parameters +# task: str (required) - The main task or prompt +# img: str (optional) - Single image to process +# imgs: List[str] (optional) - Multiple images to process +# correct_answer: str (optional) - Correct answer for validation + +# Example calls that would be made to the MCP tools: +# research_tool(task="Research the latest AI trends") +# analysis_tool(task="Analyze this data", img="path/to/image.jpg") +# writing_tool(task="Write a blog post", imgs=["img1.jpg", "img2.jpg"]) +# code_tool(task="Debug this code", correct_answer="expected_output") + +deployer.run() diff --git a/examples/demos/chart_swarm.py b/examples/demos/chart_swarm.py index ad1025e1..b75e8b5d 100644 --- a/examples/demos/chart_swarm.py +++ b/examples/demos/chart_swarm.py @@ -201,7 +201,7 @@ class ChartElement: class VisionAPI: def __init__( self, - model_name: str = "gpt-4o", + model_name: str = "gpt-4.1", max_tokens: int = 1000, temperature: float = 0.5, ): @@ -246,7 +246,7 @@ class VisionAPI: class ChartCitor: def __init__( self, - model_name: str = "gpt-4o", + model_name: str = "gpt-4.1", saved_state_path: str = "chartcitor_state.json", max_retries: int = 3, max_loops: int = 1, diff --git a/examples/demos/crypto/htx_swarm.py b/examples/demos/crypto/htx_swarm.py index 8a461c8f..461cde5c 100644 --- a/examples/demos/crypto/htx_swarm.py +++ b/examples/demos/crypto/htx_swarm.py @@ -29,7 +29,7 @@ Emphasize objective technical analysis without making direct price predictions. technical_agent = Agent( agent_name="Technical-Analyst", system_prompt=TECHNICAL_ANALYST_PROMPT, - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, verbose=True, dynamic_temperature_enabled=True, @@ -79,7 +79,7 @@ Focus on identifying both obvious and subtle risk factors. risk_agent = Agent( agent_name="Risk-Manager", system_prompt=RISK_MANAGER_PROMPT, - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, verbose=True, dynamic_temperature_enabled=True, @@ -108,7 +108,7 @@ Focus on identifying major market-moving factors and trends. macro_agent = Agent( agent_name="Macro-Analyst", system_prompt=MACRO_ANALYST_PROMPT, - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, verbose=True, dynamic_temperature_enabled=True, diff --git a/examples/demos/finance/sentiment_news_analysis.py b/examples/demos/finance/sentiment_news_analysis.py index bc283e6e..035d9273 100644 --- a/examples/demos/finance/sentiment_news_analysis.py +++ b/examples/demos/finance/sentiment_news_analysis.py @@ -193,7 +193,7 @@ agent = Agent( max_loops=1, tools_list_dictionary=tools, output_type="final", - model_name="gpt-4o", + model_name="gpt-4.1", ) diff --git a/examples/demos/medical/medical_coder_agent.py b/examples/demos/medical/medical_coder_agent.py index d4d1197c..ba866d27 100644 --- a/examples/demos/medical/medical_coder_agent.py +++ b/examples/demos/medical/medical_coder_agent.py @@ -45,7 +45,7 @@ chief_medical_officer = Agent( """, - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -69,7 +69,7 @@ virologist = Agent( * Secondary condition codes Document all findings using proper medical coding standards and include rationale for code selection.""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -94,7 +94,7 @@ internist = Agent( - Include hierarchical condition category (HCC) codes where applicable Document supporting evidence for each code selected.""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -125,7 +125,7 @@ medical_coder = Agent( 3. Symptom Codes 4. Complication Codes 5. Coding Notes""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -153,7 +153,7 @@ synthesizer = Agent( - Documentation improvements needed Include confidence levels and evidence quality for all diagnoses and codes.""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) diff --git a/examples/demos/medical/new_medical_rearrange.py b/examples/demos/medical/new_medical_rearrange.py index 0a7389bd..e57a2e75 100644 --- a/examples/demos/medical/new_medical_rearrange.py +++ b/examples/demos/medical/new_medical_rearrange.py @@ -27,7 +27,7 @@ chief_medical_officer = Agent( - Differential Diagnoses - Specialist Consultations Needed - Recommended Next Steps""", - model_name="gpt-4o", # Models from litellm -> claude-2 + model_name="gpt-4.1", # Models from litellm -> claude-2 max_loops=1, ) @@ -60,7 +60,7 @@ virologist = Agent( - Disease progression timeline - Risk factors for severe disease - Potential complications""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -91,7 +91,7 @@ internist = Agent( - System-specific symptoms - Relevant lab abnormalities - Risk factors for complications""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -127,7 +127,7 @@ synthesizer = Agent( - Confidence levels for each diagnosis - Knowledge gaps identified - Risk assessment""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) diff --git a/examples/demos/medical/rearrange_video_examples/term_sheet_swarm.py b/examples/demos/medical/rearrange_video_examples/term_sheet_swarm.py index 4e1dd72a..b9a15e72 100644 --- a/examples/demos/medical/rearrange_video_examples/term_sheet_swarm.py +++ b/examples/demos/medical/rearrange_video_examples/term_sheet_swarm.py @@ -27,7 +27,7 @@ lead_analyst = Agent( - Negotiation Points - Recommended Actions - Areas Requiring Specialist Review""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -62,7 +62,7 @@ safe_specialist = Agent( - Conversion mechanics explanation - Risk assessment for non-standard terms - Recommendations for negotiations""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -103,7 +103,7 @@ term_sheet_analyst = Agent( - Founder impact analysis - Investor rights summary - Governance implications""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -144,7 +144,7 @@ legal_analyst = Agent( - Required disclosures list - Recommended legal modifications - Jurisdiction-specific concerns""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -184,7 +184,7 @@ market_analyst = Agent( - Trend implications - Negotiation leverage points - Recommended modifications""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) diff --git a/examples/multi_agent/concurrent_examples/concurrent_example.py b/examples/multi_agent/concurrent_examples/concurrent_example.py index da9eb139..d10baed3 100644 --- a/examples/multi_agent/concurrent_examples/concurrent_example.py +++ b/examples/multi_agent/concurrent_examples/concurrent_example.py @@ -21,7 +21,7 @@ delaware_ccorp_agent = Agent( corporate law and ensure that all hiring practices are in compliance with state and federal regulations. """, - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) @@ -41,7 +41,7 @@ indian_foreign_agent = Agent( implications of hiring foreign nationals and the requirements for obtaining necessary visas and work permits. """, - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) diff --git a/examples/multi_agent/concurrent_examples/concurrent_swarm_example.py b/examples/multi_agent/concurrent_examples/concurrent_swarm_example.py index af2f659a..d9c91c61 100644 --- a/examples/multi_agent/concurrent_examples/concurrent_swarm_example.py +++ b/examples/multi_agent/concurrent_examples/concurrent_swarm_example.py @@ -9,7 +9,7 @@ if __name__ == "__main__": Agent( agent_name=f"Financial-Analysis-Agent-{i}", system_prompt=FINANCIAL_AGENT_SYS_PROMPT, - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, ) for i in range(3) # Adjust number of agents as needed diff --git a/examples/multi_agent/duo_agent.py b/examples/multi_agent/duo_agent.py index bb748cb9..de2a52c6 100644 --- a/examples/multi_agent/duo_agent.py +++ b/examples/multi_agent/duo_agent.py @@ -9,7 +9,7 @@ equity_analyst_1 = Agent( agent_description="Equity research analyst focused on fundamental analysis", system_prompt=FINANCIAL_AGENT_SYS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="swarms_corp", retry_attempts=3, @@ -28,7 +28,7 @@ equity_analyst_2 = Agent( agent_description="Equity research analyst focused on technical analysis", system_prompt=FINANCIAL_AGENT_SYS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="swarms_corp", retry_attempts=3, diff --git a/examples/multi_agent/forest_swarm_examples/forest_swarm_example.py b/examples/multi_agent/forest_swarm_examples/forest_swarm_example.py index 7955a163..c6be2244 100644 --- a/examples/multi_agent/forest_swarm_examples/forest_swarm_example.py +++ b/examples/multi_agent/forest_swarm_examples/forest_swarm_example.py @@ -21,28 +21,28 @@ def create_financial_services_forest(): budgeting, debt management, and financial goal setting. I help individuals create comprehensive financial plans and make informed decisions about their money.""", agent_name="Personal Financial Planner", - model_name="gpt-4o", + model_name="gpt-4.1", ), TreeAgent( system_prompt="""I am a tax preparation specialist with expertise in individual and small business tax returns. I help clients maximize deductions, understand tax laws, and file taxes accurately and on time.""", agent_name="Tax Preparation Specialist", - model_name="gpt-4o", + model_name="gpt-4.1", ), TreeAgent( system_prompt="""I am a retirement planning expert who helps individuals and families plan for retirement. I specialize in 401(k)s, IRAs, Social Security optimization, and creating sustainable retirement income strategies.""", agent_name="Retirement Planning Expert", - model_name="gpt-4o", + model_name="gpt-4.1", ), TreeAgent( system_prompt="""I am a debt management counselor who helps individuals and families get out of debt and build financial stability. I provide strategies for debt consolidation, negotiation, and creating sustainable repayment plans.""", agent_name="Debt Management Counselor", - model_name="gpt-4o", + model_name="gpt-4.1", ), ] @@ -54,28 +54,28 @@ def create_financial_services_forest(): fundamentals, market conditions, and economic indicators to help investors make informed decisions.""", agent_name="Stock Market Analyst", - model_name="gpt-4o", + model_name="gpt-4.1", ), TreeAgent( system_prompt="""I am an investment strategist specializing in portfolio diversification, risk management, and asset allocation. I help investors create balanced portfolios that align with their risk tolerance and financial goals.""", agent_name="Investment Strategist", - model_name="gpt-4o", + model_name="gpt-4.1", ), TreeAgent( system_prompt="""I am a cryptocurrency and blockchain expert who provides insights on digital assets, DeFi protocols, and emerging blockchain technologies. I help investors understand the risks and opportunities in the crypto market.""", agent_name="Cryptocurrency Expert", - model_name="gpt-4o", + model_name="gpt-4.1", ), TreeAgent( system_prompt="""I am a real estate investment advisor who helps investors evaluate real estate opportunities, understand market trends, and build real estate portfolios for long-term wealth building.""", agent_name="Real Estate Investment Advisor", - model_name="gpt-4o", + model_name="gpt-4.1", ), ] @@ -86,14 +86,14 @@ def create_financial_services_forest(): business valuation, mergers and acquisitions, and strategic financial planning for small to medium-sized businesses.""", agent_name="Business Financial Advisor", - model_name="gpt-4o", + model_name="gpt-4.1", ), TreeAgent( system_prompt="""I am a Delaware incorporation specialist with deep knowledge of corporate formation, tax benefits, legal requirements, and ongoing compliance for businesses incorporating in Delaware.""", agent_name="Delaware Incorporation Specialist", - model_name="gpt-4o", + model_name="gpt-4.1", ), TreeAgent( system_prompt="""I am a startup funding advisor who helps entrepreneurs secure @@ -101,14 +101,14 @@ def create_financial_services_forest(): financing options. I provide guidance on business plans, pitch decks, and investor relations.""", agent_name="Startup Funding Advisor", - model_name="gpt-4o", + model_name="gpt-4.1", ), TreeAgent( system_prompt="""I am a business tax strategist who helps businesses optimize their tax position through strategic planning, entity structure optimization, and compliance with federal, state, and local tax laws.""", agent_name="Business Tax Strategist", - model_name="gpt-4o", + model_name="gpt-4.1", ), ] diff --git a/sector_analysis_hiearchical_swarm.py b/examples/multi_agent/hiearchical_swarm/sector_analysis_hiearchical_swarm.py similarity index 100% rename from sector_analysis_hiearchical_swarm.py rename to examples/multi_agent/hiearchical_swarm/sector_analysis_hiearchical_swarm.py diff --git a/examples/multi_agent/majority_voting/_doda_majority_voting_example_new.py b/examples/multi_agent/majority_voting/_doda_majority_voting_example_new.py index 9989a557..4499626f 100644 --- a/examples/multi_agent/majority_voting/_doda_majority_voting_example_new.py +++ b/examples/multi_agent/majority_voting/_doda_majority_voting_example_new.py @@ -97,7 +97,7 @@ technical_agent = Agent( agent_description="Specialized in technical analysis, chart patterns, and trading signals", system_prompt=TECHNICAL_ANALYSIS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", ) fundamental_agent = Agent( @@ -105,7 +105,7 @@ fundamental_agent = Agent( agent_description="Specialized in financial statement analysis and company valuation", system_prompt=FUNDAMENTAL_ANALYSIS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", ) risk_agent = Agent( @@ -113,7 +113,7 @@ risk_agent = Agent( agent_description="Specialized in portfolio optimization and risk management strategies", system_prompt=RISK_MANAGEMENT_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", ) # Create the majority voting swarm with the three specialized quant agents diff --git a/examples/multi_agent/majority_voting/majority_voting_example.py b/examples/multi_agent/majority_voting/majority_voting_example.py index a2ba372a..98bd2968 100644 --- a/examples/multi_agent/majority_voting/majority_voting_example.py +++ b/examples/multi_agent/majority_voting/majority_voting_example.py @@ -14,7 +14,7 @@ agent = Agent( agent_description="Personal finance advisor agent", system_prompt=FINANCIAL_AGENT_SYS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="swarms_corp", retry_attempts=3, diff --git a/examples/multi_agent/majority_voting/snake_game_code_voting.py b/examples/multi_agent/majority_voting/snake_game_code_voting.py index 6a82d97e..aea619f9 100644 --- a/examples/multi_agent/majority_voting/snake_game_code_voting.py +++ b/examples/multi_agent/majority_voting/snake_game_code_voting.py @@ -72,7 +72,7 @@ def create_code_agents(): agent_name="Python-Code-Expert", agent_description="Senior Python developer specializing in clean, efficient code", system_prompt=PYTHON_EXPERT_PROMPT, - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, max_tokens=4000, temperature=0.7, @@ -84,7 +84,7 @@ def create_code_agents(): agent_name="Game-Dev-Specialist", agent_description="Game development expert focusing on mechanics and user experience", system_prompt=GAME_DEV_EXPERT_PROMPT, - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, max_tokens=4000, temperature=0.7, @@ -100,7 +100,7 @@ def create_consensus_agent(): agent_name="Code-Quality-Evaluator", agent_description="Senior code reviewer evaluating implementations across multiple criteria", system_prompt=CONSENSUS_EVALUATOR_PROMPT, - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, max_tokens=5000, temperature=0.3, # Lower temperature for more consistent evaluation diff --git a/examples/multi_agent/sonnet_4_5_sequential.py b/examples/multi_agent/sonnet_4_5_sequential.py new file mode 100644 index 00000000..ad0df7eb --- /dev/null +++ b/examples/multi_agent/sonnet_4_5_sequential.py @@ -0,0 +1,28 @@ +from swarms import Agent, SequentialWorkflow + +# Agent 1: The Researcher +researcher = Agent( + agent_name="Researcher", + system_prompt="Your job is to research the provided topic and provide a detailed summary.", + model_name="anthropic/claude-sonnet-4-5", + top_p=None, + dynamic_temperature_enabled=True, +) + +# Agent 2: The Writer +writer = Agent( + agent_name="Writer", + system_prompt="Your job is to take the research summary and write a beautiful, engaging blog post about it.", + model_name="anthropic/claude-sonnet-4-5", + top_p=None, + dynamic_temperature_enabled=True, +) + +# Create a sequential workflow where the researcher's output feeds into the writer's input +workflow = SequentialWorkflow(agents=[researcher, writer]) + +# Run the workflow on a task +final_post = workflow.run( + "Create a comprehensive and detailed report on Gold ETFs" +) +print(final_post) diff --git a/examples/multi_agent/swarm_router/heavy_swarm_router_example.py b/examples/multi_agent/swarm_router/heavy_swarm_router_example.py index e8349267..a0f5ac55 100644 --- a/examples/multi_agent/swarm_router/heavy_swarm_router_example.py +++ b/examples/multi_agent/swarm_router/heavy_swarm_router_example.py @@ -6,8 +6,8 @@ router = SwarmRouter( max_loops=1, swarm_type="HeavySwarm", heavy_swarm_loops_per_agent=1, - heavy_swarm_question_agent_model_name="gpt-4o", - heavy_swarm_worker_model_name="gpt-4o", + heavy_swarm_question_agent_model_name="gpt-4.1", + heavy_swarm_worker_model_name="gpt-4.1", ) router.run("What are the best ETFs for the american energy markets?") diff --git a/examples/multi_agent/swarm_router/swarm_router.py b/examples/multi_agent/swarm_router/swarm_router.py index 8b84d712..1801c25a 100644 --- a/examples/multi_agent/swarm_router/swarm_router.py +++ b/examples/multi_agent/swarm_router/swarm_router.py @@ -6,19 +6,19 @@ agents = [ agent_name="test_agent_1", agent_description="test_agent_1_description", system_prompt="test_agent_1_system_prompt", - model_name="gpt-4o", + model_name="gpt-4.1", ), Agent( agent_name="test_agent_2", agent_description="test_agent_2_description", system_prompt="test_agent_2_system_prompt", - model_name="gpt-4o", + model_name="gpt-4.1", ), Agent( agent_name="test_agent_3", agent_description="test_agent_3_description", system_prompt="test_agent_3_system_prompt", - model_name="gpt-4o", + model_name="gpt-4.1", ), ] diff --git a/examples/multi_agent/swarm_router/swarm_router_example.py b/examples/multi_agent/swarm_router/swarm_router_example.py index ef12a64e..41f6b189 100644 --- a/examples/multi_agent/swarm_router/swarm_router_example.py +++ b/examples/multi_agent/swarm_router/swarm_router_example.py @@ -19,7 +19,7 @@ portfolio_analyzer = Agent( 6. Review fund manager track record and strategy consistency Maintain focus on cost-efficiency and alignment with investment objectives.""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, saved_state_path="portfolio_analyzer.json", user_name="investment_team", @@ -47,7 +47,7 @@ allocation_strategist = Agent( 6. Account for correlation between assets Focus on creating well-diversified portfolios aligned with client goals and risk tolerance.""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, saved_state_path="allocation_strategist.json", user_name="investment_team", @@ -75,7 +75,7 @@ risk_manager = Agent( 6. Monitor factor exposures Focus on maintaining appropriate risk levels while maximizing risk-adjusted returns.""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, saved_state_path="risk_manager.json", user_name="investment_team", @@ -103,7 +103,7 @@ implementation_specialist = Agent( 6. Monitor tracking error Maintain focus on minimizing costs and maximizing tax efficiency during implementation.""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, saved_state_path="implementation_specialist.json", user_name="investment_team", @@ -131,7 +131,7 @@ monitoring_specialist = Agent( 6. Generate performance attribution reports Ensure continuous alignment with investment objectives while maintaining optimal portfolio efficiency.""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, saved_state_path="monitoring_specialist.json", user_name="investment_team", diff --git a/examples/multi_agent/swarm_router/swarm_router_test.py b/examples/multi_agent/swarm_router/swarm_router_test.py index 614740b8..208a6d90 100644 --- a/examples/multi_agent/swarm_router/swarm_router_test.py +++ b/examples/multi_agent/swarm_router/swarm_router_test.py @@ -7,42 +7,42 @@ research_manager = Agent( agent_name="Research Manager", agent_description="Manages research operations and coordinates research tasks", system_prompt="You are a research manager responsible for overseeing research projects and coordinating research efforts.", - model_name="gpt-4o", + model_name="gpt-4.1", ) data_analyst = Agent( agent_name="Data Analyst", agent_description="Analyzes data and generates insights", system_prompt="You are a data analyst specializing in processing and analyzing data to extract meaningful insights.", - model_name="gpt-4o", + model_name="gpt-4.1", ) research_assistant = Agent( agent_name="Research Assistant", agent_description="Assists with research tasks and data collection", system_prompt="You are a research assistant who helps gather information and support research activities.", - model_name="gpt-4o", + model_name="gpt-4.1", ) development_manager = Agent( agent_name="Development Manager", agent_description="Manages development projects and coordinates development tasks", system_prompt="You are a development manager responsible for overseeing software development projects and coordinating development efforts.", - model_name="gpt-4o", + model_name="gpt-4.1", ) software_engineer = Agent( agent_name="Software Engineer", agent_description="Develops and implements software solutions", system_prompt="You are a software engineer specializing in building and implementing software solutions.", - model_name="gpt-4o", + model_name="gpt-4.1", ) qa_engineer = Agent( agent_name="QA Engineer", agent_description="Tests and ensures quality of software", system_prompt="You are a QA engineer responsible for testing software and ensuring its quality.", - model_name="gpt-4o", + model_name="gpt-4.1", ) swarm_router = SwarmRouter( diff --git a/examples/multi_agent/swarms_api_examples/hedge_fund_swarm.py b/examples/multi_agent/swarms_api_examples/hedge_fund_swarm.py index c6cada55..b169a8ee 100644 --- a/examples/multi_agent/swarms_api_examples/hedge_fund_swarm.py +++ b/examples/multi_agent/swarms_api_examples/hedge_fund_swarm.py @@ -41,7 +41,7 @@ def run_single_swarm(): "agent_name": "Risk Assessment Agent", "description": "Evaluates risks in investment strategies.", "system_prompt": "You are a risk assessment expert in cryptocurrency. Identify and evaluate risks related to investment strategies, including market and credit risks. Provide a risk analysis report with assessments and mitigation strategies.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, @@ -50,7 +50,7 @@ def run_single_swarm(): "agent_name": "Portfolio Manager", "description": "Manages and optimizes investment portfolios.", "system_prompt": "You are a portfolio manager for a crypto hedge fund. Optimize asset allocation based on market conditions. Analyze existing assets, suggest adjustments, and provide diversification strategies.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, @@ -59,7 +59,7 @@ def run_single_swarm(): "agent_name": "Market Sentiment Analyst", "description": "Analyzes market sentiment for trading strategies.", "system_prompt": "You are a market sentiment analyst in cryptocurrency. Assess current sentiment by analyzing news and social media. Provide insights on how sentiment impacts investment decisions and summarize key indicators.", - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, diff --git a/examples/multi_agent/swarms_api_examples/swarms_api_client.py b/examples/multi_agent/swarms_api_examples/swarms_api_client.py index 0b241777..a9af9580 100644 --- a/examples/multi_agent/swarms_api_examples/swarms_api_client.py +++ b/examples/multi_agent/swarms_api_examples/swarms_api_client.py @@ -12,7 +12,7 @@ agents = [ description="Conducts medical research and analysis", system_prompt="You are a medical researcher specializing in clinical studies.", max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", role="worker", ), AgentInput( @@ -20,7 +20,7 @@ agents = [ description="Provides medical diagnoses based on symptoms and test results", system_prompt="You are a medical diagnostician with expertise in identifying diseases.", max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", role="worker", ), AgentInput( @@ -28,7 +28,7 @@ agents = [ description="Advises on pharmaceutical treatments and drug interactions", system_prompt="You are a pharmaceutical expert knowledgeable about medications and their effects.", max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", role="worker", ), ] diff --git a/examples/multi_agent/utils/meme_agents/bob_the_agent.py b/examples/multi_agent/utils/meme_agents/bob_the_agent.py index 3016e3b6..3028dffa 100644 --- a/examples/multi_agent/utils/meme_agents/bob_the_agent.py +++ b/examples/multi_agent/utils/meme_agents/bob_the_agent.py @@ -20,7 +20,7 @@ agent = Agent( agent_description="The funniest, most optimistic agent around who sees every problem as a building project.", system_prompt=BOB_THE_BUILDER_SYS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="swarms_corp", retry_attempts=3, diff --git a/examples/rag/qdrant_rag_example.py b/examples/rag/qdrant_rag_example.py index b39e0c1e..e9209970 100644 --- a/examples/rag/qdrant_rag_example.py +++ b/examples/rag/qdrant_rag_example.py @@ -87,7 +87,7 @@ for doc in documents: agent = Agent( agent_name="RAG-Agent", agent_description="Agent with Qdrant-powered RAG for enhanced knowledge retrieval", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, dynamic_temperature_enabled=True, long_term_memory=rag_db, diff --git a/examples/single_agent/reasoning_agent_examples/reasoning_duo.py b/examples/single_agent/reasoning_agent_examples/reasoning_duo.py index 28c00238..9ccf4550 100644 --- a/examples/single_agent/reasoning_agent_examples/reasoning_duo.py +++ b/examples/single_agent/reasoning_agent_examples/reasoning_duo.py @@ -136,7 +136,7 @@ action_agent = Agent( agent_description="Practical implementation and execution agent", system_prompt=ACTION_AGENT_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, ) diff --git a/examples/single_agent/tools/litellm_tool_example.py b/examples/single_agent/tools/litellm_tool_example.py index e79b5655..0bdd1da4 100644 --- a/examples/single_agent/tools/litellm_tool_example.py +++ b/examples/single_agent/tools/litellm_tool_example.py @@ -40,7 +40,7 @@ tool_schema = BaseTool( tool_schema = tool_schema["functions"][0] llm = LiteLLM( - model_name="gpt-4o", + model_name="gpt-4.1", ) print( diff --git a/examples/single_agent/tools/omni_modal_agent.py b/examples/single_agent/tools/omni_modal_agent.py index 242a1171..7c658d69 100644 --- a/examples/single_agent/tools/omni_modal_agent.py +++ b/examples/single_agent/tools/omni_modal_agent.py @@ -270,7 +270,7 @@ print(test) # tools=[generate_modalities], # system_prompt=self.system_prompt, # max_loops=1, -# model_name="gpt-4o", +# model_name="gpt-4.1", # ) # def run(self, task: str): diff --git a/examples/single_agent/tools/swarms_of_browser_agents.py b/examples/single_agent/tools/swarms_of_browser_agents.py index 32d31e47..5306bf37 100644 --- a/examples/single_agent/tools/swarms_of_browser_agents.py +++ b/examples/single_agent/tools/swarms_of_browser_agents.py @@ -16,7 +16,7 @@ class BrowserAgent: async def browser_agent_test(self, task: str): agent = Agent( task=task, - llm=ChatOpenAI(model="gpt-4o"), + llm=ChatOpenAI(model="gpt-4.1"), ) result = await agent.run() return result diff --git a/examples/single_agent/tools/together_deepseek_agent.py b/examples/single_agent/tools/together_deepseek_agent.py index 8a91eebb..f2a2883b 100644 --- a/examples/single_agent/tools/together_deepseek_agent.py +++ b/examples/single_agent/tools/together_deepseek_agent.py @@ -78,7 +78,7 @@ agent = Agent( agent_description="Expert cryptocurrency financial analyst and market researcher", system_prompt=CRYPTO_ANALYST_SYSTEM_PROMPT, max_loops="auto", - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="crypto_analyst", output_type="str", diff --git a/examples/single_agent/tools/tools_examples/dex_screener.py b/examples/single_agent/tools/tools_examples/dex_screener.py index 5c1bfbc1..03d2106a 100644 --- a/examples/single_agent/tools/tools_examples/dex_screener.py +++ b/examples/single_agent/tools/tools_examples/dex_screener.py @@ -9,7 +9,7 @@ agent = Agent( agent_name="Financial-Analysis-Agent", agent_description="Personal finance advisor agent", max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="swarms_corp", return_step_meta=False, diff --git a/examples/single_agent/tools/tools_examples/financial_news_agent.py b/examples/single_agent/tools/tools_examples/financial_news_agent.py index c949a4fe..8cb22fac 100644 --- a/examples/single_agent/tools/tools_examples/financial_news_agent.py +++ b/examples/single_agent/tools/tools_examples/financial_news_agent.py @@ -12,7 +12,7 @@ agent = Agent( agent_description="Personal finance advisor agent", system_prompt=FINANCIAL_AGENT_SYS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="swarms_corp", retry_attempts=3, diff --git a/examples/single_agent/tools/tools_examples/swarms_tool_example_simple.py b/examples/single_agent/tools/tools_examples/swarms_tool_example_simple.py index 96311883..678d4f09 100644 --- a/examples/single_agent/tools/tools_examples/swarms_tool_example_simple.py +++ b/examples/single_agent/tools/tools_examples/swarms_tool_example_simple.py @@ -14,7 +14,7 @@ agent = Agent( agent_description="Personal finance advisor agent", system_prompt=FINANCIAL_AGENT_SYS_PROMPT, max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="swarms_corp", return_step_meta=False, diff --git a/examples/single_agent/utils/async_agent.py b/examples/single_agent/utils/async_agent.py index 92bf0b2d..4e157e45 100644 --- a/examples/single_agent/utils/async_agent.py +++ b/examples/single_agent/utils/async_agent.py @@ -12,7 +12,7 @@ agent = Agent( + " Output the token when you're done creating a portfolio" ), max_loops=1, - model_name="gpt-4o", + model_name="gpt-4.1", dynamic_temperature_enabled=True, user_name="Kye", retry_attempts=3, diff --git a/examples/single_agent/utils/transform_prompts/transforms_agent_example.py b/examples/single_agent/utils/transform_prompts/transforms_agent_example.py index 470c1e34..b91ea8d2 100644 --- a/examples/single_agent/utils/transform_prompts/transforms_agent_example.py +++ b/examples/single_agent/utils/transform_prompts/transforms_agent_example.py @@ -25,12 +25,12 @@ agent = Agent( # Alternative way to configure transforms using dictionary # agent_with_dict_transforms = Agent( # agent_name="Trading-Agent-Dict", -# model_name="gpt-4o", +# model_name="gpt-4.1", # max_loops=1, # transforms={ # "enabled": True, # "method": "middle-out", -# "model_name": "gpt-4o", +# "model_name": "gpt-4.1", # "preserve_system_messages": True, # "preserve_recent_messages": 3, # }, diff --git a/examples/single_agent/utils/transform_prompts/transforms_examples.py b/examples/single_agent/utils/transform_prompts/transforms_examples.py index ef0bd092..cdecc211 100644 --- a/examples/single_agent/utils/transform_prompts/transforms_examples.py +++ b/examples/single_agent/utils/transform_prompts/transforms_examples.py @@ -181,7 +181,7 @@ def example_3_agent_integration(): agent = Agent( agent_name="Transformed-Agent", agent_description="AI assistant with automatic context management", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, streaming_on=False, print_on=False, @@ -189,7 +189,7 @@ def example_3_agent_integration(): transforms=TransformConfig( enabled=True, method="middle-out", - model_name="gpt-4o", + model_name="gpt-4.1", preserve_system_messages=True, preserve_recent_messages=3, ), diff --git a/examples/single_agent/vision/multimodal_example.py b/examples/single_agent/vision/multimodal_example.py index 19a2c996..6395842a 100644 --- a/examples/single_agent/vision/multimodal_example.py +++ b/examples/single_agent/vision/multimodal_example.py @@ -69,7 +69,7 @@ quality_control_agent = Agent( agent_name="Quality Control Agent", agent_description="A quality control agent that analyzes images and provides a detailed report on the quality of the product in the image.", # model_name="anthropic/claude-3-opus-20240229", - model_name="gpt-4o", + model_name="gpt-4.1", system_prompt=custom_system_prompt, multi_modal=True, max_loops=1, diff --git a/examples/swarms_api_examples/legal_team.py b/examples/swarms_api_examples/legal_team.py index 48d76b05..13131a7d 100644 --- a/examples/swarms_api_examples/legal_team.py +++ b/examples/swarms_api_examples/legal_team.py @@ -89,7 +89,7 @@ def create_legal_review_swarm(document_text): "agent_name": "Structure Analyst", "description": "Analyzes document structure and organization", "system_prompt": STRUCTURE_ANALYST_PROMPT, - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, @@ -99,7 +99,7 @@ def create_legal_review_swarm(document_text): "agent_name": "Party Identifier", "description": "Identifies parties and their legal roles", "system_prompt": PARTY_IDENTIFIER_PROMPT, - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, @@ -109,7 +109,7 @@ def create_legal_review_swarm(document_text): "agent_name": "Clause Extractor", "description": "Extracts key terms, definitions, and standard clauses", "system_prompt": CLAUSE_EXTRACTOR_PROMPT, - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, @@ -119,7 +119,7 @@ def create_legal_review_swarm(document_text): "agent_name": "Ambiguity Checker", "description": "Flags ambiguous or conflicting language", "system_prompt": AMBIGUITY_CHECKER_PROMPT, - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, @@ -129,7 +129,7 @@ def create_legal_review_swarm(document_text): "agent_name": "Compliance Reviewer", "description": "Reviews document for compliance with legal standards", "system_prompt": COMPLIANCE_REVIEWER_PROMPT, - "model_name": "gpt-4o", + "model_name": "gpt-4.1", "role": "worker", "max_loops": 1, "max_tokens": 8192, diff --git a/examples/utils/misc/conversation_structure/conversation_example_supabase.py b/examples/utils/misc/conversation_structure/conversation_example_supabase.py index 1767d833..b9daa0c2 100644 --- a/examples/utils/misc/conversation_structure/conversation_example_supabase.py +++ b/examples/utils/misc/conversation_structure/conversation_example_supabase.py @@ -130,7 +130,7 @@ def create_aggregator_agent() -> Agent: - Detailed Analysis - Key Recommendations - Implementation Steps""", - model_name="gpt-4o", + model_name="gpt-4.1", max_loops=1, verbose=True, output_type="string", @@ -141,7 +141,7 @@ def aggregate_with_supabase( workers: List[Agent], task: str = None, type: HistoryOutputType = "all", - aggregator_model_name: str = "gpt-4o", + aggregator_model_name: str = "gpt-4.1", # Backend parameters for conversation storage backend: str = "supabase", supabase_url: str = None, diff --git a/swarms/agents/auto_generate_swarm_config.py b/swarms/agents/auto_generate_swarm_config.py index 0067d13d..66a4bfbc 100644 --- a/swarms/agents/auto_generate_swarm_config.py +++ b/swarms/agents/auto_generate_swarm_config.py @@ -181,7 +181,7 @@ swarm_architecture: def generate_swarm_config( task: str, file_name: str = "swarm_config_output.yaml", - model_name: str = "gpt-4o", + model_name: str = "gpt-4.1", *args, **kwargs, ): @@ -194,7 +194,7 @@ def generate_swarm_config( Args: task (str): The task to be performed by the swarm. file_name (str, optional): The file name for the output YAML configuration. Defaults to "swarm_config_output.yaml". - model_name (str, optional): The name of the model to use for the agent. Defaults to "gpt-4o". + model_name (str, optional): The name of the model to use for the agent. Defaults to "gpt-4.1". *args: Additional positional arguments to be passed to the agent's run method. **kwargs: Additional keyword arguments to be passed to the agent's run method. diff --git a/swarms/agents/flexion_agent.py b/swarms/agents/flexion_agent.py index d77ee731..d325f34a 100644 --- a/swarms/agents/flexion_agent.py +++ b/swarms/agents/flexion_agent.py @@ -606,7 +606,7 @@ Based on the original response, evaluation, and reflection, provide an improved # # Initialize the Reflexion Agent # agent = ReflexionAgent( # agent_name="reflexion-agent", -# model_name="gpt-4o", # Using OpenAI's model +# model_name="gpt-4.1", # Using OpenAI's model # max_loops=1, # Maximum of 3 reflection iterations # ) diff --git a/swarms/agents/openai_assistant.py b/swarms/agents/openai_assistant.py index 09b8637d..4b249ef4 100644 --- a/swarms/agents/openai_assistant.py +++ b/swarms/agents/openai_assistant.py @@ -47,7 +47,7 @@ class OpenAIAssistant(Agent): >>> assistant = OpenAIAssistant( ... name="Math Tutor", ... instructions="You are a personal math tutor.", - ... model="gpt-4o", + ... model="gpt-4.1", ... tools=[{"type": "code_interpreter"}] ... ) >>> response = assistant.run("Solve 3x + 11 = 14") @@ -58,7 +58,7 @@ class OpenAIAssistant(Agent): name: str, description: str = "Standard openai assistant wrapper", instructions: Optional[str] = None, - model: str = "gpt-4o", + model: str = "gpt-4.1", tools: Optional[List[Dict[str, Any]]] = None, file_ids: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, diff --git a/swarms/agents/reasoning_duo.py b/swarms/agents/reasoning_duo.py index 72a80154..c0ddc156 100644 --- a/swarms/agents/reasoning_duo.py +++ b/swarms/agents/reasoning_duo.py @@ -32,7 +32,7 @@ class ReasoningDuo: agent_description: str = "A highly intelligent and thoughtful AI designed to provide accurate and well-reasoned answers to the user's questions.", model_name: str = "gpt-4o-mini", description: str = "A highly intelligent and thoughtful AI designed to provide accurate and well-reasoned answers to the user's questions.", - model_names: list[str] = ["gpt-4o-mini", "gpt-4o"], + model_names: list[str] = ["gpt-4o-mini", "gpt-4.1"], system_prompt: str = "You are a helpful assistant that can answer questions and help with tasks.", output_type: OutputType = "dict-all-except-first", reasoning_model_name: Optional[ diff --git a/swarms/prompts/agent_orchestration_prompt.py b/swarms/prompts/agent_orchestration_prompt.py index 08ac58ae..9b5c9a6e 100644 --- a/swarms/prompts/agent_orchestration_prompt.py +++ b/swarms/prompts/agent_orchestration_prompt.py @@ -1,4 +1,3 @@ - BOSS_SYSTEM_PROMPT = """ # Swarm Intelligence Orchestrator diff --git a/swarms/schemas/base_schemas.py b/swarms/schemas/base_schemas.py index 2669f8d4..dd5f3e1e 100644 --- a/swarms/schemas/base_schemas.py +++ b/swarms/schemas/base_schemas.py @@ -64,7 +64,7 @@ class DeltaMessage(BaseModel): class ChatCompletionRequest(BaseModel): - model: str = "gpt-4o" + model: str = "gpt-4.1" messages: List[ChatMessageInput] temperature: Optional[float] = 0.8 top_p: Optional[float] = 0.8 diff --git a/swarms/structs/agent.py b/swarms/structs/agent.py index 970c2a7a..4b41651f 100644 --- a/swarms/structs/agent.py +++ b/swarms/structs/agent.py @@ -302,19 +302,19 @@ class Agent: Examples: >>> from swarms import Agent - >>> agent = Agent(model_name="gpt-4o", max_loops=1) + >>> agent = Agent(model_name="gpt-4.1", max_loops=1) >>> response = agent.run("Generate a report on the financials.") >>> print(response) >>> # Generate a report on the financials. >>> # Real-time streaming example - >>> agent = Agent(model_name="gpt-4o", max_loops=1, streaming_on=True) + >>> agent = Agent(model_name="gpt-4.1", max_loops=1, streaming_on=True) >>> response = agent.run("Tell me a long story.") # Will stream in real-time >>> print(response) # Final complete response >>> # Fallback model example >>> agent = Agent( - ... fallback_models=["gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo"], + ... fallback_models=["gpt-4.1", "gpt-4o-mini", "gpt-3.5-turbo"], ... max_loops=1 ... ) >>> response = agent.run("Generate a report on the financials.") diff --git a/swarms/structs/aop.py b/swarms/structs/aop.py new file mode 100644 index 00000000..dce13a6d --- /dev/null +++ b/swarms/structs/aop.py @@ -0,0 +1,708 @@ +import asyncio +import sys +import traceback +from dataclasses import dataclass +from typing import Any, Dict, List, Literal, Optional + +from loguru import logger +from mcp.server.fastmcp import FastMCP + +from swarms.structs.agent import Agent +from swarms.structs.omni_agent_types import AgentType +from swarms.tools.mcp_client_tools import ( + get_tools_for_multiple_mcp_servers, +) + + +@dataclass +class AgentToolConfig: + """ + Configuration for converting an agent to an MCP tool. + + Attributes: + tool_name: The name of the tool in the MCP server + tool_description: Description of what the tool does + input_schema: JSON schema for the tool's input parameters + output_schema: JSON schema for the tool's output + timeout: Maximum time to wait for agent execution (seconds) + max_retries: Number of retries if agent execution fails + verbose: Enable verbose logging for this tool + traceback_enabled: Enable traceback logging for errors + """ + + tool_name: str + tool_description: str + input_schema: Dict[str, Any] + output_schema: Dict[str, Any] + timeout: int = 30 + max_retries: int = 3 + verbose: bool = False + traceback_enabled: bool = True + + +class AOP: + """ + A class that takes a list of agents and deploys them as unique tools in an MCP server. + + This class provides functionality to: + 1. Convert swarms agents into MCP tools + 2. Deploy multiple agents as individual tools + 3. Handle tool execution with proper error handling + 4. Manage the MCP server lifecycle + + Attributes: + mcp_server: The FastMCP server instance + agents: Dictionary mapping tool names to agent instances + tool_configs: Dictionary mapping tool names to their configurations + server_name: Name of the MCP server + """ + + def __init__( + self, + server_name: str = "AOP Cluster", + description: str = "A cluster that enables you to deploy multiple agents as tools in an MCP server.", + agents: any = None, + port: int = 8000, + transport: str = "streamable-http", + verbose: bool = False, + traceback_enabled: bool = True, + host: str = "localhost", + log_level: str = "INFO", + *args, + **kwargs, + ): + """ + Initialize the AOP. + + Args: + server_name: Name for the MCP server + agents: Optional list of agents to add initially + port: Port for the MCP server + transport: Transport type for the MCP server + verbose: Enable verbose logging + traceback_enabled: Enable traceback logging for errors + log_level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL) + """ + self.server_name = server_name + self.verbose = verbose + self.traceback_enabled = traceback_enabled + self.log_level = log_level + self.host = host + self.port = port + self.agents: Dict[str, Agent] = {} + self.tool_configs: Dict[str, AgentToolConfig] = {} + self.transport = transport + self.mcp_server = FastMCP( + name=server_name, port=port, *args, **kwargs + ) + + # Configure logger + logger.remove() # Remove default handler + logger.add( + sys.stderr, + level=log_level, + format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}", + colorize=True, + ) + + logger.info( + f"Initialized AOP with server name: {server_name}, verbose: {verbose}, traceback: {traceback_enabled}" + ) + + # Add initial agents if provided + if agents: + logger.info(f"Adding {len(agents)} initial agents") + self.add_agents_batch(agents) + + def add_agent( + self, + agent: AgentType, + tool_name: Optional[str] = None, + tool_description: Optional[str] = None, + input_schema: Optional[Dict[str, Any]] = None, + output_schema: Optional[Dict[str, Any]] = None, + timeout: int = 30, + max_retries: int = 3, + verbose: Optional[bool] = None, + traceback_enabled: Optional[bool] = None, + ) -> str: + """ + Add an agent to the MCP server as a tool. + + Args: + agent: The swarms Agent instance to deploy + tool_name: Name for the tool (defaults to agent.agent_name) + tool_description: Description of the tool (defaults to agent.agent_description) + input_schema: JSON schema for input parameters + output_schema: JSON schema for output + timeout: Maximum execution time in seconds + max_retries: Number of retries on failure + verbose: Enable verbose logging for this tool (defaults to deployer's verbose setting) + traceback_enabled: Enable traceback logging for this tool (defaults to deployer's setting) + + Returns: + str: The tool name that was registered + + Raises: + ValueError: If agent is None or tool_name already exists + """ + if agent is None: + logger.error("Cannot add None agent") + raise ValueError("Agent cannot be None") + + # Use agent name as tool name if not provided + if tool_name is None: + tool_name = ( + agent.agent_name or f"agent_{len(self.agents)}" + ) + + if tool_name in self.agents: + logger.error(f"Tool name '{tool_name}' already exists") + raise ValueError( + f"Tool name '{tool_name}' already exists" + ) + + # Use deployer defaults if not specified + if verbose is None: + verbose = self.verbose + if traceback_enabled is None: + traceback_enabled = self.traceback_enabled + + logger.debug( + f"Adding agent '{agent.agent_name}' as tool '{tool_name}' with verbose={verbose}, traceback={traceback_enabled}" + ) + + # Use agent description if not provided + if tool_description is None: + tool_description = ( + agent.agent_description + or f"Agent tool: {agent.agent_name}" + ) + + # Default input schema for task-based agents + if input_schema is None: + input_schema = { + "type": "object", + "properties": { + "task": { + "type": "string", + "description": "The task or prompt to execute with this agent", + }, + "img": { + "type": "string", + "description": "Optional image to be processed by the agent", + }, + "imgs": { + "type": "array", + "items": {"type": "string"}, + "description": "Optional list of images to be processed by the agent", + }, + "correct_answer": { + "type": "string", + "description": "Optional correct answer for validation or comparison", + }, + }, + "required": ["task"], + } + + # Default output schema + if output_schema is None: + output_schema = { + "type": "object", + "properties": { + "result": { + "type": "string", + "description": "The agent's response to the task", + }, + "success": { + "type": "boolean", + "description": "Whether the task was executed successfully", + }, + "error": { + "type": "string", + "description": "Error message if execution failed", + }, + }, + "required": ["result", "success"], + } + + # Store agent and configuration + self.agents[tool_name] = agent + self.tool_configs[tool_name] = AgentToolConfig( + tool_name=tool_name, + tool_description=tool_description, + input_schema=input_schema, + output_schema=output_schema, + timeout=timeout, + max_retries=max_retries, + verbose=verbose, + traceback_enabled=traceback_enabled, + ) + + # Register the tool with the MCP server + self._register_tool(tool_name, agent) + + logger.info( + f"Added agent '{agent.agent_name}' as tool '{tool_name}' (verbose={verbose}, traceback={traceback_enabled})" + ) + return tool_name + + def add_agents_batch( + self, + agents: List[Agent], + tool_names: Optional[List[str]] = None, + tool_descriptions: Optional[List[str]] = None, + input_schemas: Optional[List[Dict[str, Any]]] = None, + output_schemas: Optional[List[Dict[str, Any]]] = None, + timeouts: Optional[List[int]] = None, + max_retries_list: Optional[List[int]] = None, + verbose_list: Optional[List[bool]] = None, + traceback_enabled_list: Optional[List[bool]] = None, + ) -> List[str]: + """ + Add multiple agents to the MCP server as tools in batch. + + Args: + agents: List of swarms Agent instances + tool_names: Optional list of tool names (defaults to agent names) + tool_descriptions: Optional list of tool descriptions + input_schemas: Optional list of input schemas + output_schemas: Optional list of output schemas + timeouts: Optional list of timeout values + max_retries_list: Optional list of max retry values + verbose_list: Optional list of verbose settings for each agent + traceback_enabled_list: Optional list of traceback settings for each agent + + Returns: + List[str]: List of tool names that were registered + + Raises: + ValueError: If agents list is empty or contains None values + """ + if not agents: + logger.error("Cannot add empty agents list") + raise ValueError("Agents list cannot be empty") + + if None in agents: + logger.error("Agents list contains None values") + raise ValueError("Agents list cannot contain None values") + + logger.info(f"Adding {len(agents)} agents in batch") + registered_tools = [] + + for i, agent in enumerate(agents): + tool_name = ( + tool_names[i] + if tool_names and i < len(tool_names) + else None + ) + tool_description = ( + tool_descriptions[i] + if tool_descriptions and i < len(tool_descriptions) + else None + ) + input_schema = ( + input_schemas[i] + if input_schemas and i < len(input_schemas) + else None + ) + output_schema = ( + output_schemas[i] + if output_schemas and i < len(output_schemas) + else None + ) + timeout = ( + timeouts[i] if timeouts and i < len(timeouts) else 30 + ) + max_retries = ( + max_retries_list[i] + if max_retries_list and i < len(max_retries_list) + else 3 + ) + verbose = ( + verbose_list[i] + if verbose_list and i < len(verbose_list) + else None + ) + traceback_enabled = ( + traceback_enabled_list[i] + if traceback_enabled_list + and i < len(traceback_enabled_list) + else None + ) + + tool_name = self.add_agent( + agent=agent, + tool_name=tool_name, + tool_description=tool_description, + input_schema=input_schema, + output_schema=output_schema, + timeout=timeout, + max_retries=max_retries, + verbose=verbose, + traceback_enabled=traceback_enabled, + ) + registered_tools.append(tool_name) + + logger.info( + f"Added {len(agents)} agents as tools: {registered_tools}" + ) + return registered_tools + + def _register_tool( + self, tool_name: str, agent: AgentType + ) -> None: + """ + Register a single agent as an MCP tool. + + Args: + tool_name: Name of the tool to register + agent: The agent instance to register + """ + config = self.tool_configs[tool_name] + + @self.mcp_server.tool( + name=tool_name, description=config.tool_description + ) + def agent_tool( + task: str = None, + img: str = None, + imgs: List[str] = None, + correct_answer: str = None, + ) -> Dict[str, Any]: + """ + Execute the agent with the provided parameters. + + Args: + task: The task or prompt to execute with this agent + img: Optional image to be processed by the agent + imgs: Optional list of images to be processed by the agent + correct_answer: Optional correct answer for validation or comparison + **kwargs: Additional parameters passed to the agent + + Returns: + Dict containing the agent's response and execution status + """ + start_time = None + if config.verbose: + start_time = ( + asyncio.get_event_loop().time() + if asyncio.get_event_loop().is_running() + else 0 + ) + logger.debug( + f"Starting execution of tool '{tool_name}' with task: {task[:100] if task else 'None'}..." + ) + if img: + logger.debug(f"Processing single image: {img}") + if imgs: + logger.debug( + f"Processing {len(imgs)} images: {imgs}" + ) + if correct_answer: + logger.debug( + f"Using correct answer for validation: {correct_answer[:50]}..." + ) + + try: + # Validate required parameters + if not task: + error_msg = "No task provided" + logger.warning( + f"Tool '{tool_name}' called without task parameter" + ) + return { + "result": "", + "success": False, + "error": error_msg, + } + + # Execute the agent with timeout and all parameters + result = self._execute_agent_with_timeout( + agent, + task, + config.timeout, + img, + imgs, + correct_answer, + ) + + if config.verbose and start_time: + execution_time = ( + asyncio.get_event_loop().time() - start_time + if asyncio.get_event_loop().is_running() + else 0 + ) + logger.debug( + f"Tool '{tool_name}' completed successfully in {execution_time:.2f}s" + ) + + return { + "result": str(result), + "success": True, + "error": None, + } + + except Exception as e: + error_msg = str(e) + logger.error( + f"Error executing agent '{tool_name}': {error_msg}" + ) + + if config.traceback_enabled: + logger.error(f"Traceback for tool '{tool_name}':") + logger.error(traceback.format_exc()) + + if config.verbose and start_time: + execution_time = ( + asyncio.get_event_loop().time() - start_time + if asyncio.get_event_loop().is_running() + else 0 + ) + logger.debug( + f"Tool '{tool_name}' failed after {execution_time:.2f}s" + ) + + return { + "result": "", + "success": False, + "error": error_msg, + } + + def _execute_agent_with_timeout( + self, + agent: AgentType, + task: str, + timeout: int, + img: str = None, + imgs: List[str] = None, + correct_answer: str = None, + ) -> str: + """ + Execute an agent with a timeout and all run method parameters. + + Args: + agent: The agent to execute + task: The task to execute + timeout: Maximum execution time in seconds + img: Optional image to be processed by the agent + imgs: Optional list of images to be processed by the agent + correct_answer: Optional correct answer for validation or comparison + + Returns: + str: The agent's response + + Raises: + TimeoutError: If execution exceeds timeout + Exception: If agent execution fails + """ + try: + logger.debug( + f"Executing agent '{agent.agent_name}' with timeout {timeout}s" + ) + + out = agent.run( + task=task, + img=img, + imgs=imgs, + correct_answer=correct_answer, + ) + + logger.debug( + f"Agent '{agent.agent_name}' execution completed successfully" + ) + return out + + except Exception as e: + error_msg = f"Agent execution failed: {str(e)}" + logger.error( + f"Execution error for agent '{agent.agent_name}': {error_msg}" + ) + if self.traceback_enabled: + logger.error( + f"Traceback for agent '{agent.agent_name}':" + ) + logger.error(traceback.format_exc()) + raise Exception(error_msg) + + def remove_agent(self, tool_name: str) -> bool: + """ + Remove an agent from the MCP server. + + Args: + tool_name: Name of the tool to remove + + Returns: + bool: True if agent was removed, False if not found + """ + if tool_name in self.agents: + del self.agents[tool_name] + del self.tool_configs[tool_name] + logger.info(f"Removed agent tool '{tool_name}'") + return True + return False + + def list_agents(self) -> List[str]: + """ + Get a list of all registered agent tool names. + + Returns: + List[str]: List of tool names + """ + agent_list = list(self.agents.keys()) + if self.verbose: + logger.debug( + f"Listing {len(agent_list)} registered agents: {agent_list}" + ) + return agent_list + + def get_agent_info( + self, tool_name: str + ) -> Optional[Dict[str, Any]]: + """ + Get information about a specific agent tool. + + Args: + tool_name: Name of the tool + + Returns: + Dict containing agent information, or None if not found + """ + if tool_name not in self.agents: + if self.verbose: + logger.debug( + f"Requested info for non-existent agent tool '{tool_name}'" + ) + return None + + agent = self.agents[tool_name] + config = self.tool_configs[tool_name] + + info = { + "tool_name": tool_name, + "agent_name": agent.agent_name, + "agent_description": agent.agent_description, + "model_name": getattr(agent, "model_name", "Unknown"), + "max_loops": getattr(agent, "max_loops", 1), + "tool_description": config.tool_description, + "timeout": config.timeout, + "max_retries": config.max_retries, + "verbose": config.verbose, + "traceback_enabled": config.traceback_enabled, + } + + if self.verbose: + logger.debug( + f"Retrieved info for agent tool '{tool_name}': {info}" + ) + + return info + + def start_server(self) -> None: + """ + Start the MCP server. + + Args: + host: Host to bind the server to + port: Port to bind the server to + """ + logger.info( + f"Starting MCP server '{self.server_name}' on {self.host}:{self.port}" + ) + logger.info(f"Transport: {self.transport}") + logger.info(f"Log level: {self.log_level}") + logger.info(f"Verbose mode: {self.verbose}") + logger.info(f"Traceback enabled: {self.traceback_enabled}") + logger.info(f"Available tools: {self.list_agents()}") + + if self.verbose: + logger.debug("Server configuration:") + logger.debug(f" - Server name: {self.server_name}") + logger.debug(f" - Host: {self.host}") + logger.debug(f" - Port: {self.port}") + logger.debug(f" - Transport: {self.transport}") + logger.debug(f" - Total agents: {len(self.agents)}") + for tool_name, config in self.tool_configs.items(): + logger.debug( + f" - Tool '{tool_name}': timeout={config.timeout}s, verbose={config.verbose}, traceback={config.traceback_enabled}" + ) + + self.mcp_server.run(transport=self.transport) + + # Note: FastMCP doesn't have a direct start method in the current implementation + # This would need to be implemented based on the specific MCP server setup + print( + f"MCP Server '{self.server_name}' is ready with {len(self.agents)} tools" + ) + print(f"Tools available: {', '.join(self.list_agents())}") + + def run(self) -> None: + """ + Run the MCP server. + """ + self.start_server() + + def get_server_info(self) -> Dict[str, Any]: + """ + Get information about the MCP server and registered tools. + + Returns: + Dict containing server information + """ + info = { + "server_name": self.server_name, + "total_tools": len(self.agents), + "tools": self.list_agents(), + "verbose": self.verbose, + "traceback_enabled": self.traceback_enabled, + "log_level": self.log_level, + "transport": self.transport, + "tool_details": { + tool_name: self.get_agent_info(tool_name) + for tool_name in self.agents.keys() + }, + } + + if self.verbose: + logger.debug(f"Retrieved server info: {info}") + + return info + + +class AOPCluster: + def __init__( + self, + urls: List[str], + transport: str = "streamable-http", + *args, + **kwargs, + ): + self.urls = urls + self.transport = transport + + def get_tools( + self, output_type: Literal["json", "dict", "str"] = "dict" + ) -> List[Dict[str, Any]]: + return get_tools_for_multiple_mcp_servers( + urls=self.urls, + format="openai", + output_type=output_type, + transport=self.transport, + ) + + def find_tool_by_server_name( + self, server_name: str + ) -> Dict[str, Any]: + """ + Find a tool by its server name (function name). + + Args: + server_name: The name of the tool/function to find + + Returns: + Dict containing the tool information, or None if not found + """ + for tool in self.get_tools(output_type="dict"): + if tool.get("function", {}).get("name") == server_name: + return tool + return None diff --git a/swarms/structs/auto_swarm_builder.py b/swarms/structs/auto_swarm_builder.py index 1fc23069..1c705013 100644 --- a/swarms/structs/auto_swarm_builder.py +++ b/swarms/structs/auto_swarm_builder.py @@ -129,7 +129,7 @@ When creating a multi-agent system, provide: class AgentSpec(BaseModel): """Configuration for an individual agent specification.""" - + agent_name: Optional[str] = Field( None, description="The unique name assigned to the agent, which identifies its role and functionality within the swarm.", @@ -555,7 +555,9 @@ class AutoSwarmBuilder: return [self.run(task) for task in tasks] - def _create_agent_specs(self, task: str) -> Tuple[List[Agent], int]: + def _create_agent_specs( + self, task: str + ) -> Tuple[List[Agent], int]: """Create agent specifications for a given task. Args: @@ -578,10 +580,14 @@ class AutoSwarmBuilder: dict: Dictionary containing agent configurations """ logger.info("Creating agent dictionary for task") - agents_dictionary = self._create_agents_from_specs(task, return_dict=True) + agents_dictionary = self._create_agents_from_specs( + task, return_dict=True + ) return agents_dictionary - def _create_agents_from_specs(self, task: str, return_dict: bool = False): + def _create_agents_from_specs( + self, task: str, return_dict: bool = False + ): """Create agents from specifications. Args: @@ -615,7 +621,9 @@ class AutoSwarmBuilder: logger.info("Returning agents") return self.create_agents_from_specs(agents_dictionary) - def create_agents_from_specs(self, agents_dictionary: Any) -> List[Agent]: + def create_agents_from_specs( + self, agents_dictionary: Any + ) -> List[Agent]: """Create agents from agent specifications. Args: @@ -653,7 +661,7 @@ class AutoSwarmBuilder: agent_description: str, agent_system_prompt: str, max_loops: int = 1, - model_name: str = "gpt-4o", + model_name: str = "gpt-4.1", dynamic_temperature_enabled: bool = True, auto_generate_prompt: bool = False, role: str = "worker", diff --git a/swarms/structs/csv_to_agent.py b/swarms/structs/csv_to_agent.py index 11a4a554..705e424c 100644 --- a/swarms/structs/csv_to_agent.py +++ b/swarms/structs/csv_to_agent.py @@ -29,7 +29,7 @@ AgentConfigType = TypeVar( class ModelName(str, Enum): """Valid model names for swarms agents""" - GPT4O = "gpt-4o" + GPT4O = "gpt-4.1" GPT4O_MINI = "gpt-4o-mini" GPT4 = "gpt-4" GPT35_TURBO = "gpt-3.5-turbo" diff --git a/swarms/structs/majority_voting.py b/swarms/structs/majority_voting.py index 3451f27c..dc9ad9d8 100644 --- a/swarms/structs/majority_voting.py +++ b/swarms/structs/majority_voting.py @@ -64,7 +64,7 @@ def default_consensus_agent( name: str = "Consensus-Agent", system_prompt: str = None, description: str = "An agent that uses consensus to generate a final answer.", - model_name: str = "gpt-4o", + model_name: str = "gpt-4.1", *args, **kwargs, ): @@ -111,7 +111,7 @@ class MajorityVoting: consensus_agent_prompt: str = CONSENSUS_AGENT_PROMPT, consensus_agent_name: str = "Consensus-Agent", consensus_agent_description: str = "An agent that uses consensus to generate a final answer.", - consensus_agent_model_name: str = "gpt-4o", + consensus_agent_model_name: str = "gpt-4.1", additional_consensus_agent_kwargs: dict = {}, *args, **kwargs, diff --git a/swarms/structs/model_router.py b/swarms/structs/model_router.py index e2668697..28208a67 100644 --- a/swarms/structs/model_router.py +++ b/swarms/structs/model_router.py @@ -9,7 +9,7 @@ from swarms.utils.formatter import formatter from swarms.utils.litellm_wrapper import LiteLLM model_recommendations = { - "gpt-4o": { + "gpt-4.1": { "description": "Fast and efficient for simple tasks and general queries", "best_for": [ "Simple queries", diff --git a/swarms/structs/transforms.py b/swarms/structs/transforms.py index 22310049..2cf2b571 100644 --- a/swarms/structs/transforms.py +++ b/swarms/structs/transforms.py @@ -361,7 +361,7 @@ class MessageTransforms: model_limits = { "gpt-4": 8192, "gpt-4-turbo": 128000, - "gpt-4o": 128000, + "gpt-4.1": 128000, "gpt-4o-mini": 128000, "gpt-3.5-turbo": 16385, "claude-3-opus": 200000, @@ -475,7 +475,7 @@ def apply_transforms_to_messages( def handle_transforms( transforms: MessageTransforms, short_memory: Conversation = None, - model_name: Optional[str] = "gpt-4o", + model_name: Optional[str] = "gpt-4.1", ) -> str: """ Handle message transforms and return a formatted task prompt. diff --git a/swarms/structs/tree_swarm.py b/swarms/structs/tree_swarm.py index 15e9a1a5..c1b21eb1 100644 --- a/swarms/structs/tree_swarm.py +++ b/swarms/structs/tree_swarm.py @@ -134,7 +134,7 @@ class TreeAgent(Agent): name: str = None, description: str = None, system_prompt: str = None, - model_name: str = "gpt-4o", + model_name: str = "gpt-4.1", agent_name: Optional[str] = None, embedding_model_name: str = "text-embedding-ada-002", *args, diff --git a/swarms/utils/litellm_wrapper.py b/swarms/utils/litellm_wrapper.py index 76e647b8..45cb72c6 100644 --- a/swarms/utils/litellm_wrapper.py +++ b/swarms/utils/litellm_wrapper.py @@ -210,7 +210,7 @@ class LiteLLM: def __init__( self, - model_name: str = "gpt-4o", + model_name: str = "gpt-4.1", system_prompt: str = None, stream: bool = False, temperature: float = 0.5, @@ -243,7 +243,7 @@ class LiteLLM: Initialize the LiteLLM with the given parameters. Args: - model_name (str, optional): The name of the model to use. Defaults to "gpt-4o". + model_name (str, optional): The name of the model to use. Defaults to "gpt-4.1". system_prompt (str, optional): The system prompt to use. Defaults to None. stream (bool, optional): Whether to stream the output. Defaults to False. temperature (float, optional): The temperature for the model. Defaults to 0.5. @@ -496,7 +496,7 @@ class LiteLLM: if isinstance(out, BaseModel): out = out.model_dump() - + return out def output_for_reasoning(self, response: any): diff --git a/tests/agent/benchmark_agent/test_auto_test_eval.py b/tests/agent/benchmark_agent/test_auto_test_eval.py index 4f1a6090..0b4d799a 100644 --- a/tests/agent/benchmark_agent/test_auto_test_eval.py +++ b/tests/agent/benchmark_agent/test_auto_test_eval.py @@ -301,7 +301,7 @@ reporter = SwarmsIssueReporter( 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") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent(agent_name="Test-Agent", max_loops=1) result = agent.run(None) diff --git a/tests/agent/benchmark_agent/test_github_summarizer_agent.py b/tests/agent/benchmark_agent/test_github_summarizer_agent.py index e372145b..6c852b28 100644 --- a/tests/agent/benchmark_agent/test_github_summarizer_agent.py +++ b/tests/agent/benchmark_agent/test_github_summarizer_agent.py @@ -102,7 +102,7 @@ def initialize_agent() -> Agent: Initialize the Swarms agent with OpenAI model. """ logger.info("Initializing the agent with GPT-4o") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Commit-Summarization-Agent", diff --git a/tests/structs/test_agent_features.py b/tests/structs/test_agent_features.py index 37ce5321..22b6c3ea 100644 --- a/tests/structs/test_agent_features.py +++ b/tests/structs/test_agent_features.py @@ -14,7 +14,7 @@ def test_basic_agent_functionality(): """Test basic agent initialization and simple task execution""" print("\nTesting basic agent functionality...") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent(agent_name="Test-Agent", llm=model, max_loops=1) response = agent.run("What is 2+2?") @@ -34,7 +34,7 @@ def test_memory_management(): """Test agent memory management functionality""" print("\nTesting memory management...") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Memory-Test-Agent", llm=model, @@ -63,7 +63,7 @@ def test_agent_output_formats(): """Test all available output formats""" print("\nTesting all output formats...") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") test_task = "Say hello!" output_types = { @@ -110,7 +110,7 @@ def test_agent_state_management(): """Test comprehensive state management functionality""" print("\nTesting state management...") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") # Create temporary directory for test files with tempfile.TemporaryDirectory() as temp_dir: @@ -175,7 +175,7 @@ def test_agent_tools_and_execution(): """Sample tool that adds two numbers""" return x + y - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Tools-Test-Agent", llm=model, @@ -202,7 +202,7 @@ def test_agent_concurrent_execution(): """Test agent concurrent execution capabilities""" print("\nTesting concurrent execution...") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Concurrent-Test-Agent", llm=model, max_loops=1 ) @@ -235,7 +235,7 @@ def test_agent_error_handling(): """Test agent error handling and recovery""" print("\nTesting error handling...") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Error-Test-Agent", llm=model, @@ -262,7 +262,7 @@ def test_agent_configuration(): """Test agent configuration and parameters""" print("\nTesting agent configuration...") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Config-Test-Agent", llm=model, @@ -301,7 +301,7 @@ def test_agent_with_stopping_condition(): def custom_stopping_condition(response: str) -> bool: return "STOP" in response.upper() - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Stopping-Condition-Agent", llm=model, @@ -318,7 +318,7 @@ def test_agent_with_retry_mechanism(): """Test agent retry mechanism""" print("\nTesting agent retry mechanism...") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Retry-Test-Agent", llm=model, @@ -336,7 +336,7 @@ def test_bulk_and_filtered_operations(): """Test bulk operations and response filtering""" print("\nTesting bulk and filtered operations...") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Bulk-Filter-Test-Agent", llm=model, max_loops=1 ) @@ -368,7 +368,7 @@ async def test_async_operations(): """Test asynchronous operations""" print("\nTesting async operations...") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Async-Test-Agent", llm=model, max_loops=1 ) @@ -397,7 +397,7 @@ def test_memory_and_state_persistence(): state_path = os.path.join(temp_dir, "test_state.json") # Create agent with memory configuration - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent1 = Agent( agent_name="Memory-State-Test-Agent", llm=model, @@ -445,7 +445,7 @@ def test_sentiment_and_evaluation(): """Mock evaluator that checks response quality""" return "GOOD" if len(response) > 10 else "BAD" - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Sentiment-Eval-Test-Agent", llm=model, @@ -476,7 +476,7 @@ def test_tool_management(): """Sample tool 2""" return x + 2 - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Tool-Test-Agent", llm=model, @@ -503,7 +503,7 @@ def test_system_prompt_and_configuration(): """Test system prompt and configuration updates""" print("\nTesting system prompt and configuration...") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Config-Test-Agent", llm=model, max_loops=1 ) @@ -535,7 +535,7 @@ def test_agent_with_dynamic_temperature(): """Test agent with dynamic temperature""" print("\nTesting agent with dynamic temperature...") - model = OpenAIChat(model_name="gpt-4o") + model = OpenAIChat(model_name="gpt-4.1") agent = Agent( agent_name="Dynamic-Temp-Agent", llm=model, diff --git a/tests/structs/test_agentrearrange.py b/tests/structs/test_agentrearrange.py index 2110cf60..42c3c1bc 100644 --- a/tests/structs/test_agentrearrange.py +++ b/tests/structs/test_agentrearrange.py @@ -97,7 +97,7 @@ def create_functional_agents() -> List[Agent]: try: model = OpenAIChat( - api_key=api_key, model_name="gpt-4o", temperature=0.1 + api_key=api_key, model_name="gpt-4.1", temperature=0.1 ) # Create boss agent diff --git a/tests/test_comprehensive_test.py b/tests/test_comprehensive_test.py index 5c1dc65d..ed3e7a4f 100644 --- a/tests/test_comprehensive_test.py +++ b/tests/test_comprehensive_test.py @@ -246,7 +246,7 @@ def test_tool_execution_with_agent(): def test_multimodal_execution(): """Test agent's ability to process images""" agent = create_test_agent( - "VisionAgent", model_name="gpt-4o", multi_modal=True + "VisionAgent", model_name="gpt-4.1", multi_modal=True ) try: diff --git a/tests/utils/test_litellm_wrapper.py b/tests/utils/test_litellm_wrapper.py index 23d2a10b..e497e7d4 100644 --- a/tests/utils/test_litellm_wrapper.py +++ b/tests/utils/test_litellm_wrapper.py @@ -93,7 +93,7 @@ def run_test_suite(): try: logger.info("Testing basic initialization") llm = LiteLLM() - assert llm.model_name == "gpt-4o" + assert llm.model_name == "gpt-4.1" assert llm.temperature == 0.5 assert llm.max_tokens == 4000 log_test_result("Basic Initialization", True) @@ -204,7 +204,7 @@ def run_test_suite(): # Test 8: Vision Support Check try: logger.info("Testing vision support check") - llm = LiteLLM(model_name="gpt-4o") + llm = LiteLLM(model_name="gpt-4.1") # This should not raise an error for vision-capable models llm.check_if_model_supports_vision(img="test.jpg") log_test_result("Vision Support Check", True) @@ -214,7 +214,7 @@ def run_test_suite(): # Test 9: Direct URL Processing try: logger.info("Testing direct URL processing") - llm = LiteLLM(model_name="gpt-4o") + llm = LiteLLM(model_name="gpt-4.1") test_url = "https://github.com/kyegomez/swarms/blob/master/swarms_logo_new.png?raw=true" should_use_direct = llm._should_use_direct_url(test_url) assert isinstance(should_use_direct, bool) @@ -225,7 +225,7 @@ def run_test_suite(): # Test 10: Message Preparation with Image try: logger.info("Testing message preparation with image") - llm = LiteLLM(model_name="gpt-4o") + llm = LiteLLM(model_name="gpt-4.1") # Mock image URL to test message structure test_img = "https://github.com/kyegomez/swarms/blob/master/swarms_logo_new.png?raw=true" messages = llm._prepare_messages( @@ -247,7 +247,7 @@ def run_test_suite(): # Test 11: Vision Processing Methods try: logger.info("Testing vision processing methods") - llm = LiteLLM(model_name="gpt-4o") + llm = LiteLLM(model_name="gpt-4.1") messages = [] # Test OpenAI vision processing @@ -278,7 +278,7 @@ def run_test_suite(): # Test 12: Local vs URL Detection try: logger.info("Testing local vs URL detection") - llm = LiteLLM(model_name="gpt-4o") + llm = LiteLLM(model_name="gpt-4.1") # Test URL detection url_test = "https://github.com/kyegomez/swarms/blob/master/swarms_logo_new.png?raw=true" @@ -302,7 +302,7 @@ def run_test_suite(): # Test 13: Vision Message Structure try: logger.info("Testing vision message structure") - llm = LiteLLM(model_name="gpt-4o") + llm = LiteLLM(model_name="gpt-4.1") messages = [] # Test message structure for image input