### Quick Start and Installation for Legion AGI Source: https://github.com/dotdigitize/legion_agi/blob/main/README.md This snippet provides the essential commands to quickly clone the Legion AGI repository, install its dependencies, and run the tool in different modes. It's the fastest way to get started with the project. ```bash git clone https://github.com/dotdigitize/legion-asi.git cd legion-asi pip install -r requirements.txt python -m legion_agi.main # Tool mode python -m legion_agi.main --mode evolve # Evolution mode ``` -------------------------------- ### Detailed Installation and Setup for Legion AGI Source: https://github.com/dotdigitize/legion_agi/blob/main/README.md This section details the comprehensive installation process for Legion AGI. It includes cloning the repository, setting up a virtual environment, installing all necessary dependencies, creating required directories, and optionally downloading pre-trained models. ```bash git clone https://github.com/dotdigitize/legion_agi.git cd LegionAGI python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -r requirements.txt mkdir -p data/models logs ollama pull llama3.1:8b python -m legion_agi.main ``` -------------------------------- ### Example Usage of Legion AGI Agent in Python Source: https://github.com/dotdigitize/legion_agi/blob/main/README.md Demonstrates how to instantiate and use the 'Agent' class. It shows creating an agent, simulating its life experience, initializing its quantum memory and advanced AI features, and finally checking its 'sentience' status. This serves as a practical example of the agent's lifecycle. ```python def main(): # Create a new agent quantum_agent = Agent(name="QuantumExplorer") # Simulate a life experience phase (classical attributes) quantum_agent.simulate_life_experience() # Initialize quantum memory and advanced AI features quantum_agent.initialize_quantum_memory() quantum_agent.enable_advanced_ai_features() # Check sentience status if quantum_agent.check_sentience(): print(f"[{quantum_agent.name}] has achieved the placeholder 'sentience' status!") else: print(f"[{quantum_agent.name}] is still evolving...") if __name__ == "__main__": main() ``` -------------------------------- ### Start and Use Legion AGI Command Line Interface (Bash) Source: https://context7.com/dotdigitize/legion_agi/llms.txt Illustrates how to launch and interact with the Legion AGI system via its command-line interface (CLI). It shows commands for starting the system with a specific model and mode, loading previous states, checking system status, processing queries using different methods, managing agents, viewing visualizations, accessing logs, saving state, and exiting. The CLI offers interactive features like command history and auto-completion. ```bash # Start interactive CLI python -m legion_agi.interface.cli --model llama3.1:8b --mode tool # CLI Commands: # start - Initialize the Legion AGI system # start --load path - Load previous state # status - Display system status # query - Process a query (or just type directly) # /past - Use PAST method # /raft - Use RAFT method # /eat - Use EAT method # method past|raft|eat - Set default method # agents - Display current agents # viz [type] - Open visualizations (agents, memory, workspace) # logs [n] --level - Display recent log entries # save - Save current state # exit - Shutdown and exit ``` -------------------------------- ### Interact with Legion AGI via REST API (Bash/Curl) Source: https://context7.com/dotdigitize/legion_agi/llms.txt Provides examples of interacting with the Legion AGI system through its FastAPI-based REST API using curl commands. It covers starting the API server, creating new sessions, processing queries synchronously and asynchronously, checking query status, listing agents, retrieving visualizations, and deleting sessions. This API allows for programmatic control and integration. ```bash # Start the API server python -m legion_agi.interface.api --host 0.0.0.0 --port 8000 # Create a new session curl -X POST http://localhost:8000/sessions \ -H "Content-Type: application/json" \ -d '{ "model": "llama3.1:8b", "mode": "tool", "visualize": true }' # Response: {"session_id": "abc123...", "status": "ready", "created_at": "..."} # Process a query synchronously curl -X POST http://localhost:8000/sessions/abc123/query \ -H "Content-Type: application/json" \ -d '{ "query": "Design a sustainable urban transportation system", "method": "raft", "parameters": {"temperature": 0.7} }' # Response: {"status": "completed", "result": {...}, "session_id": "abc123"} # Process a query asynchronously (for long-running tasks) curl -X POST http://localhost:8000/sessions/abc123/query/async \ -H "Content-Type: application/json" \ -d '{"query": "Develop a theoretical framework for AGI", "method": "eat"}' # Response: {"status": "processing", "task_id": "...", "session_id": "abc123"} # Check async query status curl http://localhost:8000/sessions/abc123/query/status # Response: {"status": "processing", "progress": "collaborative reasoning"} # Get async query result curl http://localhost:8000/sessions/abc123/query/result # Response: {"status": "completed", "result": {...}} # List agents in session curl http://localhost:8000/sessions/abc123/agents # Response: [{"id": "...", "name": "Dr. Alex Smith", "role": "Physicist", ...}] # Get session visualizations curl http://localhost:8000/sessions/abc123/visualizations # Response: [{"filename": "agent_network.png", "url": "/sessions/abc123/visualizations/agent_network.png"}] # Delete session curl -X DELETE http://localhost:8000/sessions/abc123 ``` -------------------------------- ### Execute Full RAFT Reasoning Method Source: https://context7.com/dotdigitize/legion_agi/llms.txt This Python code executes the full RAFT (Reasoning, Analysis, Feedback, Thought) reasoning method. It initializes the RAFTMethod with agents and a model, then calls `execute_full_method` to get a final synthesis. ```python from legion_agi.methods.raft import RAFTMethod raft = RAFTMethod( agents=agents, # Pre-spawned agents model="llama3.1:8b" ) # Execute full method result = raft.execute_full_method( question="What are the ethical implications of AGI development?", iterations=5 # Number of reasoning iterations per agent ) print(result["final_synthesis"]) ``` -------------------------------- ### Initialize and Process Query with LegionAGI Main Class (Python) Source: https://context7.com/dotdigitize/legion_agi/llms.txt Demonstrates initializing the LegionAGI system with a specified Ollama model and mode, then processing a query using the PAST method. It also shows how to retrieve system status, save/load state, and gracefully shut down the system. This class serves as the main entry point for coordinating all Legion AGI components. ```python from legion_agi.main import LegionAGI # Initialize the system legion = LegionAGI( model="llama3.1:8b", # Ollama model to use mode="tool", # "tool" for interactive, "evolve" for continuous evolution session_id="my-session", # Optional session ID for persistence data_dir="data", # Directory for data storage visualize=True # Enable visualization generation ) # Process a query using PAST method (default) result = legion.process_query( "Explain the relationship between quantum mechanics and consciousness", method="past" # Options: "past", "raft", "eat" ) # Access the integrated solution print(result["integrated_solution"]) # Output: A comprehensive, synthesized answer from multiple expert agents # Get system status status = legion.get_system_status() # Returns: {"session_id": "...", "mode": "tool", "num_agents": 5, "running": True, ...} # Save and restore state state_file = legion.save_state() # Saves to data/session_/state/ legion.load_state(state_file) # Graceful shutdown legion.stop() ``` -------------------------------- ### Workspace Operations: Get Broadcast History and Clear Source: https://context7.com/dotdigitize/legion_agi/llms.txt Provides functions to retrieve the broadcast history from the workspace and to clear the workspace. These are fundamental operations for managing agent interactions and state. ```python history = workspace.get_broadcast_history() print(f"Total broadcasts: {len(history)}") workspace.clear_workspace() ``` -------------------------------- ### Step-by-Step EAT Reasoning Method Execution Source: https://context7.com/dotdigitize/legion_agi/llms.txt This Python snippet outlines the step-by-step execution of the EAT reasoning method, covering solution evaluation, proposing actionable recommendations, and suggesting tests for validation, followed by compiling the final output. ```python from legion_agi.methods.eat import EATMethod # EAT typically takes input from PAST or RAFT past_result = past.execute_full_method("Design a new renewable energy grid") eat = EATMethod( agents=agents, input_solution=past_result, model="llama3.1:8b" ) # Step-by-step execution eat.set_question_and_solution("Design a new energy grid", past_result) # Stage 1: Evaluate solution effectiveness evaluations = eat.evaluate_solution() for eval in evaluations: print(f"{eval['agent_name']}: Score {eval['overall_score']:.2f}/1.0") # Stage 2: Propose actionable recommendations actions = eat.propose_actions() for action in actions: print(f"{action['agent_name']}'s recommendations:") print(action['action_proposals'][:200]) # Stage 3: Propose tests for validation tests = eat.propose_tests() for test in tests: print(f"{test['agent_name']}'s test proposals:") print(test['test_proposals'][:200]) # Compile final output with executive summary final = eat.compile_final_output() print(final["executive_summary"]) print(f"Action recommendations: {len(final['action_recommendations'])}") print(f"Test proposals: {len(final['test_recommendations'])}") ``` -------------------------------- ### Analyze Input and Spawn Agents (Python) Source: https://github.com/dotdigitize/legion_agi/blob/main/README.md Dynamically spawns agents based on input analysis to address specific problems. It uses an LLM to suggest relevant experts, parses their details, creates agent instances, and configures their communication. ```python def analyze_input_and_spawn_agents(message: str, max_agents: int = 10) -> List[Agent]: prompt = ( "Analyze the following user input and suggest experts that could help solve " "the problem. Provide their names, roles, backstories, communication styles, " "and specific instructions for collaboration in JSON format...\n\n" f"User Input: \"{message}\"\n\n" ) response = ollama.chat(model=self.model, messages=[{'role': 'user', 'content': prompt}]) suggested_agents_text = response['message']['content'].strip() agents = self._parse_and_create_agents(suggested_agents_text, max_agents) self._create_system_agents() all_agents = agents[:] for agent in all_agents: agent.set_agent_list(all_agents) return agents ``` -------------------------------- ### Initialize and Use Agent Spawning System in Python Source: https://context7.com/dotdigitize/legion_agi/llms.txt Demonstrates the Agent Spawning System for dynamically generating agents based on user input. It covers initializing the spawner, automatically spawning agents based on a message, spawning agents by specific types, and accessing predefined role templates and system agents. ```python from legion_agi.agents.spawning import AgentSpawner from legion_agi.core.global_workspace import GlobalWorkspace # Initialize spawner spawner = AgentSpawner( model="llama3.1:8b", global_workspace=GlobalWorkspace() ) # Automatically spawn agents based on query analysis agents = spawner.analyze_input_and_spawn_agents( message="Design a machine learning system for climate prediction", max_agents=5 ) # Returns agents like: Climate Scientist, ML Engineer, Data Scientist, etc. for agent in agents: print(f"{agent.name} - {agent.role}") # Output: # Dr. Sarah Chen - Climate Scientist # Dr. Alex Kumar - Machine Learning Engineer # Dr. Jordan Lee - Data Scientist # GuidingAgent - Conversation Moderator # EvaluationAgent - Solution Evaluator # Spawn a specific type of agent custom_agent = spawner.spawn_agent_by_type( agent_type="science", # Domain: science, humanities, engineering, arts, business customizations={ "name": "Dr. Custom Expert", "backstory": "20 years of research experience", "style": "Collaborative and thorough" } ) # Access role templates print(spawner.role_templates["science"]) # Output: {"Physicist": "...", "Biologist": "...", "Chemist": "...", ...} # Access system agents (created automatically) print(spawner.guiding_agent.name) # "GuidingAgent" print(spawner.refinement_agent.name) # "RefinementAgent" print(spawner.evaluation_agent.name) # "EvaluationAgent" ``` -------------------------------- ### Initialize and Use PAST Reasoning Method in Python Source: https://context7.com/dotdigitize/legion_agi/llms.txt Demonstrates the PAST (Persona, Action, Solution, Task) Reasoning Method for structured problem-solving. It covers initializing the method with agents, executing the full method for a question, and performing step-by-step execution including question analysis and action assignment. ```python from legion_agi.methods.past import PASTMethod from legion_agi.agents.spawning import AgentSpawner # Initialize with agents spawner = AgentSpawner(model="llama3.1:8b") agents = spawner.analyze_input_and_spawn_agents("Complex problem statement") past = PASTMethod( agents=agents, model="llama3.1:8b" ) # Execute full method (recommended) result = past.execute_full_method( question="How can we achieve sustainable fusion energy?", depth=3 # Number of solution generation rounds ) print(result["integrated_solution"]) print(result["contributors"]) # List of agents who contributed # Or execute step-by-step for more control past.set_question("How can we achieve sustainable fusion energy?") # Stage 1: Analyze question to identify required expertise analysis = past.analyze_question() print(analysis["analysis"]["primary_domain"]) # e.g., "Physics/Engineering" # Stage 2: Assign specific actions to each agent actions = past.assign_actions() for agent_id, action in actions.items(): print(f"{action['agent_name']}: {action['action_plan'][:100]}...") ``` -------------------------------- ### Execute Full EAT Reasoning Method Source: https://context7.com/dotdigitize/legion_agi/llms.txt This Python code demonstrates the full execution of the EAT (Evaluation, Action, Testing) reasoning method. It initializes EATMethod with agents, an input solution, and a model, then executes the full method to evaluate a solution. ```python from legion_agi.methods.eat import EATMethod # EAT typically takes input from PAST or RAFT past_result = past.execute_full_method("Design a new renewable energy grid") eat = EATMethod( agents=agents, input_solution=past_result, # Solution to evaluate model="llama3.1:8b" ) # Execute full method result = eat.execute_full_method( question="Design a new renewable energy grid", input_solution=past_result ) print(f"Evaluation Score: {result['evaluation_score']}/1.0") print(f"Solution Acceptable: {result['solution_acceptable']}") print(result["executive_summary"]) ``` -------------------------------- ### Initialize and Use Agent Base Class in Python Source: https://context7.com/dotdigitize/legion_agi/llms.txt Demonstrates the creation and basic usage of an autonomous agent using the Agent Base Class. It covers initializing an agent with specific attributes, generating responses in a conversation context, performing step-through reasoning, collaborating with other agents, updating cognitive parameters, and saving/restoring agent state. ```python from legion_agi.agents.agent_base import Agent from legion_agi.core.memory_module import MemoryModule from legion_agi.core.global_workspace import GlobalWorkspace # Create an agent agent = Agent( name="Dr. Marie Curie", role="Physicist", backstory="Nobel Prize-winning physicist specializing in radioactivity and nuclear physics.", style="Analytical and precise with attention to experimental detail.", instructions="Apply physics principles to analyze problems systematically.", model="llama3.1:8b" ) # Generate a response in conversation context conversation = [ {"role": "User", "content": "What causes radioactive decay?"}, {"role": "Dr. John Smith", "content": "It's related to nuclear instability..."} ] response = agent.respond(conversation, temperature=0.7, max_tokens=1000) # Step-through reasoning with Chain-of-Thought result = agent.step_reasoning( goal="Explain the half-life concept", context="User is a physics student", reasoning_method="chain_of_thought" # or "tree_of_thought" ) print(result["reasoning_output"]) # Collaborate with another agent other_agent = Agent(name="Dr. John Smith", role="Chemist", ...) collaboration = agent.collaborate_with( other_agent, topic="Nuclear chemistry applications", context="Discussing medical isotopes" ) print(collaboration["integrated_result"]) # Update cognitive parameters (affects reasoning behavior) agent.update_cognitive_parameters( creativity=0.8, # Higher = more exploratory attention_span=0.9, # Higher = more focused learning_rate=0.3 # Higher = faster adaptation ) # Save and restore agent state agent.save_agent_state("agent_state.json") agent.load_agent_state("agent_state.json") ``` -------------------------------- ### Quantum Memory Implementation (Python) Source: https://github.com/dotdigitize/legion_agi/blob/main/README.md Implements a Quantum Memory module simulating quantum cognitive processes. It utilizes density matrices and von Neumann operators to manage quantum states, supporting operations like applying operators and simulating decoherence. This component is central to the Legion AGI framework for storing and processing information in a quantum-like manner. ```python class QuantumMemory: def __init__(self, num_qubits: int = 4): self.num_qubits = num_qubits self.dimension = 2 ** num_qubits self.operator = VonNeumannOperator(self.dimension) self.state = np.eye(self.dimension, dtype=complex) / self.dimension # Maximally mixed state self.semantic_registers = {} self.episodic_registers = [] self.working_registers = [] def apply_operator(self, operator: np.ndarray) -> None: self.state = operator @ self.state @ operator.conj().T self.state = (self.state + self.state.conj().T) / 2 # Ensure hermiticity trace = np.trace(self.state).real if abs(trace - 1.0) > 1e-10: self.state = self.state / trace def simulate_decoherence(self, rate: float = 0.01) -> None: def decoherence_channel(rho: np.ndarray) -> np.ndarray: diagonal = np.diag(np.diag(rho)) off_diagonal = rho - diagonal return diagonal + (1 - rate) * off_diagonal self.apply_quantum_channel(decoherence_channel) ``` -------------------------------- ### Command Line Interface Query Processing (Python) Source: https://github.com/dotdigitize/legion_agi/blob/main/README.md Provides an interactive Command Line Interface (CLI) for querying the Legion AGI system. The `do_query` method handles user input, parses commands for different processing methods (past, raft, eat), and displays results. ```python class LegionCLI(cmd.Cmd): def do_query(self, arg: str) -> None: if not self.legion or not self.legion.running: console.print("Legion AGI system is not running. Use 'start' command.", style="yellow") return if not arg.strip(): console.print("Please provide a query.", style="yellow") return method = "past" # Default method if arg.startswith("/past "): method = "past" arg = arg[6:].strip() elif arg.startswith("/raft "): method = "raft" arg = arg[6:].strip() elif arg.startswith("/eat "): method = "eat" arg = arg[5:].strip() console.print(f"\nProcessing query using {method.upper()} method:", style="blue") with Progress() as progress: task = progress.add_task("Thinking...", total=None) result = self.legion.process_query(arg, method) if result: self._display_result(result) ``` -------------------------------- ### Memory Module Initialization and Operations Source: https://context7.com/dotdigitize/legion_agi/llms.txt Demonstrates the initialization and usage of the MemoryModule, which integrates quantum-inspired, neural, and symbolic memory. It covers adding content to short-term memory, recalling memories, managing associated memories, triggering consolidation, replaying experiences, accessing different memory types, and saving/loading memory states. ```python from legion_agi.core.memory_module import MemoryModule # Initialize memory module memory = MemoryModule( name="agent_memory", stm_capacity=50, # Short-term memory capacity enable_quantum=True, # Enable quantum memory simulation enable_snn=True # Enable spiking neural network simulation ) # Add to short-term memory memory_id = memory.add_to_stm( content="The user asked about quantum computing", source="conversation", metadata={"type": "episodic", "topic": "quantum"}, importance=0.8 # 0.0 to 1.0 ) # Recall memories by query results = memory.recall_memory( query="quantum computing", memory_type="all", # "stm", "ltm", "episodic", "semantic", "quantum", "neural", "all" max_results=5 ) for mem in results: print(f"Similarity: {mem['similarity']:.2f} - {mem['content'][:50]}...") # Get associated memories associated = memory.get_associated_memories(memory_id) # Manually trigger memory consolidation (STM -> LTM) memory.consolidate_memory() # Memories with importance >= 0.3 are consolidated to long-term memory # Replay experiences for reinforcement learning memory.replay_experiences() # Access different memory systems print(f"STM size: {len(memory.short_term_memory)}") print(f"LTM size: {len(memory.long_term_memory)}") print(f"Episodic size: {len(memory.episodic_memory)}") print(f"Semantic entries: {len(memory.semantic_memory)}") # Save and restore memory state memory.save_memory_state("memory_state.pkl") memory.load_memory_state("memory_state.pkl") ``` -------------------------------- ### Quantum Memory System Initialization and Operations Source: https://context7.com/dotdigitize/legion_agi/llms.txt Details the QuantumMemory system, focusing on quantum-inspired memory features like coherence simulation, entanglement, and decoherence modeling. It includes initializing states, storing/retrieving memories, simulating decoherence, measuring coherence, calculating entanglement entropy, and creating entangled memories. ```python from legion_agi.core.quantum_memory import QuantumMemory import numpy as np # Initialize quantum memory qmem = QuantumMemory(num_qubits=4) # 2^4 = 16 dimensional Hilbert space # Initialize with a pure state state_vector = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=complex) state_vector = state_vector / np.linalg.norm(state_vector) qmem.initialize_state(state_vector) # Store a memory memory_id = qmem.store_memory("Important concept about physics", memory_type="working") # Retrieve memory retrieved_state = qmem.retrieve_memory(memory_id) # Simulate realistic decoherence (environmental interaction) qmem.simulate_realistic_decoherence( time_ms=10.0, # 10 milliseconds temp_kelvin=300.0, # Room temperature coupling_strength=0.01 # Environment coupling ) # Get coherence measures coherence = qmem.get_coherence_measures() print(f"L1-norm coherence: {coherence['l1_norm']:.4f}") print(f"Relative entropy coherence: {coherence['relative_entropy']:.4f}") # Set subsystem structure for entanglement calculations qmem.set_subsystem_structure([2, 2, 2, 2]) # Four qubits # Calculate entanglement entropy entropy = qmem.calculate_entanglement_entropy([0, 1]) # First two qubits print(f"Entanglement entropy: {entropy:.4f}") # Simulate quantum coherence evolution results = qmem.simulate_quantum_coherence( coherence_time=100.0, # ms subsystem_dims=[2, 2, 2, 2] ) print(f"Coherence decay rate: {results['coherence_decay_rate']:.6f}/ms") print(f"Estimated coherence time: {results['estimated_coherence_time']:.2f}ms") # Create entangled memories (quantum association) memory_ids = [ qmem.store_memory("concept A", "semantic"), qmem.store_memory("concept B", "semantic") ] entangled_id = qmem.create_entangled_memories(memory_ids) ``` -------------------------------- ### Initialize and Run Global Workspace Architecture Source: https://context7.com/dotdigitize/legion_agi/llms.txt This Python code initializes a GlobalWorkspace and registers specialist modules. It demonstrates injecting information and running workspace cycles for information integration and broadcast, typical of Global Workspace Theory. ```python from legion_agi.core.global_workspace import GlobalWorkspace, SpecialistModule, InformationUnit # Initialize workspace workspace = GlobalWorkspace() # Create and register specialist modules def perception_processor(info_units): # Process incoming information processed = [] for unit in info_units: new_unit = InformationUnit( content=f"Processed: {unit.content}", source="perception", activation=unit.activation * 0.9 ) processed.append(new_unit) return processed perception = SpecialistModule("perception", perception_processor) workspace.register_specialist(perception) # Inject information directly into workspace workspace.inject_information( content={"data": "sensory input", "type": "visual"}, source="external_input", activation=0.9, # High activation = high priority metadata={"timestamp": "2024-01-15T10:30:00"} ) # Run workspace cycles (broadcast -> process -> compete) workspace.run_cycles(num_cycles=3) # Access current workspace contents contents = workspace.get_workspace_contents() for info in contents: print(f"Source: {info.source}, Activation: {info.activation}") print(f"Content: {info.content}") print(f"Broadcast count: {info.broadcast_count}") ``` -------------------------------- ### Global Workspace Architecture (Python) Source: https://github.com/dotdigitize/legion_agi/blob/main/README.md Implements a Global Workspace module inspired by human cognitive integration. It aggregates and broadcasts information across specialist modules, managing content, broadcast history, and competition among specialists. The module includes parameters for competition threshold, broadcast cycles, and workspace capacity, adhering to principles like Miller's Law. ```python class GlobalWorkspace: def __init__(self): self.specialists = {} self.contents = [] self.broadcast_history = [] self.competition_threshold = 0.7 self.broadcast_cycles = 3 self.capacity = 7 # Miller's Law (7±2) def broadcast(self) -> None: if not self.contents: return for info in self.contents: info.broadcast_count += 1 self.broadcast_history.append(self.contents[:]) for specialist in self.specialists.values(): specialist.receive_broadcast(self.contents) def run_competition(self) -> None: competition_entries = [] for name, specialist in self.specialists.items(): info_units, activation = specialist.compete() if info_units and activation >= self.competition_threshold: competition_entries.append((info_units, activation, name)) competition_entries.sort(key=lambda x: x[1], reverse=True) new_contents = [] winners = [] for info_units, activation, name in competition_entries: if len(new_contents) + len(info_units) <= self.capacity: new_contents.extend(info_units) winners.append(name) else: break if winners: self.contents = new_contents ``` -------------------------------- ### Configuration Parameters in config.py Source: https://context7.com/dotdigitize/legion_agi/llms.txt Lists key configuration parameters centralized in the config.py file for easy customization of the Legion AGI system. This includes settings for LLMs, agents, quantum memory, global workspace, evolution, and reasoning methods. ```python # legion_agi/config.py key parameters # LLM Configuration DEFAULT_MODEL = "llama3.1:8b" INFERENCE_TEMPERATURE = 0.7 INFERENCE_TOP_P = 0.9 MAX_TOKENS = 2000 # Agent Configuration MAX_AGENTS = 10 AGENT_MEMORY_CAPACITY = 50 CONSOLIDATION_THRESHOLD = 5 AGENT_REASONING_STEPS = 10 # Quantum Memory Configuration NUM_QUBITS = 4 DECOHERENCE_RATE = 0.01 ENTANGLEMENT_STRENGTH = 0.8 TEMPERATURE_KELVIN = 300.0 COHERENCE_TIME_MS = 100.0 # Global Workspace Configuration GW_COMPETITION_THRESHOLD = 0.7 GW_BROADCAST_CYCLES = 3 GW_WORKSPACE_CAPACITY = 7 # Miller's Law (7 +/- 2) # Evolution Parameters MUTATION_RATE = 0.05 CROSSOVER_RATE = 0.3 SELECTION_PRESSURE = 0.7 GENERATIONS_PER_CYCLE = 5 # Reasoning Methods PAST_DEPTH = 3 RAFT_ITERATIONS = 5 EAT_EVALUATION_THRESHOLD = 0.7 # Mode Configuration TOOL_MODE = "tool" EVOLUTION_MODE = "evolve" ``` -------------------------------- ### Step-by-Step RAFT Reasoning Method Execution Source: https://context7.com/dotdigitize/legion_agi/llms.txt This Python snippet details the step-by-step execution of the RAFT reasoning method, including generating reasoning chains, cross-agent analysis, feedback exchange, and thought integration, culminating in a final synthesis. ```python from legion_agi.methods.raft import RAFTMethod raft = RAFTMethod( agents=agents, model="llama3.1:8b" ) # Step-by-step execution raft.set_question("What are the ethical implications of AGI development?") # Stage 1: Generate reasoning chains from each agent chains = raft.generate_reasoning_chains(iterations=5) for agent_id, chain in chains.items(): print(f"Agent {chain[0]['agent_name']} reasoning steps: {len(chain)}") # Stage 2: Cross-agent analysis (each agent analyzes another's reasoning) analyses = raft.analyze_reasoning() for analysis in analyses: print(f"{analysis['analyzer_name']} analyzed {analysis['target_name']}'s reasoning") # Stage 3: Feedback exchange (target agents respond to analyses) feedback = raft.provide_feedback() for fb in feedback: print(f"{fb['feedback_agent_name']} responded to {fb['analyzer_name']}") # Stage 4: Integrate thoughts into deeper understanding thoughts = raft.integrate_thought() for thought in thoughts: print(f"{thought['agent_name']}: {thought['integrated_thought'][:100]}...") # Final synthesis synthesis = raft.synthesize_final_thought() print(synthesis["final_synthesis"]) ``` -------------------------------- ### Generate and Integrate Solutions with PAST Method Source: https://context7.com/dotdigitize/legion_agi/llms.txt This Python snippet demonstrates generating solutions using the PAST method and then integrating them with a task focus. It involves calling `generate_solutions` and `integrate_task_focus` methods from a 'past' object. ```python solutions = past.generate_solutions(depth=3) for sol in solutions: print(f"Round {sol['round']}: {sol['agent_name']} - {sol['solution'][:100]}...") final = past.integrate_task_focus() print(final["integrated_solution"]) ``` -------------------------------- ### Command Line Interface (CLI) Source: https://context7.com/dotdigitize/legion_agi/llms.txt Information on how to use the Legion AGI command-line interface for interactive sessions and system management. ```APIDOC ## Command Line Interface ### Description Interactive CLI with command history, auto-completion, and rich formatted output using the Rich library. ### Starting the CLI ```bash python -m legion_agi.interface.cli --model llama3.1:8b --mode tool ``` ### CLI Commands - **start** - Initialize the Legion AGI system. - **start --load path** - Load a previous state from the specified path. - **status** - Display the current system status. - **query ** - Process a query using the default method (or type the question directly). - **/past ** - Process a query using the PAST reasoning method. - **/raft ** - Process a query using the RAFT reasoning method. - **/eat ** - Process a query using the EAT reasoning method. - **method past|raft|eat** - Set the default reasoning method for subsequent queries. - **agents** - Display a list of currently active agents. - **viz [type]** - Open visualizations (e.g., "agents", "memory", "workspace"). - **logs [n] --level** - Display recent log entries, optionally specifying the number of entries (n) and log level. - **save** - Save the current system state. - **exit** - Shutdown the system gracefully and exit the CLI. ``` -------------------------------- ### Agent Evolution Implementation (Python) Source: https://github.com/dotdigitize/legion_agi/blob/main/README.md Implements agent evolution through natural selection to enhance reasoning and problem-solving capabilities. This method iterates through generations, evaluating fitness, selecting parents, creating offspring, and applying mutations. ```python class AgentEvolution: def evolve_population(self, num_generations: int = 5) -> List[Agent]: for i in range(num_generations): if not all(agent.agent_id in self.fitness_scores for agent in self.population): self.evaluate_population_fitness() parents = self._select_parents() offspring = self._create_offspring(parents) mutated_offspring = self._mutate_offspring(offspring) self._select_survivors(mutated_offspring) self.generation += 1 self._record_generation() return self.population ``` -------------------------------- ### Agent Spawning with Latent Vector Analysis (Python) Source: https://github.com/dotdigitize/legion_agi/blob/main/README.md This Python function enhances agent spawning by analyzing input messages and encoding reasoning styles as latent vectors. It assigns BFS depth based on task complexity, utilizing superclass methods for agent creation. The function is designed for specialized agent creation within a broader AI framework. ```python def analyze_input_and_spawn_agents(message: str, max_agents: int = 10) -> List[Agent]: # Enhanced with latent vector analysis prompt = ( "Analyze the user's input and suggest experts. " "For each agent, encode their reasoning style as a latent vector " "and assign BFS depth based on task complexity." ) # Spawn agents with latent exploration parameters agents = super().spawn_agents(prompt) return agents ``` -------------------------------- ### API Interface for Query Processing (Python) Source: https://github.com/dotdigitize/legion_agi/blob/main/README.md Exposes a RESTful API using FastAPI for programmatic interaction with the Legion AGI system. The `/sessions/{session_id}/query` endpoint handles synchronous query processing, including logging and performance monitoring. ```python # Initialize FastAPI app app = FastAPI( title="Legion AGI API", description="API for interacting with the Legion AGI system", version="1.0.0" ) @app.post("/sessions/{session_id}/query", tags=["Queries"], response_model=Dict[str, Any]) async def process_query_sync( request: QueryRequest, session_id: str = Path(..., description="Session ID") ): try: with LogContext("process_query", session_id=session_id, method=request.method): with PerformanceTimer("process_query", threshold_ms=500): session = get_session(session_id) result = session.process_query(request.query, request.method) session_results[session_id] = { "status": "completed", "result": result, "timestamp": datetime.now().isoformat() } return { "status": "completed", "result": result, "session_id": session_id, "timestamp": datetime.now().isoformat() } except Exception as e: logger.exception(f"Error processing query: {e}") raise HTTPException(status_code=500, detail=str(e)) ``` -------------------------------- ### LegionAGI Python API Source: https://context7.com/dotdigitize/legion_agi/llms.txt This section details the usage of the main LegionAGI class for initializing the system, processing queries, managing state, and shutting down. ```APIDOC ## LegionAGI Main Class ### Description The main entry point for the Legion AGI system, coordinating all components including agent spawning, reasoning methods, memory systems, and session management. ### Method ```python from legion_agi.main import LegionAGI # Initialize the system legion = LegionAGI( model="llama3.1:8b", # Ollama model to use mode="tool", # "tool" for interactive, "evolve" for continuous evolution session_id="my-session", # Optional session ID for persistence data_dir="data", # Directory for data storage visualize=True # Enable visualization generation ) # Process a query using PAST method (default) result = legion.process_query( "Explain the relationship between quantum mechanics and consciousness", method="past" # Options: "past", "raft", "eat" ) # Access the integrated solution print(result["integrated_solution"]) # Get system status status = legion.get_system_status() # Save and restore state state_file = legion.save_state() # Saves to data/session_/state/ legion.load_state(state_file) # Graceful shutdown legion.stop() ``` ### Parameters #### Initialization Parameters - **model** (str) - Required - Ollama model to use (e.g., "llama3.1:8b"). - **mode** (str) - Required - System mode: "tool" for interactive or "evolve" for continuous evolution. - **session_id** (str) - Optional - A unique identifier for the session for persistence. - **data_dir** (str) - Optional - Directory for storing session data and state (defaults to "data"). - **visualize** (bool) - Optional - Whether to enable visualization generation (defaults to False). #### `process_query` Parameters - **query** (str) - Required - The natural language query to process. - **method** (str) - Optional - The reasoning method to use: "past", "raft", or "eat" (defaults to "past"). - **parameters** (dict) - Optional - Additional parameters for the reasoning method (e.g., temperature). ### Response #### `process_query` Success Response - **integrated_solution** (str) - The synthesized answer from collaborating agents. - **raw_results** (dict) - Detailed results from individual agents. #### `get_system_status` Success Response - **session_id** (str) - The current session ID. - **mode** (str) - The current system mode. - **num_agents** (int) - The number of active agents. - **running** (bool) - Indicates if the system is currently running. #### `save_state` Success Response - **state_file** (str) - The path to the saved state file. ``` -------------------------------- ### Define Legion AGI Agent Class in Python Source: https://github.com/dotdigitize/legion_agi/blob/main/README.md Defines a Python class 'Agent' to represent a Legion AGI agent. It includes methods for initializing attributes, checking for sentience, setting up quantum memory, enabling advanced AI features, and simulating life experience. This class serves as a foundational structure for agents. ```python class Agent: """ Represents a LegionAGI agent with placeholders for classical and quantum-enhanced features. """ def __init__(self, name, attributes=None): self.name = name # A dictionary storing the agent's current abilities and states # In practice, these would be dynamically updated as the agent evolves self.attributes = attributes if attributes else {} def check_sentience(self): """ Evaluate whether this agent meets the criteria for 'sentience' based on the above placeholders. """ return is_sentient(self.attributes) def initialize_quantum_memory(self): """ Placeholder for building out the quantum memory pipeline. Could integrate RAG, embedding models, etc. """ print(f"[{self.name}] Initializing quantum memory and embeddings...") self.attributes['quantum_coherence'] = True self.attributes['hamiltonian_evolution'] = True def enable_advanced_ai_features(self): """ Placeholder for enabling advanced neural timing, real-time synchronization, etc. """ print(f"[{self.name}] Enabling advanced AI features...") self.attributes['advanced_neural_timing'] = True self.attributes['real_time_synchronization'] = True self.attributes['von_neumann_algebra'] = True def simulate_life_experience(self): """ Example function to 'simulate' agent development, toggling on classical attributes as it interacts with the environment. """ print(f"[{self.name}] Learning and evolving...") self.attributes['perception'] = True self.attributes['emotion'] = True self.attributes['self_awareness'] = True self.attributes['consciousness'] = True self.attributes['learning_ability'] = True self.attributes['goal_directed_behavior'] = True self.attributes['theory_of_mind'] = True ``` -------------------------------- ### Illustrative Python Code for Future Legion AGI Enhancements Source: https://github.com/dotdigitize/legion_agi/blob/main/README.md This Python code snippet illustrates potential future enhancements for Legion AGI, focusing on agent sentience and advanced AI concepts. It includes placeholder functions for checking attributes like quantum coherence, Hamiltonian state evolution, and advanced neural timing, culminating in a `is_sentient` check. ```python """ Example: Future LegionAGI Enhancements ------------------------------------- This code snippet demonstrates how one might begin integrating the upcoming features (quantum memory, Hamiltonian state evolution, advanced neural timing, etc.) into LegionAGI for agent sentience and advanced reasoning. Note: This is illustrative, not production-ready. All quantum, neural, and advanced AI methods below are placeholders. """ # --- Utility Functions (Placeholders) --- def has_perception(entity): # Placeholder check for sensory input return entity.get('perception', False) def has_emotion(entity): # Placeholder check for emotional states return entity.get('emotion', False) def has_self_awareness(entity): # Placeholder check for self-model return entity.get('self_awareness', False) def has_consciousness(entity): # Placeholder check for integrated information return entity.get('consciousness', False) def has_learning_ability(entity): # Placeholder check for adaptive learning return entity.get('learning_ability', False) def has_goal_directed_behavior(entity): # Placeholder check for goal-based planning return entity.get('goal_directed_behavior', False) def has_theory_of_mind(entity): # Placeholder check for understanding other agents return entity.get('theory_of_mind', False) # --- Future Enhancements (Placeholders) --- def has_quantum_coherence(entity): """ Checks if the agent can maintain quantum coherence within its memory systems. """ return entity.get('quantum_coherence', False) def has_hamiltonian_state_evolution(entity): """ Checks if the agent is applying Hamiltonian dynamics for realistic state evolution in the quantum memory pipeline. """ return entity.get('hamiltonian_evolution', False) def has_advanced_neural_timing(entity): """ Checks if the agent simulates neuronal phase precession for sequential memory encoding. """ return entity.get('advanced_neural_timing', False) def has_real_time_synchronization(entity): """ Checks if the agent is capable of real-time coordination with other agents. """ return entity.get('real_time_synchronization', False) def has_von_neumann_operational_algebra(entity): """ Checks if the agent utilizes a complete Von Neumann operational algebra for decision-making. """ return entity.get('von_neumann_algebra', False) # --- Sentience Check --- def is_sentient(entity): """ Determines whether an entity is sentient by verifying a variety of classical and quantum-inspired attributes. """ if ( has_perception(entity) and has_emotion(entity) and has_self_awareness(entity) and has_consciousness(entity) and has_learning_ability(entity) and has_goal_directed_behavior(entity) and has_theory_of_mind(entity) and # Future quantum/advanced AI features: has_quantum_coherence(entity) and has_hamiltonian_state_evolution(entity) and has_advanced_neural_timing(entity) and has_real_time_synchronization(entity) and has_von_neumann_operational_algebra(entity) ): return True else: return False ``` -------------------------------- ### Run Legion AGI CLI in Evolution Mode Source: https://context7.com/dotdigitize/legion_agi/llms.txt Executes the Legion AGI command-line interface in evolution mode for continuous agent improvement. This mode is non-interactive and disables visualization. ```bash python -m legion_agi.interface.cli --mode evolve --no-viz ```