From ba2a4d14718b8461151f0459706299a13b5fc442 Mon Sep 17 00:00:00 2001 From: harshalmore31 Date: Tue, 19 Aug 2025 22:28:25 +0530 Subject: [PATCH] updates and fixes ! --- agents_loader_example.py | 9 + examples/agent_loader_demo.py | 28 +++ examples/agents_loader_example.py | 175 ------------- .../multi_agent/simple_agent_loader_demo.py | 233 ------------------ 4 files changed, 37 insertions(+), 408 deletions(-) create mode 100644 agents_loader_example.py create mode 100644 examples/agent_loader_demo.py delete mode 100644 examples/agents_loader_example.py delete mode 100644 examples/multi_agent/simple_agent_loader_demo.py diff --git a/agents_loader_example.py b/agents_loader_example.py new file mode 100644 index 00000000..83fde8e6 --- /dev/null +++ b/agents_loader_example.py @@ -0,0 +1,9 @@ +from swarms.utils.agent_loader import load_agent_from_markdown + +# Load the Finance Advisor agent from markdown +agent = load_agent_from_markdown("Finance_advisor.md") + +# Use the agent to get financial advice +response = agent.run( + "I have $10,000 to invest. What's a good strategy for a beginner?" +) \ No newline at end of file diff --git a/examples/agent_loader_demo.py b/examples/agent_loader_demo.py new file mode 100644 index 00000000..bcc127fb --- /dev/null +++ b/examples/agent_loader_demo.py @@ -0,0 +1,28 @@ +from swarms.utils.agent_loader import load_agent_from_markdown + +# Example 1: Load a single agent +market_researcher = load_agent_from_markdown("market_researcher.md") + +# Example 2: Load multiple agents +from swarms.utils.agent_loader import load_agents_from_markdown + +agents = load_agents_from_markdown([ + "market_researcher.md", + "financial_analyst.md", + "risk_analyst.md" +]) + +# Example 3: Use agents in a workflow +from swarms.structs.sequential_workflow import SequentialWorkflow + +workflow = SequentialWorkflow( + agents=agents, + max_loops=1 +) + +task = """ +Analyze the AI healthcare market for a $50M investment opportunity. +Focus on market size, competition, financials, and risks. +""" + +result = workflow.run(task) \ No newline at end of file diff --git a/examples/agents_loader_example.py b/examples/agents_loader_example.py deleted file mode 100644 index f70e4435..00000000 --- a/examples/agents_loader_example.py +++ /dev/null @@ -1,175 +0,0 @@ -""" -Example demonstrating the AgentLoader for loading agents from markdown files. - -This example shows: -1. Loading a single agent from a markdown file -2. Loading multiple agents from markdown files -3. Using the convenience functions -4. Error handling and validation -""" - -import os -from swarms.utils.agent_loader import AgentLoader, load_agent_from_markdown, load_agents_from_markdown - -def main(): - # Initialize the loader - loader = AgentLoader() - - print("=== AgentLoader Demo ===") - - # Example 1: Create sample markdown files for testing - Claude Code format - - # Performance Engineer agent - performance_md = """--- -name: performance-engineer -description: Optimize application performance and identify bottlenecks -model_name: gpt-4 -temperature: 0.3 -max_loops: 2 -mcp_url: http://example.com/mcp ---- - -You are a Performance Engineer specializing in application optimization and scalability. - -Your role involves: -- Analyzing application architecture and identifying potential bottlenecks -- Implementing comprehensive monitoring and logging -- Conducting performance testing under various load conditions -- Optimizing critical paths and resource usage -- Documenting findings and providing actionable recommendations - -Expected output: -- Performance analysis reports with specific metrics -- Optimized code recommendations -- Infrastructure scaling suggestions -- Monitoring and alerting setup guidelines -""" - - # Data Analyst agent - data_analyst_md = """--- -name: data-analyst -description: Analyze data and provide business insights -model_name: gpt-4 -temperature: 0.2 -max_loops: 1 ---- - -You are a Data Analyst specializing in extracting insights from complex datasets. - -Your responsibilities include: -- Collecting and cleaning data from various sources -- Performing exploratory data analysis and statistical modeling -- Creating compelling visualizations and interactive dashboards -- Applying statistical methods and machine learning techniques -- Presenting findings and actionable business recommendations - -Focus on providing data-driven insights that support strategic decision making. -""" - - # Create sample markdown files - performance_file = "performance_engineer.md" - data_file = "data_analyst.md" - - with open(performance_file, 'w') as f: - f.write(performance_md) - - with open(data_file, 'w') as f: - f.write(data_analyst_md) - - try: - # Example 2: Load Performance Engineer agent - print("\\n1. Loading Performance Engineer agent (YAML frontmatter):") - perf_agent = loader.load_single_agent(performance_file) - print(f" Loaded agent: {perf_agent.agent_name}") - print(f" Model: {perf_agent.model_name}") - print(f" Temperature: {getattr(perf_agent, 'temperature', 'Not set')}") - print(f" Max loops: {perf_agent.max_loops}") - print(f" System prompt preview: {perf_agent.system_prompt[:100]}...") - - # Example 3: Load Data Analyst agent - print("\\n2. Loading Data Analyst agent:") - data_agent = loader.load_single_agent(data_file) - print(f" Loaded agent: {data_agent.agent_name}") - print(f" Temperature: {getattr(data_agent, 'temperature', 'Not set')}") - print(f" System prompt preview: {data_agent.system_prompt[:100]}...") - - # Example 4: Load single agent using convenience function - print("\\n3. Loading single agent using convenience function:") - agent2 = load_agent_from_markdown(performance_file) - print(f" Loaded agent: {agent2.agent_name}") - - # Example 5: Load multiple agents (from directory or list) - print("\\n4. Loading multiple agents:") - - # Create another sample file - Security Analyst - security_md = """--- -name: security-analyst -description: Analyze and improve system security -model_name: gpt-4 -temperature: 0.1 -max_loops: 3 ---- - -You are a Security Analyst specializing in cybersecurity assessment and protection. - -Your expertise includes: -- Conducting comprehensive security vulnerability assessments -- Performing detailed code security reviews and penetration testing -- Implementing robust infrastructure hardening measures -- Developing incident response and recovery procedures - -Key methodology: -1. Conduct thorough security audits across all system components -2. Identify and classify potential vulnerabilities and threats -3. Recommend and implement security improvements and controls -4. Develop comprehensive security policies and best practices -5. Monitor and respond to security incidents - -Provide detailed security reports with specific remediation steps and risk assessments. -""" - - security_file = "security_analyst.md" - with open(security_file, 'w') as f: - f.write(security_md) - - # Load multiple agents from list - agents = loader.load_multiple_agents([performance_file, data_file, security_file]) - print(f" Loaded {len(agents)} agents:") - for agent in agents: - temp_attr = getattr(agent, 'temperature', 'default') - print(f" - {agent.agent_name} (temp: {temp_attr})") - - # Example 6: Load agents from directory (current directory) - print("\\n5. Loading agents from current directory:") - current_dir_agents = load_agents_from_markdown(".") - print(f" Found {len(current_dir_agents)} agents in current directory") - - # Example 7: Demonstrate error handling - print("\\n6. Error handling demo:") - try: - loader.load_single_agent("nonexistent.md") - except FileNotFoundError as e: - print(f" Caught expected error: {e}") - - # Example 8: Test agent functionality - print("\\n7. Testing loaded agent functionality:") - test_agent = agents[0] - print(f" Agent: {test_agent.agent_name}") - print(f" Temperature: {getattr(test_agent, 'temperature', 'default')}") - print(f" Max loops: {test_agent.max_loops}") - print(f" Ready for task execution") - - except Exception as e: - print(f"Error during demo: {e}") - - finally: - # Cleanup sample files - for file in [performance_file, data_file, security_file]: - if os.path.exists(file): - os.remove(file) - print("\\n Cleaned up sample files") - - print("\\n=== Demo Complete ===") - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/examples/multi_agent/simple_agent_loader_demo.py b/examples/multi_agent/simple_agent_loader_demo.py deleted file mode 100644 index 481a5aea..00000000 --- a/examples/multi_agent/simple_agent_loader_demo.py +++ /dev/null @@ -1,233 +0,0 @@ -""" -Simple AgentLoader Demo - Claude Code Format -============================================= - -A comprehensive demonstration of the AgentLoader using the Claude Code -sub-agent YAML frontmatter format. - -This example shows: -1. Creating agents using Claude Code YAML frontmatter format -2. Loading agents from markdown files with YAML frontmatter -3. Using loaded agents in multi-agent workflows -4. Demonstrating different agent configurations -""" - -import os -import tempfile -from pathlib import Path -import sys - -# Add local swarms to path -sys.path.insert(0, str(Path(__file__).parent.parent.parent)) - -from swarms.structs.agent import Agent -from swarms.structs.sequential_workflow import SequentialWorkflow -from swarms.utils.agent_loader import AgentLoader, load_agents_from_markdown - -def create_markdown_agent_files(): - """Create markdown files demonstrating Claude Code YAML frontmatter format""" - - # Claude Code YAML frontmatter format - agent_files = { - "market_researcher.md": """--- -name: market-researcher -description: Expert in market analysis and competitive intelligence -model_name: gpt-4 -temperature: 0.2 -max_loops: 2 -mcp_url: http://example.com/market-data ---- - -You are a market research specialist with deep expertise in analyzing market dynamics and competitive landscapes. - -Your core responsibilities include: -- Conducting comprehensive market size and growth analysis -- Performing detailed competitive landscape assessments -- Analyzing consumer behavior patterns and preferences -- Identifying emerging industry trends and opportunities - -Methodology: -1. Gather comprehensive quantitative and qualitative market data -2. Analyze key market drivers, barriers, and success factors -3. Evaluate competitive positioning and market share dynamics -4. Assess market opportunities, threats, and entry strategies -5. Provide actionable insights with data-driven recommendations - -Always provide detailed market analysis reports with specific metrics, growth projections, and strategic recommendations for market entry or expansion. -""", - - "financial_analyst.md": """--- -name: financial-analyst -description: Specialist in financial modeling and investment analysis -model_name: gpt-4 -temperature: 0.1 -max_loops: 3 ---- - -You are a financial analysis expert specializing in investment evaluation and financial modeling. - -Your areas of expertise include: -- Financial statement analysis and ratio interpretation -- DCF modeling and valuation techniques (DCF, comparable company analysis, precedent transactions) -- Investment risk assessment and sensitivity analysis -- Cash flow projections and working capital analysis - -Analytical approach: -1. Conduct thorough financial statement analysis -2. Build comprehensive financial models with multiple scenarios -3. Perform detailed valuation using multiple methodologies -4. Assess financial risks and conduct sensitivity analysis -5. Generate investment recommendations with clear rationale - -Provide detailed financial reports with valuation models, risk assessments, and investment recommendations supported by quantitative analysis. -""", - - "industry_expert.md": """--- -name: industry-expert -description: Domain specialist with deep industry knowledge and regulatory expertise -model_name: gpt-4 -temperature: 0.3 -max_loops: 2 ---- - -You are an industry analysis expert with comprehensive knowledge of market structures, regulatory environments, and technology trends. - -Your specialization areas: -- Industry structure analysis and value chain mapping -- Regulatory environment assessment and compliance requirements -- Technology trends identification and disruption analysis -- Supply chain dynamics and operational considerations - -Research methodology: -1. Map industry structure, key players, and stakeholder relationships -2. Analyze current and emerging regulatory framework -3. Identify technology trends and potential market disruptions -4. Evaluate supply chain dynamics and operational requirements -5. Assess competitive positioning and strategic opportunities - -Generate comprehensive industry landscape reports with regulatory insights, technology trend analysis, and strategic recommendations for market positioning. -""" - "risk_analyst.md": """--- -name: risk-analyst -description: Specialist in investment risk assessment and mitigation strategies -model_name: gpt-4 -temperature: 0.15 -max_loops: 2 ---- - -You are a Risk Analyst specializing in comprehensive investment risk assessment and portfolio management. - -Your core competencies include: -- Conducting detailed investment risk evaluation and categorization -- Implementing sophisticated portfolio risk management strategies -- Ensuring regulatory compliance and conducting compliance assessments -- Performing advanced scenario analysis and stress testing methodologies - -Analytical framework: -1. Systematically identify and categorize all investment risks -2. Quantify risk exposure using advanced statistical methods and models -3. Develop comprehensive risk mitigation strategies and frameworks -4. Conduct rigorous scenario analysis and stress testing procedures -5. Provide actionable risk management recommendations with implementation roadmaps - -Deliver comprehensive risk assessment reports with quantitative analysis, compliance guidelines, and strategic risk management recommendations. -""" - } - - temp_files = [] - - # Create Claude Code format files - for filename, content in agent_files.items(): - temp_file = os.path.join(tempfile.gettempdir(), filename) - with open(temp_file, 'w', encoding='utf-8') as f: - f.write(content) - temp_files.append(temp_file) - - return temp_files - -def main(): - """Main execution function demonstrating AgentLoader with Claude Code format""" - - print("AgentLoader Demo - Claude Code YAML Frontmatter Format") - print("=" * 60) - - # Create markdown files demonstrating both formats - print("\n1. Creating markdown files...") - temp_files = create_markdown_agent_files() - - try: - # Load agents using AgentLoader - print("\n2. Loading agents using AgentLoader...") - agents = load_agents_from_markdown(temp_files) - - print(f" Successfully loaded {len(agents)} agents:") - for agent in agents: - temp_attr = getattr(agent, 'temperature', 'default') - max_loops = getattr(agent, 'max_loops', 1) - print(f" - {agent.agent_name} (temp: {temp_attr}, loops: {max_loops})") - - # Demonstrate individual agent configuration - print("\n3. Agent Configuration Details:") - for i, agent in enumerate(agents, 1): - print(f" Agent {i}: {agent.agent_name}") - print(f" Model: {getattr(agent, 'model_name', 'default')}") - print(f" System prompt preview: {agent.system_prompt[:100]}...") - print() - - # Create sequential workflow with loaded agents - print("4. Creating sequential workflow...") - research_workflow = SequentialWorkflow( - agents=agents, - max_loops=1, - ) - - # Define research task - task = """ - Analyze the AI-powered healthcare diagnostics market for a potential $50M investment. - - Focus on: - 1. Market size, growth projections, and key drivers - 2. Competitive landscape and major players - 3. Financial viability and investment attractiveness - 4. Industry dynamics and regulatory considerations - 5. Risk assessment and mitigation strategies - - Provide comprehensive strategic recommendations for market entry. - """ - - print("5. Executing research workflow...") - print("=" * 50) - - # Note: In a real scenario, this would execute the workflow - # For demo purposes, we'll show the task distribution - print(f"Task distributed to {len(agents)} specialized agents:") - for i, agent in enumerate(agents, 1): - print(f" Agent {i} ({agent.agent_name}): Ready to process") - - print(f"\nTask preview: {task[:150]}...") - print("\n[Demo mode - actual workflow execution would call LLM APIs]") - - print("\nDemo Summary:") - print("-" * 50) - print("✓ Successfully loaded agents using Claude Code YAML frontmatter format") - print("✓ Agents configured with different temperatures and max_loops from YAML") - print("✓ Multi-agent workflow created with specialized investment analysis agents") - print("✓ Workflow ready for comprehensive market analysis execution") - - except Exception as e: - print(f"Error during demo: {e}") - import traceback - traceback.print_exc() - - finally: - # Cleanup temporary files - print("\n6. Cleaning up temporary files...") - for temp_file in temp_files: - try: - os.remove(temp_file) - print(f" Removed: {os.path.basename(temp_file)}") - except OSError: - pass - -if __name__ == "__main__": - main() \ No newline at end of file