Buckets:
tahamajs/Sysmem2_in_AI / ComputerAssignments /CA14_multi_agent_reasoning /scripts /generate_notebooks.py
| """ | |
| Script to generate comprehensive Jupyter notebooks for multi-agent reasoning | |
| """ | |
| import nbformat as nbf | |
| import os | |
| def create_fundamentals_notebook(): | |
| """Create the fundamentals notebook""" | |
| nb = nbf.v4.new_notebook() | |
| cells = [] | |
| # Title | |
| cells.append(nbf.v4.new_markdown_cell("""# Multi-Agent Reasoning Fundamentals | |
| This notebook demonstrates fundamental concepts in multi-agent reasoning systems, including: | |
| - Agent communication protocols | |
| - Collaborative decision-making | |
| - Task decomposition and coordination | |
| - ReAct (Reasoning + Acting) pattern | |
| - Multi-agent orchestration""")) | |
| # Imports | |
| cells.append(nbf.v4.new_code_cell("""import sys | |
| import os | |
| sys.path.append(os.path.abspath('..')) | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| from typing import Dict, List, Any | |
| import logging | |
| logging.basicConfig(level=logging.INFO) | |
| print("✅ Imports successful")""")) | |
| # Section 1: Communication | |
| cells.append(nbf.v4.new_markdown_cell("""## 1. Message Passing and Communication | |
| Multi-agent systems rely on efficient communication protocols.""")) | |
| cells.append(nbf.v4.new_code_cell("""from src.core.communication import MessageBroker, MessagePriority, CommunicationProtocol | |
| broker = MessageBroker(max_queue_size=100) | |
| agent1_comm = CommunicationProtocol("agent_1", broker) | |
| agent2_comm = CommunicationProtocol("agent_2", broker) | |
| message_id = agent1_comm.request_task( | |
| target_agent="agent_2", | |
| task_description="Analyze dataset", | |
| priority=MessagePriority.HIGH | |
| ) | |
| print(f"📨 Message sent: {message_id}") | |
| messages = agent2_comm.get_pending_messages() | |
| print(f"📬 Agent 2 received {len(messages)} message(s)")""")) | |
| # Section 2: Memory | |
| cells.append(nbf.v4.new_markdown_cell("""## 2. Working Memory System | |
| Agents maintain context through structured memory."""")) | |
| cells.append(nbf.v4.new_code_cell("""from src.core.memory import WorkingMemory | |
| memory = WorkingMemory(max_size=10) | |
| memory.store("task", "Plan a trip to Paris") | |
| memory.store("destination", "Paris, France") | |
| print(f"Task: {memory.retrieve('task')}") | |
| print(f"Destination: {memory.retrieve('destination')}") | |
| print(f"Memory size: {memory.size()}/{memory.max_size}")""")) | |
| # Section 3: ReAct Agent | |
| cells.append(nbf.v4.new_markdown_cell("""## 3. ReAct Agent - Reasoning and Acting | |
| The ReAct pattern combines reasoning with tool use.""")) | |
| cells.append(nbf.v4.new_code_cell("""from src.agents.react_agent import ReActAgent | |
| from src.utils.llm_interface import LLMInterface | |
| def search_flights(destination: str, date: str) -> str: | |
| return f"✅ Found flight to {destination} on {date}" | |
| def search_hotels(destination: str, date: str, area: str) -> str: | |
| return f"✅ Found hotel in {area}, {destination}" | |
| tools = {"search_flights": search_flights, "search_hotels": search_hotels} | |
| llm = LLMInterface(primary_provider="mock") | |
| react_agent = ReActAgent(tools=tools, llm_interface=llm, max_steps=5) | |
| print("✅ ReAct Agent created")""")) | |
| cells.append(nbf.v4.new_code_cell("""task = "Plan a trip to Paris" | |
| result = react_agent.execute(task) | |
| print(f"Success: {result.success}") | |
| print(f"Steps: {len(result.steps)}") | |
| print(f"Quality: {result.reasoning_quality:.2%}") | |
| print(f"\\nFinal Answer: {result.final_answer}")""")) | |
| # Section 4: Nexus | |
| cells.append(nbf.v4.new_markdown_cell("""## 4. Multi-Agent Orchestration with Nexus | |
| Nexus coordinates multiple specialized agents.""")) | |
| cells.append(nbf.v4.new_code_cell("""from src.agents.nexus_orchestrator import NexusMultiAgentSystem | |
| nexus = NexusMultiAgentSystem(tools=tools) | |
| print(f"👥 Worker Agents: {list(nexus.worker_agents.keys())}") | |
| complex_task = "Create a complete travel package" | |
| nexus_result = nexus.execute_complex_task(complex_task) | |
| print(f"\\nSuccess: {nexus_result.success}") | |
| print(f"Agents: {len(nexus_result.execution_results)}") | |
| print(f"Time: {nexus_result.total_execution_time:.2f}s")""")) | |
| # Section 5: Visualization | |
| cells.append(nbf.v4.new_markdown_cell("""## 5. Performance Visualization""")) | |
| cells.append(nbf.v4.new_code_cell("""stats = react_agent.get_performance_stats() | |
| if stats['most_used_tools']: | |
| plt.figure(figsize=(10, 6)) | |
| tools_list = list(stats['most_used_tools'].keys()) | |
| counts = list(stats['most_used_tools'].values()) | |
| plt.bar(tools_list, counts, color='steelblue', alpha=0.7) | |
| plt.xlabel('Tools') | |
| plt.ylabel('Usage Count') | |
| plt.title('Tool Usage Distribution') | |
| plt.xticks(rotation=45) | |
| plt.tight_layout() | |
| plt.show()""")) | |
| # Key Takeaways | |
| cells.append(nbf.v4.new_markdown_cell("""## Key Takeaways | |
| 1. **Communication**: Message brokers enable asynchronous agent communication | |
| 2. **Memory**: Structured memory maintains context across reasoning steps | |
| 3. **ReAct**: Combining reasoning and acting improves problem-solving | |
| 4. **Orchestration**: Supervisor agents coordinate specialized workers | |
| 5. **Performance**: Monitoring metrics helps optimize agent behavior | |
| ## Next Steps | |
| Explore advanced topics in other notebooks: | |
| - `02_Advanced_Collaborative_Reasoning.ipynb` | |
| - `03_Meta_Learning_Agents.ipynb` | |
| - `04_Complete_Multi_Agent_Project.ipynb`""")) | |
| nb['cells'] = cells | |
| return nb | |
| def create_collaborative_reasoning_notebook(): | |
| """Create collaborative reasoning notebook""" | |
| nb = nbf.v4.new_notebook() | |
| cells = [] | |
| cells.append(nbf.v4.new_markdown_cell("""# Advanced Collaborative Reasoning | |
| This notebook demonstrates: | |
| - Analysis of Competing Hypotheses (ACH) | |
| - Multi-agent collaborative decision-making | |
| - Evidence-based reasoning | |
| - Hypothesis evaluation and ranking""")) | |
| cells.append(nbf.v4.new_code_cell("""import sys | |
| import os | |
| sys.path.append(os.path.abspath('..')) | |
| from src.agents.collaborative_reasoning_agent import CollaborativeReasoningAgent, Hypothesis, Evidence | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| print("✅ Imports successful")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 1. Creating Collaborative Agents | |
| Let's create agents with different expertise domains.""")) | |
| cells.append(nbf.v4.new_code_cell("""agent1 = CollaborativeReasoningAgent("analyst_1", "financial_analysis") | |
| agent2 = CollaborativeReasoningAgent("analyst_2", "market_research") | |
| print(f"✅ Created {agent1.agent_id} - {agent1.expertise_domain}") | |
| print(f"✅ Created {agent2.agent_id} - {agent2.expertise_domain}")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 2. Defining Hypotheses | |
| Create competing hypotheses for investment decision.""")) | |
| cells.append(nbf.v4.new_code_cell("""h1 = Hypothesis("H1", "Investment will yield high returns", prior_probability=0.4) | |
| h2 = Hypothesis("H2", "Investment will yield moderate returns", prior_probability=0.35) | |
| h3 = Hypothesis("H3", "Investment will yield low returns", prior_probability=0.25) | |
| for h in [h1, h2, h3]: | |
| agent1.add_hypothesis(h) | |
| agent2.add_hypothesis(Hypothesis(h.id, h.description, h.prior_probability)) | |
| print(f"Added {len(agent1.hypotheses)} hypotheses to each agent")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 3. Adding Evidence | |
| Different agents gather different evidence.""")) | |
| cells.append(nbf.v4.new_code_cell("""# Agent 1's evidence | |
| e1 = Evidence("E1", "Strong financial fundamentals", | |
| reliability=0.9, relevance=0.85, source="financial_analysis") | |
| e2 = Evidence("E2", "Positive cash flow trends", | |
| reliability=0.85, relevance=0.8, source="financial_analysis") | |
| agent1.add_evidence(e1) | |
| agent1.add_evidence(e2) | |
| # Agent 2's evidence | |
| e3 = Evidence("E3", "Growing market demand", | |
| reliability=0.8, relevance=0.75, source="market_research") | |
| e4 = Evidence("E4", "Competitive landscape intensifying", | |
| reliability=0.75, relevance=0.7, source="market_research") | |
| agent2.add_evidence(e3) | |
| agent2.add_evidence(e4) | |
| print(f"Agent 1: {len(agent1.evidence)} pieces of evidence") | |
| print(f"Agent 2: {len(agent2.evidence)} pieces of evidence")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 4. Individual Analysis | |
| Each agent analyzes independently.""")) | |
| cells.append(nbf.v4.new_code_cell("""result1 = agent1.analyze_competing_hypotheses() | |
| print("Agent 1 Analysis:") | |
| print(f" Best: {result1['best_hypothesis']['description']}") | |
| print(f" Score: {result1['best_hypothesis']['score']:.2f}") | |
| print(f" Confidence: {agent1.get_confidence():.2%}") | |
| result2 = agent2.analyze_competing_hypotheses() | |
| print("\\nAgent 2 Analysis:") | |
| print(f" Best: {result2['best_hypothesis']['description']}") | |
| print(f" Score: {result2['best_hypothesis']['score']:.2f}") | |
| print(f" Confidence: {agent2.get_confidence():.2%}")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 5. Collaborative Analysis | |
| Agents share information and collaborate.""")) | |
| cells.append(nbf.v4.new_code_cell("""collab_result = agent1.collaborate_with(agent2) | |
| print("Collaborative Analysis:") | |
| print(f" Combined hypotheses: {collab_result['collaboration']['combined_hypotheses']}") | |
| print(f" Combined evidence: {collab_result['collaboration']['combined_evidence']}") | |
| print(f" Best hypothesis: {collab_result['joint_analysis']['best_hypothesis']['description']}") | |
| print(f" Joint confidence: {agent1.get_confidence():.2%}")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 6. Explanation | |
| Generate natural language explanation.""")) | |
| cells.append(nbf.v4.new_code_cell("""explanation = agent1.explain_decision() | |
| print(explanation)""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## Key Insights | |
| - ACH systematically evaluates competing hypotheses | |
| - Multiple agents provide diverse perspectives | |
| - Collaboration improves decision quality | |
| - Evidence reliability and relevance matter | |
| - Transparency through explanations builds trust""")) | |
| nb['cells'] = cells | |
| return nb | |
| def create_meta_thinking_notebook(): | |
| """Create meta-thinking notebook""" | |
| nb = nbf.v4.new_notebook() | |
| cells = [] | |
| cells.append(nbf.v4.new_markdown_cell("""# Meta-Thinking and Hierarchical Reasoning | |
| This notebook demonstrates: | |
| - Strategic, tactical, and operational thinking levels | |
| - Hierarchical problem decomposition | |
| - Adaptive planning and execution | |
| - Meta-level monitoring and control""")) | |
| cells.append(nbf.v4.new_code_cell("""import sys | |
| import os | |
| sys.path.append(os.path.abspath('..')) | |
| from src.agents.meta_thinking_agent import MetaThinkingAgent | |
| import matplotlib.pyplot as plt | |
| print("✅ Imports successful")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 1. Creating Meta-Thinking Agent""")) | |
| cells.append(nbf.v4.new_code_cell("""agent = MetaThinkingAgent("meta_agent", "strategic_planning") | |
| print(f"✅ Created {agent.agent_id} - {agent.domain}")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 2. Strategic Planning | |
| High-level problem analysis and strategy formulation.""")) | |
| cells.append(nbf.v4.new_code_cell("""problem = "Launch AI-powered product in competitive market" | |
| context = { | |
| "market_size": "large", | |
| "competition": "high", | |
| "resources": ["engineering_team", "marketing_budget"], | |
| "timeline": "6 months" | |
| } | |
| plan = agent.strategic_thinking(problem, context) | |
| print(f"Goal: {plan.goal}") | |
| print(f"Strategy: {plan.strategy}") | |
| print(f"\\nSub-goals:") | |
| for i, sg in enumerate(plan.sub_goals, 1): | |
| print(f" {i}. {sg}")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 3. Tactical Planning | |
| Mid-level coordination and resource allocation.""")) | |
| cells.append(nbf.v4.new_code_cell("""tactical_plan = agent.tactical_thinking(plan.sub_goals[0], context) | |
| print(f"Sub-goal: {tactical_plan['sub_goal']}") | |
| print(f"\\nTactical steps:") | |
| for step in tactical_plan['tactical_steps']: | |
| print(f" - {step}") | |
| print(f"\\nEstimated time: {tactical_plan['estimated_time']:.1f} units")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 4. Operational Execution | |
| Low-level task execution.""")) | |
| cells.append(nbf.v4.new_code_cell("""results = [] | |
| for step in tactical_plan['tactical_steps']: | |
| result = agent.operational_thinking(step, "agile_method") | |
| results.append(result) | |
| status = "✅" if result['success'] else "❌" | |
| print(f"{status} {step}: {result['result']['status']}")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 5. Monitoring and Adaptation""")) | |
| cells.append(nbf.v4.new_code_cell("""monitoring = agent.monitor_and_adapt() | |
| print(f"Success rate: {monitoring['progress']['success_rate']:.1%}") | |
| print(f"Completed tasks: {monitoring['progress']['completed_tasks']}") | |
| print(f"Adaptation needed: {monitoring['adaptation_needed']}")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 6. Reasoning Explanation""")) | |
| cells.append(nbf.v4.new_code_cell("""explanation = agent.explain_reasoning() | |
| print(explanation)""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## Key Insights | |
| - Hierarchical thinking separates concerns | |
| - Strategic level focuses on "what" and "why" | |
| - Tactical level handles "how" and "when" | |
| - Operational level executes specific tasks | |
| - Meta-monitoring enables adaptation""")) | |
| nb['cells'] = cells | |
| return nb | |
| def create_complete_project_notebook(): | |
| """Create complete project notebook""" | |
| nb = nbf.v4.new_notebook() | |
| cells = [] | |
| cells.append(nbf.v4.new_markdown_cell("""# Complete Multi-Agent Reasoning Project | |
| This comprehensive notebook integrates all concepts: | |
| - ReAct agents | |
| - Nexus orchestration | |
| - Collaborative reasoning | |
| - Meta-thinking | |
| - Real-world scenarios""")) | |
| cells.append(nbf.v4.new_code_cell("""import sys | |
| import os | |
| sys.path.append(os.path.abspath('..')) | |
| from demos.complete_multi_agent_project import MultiAgentReasoningSystem | |
| import matplotlib.pyplot as plt | |
| import json | |
| print("✅ Imports successful")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 1. Initialize Complete System""")) | |
| cells.append(nbf.v4.new_code_cell("""system = MultiAgentReasoningSystem() | |
| system.initialize_agents() | |
| print("✅ System initialized") | |
| print(f" ReAct Agent: {system.react_agent.agent_id}") | |
| print(f" Nexus System: {len(system.nexus_system.worker_agents)} workers") | |
| print(f" Collaborative Agents: {len(system.collaborative_agents)}") | |
| print(f" Meta Agent: {system.meta_agent.agent_id}")""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 2. Scenario 1: Travel Planning""")) | |
| cells.append(nbf.v4.new_code_cell("""result1 = system.scenario_1_travel_planning() | |
| print(json.dumps(result1, indent=2))""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 3. Scenario 2: Collaborative Decision""")) | |
| cells.append(nbf.v4.new_code_cell("""result2 = system.scenario_2_collaborative_decision() | |
| print(json.dumps(result2, indent=2))""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 4. Scenario 3: Hierarchical Planning""")) | |
| cells.append(nbf.v4.new_code_cell("""result3 = system.scenario_3_hierarchical_planning() | |
| print(json.dumps(result3, indent=2))""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## 5. System Performance Analysis""")) | |
| cells.append(nbf.v4.new_code_cell("""# Visualize results | |
| scenarios = [r['scenario'] for r in system.execution_history] | |
| success_rates = [] | |
| for result in system.execution_history: | |
| if 'react_result' in result: | |
| success_rates.append(1.0 if result['react_result']['success'] else 0.0) | |
| elif 'success_rate' in result: | |
| success_rates.append(result['success_rate']) | |
| else: | |
| success_rates.append(0.8) | |
| plt.figure(figsize=(10, 6)) | |
| plt.bar(scenarios, success_rates, color='steelblue', alpha=0.7) | |
| plt.xlabel('Scenario') | |
| plt.ylabel('Success Rate') | |
| plt.title('Multi-Agent System Performance') | |
| plt.ylim([0, 1.1]) | |
| plt.xticks(rotation=45, ha='right') | |
| plt.tight_layout() | |
| plt.show()""")) | |
| cells.append(nbf.v4.new_markdown_cell("""## Conclusion | |
| This project demonstrates: | |
| - Integration of multiple agent architectures | |
| - Scalable multi-agent coordination | |
| - Adaptive reasoning and planning | |
| - Real-world problem-solving capabilities | |
| ### Future Enhancements | |
| - Add reinforcement learning | |
| - Implement distributed execution | |
| - Enhance communication protocols | |
| - Add more specialized agents""")) | |
| nb['cells'] = cells | |
| return nb | |
| def main(): | |
| """Generate all notebooks""" | |
| notebooks_dir = "../notebooks" | |
| os.makedirs(notebooks_dir, exist_ok=True) | |
| notebooks = { | |
| "01_Multi_Agent_Reasoning_Fundamentals.ipynb": create_fundamentals_notebook(), | |
| "02_Advanced_Collaborative_Reasoning.ipynb": create_collaborative_reasoning_notebook(), | |
| "03_Meta_Thinking_Agents.ipynb": create_meta_thinking_notebook(), | |
| "04_Complete_Multi_Agent_Project.ipynb": create_complete_project_notebook() | |
| } | |
| for filename, notebook in notebooks.items(): | |
| filepath = os.path.join(notebooks_dir, filename) | |
| with open(filepath, 'w') as f: | |
| nbf.write(notebook, f) | |
| print(f"✅ Created: {filepath}") | |
| print(f"\n🎉 Generated {len(notebooks)} notebooks successfully!") | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 17.1 kB
- Xet hash:
- b7f1a146af18cf19648118cbfc1134f34e5c596bbb61af00c6313320a68c10bb
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.