### Setup and Run Project with Poetry Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/development/index.md This snippet demonstrates how to clone the Reactive Agents repository, install its dependencies using Poetry, and run tests, including coverage checks. It assumes you have Git and Poetry installed. ```bash git clone https://github.com/tylerjrbuell/reactive-agents cd reactive-agents poetry install poetry run pytest poetry run pytest --cov=reactive_agents ``` -------------------------------- ### Install Reactive Agents Framework Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/examples/index.md Installs the reactive-agents Python package using pip. This is a prerequisite for running any of the provided examples. ```bash pip install reactive-agents ``` -------------------------------- ### Development Installation of reactive-agents Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/getting-started/installation.md Sets up the reactive-agents project from source for development or contribution. Clones the repository and installs dependencies using Poetry. ```bash git clone https://github.com/tylerjrbuell/reactive-agents.git cd reactive-agents poetry install ``` ```bash poetry install --with docs ``` -------------------------------- ### Start Production Services with Docker Compose Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/reactive_agents/docker/README.md Builds and starts all services for a production deployment using the deploy script or directly with docker-compose. This is the primary method for getting the production environment up and running. ```bash # Build and start all services ./deploy.sh up --build # Or using docker-compose directly docker-compose up -d --build ``` -------------------------------- ### Development Setup and Testing with Poetry Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/README.md This set of bash commands outlines the essential steps for setting up the development environment, running tests, and performing code quality checks using Poetry. It includes cloning the repository, installing dependencies, running tests, and applying code formatting and linting. ```bash # Clone and setup git clone https://github.com/tylerjrbuell/reactive-agents cd reactive-agents poetry install # Run tests poetry run pytest # Run with coverage poetry run pytest --cov=reactive_agents # Lint and format poetry run black . poetry run ruff check . ``` -------------------------------- ### Example Environment Variables for Reflex Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/reactive_agents/docker/README.md Provides a sample `.env` file showcasing essential configuration options for the Reflex framework. This includes settings for LLM models, API keys, vector database connections, and agent behavior. ```env # Model Configuration DEFAULT_MODEL=ollama:qwen2:7b OLLAMA_HOST=http://ollama:11434 # API Keys GROQ_API_KEY=your_key_here OPENAI_API_KEY=your_key_here # Vector Database CHROMA_HOST=http://chromadb:8000 # Agent Settings MAX_ITERATIONS=10 CONTEXT_WINDOW=8000 MEMORY_ENABLED=true ``` -------------------------------- ### Install reactive-agents using pip and Poetry Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/README.md Provides instructions for installing the reactive-agents library. It covers both basic installation using pip and Poetry, as well as a development installation process involving cloning the repository and running tests. ```bash # Using pip pip install reactive-agents # Using Poetry poetry add reactive-agents ``` ```bash # Clone the repository git clone https://github.com/tylerjrbuell/reactive-agents cd reactive-agents # Install with Poetry poetry install # Run tests poetry run pytest ``` -------------------------------- ### Start Development Environment with Docker Compose Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/reactive_agents/docker/README.md Initiates the development environment, including necessary tools and configurations for active development. It can be started using the deploy script or by directly invoking docker-compose with the development configuration file. ```bash # Start development environment ./deploy.sh --dev up --build # Or using docker-compose directly docker-compose -f docker-compose.dev.yml up -d --build ``` -------------------------------- ### Development Workflow Commands Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/reactive_agents/docker/README.md Outlines the sequence of commands for setting up and working within the Reflex development environment. It covers starting the environment, opening a shell, running agent tasks, testing, and code formatting. ```bash # Start development environment ./deploy.sh --dev up # Open development shell ./deploy.sh --dev shell # Inside container: reflex make agent --task "Test task" pytest black . ``` -------------------------------- ### Start Debugger for Reflex Application Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/reactive_agents/docker/README.md Instructions for starting the Reflex application with the debugpy debugger enabled in the development environment. This allows remote debugging by connecting a debugger client to the specified host and port. ```bash # Start with debugger docker-compose -f docker-compose.dev.yml exec reflex-dev python -m debugpy --listen 0.0.0.0:5678 -m reactive_agents.console.cli # Connect debugger to localhost:5678 ``` -------------------------------- ### Example Sub-Agent Configurations (Python) Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/agent/META_AGENT_ARCHITECTURE.md Illustrates how to configure different types of sub-agents with specific tool sets, iteration limits, and timeouts, emphasizing their focused and lightweight nature. ```python # File searcher - just finds files FileSearchAgent( tools=["search_files", "list_directory"], max_iterations=3, timeout=30, ) # Data analyzer - just analyzes DataAnalyzerAgent( tools=["read_csv", "calculate_stats", "create_chart"], max_iterations=5, timeout=60, ) # File writer - just writes FileWriterAgent( tools=["write_file", "append_to_file"], max_iterations=2, timeout=20, ) # Pure calculator - single shot CalculatorAgent( tools=["calculate"], max_iterations=1, timeout=10, ) ``` -------------------------------- ### Configure Groq LLM Provider Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/getting-started/installation.md Sets up the agent to use Groq models. Requires a Groq API key set as an environment variable. ```bash export GROQ_API_KEY="your-key-here" ``` ```python .with_model("groq:llama3-70b") ``` -------------------------------- ### Install reactive-agents with Poetry Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/getting-started/installation.md Adds the reactive-agents Python package as a dependency using the Poetry package manager. Requires Poetry to be installed. ```bash poetry add reactive-agents ``` -------------------------------- ### Verify reactive-agents Installation Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/getting-started/installation.md Checks if the reactive-agents library is installed correctly by printing its version number. ```python import reactive_agents print(reactive_agents.__version__) ``` -------------------------------- ### Create an AI Agent with Custom Tools in Python Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/getting-started/quickstart.md This example demonstrates building an AI agent with custom tools, 'calculate' and 'get_weather', using the @tool decorator. The agent is configured with a name, model, and reasoning strategy, then provided with the custom tools. It runs a task that utilizes these tools to answer a complex query. ```python import asyncio from reactive_agents import ReactiveAgentBuilder, tool, ReasoningStrategies @tool() async def calculate(expression: str) -> str: """Evaluate a mathematical expression. Args: expression: A mathematical expression like "2 + 2" """ try: result = eval(expression) return f"The result is: {result}" except Exception as e: return f"Error: {e}" @tool() async def get_weather(city: str) -> str: """Get the current weather for a city. Args: city: Name of the city """ # In a real app, call a weather API return f"The weather in {city} is sunny, 72°F" async def main(): agent = await ( ReactiveAgentBuilder() .with_name("ToolAgent") .with_model("ollama:llama3") .with_reasoning_strategy(ReasoningStrategies.REACTIVE) .with_custom_tools([calculate, get_weather]) .build() ) result = await agent.run("What is 15 * 7 and what's the weather in Paris?") print(result.final_answer) await agent.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Debugging Agent Startup Failures Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/AGENTS.md Guides users on troubleshooting issues where the agent fails to start or build. It directs checks to component factory, configuration parameters, and provider initialization. ```python # Check: `ComponentFactory.create_all_components()` in `core/factory/component_factory.py` # Check: Required parameters in `ReactiveAgentConfig` in `core/types/agent_types.py` # Check: Provider initialization in `providers/llm/factory.py` ``` -------------------------------- ### Run Basic Agent Example Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/examples/index.md Executes a basic agent example script using Python. This demonstrates the fundamental usage of the reactive-agents framework. ```bash python examples/basic_agent.py ``` -------------------------------- ### View Docker System Information (Bash) Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/reactive_agents/docker/README.md This bash command provides detailed information about the Docker installation, including the version, operating system, kernel, storage drivers, and more. It's helpful for diagnosing environment-specific issues. ```bash # View system info docker system info ``` -------------------------------- ### Download Llama3 Model with Ollama Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/examples/index.md Downloads the Llama3 language model using the Ollama tool. This is required if you plan to use Llama3 as your LLM provider for the examples. ```bash ollama pull llama3 ``` -------------------------------- ### Install Dependencies with Poetry Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/AGENTS.md Installs all project dependencies defined in `pyproject.toml` using Poetry. This command should be run when setting up the project for the first time or after modifying dependencies. ```bash poetry install ``` -------------------------------- ### Multi-Provider Streaming API Consistency Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/examples/streaming.md Illustrates the consistent streaming API across different LLM providers including OpenAI, Anthropic, Ollama, Groq, and Google. Each example shows how to initialize a provider and stream chat completions using the same method signature. ```python from reactive_agents.providers.llm import OpenAIModelProvider provider = OpenAIModelProvider(model="gpt-4o") async for chunk in provider.stream_chat_completion(messages): print(chunk.content, end="", flush=True) ``` ```python from reactive_agents.providers.llm import AnthropicModelProvider provider = AnthropicModelProvider(model="claude-3-5-sonnet-20241022") async for chunk in provider.stream_chat_completion(messages): print(chunk.content, end="", flush=True) ``` ```python from reactive_agents.providers.llm import OllamaModelProvider provider = OllamaModelProvider(model="llama3") async for chunk in provider.stream_chat_completion(messages): print(chunk.content, end="", flush=True) ``` ```python from reactive_agents.providers.llm import GroqModelProvider provider = GroqModelProvider(model="llama-3.1-70b-versatile") async for chunk in provider.stream_chat_completion(messages): print(chunk.content, end="", flush=True) ``` ```python from reactive_agents.providers.llm import GoogleModelProvider provider = GoogleModelProvider(model="gemini-1.5-pro") async for chunk in provider.stream_chat_completion(messages): print(chunk.content, end="", flush=True) ``` -------------------------------- ### Clone and Set Up Project with Poetry Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/development/contributing.md Instructions to clone the Reactive Agents repository and install its dependencies using Poetry. This involves cloning the repo, navigating into the directory, installing dependencies, and activating the virtual environment. ```bash git clone https://github.com/tylerjrbuell/reactive-agents cd reactive-agents poetry install poetry shell ``` -------------------------------- ### Monitor AI Agent Execution with Events in Python Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/getting-started/quickstart.md This Python snippet illustrates how to monitor an AI agent's execution in real-time using event listeners. It subscribes to various events like session start, tool calls, iteration completion, and session end, printing messages to the console when each event occurs. The agent is then run, and its final answer is displayed. ```python import asyncio from reactive_agents import ReactiveAgentBuilder, ReasoningStrategies async def main(): agent = await ( ReactiveAgentBuilder() .with_name("EventAgent") .with_model("ollama:llama3") .build() ) # Subscribe to events agent.on_session_started(lambda e: print(f"Started: {e['agent_name']}")) agent.on_tool_called(lambda e: print(f"Tool called: {e['tool_name']}")) agent.on_iteration_completed(lambda e: print(f"Iteration {e['iteration']} complete")) agent.on_session_ended(lambda e: print(f"Session ended")) result = await agent.run("Tell me a joke") print(result.final_answer) await agent.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Define Tool with Multiple Parameters (Python) Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/examples/tool-usage.md Shows how to define an asynchronous tool that accepts multiple parameters, including optional ones with default values. This example uses `query`, `limit`, and `sort` parameters for a search-like functionality. The docstring clearly outlines each parameter and its purpose. ```python @tool() async def advanced_tool( query: str, limit: int = 10, sort: str = "relevance" ) -> str: """Search with advanced options. Args: query: The search query limit: Maximum results (default: 10) sort: Sort order (default: relevance) """ return f"Searching '{query}' with limit={limit}, sort={sort}" ``` -------------------------------- ### Tool Best Practice: Clear Descriptions (Python) Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/examples/tool-usage.md Highlights the importance of providing clear and informative docstrings for tools. The docstring serves as the description that the LLM uses to understand the tool's purpose, usage, and parameters. This example shows a `web_search` tool with a detailed docstring explaining when and how to use it. ```python @tool() async def web_search(query: str) -> str: """Search the web for current information about a topic. Use this tool when you need up-to-date information that may not be in your training data. Args: query: A specific search query (be as specific as possible) """ pass ``` -------------------------------- ### Configure Ollama LLM Provider Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/getting-started/installation.md Sets up the agent to use a local Ollama model. Requires Ollama to be installed and a model to be pulled. ```bash ollama pull llama3 ``` ```python .with_model("ollama:llama3") ``` -------------------------------- ### Testing Provider Parameter Mapping (Bash) Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/README.md Provides a command-line example using Python to test the parameter mapping between the universal format and native formats for specific LLM providers. This is useful for debugging and verifying the translation logic. ```bash # Test parameter mapping python -c " from reactive_agents.providers.llm.ollama import OllamaModelProvider provider = OllamaModelProvider('cogito:14b') options = {'temperature': 0.2, 'max_tokens': 100} print('OpenAI params:', provider.get_openai_params(options)) print('Native params:', provider.get_native_params(options)) " ``` -------------------------------- ### Build a Reactive Agent using Python Builder Pattern Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/getting-started/index.md Demonstrates how to create a Reactive Agent using the builder pattern in Python. This involves chaining methods to configure the agent's name, LLM model, role, instructions, and reasoning strategy. The code requires the 'reactive_agents' library and a compatible LLM provider. ```python from reactive_agents import ReactiveAgentBuilder, ReasoningStrategies agent = await ( ReactiveAgentBuilder() .with_name("MyAgent") .with_model("ollama:llama3") .with_role("Assistant") .with_instructions("Help users with their tasks") .with_reasoning_strategy(ReasoningStrategies.REACTIVE) .build() ) ``` -------------------------------- ### Quickly Create an Agent with Task and Tools (Python) Source: https://context7.com/tylerjrbuell/reactive-agents/llms.txt Provides a simplified method for creating an agent with a specific task, model, and tools. This example uses `quick_create_agent` to instantiate an agent for a time query and prints the final answer. ```python from reactive_agents.app.builders.agent import quick_create_agent async def quick_example(): result = await quick_create_agent( task="What time is it in Tokyo?", model="ollama:llama3", tools=["time"], interactive=False ) print(result.final_answer) ``` -------------------------------- ### Python Example: Progress Monitor Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/user-guide/events.md A Python class that monitors agent execution progress by subscribing to session start, iteration start, tool calls, and session end events. It prints relevant information to the console. ```python class ProgressMonitor: def __init__(self, agent): self.agent = agent self.events = [] agent.on_session_started(self.on_start) agent.on_iteration_started(self.on_iteration) agent.on_tool_called(self.on_tool) agent.on_session_ended(self.on_end) def on_start(self, e): print(f"Starting task: {e.get('initial_task', '')}") def on_iteration(self, e): print(f"Iteration {e['iteration']}/{e['max_iterations']} - {e['strategy']}") def on_tool(self, e): print(f" Tool: {e['tool_name']}") def on_end(self, e): print("Task completed") # Usageagent = await builder.build() monitor = ProgressMonitor(agent) result = await agent.run("Do something") ``` -------------------------------- ### Serve Documentation Locally with MkDocs Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/AGENTS.md Serves the project's documentation locally using MkDocs, allowing for live preview during development. This command should be run from the 'docs' directory. ```bash cd docs mkdocs serve ``` -------------------------------- ### Create a Basic AI Agent with Python Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/README.md Demonstrates how to create and run a simple AI agent using the ReactiveAgentBuilder. It configures the agent with a name, model, tools, instructions, and a reactive reasoning strategy, then executes a query. ```python import asyncio from reactive_agents import ReactiveAgentBuilder, ReasoningStrategies async def main(): # Create an intelligent research agent agent = await ( ReactiveAgentBuilder() .with_name("Research Assistant") .with_model("ollama:llama3") # or "openai:gpt-4", "anthropic:claude-3-sonnet" .with_tools(["brave-search", "time"]) # Auto-detects MCP tools vs custom tools .with_instructions("Research thoroughly and provide detailed analysis") .with_reasoning_strategy(ReasoningStrategies.REACTIVE) .build() ) async with agent: result = await agent.run( "What are the latest developments in quantum computing this week?" ) print(result.final_answer) print(f"Status: {result.status_message}") asyncio.run(main()) ``` -------------------------------- ### Running the Project Demo Script Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/reactive_agents/providers/llm/README.md Shows the command to execute a demo script that provides usage examples for the project's features, particularly for OpenAI and Anthropic providers. ```bash python reactive_agents/examples/openai_anthropic_demo.py ``` -------------------------------- ### Configure Environment Variables for LLM Providers and Tools Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/README.md Shows an example of an environment configuration file (`.env`) for setting up API keys and host information for various LLM providers (OpenAI, Anthropic, Groq, Ollama) and MCP tools (Brave Search). It also includes an option for custom MCP configuration. ```bash # LLM Providers OPENAI_API_KEY=your_openai_key ANTHROPIC_API_KEY=your_anthropic_key GROQ_API_KEY=your_groq_key OLLAMA_HOST=http://localhost:11434 # MCP Tools BRAVE_API_KEY=your_brave_search_key # Optional: Custom MCP configuration MCP_CONFIG_PATH=/path/to/custom/mcp_config.json ``` -------------------------------- ### Configure OpenAI LLM Provider Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/getting-started/installation.md Configures the agent to use OpenAI models. Requires an OpenAI API key set as an environment variable. ```bash export OPENAI_API_KEY="your-key-here" ``` ```python .with_model("openai:gpt-4") ``` -------------------------------- ### Progressive Agent Complexity Examples in Python Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/agent/MULTI_AGENT_ARCHITECTURE.md Demonstrates the evolution of agent complexity using builder patterns in Python, starting from a solo agent and progressing to teams with validators and shared workspaces, and finally to swarms of multiple teams. This illustrates a 'start simple, add complexity' approach. ```python # Week 1: Solo agent agent = await AgentBuilder().with_tools([...]).build() await agent.run("simple task") # Week 2: Add a helper team = await ( TeamBuilder() .with_leader("main") .add_worker("helper", tools=[...]) .build() ) # Week 3: Add validation team = await ( TeamBuilder() .with_leader("main") .add_worker("worker", tools=[...]) .add_validator("checker", tools=[...]) # NEW .build() ) # Week 4: Add shared workspace team = await ( TeamBuilder() .with_leader("main") .add_worker("worker", tools=[...]) .add_validator("checker", tools=[...]) .with_shared_workspace() # NEW - semantic search .build() ) # Week 5: Multiple teams swarm = await ( SwarmBuilder() .add_team("team1", team1) .add_team("team2", team2) .build() ) ``` -------------------------------- ### Advanced Provider-Specific Optimizations (Python) Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/README.md Demonstrates how to apply provider-specific optimizations while still leveraging the universal interface. This example shows conditional configuration for Ollama, Anthropic, and Google providers, including parameters like GPU layers, context window, top-k sampling, and response schemas. ```python # Provider-specific optimizations while maintaining compatibility builder = ReactiveAgentBuilder() # Ollama with GPU acceleration if provider == "ollama": builder.with_model_provider_options({ "temperature": 0.2, "max_tokens": 1000, "num_gpu": 256, # Ollama-specific: GPU layers "num_ctx": 8192, # Ollama-specific: context window }) # Anthropic with advanced parameters elif provider == "anthropic": builder.with_model_provider_options({ "temperature": 0.2, "max_tokens": 1000, "top_k": 50, # Anthropic-specific: top-k sampling }) # Google with structured schema elif provider == "google": builder.with_model_provider_options({ "temperature": 0.2, "max_tokens": 1000, "candidate_count": 3, # Google-specific: multiple candidates "response_schema": schema # Google-specific: schema validation }) agent = await builder.build() ``` -------------------------------- ### Streaming LLM Responses with Tool Calls in Python Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/examples/streaming.md Provides an example of streaming LLM responses that may include tool calls, using OpenAI's provider. It defines a tool for getting weather information and demonstrates how to process tool calls within the streamed chunks. ```python import asyncio from reactive_agents.providers.llm import OpenAIModelProvider async def main(): provider = OpenAIModelProvider(model="gpt-4o-mini") messages = [ {"role": "user", "content": "What's the weather in Paris?"} ] tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City name" } }, "required": ["location"] } } } ] async for chunk in provider.stream_chat_completion(messages, tools=tools): if chunk.content: print(chunk.content, end="", flush=True) if chunk.is_final and chunk.tool_calls: print("\n\nTool calls:") for tc in chunk.tool_calls: print(f" - {tc['function']['name']}({tc['function']['arguments']})") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Structured LLM Responses with Pydantic in Python Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/README.md This Python example demonstrates how to obtain validated, structured output from LLMs using the Instructor Python Package within reactive-agents. It defines a Pydantic model `ResearchResult` and uses the agent to get a response conforming to this model, ensuring type safety across different LLM providers. ```python from pydantic import BaseModel from typing import List from reactive_agents import ReactiveAgentBuilder class ResearchResult(BaseModel): summary: str key_findings: List[str] confidence_score: float sources: List[str] # Works identically across ALL providers agent = await ReactiveAgentBuilder() .with_model("ollama:qwen2:7b") # or any provider .build() # Get validated, structured output result: ResearchResult = await agent.get_structured_response( ResearchResult, "Research the latest AI developments" ) print(result.summary) # ✅ Type-safe string print(result.confidence_score) # ✅ Type-safe float ``` -------------------------------- ### Configure Google Gemini LLM Provider Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/getting-started/installation.md Configures the agent to use Google Gemini models. Requires a Google API key set as an environment variable. ```bash export GOOGLE_API_KEY="your-key-here" ``` ```python .with_model("google:gemini-pro") ``` -------------------------------- ### Build and Run a Basic AI Agent with Python Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/getting-started/quickstart.md This snippet shows how to build a basic AI agent using ReactiveAgentBuilder. It configures the agent's name, model, role, instructions, reasoning strategy, and maximum iterations. The agent is then used to run a task and its result is printed. Finally, the agent is closed. ```python import asyncio from reactive_agents import ReactiveAgentBuilder, ReasoningStrategies async def main(): # Build the agent agent = await ( ReactiveAgentBuilder() .with_name("QuickStartAgent") .with_model("ollama:llama3") .with_role("Helpful Assistant") .with_instructions("Help users with their questions") .with_reasoning_strategy(ReasoningStrategies.REACTIVE) .with_max_iterations(10) .build() ) # Run a task result = await agent.run("What is the capital of France?") # Check the result print(f"Status: {result.status}") print(f"Answer: {result.final_answer}") # Clean up await agent.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Configure Anthropic LLM Provider Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/getting-started/installation.md Sets up the agent to use Anthropic models (e.g., Claude). Requires an Anthropic API key set as an environment variable. ```bash export ANTHROPIC_API_KEY="your-key-here" ``` ```python .with_model("anthropic:claude-3-sonnet") ``` -------------------------------- ### Conductor Agent Workflow Example (Python) Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/agent/META_AGENT_ARCHITECTURE.md Demonstrates a conductor agent orchestrating sub-agents for a data analysis task. It shows spawning agents, retrieving results, and implementing fallback logic if an initial search fails. ```python # Assuming spawn_sub_agent and get_sub_agent_result are defined elsewhere # Conductor receives task # Step 1: Find data search_agent = spawn_sub_agent( task="Find sales data files in /data/sales", tools=["search_files", "list_directory"], max_iterations=3, ) files = get_sub_agent_result(search_agent.agent_id) if files.status == "failed": # Try different approach search_agent2 = spawn_sub_agent( task="Search for CSV files with 'sales' in name", tools=["find_files_by_pattern"], max_iterations=2, ) files = get_sub_agent_result(search_agent2.agent_id) # Step 2: Analyze data analyzer = spawn_sub_agent( task=f"Calculate total sales, average, trends from {files.result}", tools=["read_csv", "calculate_stats"], max_iterations=5, ) stats = get_sub_agent_result(analyzer.agent_id) ``` -------------------------------- ### Build Documentation with MkDocs Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/AGENTS.md Builds the project's documentation using MkDocs. This command should be run from the 'docs' directory. ```bash cd docs mkdocs build ``` -------------------------------- ### Deploy and Manage Services with Deploy Script Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/reactive_agents/docker/README.md Utilizes the `deploy.sh` script for managing Reflex services in both production and development environments. Supports starting, stopping, restarting, viewing logs, checking status, and accessing shells. ```bash # Production deployment ./deploy.sh up # Start services ./deploy.sh down # Stop services ./deploy.sh restart # Restart services ./deploy.sh logs # View logs ./deploy.sh status # Check status ./deploy.sh shell # Open shell # Development deployment ./deploy.sh --dev up # Start dev environment ./deploy.sh --dev shell # Open dev shell ``` -------------------------------- ### Configure LLM Model Providers and Options Source: https://context7.com/tylerjrbuell/reactive-agents/llms.txt Illustrates how to configure different LLM providers (OpenAI, Anthropic, Ollama, Groq, Google) with unified options. It covers setting universal parameters like temperature and max tokens. ```python from reactive_agents import ReactiveAgentBuilder, Provider from pydantic import BaseModel from typing import List # Supported providers providers = { Provider.OPENAI: "openai:gpt-4o", Provider.ANTHROPIC: "anthropic:claude-3-5-sonnet-latest", Provider.OLLAMA: "ollama:llama3:8b", Provider.GROQ: "groq:llama-3.1-8b-instant", Provider.GOOGLE: "google:gemini-2.5-flash", } async def configure_model_options(): # Universal options (OpenAI-style) work across all providers universal_options = { "temperature": 0.2, "max_tokens": 500, "top_p": 0.9, "frequency_penalty": 0.1, "presence_penalty": 0.05, "stop": ["END", "STOP"], "seed": 42 } agent = await ( ReactiveAgentBuilder() .with_name("Configured Agent") .with_model("anthropic:claude-3-sonnet") .with_model_provider_options(universal_options) .build() ) return agent ``` -------------------------------- ### Dual-Parameter Architecture: UI vs. Provider Optimization (Python) Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/README.md Illustrates the dual-parameter system used by the framework. It shows the standardized OpenAI-style user interface parameters and how they are translated into native formats for different providers like Ollama, Anthropic, Groq, and Google. ```python # Clean, standardized interface { "temperature": 0.3, "max_tokens": 200, "top_p": 0.8, "frequency_penalty": 0.1 } ``` ```python # Ollama native (automatically translated) { "temperature": 0.3, "num_predict": 200, # max_tokens → num_predict "top_p": 0.8, "repeat_penalty": 1.1, # frequency_penalty → repeat_penalty (scaled) "num_ctx": 4096, # Added Ollama optimizations "repeat_last_n": 64, "top_k": 40 } ``` ```python # Anthropic native (automatically translated) { "temperature": 0.3, "max_tokens": 200, # Direct mapping "top_p": 0.8, "stop_sequences": ["END"] # stop → stop_sequences } ``` ```python # Groq native (automatically translated) { "temperature": 0.3, "max_completion_tokens": 200, # max_tokens → max_completion_tokens "top_p": 0.8, "frequency_penalty": 0.1 # Direct OpenAI compatibility } ``` ```python # Google native (automatically translated) { "temperature": 0.3, "max_output_tokens": 200, # max_tokens → max_output_tokens "top_p": 0.8, "stop_sequences": ["END"], # stop → stop_sequences (up to 5) "top_k": 40 # Google-specific optimization } ``` -------------------------------- ### Universal LLM Provider Configuration and Execution (Python) Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/README.md Demonstrates how to configure a ReactiveAgent with universal options and execute it across multiple LLM providers. The same set of options is applied to different models, showcasing the framework's ability to abstract provider-specific details. ```python universal_options = { "temperature": 0.2, "max_tokens": 500, "top_p": 0.9, "frequency_penalty": 0.1, "presence_penalty": 0.05, "stop": ["END", "STOP"], "seed": 42 } providers = [ "openai:gpt-4o", "anthropic:claude-3-5-sonnet-latest", "groq:llama-3.1-8b-instant", "ollama:cogito:14b", "google:gemini-2.5-flash" ] for provider_model in providers: agent = await ReactiveAgentBuilder() .with_model(provider_model) .with_model_provider_options(universal_options) .build() result = await agent.run("Analyze this data...") ``` -------------------------------- ### Python Example: Real-time UI with Rich Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/user-guide/events.md A Python class using the 'rich' library to create a live, updating UI that displays agent progress, strategy, and current tool. It subscribes to iteration start, tool call, and session end events. ```python from rich.live import Live from rich.table import Table class LiveUI: def __init__(self, agent): self.current_iteration = 0 self.max_iterations = 0 self.current_tool = None self.status = "Starting" agent.on_iteration_started(self.on_iteration) agent.on_tool_called(self.on_tool) agent.on_session_ended(self.on_end) def on_iteration(self, e): self.current_iteration = e["iteration"] self.max_iterations = e["max_iterations"] self.status = e["strategy"] def on_tool(self, e): self.current_tool = e["tool_name"] def on_end(self, e): self.status = "Complete" def render(self): table = Table() table.add_column("Metric") table.add_column("Value") table.add_row("Progress", f"{self.current_iteration}/{self.max_iterations}") table.add_row("Strategy", self.status) table.add_row("Current Tool", self.current_tool or "-") return table ``` -------------------------------- ### Monitoring Agent Events in Python Source: https://github.com/tylerjrbuell/reactive-agents/blob/main/docs/examples/basic-agent.md Demonstrates how to attach event handlers to an agent to observe its lifecycle and internal processes. This includes listening for session start/end events and iteration start events, providing insights into the agent's execution flow. ```python agent.on_session_started( lambda e: print(f"Started session {e['session_id']}") ) agent.on_iteration_started( lambda e: print(f"Iteration {e['iteration']}") ) agent.on_session_ended( lambda e: print("Session complete") ) ```