### Complete CLIEnvironment Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/environments.md Demonstrates initializing CLIEnvironment, resetting it, listing files, checking disk usage, and getting environment status. ```python from react_agent_framework.core.environment import CLIEnvironment, Action # System admin agent with CLIEnvironment(working_directory="/tmp", safe_mode=True) as env: # Check current directory obs = env.reset() print(f"Working in: {obs.data['directory']}") # List files action = Action(name="execute", parameters={"command": "ls -l"}) obs = env.step(action) print(f"Files:\n{obs.data['stdout']}") # Check disk usage action = Action(name="execute", parameters={"command": "df -h"}) obs = env.step(action) print(f"Disk usage:\n{obs.data['stdout']}") # Get environment status status = env.get_status() print(f"Steps executed: {status['steps']}") ``` -------------------------------- ### Ollama Setup Instructions Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/guides/custom-providers.md Instructions for installing Ollama, pulling a model, and starting the Ollama server to enable local LLM usage. ```bash # Install Ollama curl -fsSL https://ollama.ai/install.sh | sh # Pull a model ollama pull llama3.2 # Start Ollama server ollama serve ``` -------------------------------- ### Project Setup with React Agent Framework Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/first-agent.md Set up your project directory, create a virtual environment, activate it, and install the React Agent Framework. Also, configure your OpenAI API key in the .env file. ```bash mkdir my-agent-project cd my-agent-project python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install react-agent-framework ``` ```env OPENAI_API_KEY=sk-your-key-here ``` -------------------------------- ### PyPI Installation with All Providers Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Install the package with support for all available AI providers. ```bash pip install react-agent-framework[anthropic,google] ``` -------------------------------- ### Verify Installation and Basic Usage Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Check the installed version and create a basic agent instance to confirm the installation is successful. ```python from react_agent_framework import ReactAgent # Check version import react_agent_framework print(react_agent_framework.__version__) # Should print: 0.9.0 # Create a basic agent to test agent = ReactAgent(name="Test Agent") print(agent) # Should print agent info ``` -------------------------------- ### PyPI Installation with All Extras Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Install the package with all available extras, including all providers and memory backends. ```bash pip install react-agent-framework[all] ``` -------------------------------- ### Run FastAPI-style Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/README.md Execute the FastAPI-style example script for the React Agent Framework. ```bash python -m react_agent_framework.examples.fastapi_style ``` -------------------------------- ### Troubleshooting: Provider Not Found Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md If a provider is not found, install the specific provider package. Examples for Anthropic and Google are shown. ```bash pip install react-agent-framework[anthropic] # For Claude pip install react-agent-framework[google] # For Gemini ``` -------------------------------- ### Install from Source with All Extras Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Install the package from source in editable mode with all extras enabled. ```bash pip install -e ".[all]" ``` -------------------------------- ### Basic PyPI Installation Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Install the core react-agent-framework package using pip. ```bash pip install react-agent-framework ``` -------------------------------- ### Install Optional Development Tools Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Install development dependencies for contributing to the framework. ```bash pip install react-agent-framework[dev] ``` -------------------------------- ### Complete File Environment Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/environments.md Demonstrates initializing, listing, searching, reading, and writing files using the FileEnvironment. ```python from react_agent_framework.core.environment import FileEnvironment, Action # File manager agent with FileEnvironment(root_directory="./project") as env: # Initialize and list files obs = env.reset() print(f"Project files: {len(obs.data['contents'])} items") # Search for Python files action = Action(name="search", parameters={"pattern": "*.py"}) obs = env.step(action) print(f"Found {obs.data['count']} Python files") # Read a specific file action = Action(name="read", parameters={"filepath": "main.py"}) obs = env.step(action) print(f"File size: {obs.data['size']} bytes") # Create a report report = f"Project analysis:\n{len(obs.data['content'])} lines of code" action = Action( name="write", parameters={"filepath": "report.txt", "content": report} ) obs = env.step(action) print(f"Report saved ({obs.data['bytes_written']} bytes)") ``` -------------------------------- ### Complete Example with Multiple MCP Servers Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/mcp-integration.md An end-to-end example demonstrating agent creation, connection to filesystem and GitHub MCP servers, listing available tools, executing tasks using these tools, and cleaning up connections. ```python from react_agent_framework import ReactAgent # Create agent agent = ReactAgent( name="Multi-Source Agent", description="Agent with access to multiple data sources", provider="gpt-4o-mini" ) # Connect to filesystem fs_server = agent.add_mcp_server( command="npx", args=["-y", "@modelcontextprotocol/server-filesystem", "."], name="filesystem" ) # Connect to GitHub (if token available) try: gh_server = agent.add_mcp_server( command="npx", args=["-y", "@modelcontextprotocol/server-github"], env={"GITHUB_TOKEN": "ghp_..."}, name="github" ) except: print("GitHub server not configured") # List all available tools print("\nAvailable MCP Tools:") for tool in agent.list_mcp_tools(): print(f" - {tool}") # Use the agent tasks = [ "List all Python files in current directory", "Read the contents of README.md", ] for task in tasks: print(f"\nTask: {task}") result = agent.run(task) print(f"Result: {result}") # Cleanup agent.disconnect_mcp_server(fs_server) ``` -------------------------------- ### Create a Production-Ready Agent Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/first-agent.md This example demonstrates how to create a fully configured agent with logging, a specific provider, temperature, iteration limits, chat memory, and custom tools. It includes a factory function for agent creation and an example of running a task. ```python from react_agent_framework import ReactAgent from react_agent_framework.core.memory.chat import SimpleChatMemory import logging # Setup logging logging.basicConfig(level=logging.INFO) def create_agent(): """Factory function to create configured agent""" agent = ReactAgent( name="Production Assistant", description="A production-ready AI assistant", provider="gpt-4o-mini", temperature=0.3, max_iterations=10, chat_memory=SimpleChatMemory(max_messages=100) ) # Add tools agent.use_tools("search.*", "computation.*") @agent.tool() def custom_tool(param: str) -> str: """Custom tool with proper error handling""" try: # Your implementation result = f"Processed: {param}" return result except Exception as e: logging.error(f"Tool error: {e}") return f"Error: {str(e)}" return agent def main(): agent = create_agent() # Example usage result = agent.run( "Search for Python best practices and summarize", verbose=True ) print(f"\nResult: {result}") if __name__ == "__main__": main() ``` -------------------------------- ### Install React Agent Framework Source: https://github.com/marcosf63/react-agent-framework/blob/main/README.md Install the framework via pip. Use the `[all]` option for all dependencies, or specify providers like `[anthropic]` or `[google]`. Memory backends like `[memory-chroma]` or `[memory-faiss]` can also be installed. ```bash pip install react-agent-framework pip install react-agent-framework[all] pip install react-agent-framework[anthropic] pip install react-agent-framework[google] pip install react-agent-framework[memory-chroma] pip install react-agent-framework[memory-faiss] pip install react-agent-framework[mcp] ``` -------------------------------- ### Install React Agent Framework from Source Source: https://github.com/marcosf63/react-agent-framework/blob/main/README.md Clone the repository, set up a virtual environment, and install the framework in editable mode for development. Remember to configure your OpenAI API key in the `.env` file. ```bash # Clone the repository git clone https://github.com/marcosf63/react-agent-framework.git cd react-agent-framework # Create and activate virtual environment python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate # Install in editable mode pip install -e . # Configure OpenAI key cp .env.example .env # Edit .env file and add your OPENAI_API_KEY ``` -------------------------------- ### Basic Agent Usage Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/README.md This example demonstrates how to initialize a ReactAgent, define a custom tool, and run the agent with a query. ```APIDOC ## Basic Example ```python from react_agent_framework import ReactAgent agent = ReactAgent(name="Assistant") @agent.tool() def greet(name: str) -> str: """Greet someone""" return f"Hello, {name}!" answer = agent.run("Greet John") print(answer) # "Hello, John!" ``` ``` -------------------------------- ### PyPI Installation with Memory Backends Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Install the package with support for specified memory backends. ```bash pip install react-agent-framework[chroma,faiss] ``` -------------------------------- ### Complete Production System Setup Source: https://github.com/marcosf63/react-agent-framework/blob/main/LLMs.txt Illustrates the setup of a production-ready enterprise agent, including infrastructure components like memory, monitoring, resilience, security, cost control, and human-in-the-loop approval. It configures agent capabilities, tools, and objectives. ```python from react_agent_framework import ReactAgent from react_agent_framework.core.memory.chat import SQLiteChatMemory from react_agent_framework.core.memory.knowledge import ChromaKnowledgeMemory from react_agent_framework.core.objectives import Objective, Priority from react_agent_framework.infrastructure.monitoring import AgentMetrics, AgentLogger, AgentTelemetry from react_agent_framework.infrastructure.resilience import RetryStrategy, CircuitBreaker from react_agent_framework.infrastructure.security import RBACManager, Sandbox, AuditLogger from react_agent_framework.infrastructure.cost_control import BudgetTracker, RateLimiter from react_agent_framework.infrastructure.human_loop import ApprovalManager # Infrastructure metrics = AgentMetrics("enterprise_agent") logger = AgentLogger("enterprise_agent") telemetry = AgentTelemetry("enterprise") retry = RetryStrategy(max_attempts=3) breaker = CircuitBreaker() rbac = RBACManager() sandbox = Sandbox() audit = AuditLogger() budget = BudgetTracker() limiter = RateLimiter(max_calls=1000, window_seconds=3600) approver = ApprovalManager(policy="high_risk_only") # Setup rabc.create_role("analyst", {"tools.search", "tools.read", "tools.analyze"}) rabc.assign_role("enterprise_agent", "analyst") budget.set_budget("daily", 100.0) budget.set_budget("monthly", 2000.0) # Agent agent = ReactAgent( name="Enterprise Agent", description="Production-ready enterprise agent", provider="gpt-4o-mini", chat_memory=SQLiteChatMemory("./enterprise_chat.db"), knowledge_memory=ChromaKnowledgeMemory("./enterprise_kb") ) agent.use_tools("search.*", "filesystem.read") # Add objective agent.objectives.add(Objective( goal="Analyze Q4 2024 market trends", priority=Priority.HIGH, success_criteria=["Collect data", "Analyze trends", "Generate report"] )) ``` -------------------------------- ### Install from Source (Editable Mode) Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Clone the repository and install the package in editable mode for development. This includes setting up a virtual environment. ```bash # Clone the repository git clone https://github.com/marcosf63/react-agent-framework.git cd react-agent-framework # Create virtual environment python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate # Install in editable mode pip install -e . ``` -------------------------------- ### Run Custom Tools Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/README.md Execute the custom tools example script for the React Agent Framework. ```bash python -m react_agent_framework.examples.custom_tools ``` -------------------------------- ### Run Agent Source: https://github.com/marcosf63/react-agent-framework/blob/main/LLMs.txt Example of running an agent to get an answer to a question. ```python answer = agent.run("What is the capital of France?") ``` -------------------------------- ### Basic React Agent Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/README.md Demonstrates how to initialize a ReactAgent and register a simple tool. The agent can then be run with a query to execute the tool. ```python from react_agent_framework import ReactAgent agent = ReactAgent(name="Assistant") @agent.tool() def greet(name: str) -> str: """Greet someone""" return f"Hello, {name}!" answer = agent.run("Greet John") print(answer) # "Hello, John!" ``` -------------------------------- ### Install ReAct Agent Framework Source: https://context7.com/marcosf63/react-agent-framework/llms.txt Install the package from PyPI with optional extras for providers, memory backends, and MCP. Configure API keys by creating a .env file. ```bash # Minimal install (OpenAI only) pip install react-agent-framework # All providers + all memory + MCP pip install react-agent-framework[all] # Selective extras pip install react-agent-framework[anthropic] # Claude support pip install react-agent-framework[google] # Gemini support pip install react-agent-framework[knowledge-chroma] # ChromaDB RAG pip install react-agent-framework[knowledge-faiss] # FAISS RAG pip install react-agent-framework[mcp] # Model Context Protocol # Configure API keys echo "OPENAI_API_KEY=sk-..."> .env ``` -------------------------------- ### Virtual Environment Setup Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Instructions for creating and activating a virtual environment using Python's `venv` module. ```bash python -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/contributing.md Clone your fork of the repository, set up a virtual environment, and install the project in editable mode with development dependencies. ```bash git clone https://github.com/YOUR_USERNAME/react-agent-framework.git cd react-agent-framework python -m venv .venv source .venv/bin/activate pip install -e ".[dev]" ``` -------------------------------- ### Install Optional AI Provider: Google Gemini Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Install the package with support for Google Gemini. ```bash pip install react-agent-framework[google] ``` -------------------------------- ### Production Agent with Infrastructure Setup Source: https://github.com/marcosf63/react-agent-framework/blob/main/LLMs.txt Demonstrates setting up various infrastructure components like monitoring, resilience, security, and cost control before creating a production-ready ReactAgent. ```python from react_agent_framework import ReactAgent from react_agent_framework.infrastructure.monitoring import AgentMetrics, AgentLogger from react_agent_framework.infrastructure.resilience import RetryStrategy, CircuitBreaker from react_agent_framework.infrastructure.security import RBACManager, Sandbox from react_agent_framework.infrastructure.cost_control import BudgetTracker # Setup infrastructure metrics = AgentMetrics("prod_agent") logger = AgentLogger("prod_agent", log_file="./logs/agent.log") retry = RetryStrategy(max_attempts=3) breaker = CircuitBreaker(failure_threshold=5) rbac = RBACManager() sandbox = Sandbox() budget = BudgetTracker() budget.set_budget("daily", 50.0) # Create agent agent = ReactAgent( name="Production Agent", provider="gpt-4o-mini" ) ``` -------------------------------- ### Install Optional Memory Backend: ChromaDB Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Install the package with support for ChromaDB memory backend. ```bash pip install react-agent-framework[chroma] ``` -------------------------------- ### Install Optional Memory Backend: FAISS Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Install the package with support for FAISS memory backend. ```bash pip install react-agent-framework[faiss] ``` -------------------------------- ### Complete Personal Assistant Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/guides/custom-tools.md An example of a personal assistant agent with multiple custom tools for date/time, random number generation, and temperature conversion. ```python from react_agent_framework import ReactAgent from datetime import datetime import random agent = ReactAgent( name="Personal Assistant", provider="gpt-4o-mini" ) @agent.tool() def get_datetime() -> str: """Get current date and time""" now = datetime.now() return f"Date: {now.strftime('%Y-%m-%d')}, Time: {now.strftime('%H:%M:%S')}" @agent.tool() def random_number(range_str: str) -> str: """Generate random number. Format: 'min-max' (e.g., '1-100')""" try: min_val, max_val = map(int, range_str.split("-")) number = random.randint(min_val, max_val) return f"Random number between {min_val} and {max_val}: {number}" except Exception as e: return "Error: Use format 'min-max' (e.g., '1-100')" @agent.tool() def convert_temperature(input_str: str) -> str: """Convert temperature. Format: 'C to F: 25' or 'F to C: 77'""" try: if "C to F" in input_str.upper(): celsius = float(input_str.split(":")[-1].strip()) fahrenheit = (celsius * 9/5) + 32 return f"{celsius}°C = {fahrenheit}°F" elif "F to C" in input_str.upper(): fahrenheit = float(input_str.split(":")[-1].strip()) celsius = (fahrenheit - 32) * 5/9 return f"{fahrenheit}°F = {celsius:.2f}°C" else: return "Use format: 'C to F: value' or 'F to C: value'" except Exception as e: return f"Conversion error: {str(e)}" # Use the tools answer = agent.run("What time is it?") answer = agent.run("Generate a random number between 1 and 100") answer = agent.run("Convert 25 Celsius to Fahrenheit") ``` -------------------------------- ### Install Browser Automation Tools Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/environments.md Instructions for installing Playwright and its browser binaries, necessary for full browser automation with the WebEnvironment. ```bash pip install playwright playwright install chromium ``` -------------------------------- ### Install Knowledge Memory Packages Source: https://github.com/marcosf63/react-agent-framework/blob/main/MIGRATION_GUIDE.md Install optional dependencies for knowledge memory. Use specific extras like '[knowledge-chroma]' or '[knowledge-faiss]', or '[all-memory]' for both. ```bash # ChromaDB pip install react-agent-framework[knowledge-chroma] # FAISS pip install react-agent-framework[knowledge-faiss] # Both pip install react-agent-framework[all-memory] ``` -------------------------------- ### Install Chat Memory (SQLite) Source: https://github.com/marcosf63/react-agent-framework/blob/main/MIGRATION_GUIDE.md Install the react-agent-framework package. SQLite is included by default as it's part of the Python standard library. ```bash pip install react-agent-framework # SQLite included (stdlib) ``` -------------------------------- ### Install react-agent-framework with MCP support Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/mcp-integration.md Install the necessary package to enable MCP integration with your agents. ```bash pip install react-agent-framework[mcp] ``` -------------------------------- ### Create a Simple Agent Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/examples/basic-usage.md Demonstrates the creation of a basic agent with a single calculation tool. Ensure the 'react-agent-framework' library is installed. ```python from react_agent_framework import ReactAgent # Create agent agent = ReactAgent( name="Simple Assistant", provider="gpt-4o-mini" ) # Add a tool @agent.tool() def calculate(expression: str) -> str: """Perform mathematical calculations""" try: result = eval(expression, {"__builtins__": {}}, {}) return f"Result: {result}" except Exception as e: return f"Error: {str(e)}" # Run agent answer = agent.run("What is 15% of 340?") print(answer) # Output: 15% of 340 is 51 ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/marcosf63/react-agent-framework/blob/main/README.md Install all development dependencies, including optional ones, for the project using pip. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Multi-Agent System Setup and Orchestration Source: https://github.com/marcosf63/react-agent-framework/blob/main/LLMs.txt Demonstrates setting up a multi-agent system with a MessageBus, ACLProtocol, Orchestrator, and TeamManager. Agents are created, registered, and assigned to a team for collaborative task execution. ```python from react_agent_framework import ReactAgent from react_agent_framework.multi_agent.communication import MessageBus, ACLProtocol from react_agent_framework.multi_agent.orchestration import Orchestrator from react_agent_framework.multi_agent.collaboration import TeamManager # Setup bus = MessageBus() protocol = ACLProtocol(bus) orch = Orchestrator(bus, "main") teams = TeamManager() # Create agents researcher = ReactAgent(name="Researcher") writer = ReactAgent(name="Writer") reviewer = ReactAgent(name="Reviewer") # Register orch.register_agent("researcher", {"research", "analyze"}) orch.register_agent("writer", {"write", "format"}) orch.register_agent("reviewer", {"review", "edit"}) # Create team teams.create_team("content_team", "Content Creation", leader="researcher") teams.add_member("content_team", "writer") teams.add_member("content_team", "reviewer") # Orchestrate workflow result_1 = orch.distribute_task("task_1", "research", {"topic": "AI"}) result_2 = orch.distribute_task("task_2", "write", {"content": result_1}) result_3 = orch.distribute_task("task_3", "review", {"draft": result_2}) ``` -------------------------------- ### Backward Compatibility Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/REFACTORING_SUMMARY.md Demonstrates how older code using SimpleMemory still functions with the new structure via adapters. ```python # Código v0.9.x (ainda funciona) from react_agent_framework.core.memory import SimpleMemory agent = ReactAgent(memory=SimpleMemory()) # Código v0.10.0 (recomendado) from react_agent_framework.core.memory.chat import SimpleChatMemory agent = ReactAgent(chat_memory=SimpleChatMemory()) ``` -------------------------------- ### Complete Objective Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/objectives.md Demonstrates creating a ReactAgent with multiple objectives and a custom tool, then running the agent to achieve a goal. ```python from react_agent_framework import ReactAgent from react_agent_framework.core.objectives import Objective # Create objectives objectives = [ Objective( goal="Calculate quarterly revenue", priority="critical", success_criteria=[ "Get Q1 sales: $50K", "Get Q2 sales: $60K", "Get Q3 sales: $55K", "Get Q4 sales: $65K", "Sum total" ] ), Objective( goal="Analyze growth rate", priority="high", success_criteria=["Calculate YoY growth"] ) ] # Create agent agent = ReactAgent( name="Financial Analyst", provider="gpt-4o-mini", objectives=objectives ) # Add calculator tool @agent.tool() def calculate(expression: str) -> str: """Perform calculations""" try: result = eval(expression, {"__builtins__": {}}, {}) return f"Result: {result}" except Exception as e: return f"Error: {str(e)}" # Agent works on objectives print("📋 Initial Objectives:") print(agent.objectives.get_summary()) # Run agent - it knows its goals answer = agent.run("Calculate the total quarterly revenue", verbose=True) print(f"\n✅ Answer: {answer}") # Check progress print("\n📊 Updated Objectives:") print(agent.objectives.get_summary()) ``` -------------------------------- ### Configure API Keys Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Set up API keys for various services by creating a `.env` file in your project root. This example shows keys for OpenAI, Anthropic, Google, and GitHub. ```env # OpenAI (default provider) OPENAI_API_KEY=sk-... # Anthropic (optional) ANTHROPIC_API_KEY=sk-ant-... # Google (optional) GOOGLE_API_KEY=AI... # Other services (optional) GITHUB_TOKEN=ghp_... BRAVE_API_KEY=... ``` -------------------------------- ### Multi-Tool Agent Setup Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/built-in-tools.md Combine tools from different categories, such as search, computation, and filesystem operations, for a versatile agent. Set temperature to 0 for deterministic behavior. ```python from react_agent_framework import ReactAgent agent = ReactAgent( name="Multi-Tool Assistant", provider="gpt-4o-mini", temperature=0 ) # Register tools from different categories agent.use_tools( "search.duckduckgo", # Web search "computation.calculator", # Math "filesystem.list" # File operations ) ``` -------------------------------- ### Complete Web Scraping Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/environments.md A comprehensive example of using WebEnvironment for web scraping, including resetting the environment, extracting data, and listing available actions. ```python from react_agent_framework.core.environment import WebEnvironment, Action # Web scraping agent with WebEnvironment(start_url="https://news.ycombinator.com") as env: # Navigate to Hacker News obs = env.reset() print(f"Loaded: {obs.data['title']}") # Extract top stories action = Action( name="extract", parameters={"selector": ".storylink"} ) obs = env.step(action) print(f"Top stories: {obs.data['text']}") # Get available actions print(f"Available actions: {env.get_available_actions()}") # Output: ['navigate', 'click', 'type', 'scroll', 'extract'] ``` -------------------------------- ### Multi-Tool Agent Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/examples/basic-usage.md Demonstrates an agent with multiple tools for time, calculation, random number generation, and date analysis. Use this when an agent needs to perform diverse tasks. ```python from react_agent_framework import ReactAgent from datetime import datetime import random agent = ReactAgent( name="Multi-Purpose Assistant", provider="gpt-4o-mini", max_iterations=15 ) @agent.tool() def get_current_time() -> str: """Get the current time""" return datetime.now().strftime("%Y-%m-%d %H:%M:%S") @agent.tool() def calculate(expression: str) -> str: """Perform calculations""" try: result = eval(expression, {"__builtins__": {}}, {}) return str(result) except Exception as e: return f"Error: {str(e)}" @agent.tool() def generate_random_number(min_val: int = 1, max_val: int = 100) -> str: """Generate a random number between min and max""" return str(random.randint(min_val, max_val)) @agent.tool() def get_day_of_week(date_str: str) -> str: """Get day of week for a date (format: YYYY-MM-DD)""" try: date = datetime.strptime(date_str, "%Y-%m-%d") return date.strftime("%A") except Exception as e: return f"Error: {str(e)}" # Complex queries queries = [ "What time is it right now?", "Calculate 25 * 48 + 130", "Generate a random number between 1 and 50", "What day of the week was 2024-01-01?" ] for query in queries: print(f"\n❓ {query}") answer = agent.run(query, verbose=True) print(f"💡 {answer}\n") ``` -------------------------------- ### Multi-Provider Agent Setup Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/examples/basic-usage.md Configure and use agents with different Large Language Model (LLM) providers, including OpenAI, Anthropic, Google, and local Ollama instances. Each agent can have its own tools registered. ```python from react_agent_framework import ReactAgent # OpenAI (default) agent_openai = ReactAgent( name="OpenAI Agent", provider="gpt-4o-mini" ) # Anthropic Claude agent_claude = ReactAgent( name="Claude Agent", provider="anthropic://claude-3-5-sonnet-20241022" ) # Google Gemini agent_gemini = ReactAgent( name="Gemini Agent", provider="google://gemini-1.5-flash" ) # Ollama (local) agent_ollama = ReactAgent( name="Llama Agent", provider="ollama://llama3.2" ) # Add tools to each for agent in [agent_openai, agent_claude, agent_gemini, agent_ollama]: @agent.tool() def greet(name: str) -> str: return f"Hello, {name}!" # Compare responses question = "Greet me using my name 'Alex'" print("\nOpenAI:", agent_openai.run(question)) print("\nClaude:", agent_claude.run(question)) print("\nGemini:", agent_gemini.run(question)) print("\nLlama:", agent_ollama.run(question)) ``` -------------------------------- ### Initialize ReactAgent with OpenAI Providers Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/multi-provider.md Instantiate ReactAgent using OpenAI models like gpt-4o-mini or gpt-4. No specific setup is required if your OpenAI API key is configured. ```python agent = ReactAgent(provider="gpt-4o-mini") agent = ReactAgent(provider="gpt-4") ``` -------------------------------- ### Basic FileEnvironment Usage Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/environments.md Initialize FileEnvironment with a root directory, safe mode, and max file size. Reset the environment to get initial contents and read a file. ```python from react_agent_framework.core.environment import FileEnvironment, Action # Create file environment env = FileEnvironment( root_directory="./data", safe_mode=True, # Protect sensitive files max_file_size=10 * 1024 * 1024 # 10MB limit ) # Initialize obs = env.reset() print(f"Files: {obs.data['contents']}") # Read a file action = Action( name="read", parameters={"filepath": "example.txt"} ) obs = env.step(action) print(obs.data['content']) ``` -------------------------------- ### Async Tool (Future Support) Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/guides/custom-tools.md An example of an asynchronous tool, noting that direct async support may be limited and a synchronous wrapper is used for now. ```python import asyncio @agent.tool() def fetch_data(url: str) -> str: """Fetch data from URL""" # For now, use sync wrapper async def _fetch(): # async implementation pass # Run in event loop loop = asyncio.get_event_loop() result = loop.run_until_complete(_fetch()) return result ``` -------------------------------- ### Initialize ReactAgent with MCP Server Support Source: https://context7.com/marcosf63/react-agent-framework/llms.txt Sets up a ReactAgent capable of connecting to external tool servers via MCP. Ensure the 'react-agent-framework[mcp]' package is installed. ```python from react_agent_framework import ReactAgent # Requires: pip install react-agent-framework[mcp] agent = ReactAgent(name="MCP Agent", provider="gpt-4o-mini") ``` -------------------------------- ### Initialize ReactAgent with Google Gemini Providers Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/multi-provider.md Integrate with Google Gemini models by using the google:// prefix, for example, gemini-1.5-flash or gemini-1.5-pro. Your GOOGLE_API_KEY must be configured. ```python agent = ReactAgent(provider="google://gemini-1.5-flash") agent = ReactAgent(provider="google://gemini-1.5-pro") ``` -------------------------------- ### Agent with Custom Instructions Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/reasoning-strategies.md Guide agent behavior by providing specific instructions during initialization. These instructions help the agent adhere to a particular role, methodology, or set of rules for its reasoning process. ```python agent = ReactAgent( name="Data Analyst", provider="gpt-4o-mini", instructions="""You are a data analyst. Follow these guidelines: 1. Always verify data before drawing conclusions 2. Use calculations to support your analysis 3. Provide specific numbers and percentages 4. If data is missing, use search to find it 5. Be concise but thorough in your answers """ ) @agent.tool() def calculate(expression: str) -> str: """Perform calculations""" return str(eval(expression, {"__builtins__": {}}, {})) @agent.tool() def search(query: str) -> str: """Search for data""" # Implementation return results # The agent will follow your guidelines answer = agent.run( "What percentage of global GDP does the US represent?", verbose=True ) ``` -------------------------------- ### Start Next Objective with Tracker Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/objectives.md Use ObjectiveTracker.start_next() to automatically select and start the highest priority pending objective. The method returns the started objective. ```python from react_agent_framework.core.objectives import Objective, ObjectiveTracker tracker = ObjectiveTracker() # Add objectives tracker.add(Objective(goal="Task 1", priority="low")) tracker.add(Objective(goal="Task 2", priority="critical")) tracker.add(Objective(goal="Task 3", priority="high")) # Start next (will pick "Task 2" - critical priority) next_obj = tracker.start_next() print(f"Started: {next_obj.goal}") ``` -------------------------------- ### Initialize and Use WebEnvironment Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/environments.md Demonstrates basic usage of the WebEnvironment, including initialization, navigation, and closing the environment. Set headless to True to run without a visible browser. ```python from react_agent_framework.core.environment import WebEnvironment, Action # Create web environment env = WebEnvironment( start_url="https://example.com", headless=True, # Run without visible browser browser_type="chromium" # chromium, firefox, or webkit ) # Initialize environment initial_obs = env.reset() print(initial_obs.to_string()) # Navigate to a page action = Action( name="navigate", parameters={"url": "https://python.org"} ) obs = env.step(action) print(f"Page title: {obs.data['title']}") # Close when done env.close() ``` -------------------------------- ### Install Optional AI Provider: Anthropic Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/installation.md Install the package with support for Anthropic Claude. ```bash pip install react-agent-framework[anthropic] ``` -------------------------------- ### Conventional Commit Message Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/contributing.md An example of a commit message following the Conventional Commits specification for adding a new feature. ```git feat: add support for Google Gemini provider Adds GoogleProvider class with proper integration ``` -------------------------------- ### Load Pre-built Tools with agent.use_tools() Source: https://context7.com/marcosf63/react-agent-framework/llms.txt Load pre-built tools from the internal registry using glob patterns. Available categories include 'search', 'filesystem', and 'computation'. ```python from react_agent_framework import ReactAgent agent = ReactAgent(name="Full-Stack Agent", provider="gpt-4o-mini") # Load all search tools (DuckDuckGo) agent.use_tools("search.*") # Load specific filesystem tools agent.use_tools("filesystem.read", "filesystem.list") # Load all computation tools (calculator, code executor, shell) agent.use_tools("computation.*") # Load absolutely every registered tool agent.use_tools("*") # Verify loaded tools print(agent.get_tools()) # { # 'search.duckduckgo': 'Search the web using DuckDuckGo', # 'filesystem.read': 'Read file contents', # 'filesystem.list': 'List directory contents', # ... # } answer = agent.run("Search for the latest Python release and list files in /tmp") print(answer) ``` -------------------------------- ### Interact with Web Environment Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/index.md Set up a WebEnvironment and perform an action, such as navigating to a URL. ```python env = WebEnvironment() env.step(Action("navigate", {"url": "..."})) ``` -------------------------------- ### Basic Agent Connection to Filesystem MCP Server Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/mcp-integration.md Demonstrates creating an agent and connecting it to a local filesystem MCP server. This allows the agent to interact with files and directories. ```python from react_agent_framework import ReactAgent # Create agent agent = ReactAgent(name="MCP Agent") # Connect to filesystem MCP server server_id = agent.add_mcp_server( command="npx", args=["-y", "@modelcontextprotocol/server-filesystem", "/tmp"], name="filesystem" ) # All tools from the server are now available! answer = agent.run("List files in the /tmp directory") ``` -------------------------------- ### Connect to Filesystem and GitHub MCP Servers Source: https://context7.com/marcosf63/react-agent-framework/llms.txt Demonstrates how to connect to MCP servers for filesystem and GitHub access. Tools are automatically registered upon connection. Environment variables can be passed for authentication. ```python fs_server_id = agent.add_mcp_server( command="npx", args=["-y", "@modelcontextprotocol/server-filesystem", "/tmp"], name="filesystem", auto_register=True, # tools are added to agent immediately ) print(f"Filesystem server connected with ID: {fs_server_id}") # Connect to GitHub MCP server gh_server_id = agent.add_mcp_server( command="npx", args=["-y", "@modelcontextprotocol/server-github"], env={"GITHUB_TOKEN": "ghp_your_token_here"}, name="github", ) ``` -------------------------------- ### List and Use Connected MCP Servers and Tools Source: https://context7.com/marcosf63/react-agent-framework/llms.txt Shows how to list all connected MCP servers and their tools, and how to list tools from a specific server. The agent can then use these tools in its reasoning loop. ```python # List all connected servers servers = agent.list_mcp_servers() for srv in servers: print(f" [{srv['id']}] {srv['name']}: {srv['num_tools']} tools") # List tools from all servers (or a specific server) tools = agent.list_mcp_tools() # all servers fs_tools = agent.list_mcp_tools(server_id=fs_server_id) for tool_desc in fs_tools: print(tool_desc) # Agent can now use MCP tools in its reasoning loop answer = agent.run( "List the files in /tmp and tell me how many there are", verbose=True ) print(answer) # Disconnect when done agent.disconnect_mcp_server(gh_server_id) ``` -------------------------------- ### Create and Run a Basic Agent Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/index.md Initialize a ReactAgent, define a search tool using a decorator, and run a query. ```python from react_agent_framework import ReactAgent # Create an agent agent = ReactAgent( name="Assistant", description="A helpful AI assistant", provider="gpt-4o-mini" ) # Add tools with decorators @agent.tool() def search(query: str) -> str: """Search the internet for information""" # Your search implementation return search_results # Run the agent answer = agent.run("What is the capital of France?") print(answer) # "The capital of France is Paris" ``` -------------------------------- ### Objective Tracker Summary Output Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/objectives.md Example output from ObjectiveTracker.get_summary(), showing counts of objectives by priority and status. ```text 📋 OBJECTIVES SUMMARY ==================== 🔥 CRITICAL: 1 ⬆️ HIGH: 1 ➡️ MEDIUM: 1 ⬇️ LOW: 0 Total: 3 objectives Active: 0 | Pending: 3 | Completed: 0 | Failed: 0 ``` -------------------------------- ### Retrieve Tools by Pattern Source: https://github.com/marcosf63/react-agent-framework/blob/main/LLMs.txt Use ToolRegistry to get tools that match a specific pattern, such as all search-related tools. ```python search_tools = registry.get_tools_by_pattern("search.*") ``` -------------------------------- ### Objective with Deadline Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/objectives.md Shows how to set a deadline for a time-sensitive objective using Python's datetime module. ```python from datetime import datetime, timedelta Objective( goal="Prepare quarterly report", priority="high", deadline=datetime.now() + timedelta(days=7) ) ``` -------------------------------- ### Combine Chat and Knowledge Memory Source: https://github.com/marcosf63/react-agent-framework/blob/main/MIGRATION_GUIDE.md Example of creating an agent that utilizes both SQLiteChatMemory for conversation history and FAISSKnowledgeMemory for RAG. ```python from react_agent_framework import ReactAgent from react_agent_framework.core.memory.chat import SQLiteChatMemory from react_agent_framework.core.memory.knowledge import FAISSKnowledgeMemory # Create agent with both types agent = ReactAgent( name="Technical Assistant", chat_memory=SQLiteChatMemory("./chat.db"), knowledge_memory=FAISSKnowledgeMemory("./tech_docs") ) # Load technical documentation docs = [ "Docker is a containerization platform", "Kubernetes orchestrates containers", "FastAPI is a modern Python web framework" ] agent.knowledge_memory.add_documents(docs) # Chat with RAG answer = agent.run("How do I deploy a FastAPI app with Docker?") # Agent uses: # 1. chat_memory for conversation context # 2. knowledge_memory for technical documentation ``` -------------------------------- ### Create a Basic Agent with a Custom Tool Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/getting-started/quickstart.md Create a Python file to define and run a simple agent with a custom greeting tool. ```python from react_agent_framework import ReactAgent # Create agent agent = ReactAgent( name="Assistant", description="A helpful AI assistant" ) # Add a simple tool @agent.tool() def greet(name: str) -> str: """Greet someone by name""" return f"Hello, {name}! Nice to meet you!" # Run the agent answer = agent.run("Greet Alice") print(answer) ``` -------------------------------- ### Initialize Agent with FAISS Memory Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/index.md Initializes a ReactAgent with FAISSMemory for high-performance similarity search. Ensure FAISS is installed and configured. ```python agent = ReactAgent(memory=FAISSMemory(dimension=1536)) ``` -------------------------------- ### Objective Progress Tracking Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/objectives.md Illustrates how to update the progress of an objective using a tracker object, showing incremental completion. ```python # Update progress as work is done tracker.update_progress(obj.id, 0.25, "Database design complete") tracker.update_progress(obj.id, 0.50, "API endpoints implemented") tracker.update_progress(obj.id, 0.75, "Testing in progress") tracker.update_progress(obj.id, 1.0, "Deployment successful") ``` -------------------------------- ### Initialize and Use CLIEnvironment Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/environments.md Demonstrates basic usage of the CLIEnvironment for executing shell commands. Safe mode restricts commands to a predefined list, and a timeout prevents long-running processes. ```python from react_agent_framework.core.environment import CLIEnvironment, Action # Create CLI environment env = CLIEnvironment( working_directory="/tmp", safe_mode=True, # Restrict to safe commands timeout=30 # Command timeout in seconds ) # Initialize obs = env.reset() print(obs.data['directory']) # Execute command action = Action( name="execute", parameters={"command": "ls -la"} ) obs = env.step(action) print(obs.data['stdout']) ``` -------------------------------- ### Migrate Mixed-Purpose Memory to KnowledgeMemory Source: https://github.com/marcosf63/react-agent-framework/blob/main/MIGRATION_GUIDE.md Example showing the migration from a mixed-purpose ChromaMemory (v0.9.x) to the dedicated ChromaKnowledgeMemory (v0.10.0) for RAG. ```python from react_agent_framework import ReactAgent from react_agent_framework.core.memory import ChromaMemory agent = ReactAgent( name="Assistant", memory=ChromaMemory(collection_name="docs") ) # This was confusing - was it for chat or RAG? agent.memory.add("Python is a programming language", role="system") ``` ```python from react_agent_framework import ReactAgent from react_agent_framework.core.memory.chat import SQLiteChatMemory from react_agent_framework.core.memory.knowledge import ChromaKnowledgeMemory agent = ReactAgent( name="Assistant", chat_memory=SQLiteChatMemory("./chat.db"), # Conversation history knowledge_memory=ChromaKnowledgeMemory("./kb") # RAG knowledge base ) # Add documents to knowledge base agent.knowledge_memory.add_document( "Python is a programming language", metadata={"category": "programming"} ) # Search knowledge base results = agent.knowledge_memory.search("programming languages", top_k=3) for doc in results: print(doc.content) ``` -------------------------------- ### Migrate Simple Memory to SimpleChatMemory Source: https://github.com/marcosf63/react-agent-framework/blob/main/MIGRATION_GUIDE.md Example demonstrating the migration from SimpleMemory (v0.9.x) to SimpleChatMemory (v0.10.0) for managing chat history. ```python from react_agent_framework import ReactAgent from react_agent_framework.core.memory import SimpleMemory agent = ReactAgent( name="Assistant", memory=SimpleMemory(max_messages=100) ) ``` ```python from react_agent_framework import ReactAgent from react_agent_framework.core.memory.chat import SimpleChatMemory agent = ReactAgent( name="Assistant", chat_memory=SimpleChatMemory(max_messages=100) ) ``` -------------------------------- ### Instantiate ReAct Reasoning Strategy Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/index.md Create a ReActReasoning instance, passing the agent and available tools. ```python reasoning = ReActReasoning(agent, tools) ``` -------------------------------- ### Initialize and Use Web Environment Source: https://github.com/marcosf63/react-agent-framework/blob/main/LLMs.txt Initializes a WebEnvironment, allowing interaction with web pages. Supports actions like navigating, clicking, and typing. Headless mode is optional. ```python from react_agent_framework.core.environment import WebEnvironment, Action env = WebEnvironment(headless=True) obs = env.step(Action("navigate", {"url": "https://example.com"})) obs = env.step(Action("click", {"selector": "#button"})) obs = env.step(Action("type", {"selector": "#input", "text": "hello"})) ``` -------------------------------- ### Get All Registered Tools Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/features/built-in-tools.md Retrieve a dictionary of all tools currently registered with an agent. This allows inspection of available tools and their descriptions. ```python agent = ReactAgent(name="Agent") agent.use_tools("*") # Get all registered tools tools = agent.get_tools() # Print tool names and descriptions for name, description in tools.items(): print(f"{name}:") print(f" {description}\n") ``` -------------------------------- ### Agent with Memory Example Source: https://github.com/marcosf63/react-agent-framework/blob/main/docs/examples/basic-usage.md Shows an agent that can remember previous parts of a conversation using SimpleMemory. Useful for maintaining context in dialogues. ```python from react_agent_framework import ReactAgent from react_agent_framework.core.memory import SimpleMemory # Create agent with memory agent = ReactAgent( name="Personal Assistant", provider="gpt-4o-mini", memory=SimpleMemory(), instructions="Remember what the user tells you and use that context in future responses." ) @agent.tool() def set_reminder(task: str) -> str: """Set a reminder for a task""" return f"✅ Reminder set: {task}" @agent.tool() def search(query: str) -> str: """Search for information""" return f"Search results for: {query}" # Conversation with context print("Conversation 1:") response1 = agent.run("My name is Alice and I love Python programming") print(response1) print("\nConversation 2:") response2 = agent.run("What's my name?") print(response2) # Agent remembers: "Alice" print("\nConversation 3:") response3 = agent.run("What programming language do I like?") print(response3) # Agent remembers: "Python" print("\nConversation 4:") response4 = agent.run("Set a reminder to study Python tomorrow") print(response4) ```