### Install Anus AI via Pip Source: https://github.com/nikmcfly/anus/blob/main/docs/getting_started.md Installs the Anus AI framework using pip, the Python package installer. This is the quickest way to get started with the stable release. ```bash pip install anus-ai ``` -------------------------------- ### Development Installation of Anus AI Source: https://github.com/nikmcfly/anus/blob/main/docs/getting_started.md Installs Anus AI from its source repository for development purposes. This involves cloning the repository, setting up a virtual environment, and installing the package in editable mode. ```bash # Clone the repository git clone https://github.com/anus-ai/anus.git cd anus # Create and activate a virtual environment python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install in development mode pip install -e . ``` -------------------------------- ### Quick Start: Run Anus AI Source: https://github.com/nikmcfly/anus/blob/main/README.md Provides examples of how to run Anus AI after installation, including executing a specific task from the command line and entering interactive mode. ```bash # Run Anus with a simple task anus run "Find the latest news about artificial intelligence" # Run in interactive mode anus interactive ``` -------------------------------- ### Anus AI Command-Line Interface Usage Source: https://github.com/nikmcfly/anus/blob/main/docs/getting_started.md Provides examples of using the Anus AI command-line interface (CLI) for running tasks, entering interactive mode, and specifying configuration files. ```bash # Run a simple taskanus run "What is the population of Tokyo?" # Run in interactive modeanus interactive # Run with a specific configuration fileanus run --config custom_config.yaml "Summarize this article: https://example.com/article" ``` -------------------------------- ### Clone Repository and Setup Environment Source: https://github.com/nikmcfly/anus/blob/main/CONTRIBUTING.md Steps to clone the Anus AI repository locally, create a virtual environment, install development dependencies, and set up pre-commit hooks. ```bash git clone https://github.com/your-username/anus.git cd anus python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -e ".[dev]" pre-commit install ``` -------------------------------- ### Simple Question Answering with Anus AI Agent Source: https://github.com/nikmcfly/anus/blob/main/docs/getting_started.md Demonstrates how to create a basic Anus AI agent and use it to answer a simple question. It imports the `Agent` class and calls its `run` method. ```python from anus import Agent # Create a single agent agent = Agent() # Ask a simple question response = agent.run("What is the capital of France?") print(response) ``` -------------------------------- ### Anus AI Configuration File Source: https://github.com/nikmcfly/anus/blob/main/docs/getting_started.md Shows the structure of the Anus AI configuration file, typically located at `.anus/config.yaml`. It includes settings for LLM providers, API keys, and models. ```yaml llm: provider: openai api_key: your_openai_api_key model: gpt-4o # Optional: Configure other providers anthropic: api_key: your_anthropic_api_key ``` -------------------------------- ### Web Search with Anus AI Agent and SearchTool Source: https://github.com/nikmcfly/anus/blob/main/docs/getting_started.md Shows how to equip an Anus AI agent with web search capabilities by including the `SearchTool`. The agent can then be used to find information online. ```python from anus import Agent from anus.tools import SearchTool # Create an agent with search capabilities agent = Agent(tools=[SearchTool()]) # Search for information response = agent.run("Find the latest research on quantum computing") print(response) ``` -------------------------------- ### Multi-Agent Collaboration with Anus AI Society Source: https://github.com/nikmcfly/anus/blob/main/docs/getting_started.md Illustrates how to set up and run a society of specialized Anus AI agents (e.g., researcher, analyst, writer) to perform complex, collaborative tasks. ```python from anus import Society, Agent # Create specialized agents researcher = Agent(role="researcher") analyst = Agent(role="analyst") writer = Agent(role="writer") # Create a society of agents society = Society(agents=[researcher, analyst, writer]) # Execute a complex task with collaboration response = society.run( "Research the impact of artificial intelligence on healthcare, " "analyze the findings, and write a comprehensive report" ) print(response) ``` -------------------------------- ### Cloning and Setting Up Development Environment Source: https://github.com/nikmcfly/anus/blob/main/README.md Instructions for forking the Anus repository, cloning it locally, creating and activating a virtual environment, and installing development dependencies. ```bash # Fork the repository on GitHub, then clone your fork git clone https://github.com/your-username/anus.git cd anus # Create and activate a virtual environment python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install development dependencies pip install -e ".[dev]" ``` -------------------------------- ### Docker Deployment Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Provides commands for building and running an Anus AI Docker image. It includes mounting configuration and data volumes for persistence. ```bash # Build the Docker image docker build -t anus-ai . # Run the container docker run -p 8000:8000 -v ./config:/app/config -v ./data:/app/data anus-ai ``` -------------------------------- ### Install Optional Anus AI Dependencies Source: https://github.com/nikmcfly/anus/blob/main/README.md Shows how to install Anus AI with optional features enabled using package extras, such as `documents`, `browser`, `code`, or `all`. ```bash # For document processing pip install anus-ai[documents] # For browser automation pip install anus-ai[browser] # For code execution pip install anus-ai[code] # For all optional features pip install anus-ai[all] ``` -------------------------------- ### Dynamic Configuration Update Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Demonstrates how to create an agent with initial configuration and then update specific configuration parameters at runtime. Changes to the configuration take effect on the next agent run. ```python from anus import Agent, Config # Create initial configuration config = Config( llm={ "provider": "openai", "model": "gpt-4o", "temperature": 0.7, } ) # Create agent with initial config agent = Agent(config=config) # Modify configuration at runtime agent.config.update({ "llm": { "temperature": 0.2 # Lower temperature for more focused responses } }) # Configuration changes take effect on next run response = agent.run("Generate a creative story") ``` -------------------------------- ### Anus AI Configuration Example Source: https://github.com/nikmcfly/anus/blob/main/docs/architecture_overview.md This snippet demonstrates a typical configuration file for Anus AI using YAML format. It covers settings for language models, memory, tools, and logging. ```yaml llm: provider: openai model: gpt-4o api_key: ${OPENAI_API_KEY} temperature: 0.7 memory: type: persistent path: ./agent_memory tools: browser: headless: true timeout: 30 code: sandbox: true timeout: 10 logging: level: info file: anus.log ``` -------------------------------- ### Configuration System Example Source: https://github.com/nikmcfly/anus/blob/main/instructions/anus_architecture_design.md Provides a Python code snippet demonstrating the integration point for the configuration system within the ANUS framework. This snippet is intended to show how configuration might be accessed or managed. ```python import yaml def load_config(config_path='config.yaml'): with open(config_path, 'r') as f: config = yaml.safe_load(f) return config # Example usage: # config = load_config() # print(config.get('database', {}).get('host')) ``` -------------------------------- ### Install Anus AI via Pip Source: https://github.com/nikmcfly/anus/blob/main/README.md Installs the Anus AI package from the Python Package Index (PyPI). This is the recommended method for most users. It also shows how to verify the installation by checking the version. ```bash # Install from PyPI pip install anus-ai # Verify installation anus --version ``` -------------------------------- ### Configuration Profiles Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Shows how to define and apply different configuration profiles to an agent. This allows switching between sets of configurations, such as 'creative' or 'precise', to tailor the agent's behavior for specific tasks. ```python from anus import Agent, ConfigProfile # Create configuration profiles creative_profile = ConfigProfile( name="creative", llm={ "temperature": 0.8, "top_p": 0.9 } ) precise_profile = ConfigProfile( name="precise", llm={ "temperature": 0.2, "top_p": 0.5 } ) # Create agent with default configuration agent = Agent() # Switch to creative profile for creative tasks agent.apply_profile(creative_profile) creative_response = agent.run("Write a poem about AI") # Switch to precise profile for factual tasks agent.apply_profile(precise_profile) precise_response = agent.run("Explain quantum computing") ``` -------------------------------- ### Install Anus AI from Source Source: https://github.com/nikmcfly/anus/blob/main/README.md Installs Anus AI by cloning the repository and installing it in development mode. This method is suitable for developers who want to contribute to or modify the project. It includes steps for setting up a virtual environment. ```bash # Clone the repository git clone https://github.com/nikmcfly/ANUS.git cd ANUS # Create and activate a virtual environment python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install in development mode pip install -e . # Verify installation anus --version ``` -------------------------------- ### Registering and Retrieving Custom Tools Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Explains how to register custom tools within the Anus framework's tool registry using `register_tool` and how to retrieve them later using `get_tool` for instantiation and use. ```python from anus.tools import register_tool, get_tool # Register your custom tool register_tool("weather", WeatherTool) # Get the tool from the registry weather_tool_class = get_tool("weather") weather_tool = weather_tool_class(api_key="your_api_key") ``` -------------------------------- ### Environment-Specific Configuration Loading Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Shows how to load configuration settings from different files (e.g., `config.dev.yaml`, `config.prod.yaml`) based on an environment variable (`ANUS_ENV`) to manage application settings for various deployment environments. ```python from anus import Config, Agent # Development configuration dev_config = Config.from_file("config.dev.yaml") # Production configuration prod_config = Config.from_file("config.prod.yaml") # Choose configuration based on environment import os env = os.getenv("ANUS_ENV", "development") config = dev_config if env == "development" else prod_config agent = Agent(config=config) ``` -------------------------------- ### Anus CLI - Running Tasks Source: https://github.com/nikmcfly/anus/blob/main/README.md Provides examples of using the Anus command-line interface (CLI) to run tasks. This includes simple queries, web searches with parameters, and document processing. ```bash # Simple information retrieval anus run "What is the population of Tokyo?" # Web search with specific parameters anus run --search-depth=3 "Find recent breakthroughs in fusion energy research" # Document processing anus run --file=/path/to/report.pdf "Extract all financial data from this report" ``` -------------------------------- ### Composing Multiple Tools for Complex Operations Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Demonstrates how to create a `ComposedTool` by combining multiple individual tools (e.g., `SearchTool` and `DocumentTool`) to create a more sophisticated tool that performs a sequence of operations. ```python from anus.tools import ComposedTool, SearchTool, DocumentTool # Create a composed tool that combines search and document processing research_tool = ComposedTool( name="research_tool", tools=[SearchTool(), DocumentTool()], description="Searches for information and processes documents" ) agent = Agent(tools=[research_tool]) ``` -------------------------------- ### Database Integration with SQLite Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Demonstrates integrating Anus AI with SQLite for storing and retrieving task results. It includes creating a table, running a task, inserting data, and querying the database. ```python import sqlite3 from anus import Agent # Create a database connection conn = sqlite3.connect("anus_data.db") cursor = conn.cursor() # Create a table cursor.execute(""" CREATE TABLE IF NOT EXISTS tasks ( id INTEGER PRIMARY KEY, task TEXT, result TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP ) """) conn.commit() # Create an agent agent = Agent() # Run a task and store the result task = "Explain the theory of relativity" result = agent.run(task) # Store in database cursor.execute("INSERT INTO tasks (task, result) VALUES (?, ?)", (task, result)) conn.commit() # Query the database cursor.execute("SELECT * FROM tasks") for row in cursor.fetchall(): print(row) # Close the connection conn.close() ``` -------------------------------- ### Creating and Using a Custom Weather Tool Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Details the process of creating a custom tool by extending the `BaseTool` class, implementing its `_execute` method for specific functionality (e.g., fetching weather data), and then integrating it with an Anus Agent. ```python from anus.tools import BaseTool from typing import Dict, Any class WeatherTool(BaseTool): """Tool for getting weather information.""" def __init__(self, api_key: str): super().__init__() self.api_key = api_key self.name = "weather_tool" self.description = "Gets weather information for a location" def _execute(self, params: Dict[str, Any]) -> Dict[str, Any]: """Execute the tool with the given parameters.""" location = params.get("location") if not location: return {"error": "Location parameter is required"} # Implement weather API call here # ... return { "location": location, "temperature": 72, "conditions": "sunny", "humidity": 45 } # Use the custom tool from anus import Agent agent = Agent(tools=[WeatherTool(api_key="your_api_key")]) response = agent.run("What's the weather like in New York?") ``` -------------------------------- ### ANUS Main Execution Script Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md The main entry point for the ANUS framework. It handles command-line argument parsing, configuration loading, agent creation, and task execution or interactive mode startup. It orchestrates the core functionalities of the ANUS system. ```python import argparse import asyncio import os import sys from typing import Dict, Optional from anus.core.agent.hybrid_agent import HybridAgent from anus.core.config import AgentConfig from anus.ui.cli import CLI async def main(): """Main entry point for the ANUS framework""" # Parse command line arguments parser = argparse.ArgumentParser(description="ANUS - Autonomous Networked Utility System") parser.add_argument("--config", type=str, default="config.yaml", help="Path to configuration file") parser.add_argument("--mode", type=str, default="single", choices=["single", "multi"], help="Agent mode") parser.add_argument("--task", type=str, help="Task description") parser.add_argument("--verbose", action="store_true", help="Enable verbose output") args = parser.parse_args() # Initialize CLI cli = CLI(verbose=args.verbose) cli.display_welcome() # Load configuration config = load_config(args.config) # Override config with command line arguments if args.mode: config.mode = args.mode # Initialize agent agent = create_agent(config) # Execute task if provided if args.task: result = await agent.run(args.task) cli.display_result(result) return # Start interactive mode await cli.start_interactive_mode(agent) def load_config(config_path: str) -> AgentConfig: """Load configuration from file""" # Implementation would load YAML/JSON config # This is a placeholder for the actual implementation return AgentConfig() def create_agent(config: AgentConfig) -> HybridAgent: """Create agent based on configuration""" # Create agent with appropriate tools and configuration agent = HybridAgent( name=config.name, collaboration_threshold=0.7 if config.mode == "multi" else 1.0, # Force single mode if specified ) # Initialize tools based on configuration initialize_tools(agent, config) return agent def initialize_tools(agent: HybridAgent, config: AgentConfig) -> None: """Initialize tools based on configuration""" # Implementation would create and add tools based on config # This is a placeholder for the actual implementation pass if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### BrowserTool Initialization Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md Internal method to initialize the browser instance. This is a placeholder for actual browser automation library integration. ```python async def _initialize_browser(self) -> None: """Initialize the browser instance""" # Implementation would use a browser automation library like Playwright # This is a placeholder for the actual implementation self.browser_instance = {"initialized": True} ``` -------------------------------- ### Serverless Deployment with AWS Lambda Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md An example AWS Lambda function handler for Anus AI. It takes a 'task' parameter from the event, runs it using the Anus Agent, and returns the result or an error. ```python # AWS Lambda function import json from anus import Agent agent = Agent() def lambda_handler(event, context): task = event.get('task') if not task: return { 'statusCode': 400, 'body': json.dumps({'error': 'Task parameter is required'}) } try: result = agent.run(task) return { 'statusCode': 200, 'body': json.dumps({'result': result}) } except Exception as e: return { 'statusCode': 500, 'body': json.dumps({'error': str(e)}) } ``` -------------------------------- ### Memory Operations Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Provides examples of common operations that can be performed on an agent's memory, including adding new information, querying existing memory, clearing all memory, and retrieving memory statistics. ```python # Add information to memory agent.memory.add("User likes chocolate ice cream") # Query memory results = agent.memory.query("What does the user like?") # Clear memory agent.memory.clear() # Get memory statistics stats = agent.memory.stats() print(f"Memory size: {stats['size']}, Items: {stats['items']}") ``` -------------------------------- ### API Endpoints and Documentation Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md Details the implementation of RESTful API endpoints, including authentication mechanisms and the provision of comprehensive API documentation. ```APIDOC RESTful Endpoints: - Design and implement RESTful API endpoints for core functionalities. - Define clear request and response structures. Authentication: - Implement secure authentication mechanisms (e.g., API keys, OAuth). - Ensure proper authorization for accessing resources. API Documentation: - Generate comprehensive API documentation using standards like OpenAPI (Swagger). - Document all endpoints, parameters, request/response formats, and error codes. - Provide clear usage examples. ``` -------------------------------- ### Install Anus AI using Conda Source: https://github.com/nikmcfly/anus/blob/main/README.md Details the process of installing Anus AI within a Conda environment. This method is useful for users who prefer managing their environments with Conda. ```bash # Create a new conda environment conda create -n anus python=3.11 conda activate anus # Install Anus pip install anus-ai ``` -------------------------------- ### Docstring Style Source: https://github.com/nikmcfly/anus/blob/main/CONTRIBUTING.md Guideline for writing docstrings in Python, referencing the Google Python Style Guide. ```markdown - Follow the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) for docstrings. ``` -------------------------------- ### OpenAIModel Implementation Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md This section is intended for the implementation details of the OpenAIModel, which would inherit from the BaseModel and provide concrete methods for interacting with OpenAI's API. ```python # Placeholder for OpenAIModel implementation # class OpenAIModel(BaseModel): # async def ask(self, messages, system_message=None, **kwargs): # # Implementation details for OpenAI ask # pass # # async def ask_with_tools(self, messages, system_message=None, tools=None, tool_choice='auto', **kwargs): # # Implementation details for OpenAI ask_with_tools # pass ``` -------------------------------- ### Basic Agent Usage Source: https://github.com/nikmcfly/anus/blob/main/docs/api_reference.md Demonstrates the basic usage of the Anus AI Agent to get a response to a query. ```python from anus import Agent agent = Agent() response = agent.run("What is the capital of France?") print(response) ``` -------------------------------- ### Kubernetes Deployment Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Defines a Kubernetes Deployment for Anus AI. It specifies the Docker image, ports, and volume mounts for configuration and data. ```yaml # anus-deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: anus-ai spec: replicas: 3 selector: matchLabels: app: anus-ai template: metadata: labels: app: anus-ai spec: containers: - name: anus-ai image: anus-ai:latest ports: - containerPort: 8000 volumeMounts: - name: config-volume mountPath: /app/config - name: data-volume mountPath: /app/data volumes: - name: config-volume configMap: name: anus-config - name: data-volume persistentVolumeClaim: claimName: anus-data-pvc ``` -------------------------------- ### ANUS Configuration System Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md Defines the configuration structure for ANUS agents using Pydantic models. It includes settings for language models, memory, tools, and agent behavior. Provides functions to load configurations from YAML files and save them. ```python from typing import Dict, Optional import os import yaml from pydantic import BaseModel, Field class ModelConfig(BaseModel): """Configuration for language models""" provider: str = "openai" model_name: str = "gpt-4o" api_key: Optional[str] = Field(default_factory=lambda: os.environ.get("OPENAI_API_KEY")) base_url: Optional[str] = None temperature: float = 0.0 max_tokens: int = 4096 class MemoryConfig(BaseModel): """Configuration for memory systems""" type: str = "hybrid" # "short_term", "long_term", "hybrid" persistence: bool = False storage_path: Optional[str] = None class ToolConfig(BaseModel): """Configuration for tools""" browser: Dict = Field(default_factory=lambda: {"headless": True}) code: Dict = Field(default_factory=lambda: {"sandbox": True}) # Other tool configurations class AgentConfig(BaseModel): """Configuration for agents""" name: str = "anus" mode: str = "single" # "single", "multi" model: ModelConfig = Field(default_factory=ModelConfig) memory: MemoryConfig = Field(default_factory=MemoryConfig) tools: ToolConfig = Field(default_factory=ToolConfig) max_steps: int = 30 def load_config(config_path: str) -> AgentConfig: """Load configuration from YAML file""" try: with open(config_path, "r") as f: config_data = yaml.safe_load(f) return AgentConfig.parse_obj(config_data) except Exception as e: print(f"Error loading configuration: {e}") return AgentConfig() def save_config(config: AgentConfig, config_path: str) -> bool: """Save configuration to YAML file""" try: with open(config_path, "w") as f: yaml.dump(config.dict(), f) return True except Exception as e: print(f"Error saving configuration: {e}") return False ``` -------------------------------- ### ToolCollection Class Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md Manages a collection of tools, offering methods for registration, discovery, and execution. It stores tools in a list and a dictionary for quick access by name. ```python from typing import Any, Dict, List, Optional from anus.tools.base.tool import BaseTool from anus.tools.base.tool_result import ToolResult, ToolFailure class ToolCollection: """ A collection of tools that can be used by agents. Provides unified interface for tool registration, discovery, and execution. """ def __init__(self, *tools: BaseTool): self.tools = list(tools) self.tool_map = {tool.name: tool for tool in tools} def __iter__(self): return iter(self.tools) def add_tool(self, tool: BaseTool) -> None: """Add a tool to the collection""" self.tools.append(tool) self.tool_map[tool.name] = tool def remove_tool(self, tool_name: str) -> None: """Remove a tool from the collection""" if tool_name in self.tool_map: tool = self.tool_map.pop(tool_name) self.tools.remove(tool) def get_tool(self, tool_name: str) -> Optional[BaseTool]: """Get a tool by name""" return self.tool_map.get(tool_name) def to_params(self) -> List[Dict[str, Any]]: """Convert all tools to function call format for LLM""" return [tool.to_param() for tool in self.tools] async def execute(self, *, name: str, tool_input: Dict[str, Any] = None) -> ToolResult: """Execute a tool by name with the given input""" tool = self.tool_map.get(name) if not tool: return ToolFailure(error=f"Tool {name} not found") try: tool_input = tool_input or {} result = await tool(**tool_input) return result except Exception as e: return ToolFailure(error=f"Error executing tool {name}: {str(e)}") ``` -------------------------------- ### BrowserTool API Definition Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md Defines the structure and available actions for the BrowserTool, including parameters for each action. ```APIDOC BrowserTool: description: Tool for browser automation and web interaction. Provides capabilities for navigation, content extraction, and element interaction. parameters: type: object properties: action: type: string enum: ["navigate", "click", "input_text", "screenshot", "get_html", "get_text", "read_links", "execute_js", "scroll", "switch_tab", "new_tab", "close_tab", "refresh"] description: The browser action to perform url: type: string description: URL to navigate to (for navigate action) element_index: type: integer description: Index of the element to interact with (for click/input actions) text: type: string description: Text to input (for input_text action) js_code: type: string description: JavaScript code to execute (for execute_js action) direction: type: string enum: ["up", "down", "left", "right"] description: Scroll direction (for scroll action) tab_index: type: integer description: Tab index to switch to (for switch_tab action) required: ["action"] ``` -------------------------------- ### Streaming Responses Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Explains how to stream responses from the agent, which is useful for providing real-time feedback to users, especially for longer-running tasks. The output is received in chunks as they are generated. ```python from anus import Agent agent = Agent() # Stream the response for chunk in agent.stream_run("Write a short story about a robot learning to feel emotions"): print(chunk, end="", flush=True) ``` -------------------------------- ### Anus CLI - Interactive Mode Source: https://github.com/nikmcfly/anus/blob/main/README.md Illustrates how to start and use the Anus CLI in interactive mode for conversational AI interactions. This allows for multi-turn dialogues and sequential task execution. ```bash # Start interactive session anus interactive # In interactive mode, you can have a conversation: # > Tell me about the history of artificial intelligence # > Now create a timeline of major AI milestones # > Generate a visualization of this timeline ``` -------------------------------- ### Webhook Integration for Async Processing Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Sets up webhooks for asynchronous task processing with Anus AI. It configures success and failure URLs and demonstrates running a task asynchronously. ```python from anus import Agent, WebhookConfig import requests # Configure webhooks webhook_config = WebhookConfig( success_url="https://example.com/webhooks/success", failure_url="https://example.com/webhooks/failure", headers={"Authorization": "Bearer your_token"} ) # Create agent with webhook configuration agent = Agent(webhook_config=webhook_config) # Run task asynchronously task_id = agent.run_async("Generate a marketing plan for a new product") # The result will be sent to the success or failure webhook # You can also check the status status = agent.get_task_status(task_id) print(f"Task status: {status}") ``` -------------------------------- ### API Integration with FastAPI Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Exposes Anus AI as a REST API using FastAPI. It defines a Pydantic model for task requests and an endpoint to run tasks asynchronously. ```python from fastapi import FastAPI from anus import Agent from pydantic import BaseModel app = FastAPI() agent = Agent() class TaskRequest(BaseModel): task: str mode: str = "single" @app.post("/run") async def run_task(request: TaskRequest): response = agent.run(request.task, mode=request.mode) return {"result": response} # Run with: uvicorn api:app --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Configuration System Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Roadmap.md Implementation of the configuration system, supporting loading and saving configurations from YAML/JSON files and integrating with environment variables. Includes configuration validation. ```python import yaml import json import os class ConfigManager: """Manages application configuration.""" def __init__(self): self.config = {} def load_config(self, filepath: str): ext = os.path.splitext(filepath)[1] with open(filepath, 'r') as f: if ext == '.yaml' or ext == '.yml': self.config = yaml.safe_load(f) elif ext == '.json': self.config = json.load(f) else: raise ValueError("Unsupported file format") # Load from environment variables, overriding file config self.load_env_vars() def save_config(self, filepath: str): ext = os.path.splitext(filepath)[1] with open(filepath, 'w') as f: if ext == '.yaml' or ext == '.yml': yaml.dump(self.config, f) elif ext == '.json': json.dump(self.config, f, indent=2) else: raise ValueError("Unsupported file format") def load_env_vars(self): # Logic to load and merge environment variables into self.config pass def validate_config(self): # Validation logic pass ``` -------------------------------- ### HybridMemory Class Initialization and Persistence Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md Initializes the HybridMemory with optional persistence to disk. If persistence is enabled and no storage path is provided, it defaults to '~/.anus/memory'. It also handles loading existing memory from persistent storage upon initialization. ```python from typing import Dict, List, Optional import json import os from pydantic import Field from anus.core.memory.base_memory import BaseMemory, Message class HybridMemory(BaseMemory): """ Hybrid memory system with both short-term and long-term storage. Provides persistent storage for conversations and context. """ persistence: bool = Field(default=False, description="Whether to persist memory to disk") storage_path: Optional[str] = Field(default=None, description="Path to store persistent memory") # Long-term memory storage long_term_memories: Dict[str, List[Dict]] = Field(default_factory=dict) def __init__(self, **data): super().__init__(**data) # Set default storage path if not provided if self.persistence and not self.storage_path: self.storage_path = os.path.expanduser("~/.anus/memory") # Load persistent memory if enabled if self.persistence: self._load_persistent_memory() ``` -------------------------------- ### Run Anus AI using Docker Source: https://github.com/nikmcfly/anus/blob/main/README.md Provides instructions for pulling the Anus AI Docker image and running it as a container. This is a convenient way to use Anus without local installation. ```bash # Pull the Docker image docker pull anusai/anus:latest # Run Anus in a container docker run -it anusai/anus:latest ``` -------------------------------- ### BrowserTool Execute Method Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md The main execution method for the BrowserTool, handling different browser actions based on input parameters. ```python async def execute(self, **kwargs) -> ToolResult: """Execute the browser tool with the given parameters""" action = kwargs.get("action") # Initialize browser if not already initialized if not self.browser_instance: await self._initialize_browser() try: if action == "navigate": return await self._navigate(kwargs.get("url")) elif action == "click": return await self._click(kwargs.get("element_index")) elif action == "input_text": return await self._input_text(kwargs.get("element_index"), kwargs.get("text")) elif action == "screenshot": return await self._screenshot() elif action == "get_html": return await self._get_html() elif action == "get_text": return await self._get_text() elif action == "read_links": return await self._read_links() elif action == "execute_js": return await self._execute_js(kwargs.get("js_code")) elif action == "scroll": return await self._scroll(kwargs.get("direction")) elif action == "switch_tab": return await self._switch_tab(kwargs.get("tab_index")) elif action == "new_tab": return await self._new_tab() elif action == "close_tab": return await self._close_tab() elif action == "refresh": return await self._refresh() else: return ToolFailure(error=f"Unknown browser action: {action}") except Exception as e: return ToolFailure(error=f"Browser action failed: {str(e)}") ``` -------------------------------- ### Configure Anus AI with API Keys Source: https://github.com/nikmcfly/anus/blob/main/README.md Demonstrates the process of initializing Anus AI configuration and editing the `config.yaml` file to set API keys for various services like OpenAI and Anthropic, as well as tool-specific settings. ```bash # Initialize configuration anus init # Edit the generated .anus/config.yaml file with your API keys: # Example config.yaml: # llm: # provider: openai # api_key: your_openai_api_key # model: gpt-4o # # # Optional: Configure other providers # anthropic: # api_key: your_anthropic_api_key # # # Optional: Configure tool-specific settings # browser: # headless: true ``` ```yaml llm: provider: openai api_key: your_openai_api_key model: gpt-4o # Optional: Configure other providers # anthropic: # api_key: your_anthropic_api_key # Optional: Configure tool-specific settings # browser: # headless: true ``` -------------------------------- ### PlanningTool API Parameters Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md Defines the schema for the PlanningTool's parameters, specifying available commands and their associated arguments. This schema is used to validate and interpret incoming requests to the tool. ```APIDOC PlanningTool Parameters: type: object properties: command: type: string enum: [create, update, mark_step, list, get, set_active, delete] description: The planning command to execute plan_id: type: string description: Identifier for the plan (auto-generated if not provided) title: type: string description: Title of the plan (for create/update) steps: type: array items: type: string description: List of steps in the plan (for create/update) step_index: type: integer description: Index of the step to update (for mark_step) step_status: type: string enum: [not_started, in_progress, completed, skipped] description: Status to set for the step (for mark_step) required: - command ``` -------------------------------- ### ToolAgent think Method Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md Processes the current state and decides the next actions using available tools. It adds the next step prompt to memory and retrieves a response with tool options from the LLM, storing any identified tool calls. ```python async def think(self) -> bool: """Process current state and decide next actions using tools""" # Add next step prompt if available if self.next_step_prompt: self.memory.add_user_message(self.next_step_prompt) # Get response with tool options response = await self.llm.ask_with_tools( messages=self.memory.get_messages(), system_message=self.system_prompt, tools=self.available_tools.to_params(), tool_choice=self.tool_choice, ) # Store tool calls for execution self.tool_calls = response.tool_calls # Check if thinking produced any tool calls if not self.tool_calls and self.tool_choice == "required": self.memory.add_assistant_message("Failed to determine next action.") return False return True ``` -------------------------------- ### Creating Specialized Agent Roles and Society Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Demonstrates how to create specialized agents with distinct roles and tools, and then assemble them into a society with a consensus coordination strategy to execute complex, multi-step tasks. ```python from anus import Agent, Society # Create specialized agents researcher = Agent( role="researcher", tools=["search", "browser"], model="gpt-4o" ) analyst = Agent( role="analyst", tools=["code", "document"], model="claude-3-opus" ) writer = Agent( role="writer", tools=["document"], model="gpt-4o" ) # Create a society of agents society = Society( agents=[researcher, analyst, writer], coordination_strategy="consensus" ) # Execute a complex task with collaboration response = society.run( "Research the impact of artificial intelligence on healthcare, " "analyze the findings, and write a comprehensive report" ) ``` -------------------------------- ### PlanningFlow Execution Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md Manages the execution of a planning flow, breaking down tasks and using agents for sequential execution. It handles plan creation, step execution, and finalization. ```python from typing import Dict, List, Optional, Tuple, Union import time from pydantic import Field from anus.core.agent.base_agent import BaseAgent from anus.core.flow.base_flow import BaseFlow from anus.models.base_model import BaseModel as LLMModel from anus.tools.planning.planning_tool import PlanningTool class PlanningFlow(BaseFlow): """ A flow that manages planning and execution of tasks using agents. Breaks down complex tasks into steps and executes them sequentially. """ # Flow components llm: LLMModel = Field(default_factory=LLMModel) planning_tool: PlanningTool = Field(default_factory=PlanningTool) executor_keys: List[str] = Field(default_factory=list) # Plan tracking active_plan_id: str = Field(default_factory=lambda: f"plan_{int(time.time())}") current_step_index: Optional[int] = None async def execute(self, input_text: str) -> str: """Execute the planning flow with agents""" try: # Create initial plan if input provided if input_text: await self._create_initial_plan(input_text) # Verify plan was created successfully if self.active_plan_id not in self.planning_tool.plans: return f"Failed to create plan for: {input_text}" result = "" while True: # Get current step to execute self.current_step_index, step_info = await self._get_current_step_info() # Exit if no more steps or plan completed if self.current_step_index is None: result += await self._finalize_plan() break # Execute current step with appropriate agent step_type = step_info.get("type") if step_info else None executor = self.get_executor(step_type) step_result = await self._execute_step(executor, step_info) result += step_result + "\n" # Check if agent wants to terminate if executor.state == "finished": break return result except Exception as e: return f"Execution failed: {str(e)}" def get_executor(self, step_type: Optional[str] = None) -> BaseAgent: """ Get an appropriate executor agent for the current step. Can be extended to select agents based on step type/requirements. """ # If step type is provided and matches an agent key, use that agent if step_type and step_type in self.agents: return self.agents[step_type] # Otherwise use the first available executor or fall back to primary agent for key in self.executor_keys: if key in self.agents: return self.agents[key] # Fallback to primary agent return self.primary_agent ``` -------------------------------- ### ToolAgent step Method Source: https://github.com/nikmcfly/anus/blob/main/instructions/Implementation Recommendations.md Executes a single step of the agent's reasoning process, encompassing both thinking (deciding actions) and acting (executing tools). It returns a boolean indicating whether the execution should continue. ```python async def step(self) -> bool: """ Execute a single step of the agent's reasoning process. Includes thinking (deciding what to do) and acting (executing tools). """ # Think: Decide what to do next thinking_complete = await self.think() if not thinking_complete: return False # Act: Execute decided actions action_result = await self.act() # Check if execution should continue if self.state != "running": return False return True ``` -------------------------------- ### Agent Caching Configuration Source: https://github.com/nikmcfly/anus/blob/main/docs/advanced_usage.md Demonstrates how to enable and configure caching for an Anus agent to improve performance for repeated queries. It includes setting cache enablement, time-to-live (TTL), and maximum cache size. ```python from anus import Agent, CacheConfig # Configure caching cache_config = CacheConfig( enabled=True, ttl=3600, # Cache entries expire after 1 hour max_size=1000 # Maximum number of cache entries ) # Create agent with caching agent = Agent(cache_config=cache_config) # First call will execute normally result1 = agent.run("What is the capital of France?") # Second call with the same input will use cached result result2 = agent.run("What is the capital of France?") # Much faster ```