### Install Dependencies and Configure Environment Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/examples/index.md Initial setup steps for installing the package and configuring API keys via environment variables. ```bash # Install dependencies pip install agent-patterns # Set up API keys cp .env.example .env # Edit .env with your keys ``` -------------------------------- ### Development Environment Setup Commands Source: https://github.com/osok/agent-patterns/blob/main/docs/notes.md Standard commands to initialize the virtual environment and install dependencies for the project. ```bash python -m venv venv source venv/bin/activate # or venv\Scripts\activate on Windows pip install -e . pytest tests/ ``` -------------------------------- ### Basic STORMAgent Usage Example Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/patterns/storm.md Demonstrates the basic setup and execution of the STORMAgent. This includes defining a simple web search retrieval tool, configuring LLMs, initializing the agent, and running it to generate a report on 'Artificial Intelligence in Healthcare'. ```python from agent_patterns.patterns import STORMAgent # Define retrieval tool def search_web(query: str) -> str: """Search the web and return relevant information""" # Use actual search API in production import requests response = requests.get(f"https://api.search.com/search?q={query}") return response.json()["snippet"] # Configure LLMs llm_configs = { "thinking": { "provider": "openai", "model": "gpt-4", "temperature": 0.7, }, "documentation": { "provider": "openai", "model": "gpt-4", "temperature": 0.7, } } # Create agent agent = STORMAgent( llm_configs=llm_configs, retrieval_tools={"search": search_web} ) # Generate comprehensive report report = agent.run("Artificial Intelligence in Healthcare") print(report) # Output: Multi-section report with: # - Introduction from multiple perspectives # - Applications (expert, practitioner views) # - Challenges and limitations (critic view) # - Research directions (researcher view) # - Conclusion synthesizing all perspectives ``` -------------------------------- ### Example Tool Implementations Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/patterns/react.md Practical examples of file system and directory tools. ```python def read_file(filepath: str) -> str: """Read contents of a file""" try: with open(filepath, 'r') as f: return f.read() except FileNotFoundError: return f"Error: File '{filepath}' not found" except Exception as e: return f"Error reading file: {str(e)}" def write_file(filepath: str, content: str) -> str: """Write content to a file""" try: with open(filepath, 'w') as f: f.write(content) return f"Successfully wrote to '{filepath}'" except Exception as e: return f"Error writing file: {str(e)}" def list_directory(path: str = ".") -> str: """List contents of a directory""" import os try: files = os.listdir(path) return "\n".join(files) except Exception as e: return f"Error listing directory: {str(e)}" ``` -------------------------------- ### Install agent-patterns from source Source: https://github.com/osok/agent-patterns/blob/main/README.md Steps to clone the repository and install in development mode. ```bash # Clone the repository git clone https://github.com/osok/agent-patterns.git cd agent-patterns # Create and activate virtual environment python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install in development mode pip install -e . # Or install with dev dependencies pip install -e ".[dev]" ``` -------------------------------- ### Execute Agent Examples Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/examples/index.md Commands to run pre-built example scripts from the repository. ```bash # From repository root python examples/react_example.py # Or specific example python examples/reflection_example.py ``` -------------------------------- ### Install agent-patterns via PyPI Source: https://github.com/osok/agent-patterns/blob/main/README.md Standard installation command for the library. ```bash pip install agent-patterns ``` -------------------------------- ### Execute Agent Examples Source: https://github.com/osok/agent-patterns/blob/main/examples/README.md Run example scripts from the project root directory to ensure environment variables are correctly loaded. ```bash # Run from the project root (where .env is located) python examples/react_example.py python examples/reflection_example.py # etc. ``` -------------------------------- ### Virtual Environment Setup using venv Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/installation.md Standard Python virtual environment setup using the built-in `venv` module. Includes creation, activation for different OS, installation, and deactivation. ```bash # Create virtual environment python -m venv venv # Activate on Linux/macOS source venv/bin/activate # Activate on Windows virtualenv\Scripts\activate # Install Agent Patterns pip install agent-patterns # Deactivate when done deactivate ``` -------------------------------- ### Copy Example Environment File Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/installation.md Create a local .env file by copying the provided example. This file will store your API keys and configuration settings. ```bash cp .env.example .env ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/osok/agent-patterns/blob/main/DOCUMENTATION_SUMMARY.md Install the necessary Python packages for building the documentation. Ensure you are in the `usr-docs` directory. ```bash cd usr-docs pip install -r requirements.txt ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/README.md Install the necessary Python packages for building the documentation. Ensure you have a requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Custom Instructions Example Source: https://github.com/osok/agent-patterns/blob/main/COMPLETE_UPDATE_SUMMARY.md Demonstrates how to use custom instructions in Python. This example is part of the project's example files. ```python from langgraph.graph import StateGraph, END def main(): # ... (rest of the code for custom_instructions_example.py) pass if __name__ == "__main__": main() ``` -------------------------------- ### Install and Test Project Source: https://github.com/osok/agent-patterns/blob/main/README.md Commands to install development dependencies, execute the test suite, and run code quality tools. ```bash # Install dev dependencies pip install -e ".[dev]" # Run tests pytest # Format and lint black agent_patterns tests examples ruff check agent_patterns tests examples mypy agent_patterns ``` -------------------------------- ### Prioritize Key Guidelines in Instructions Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/guides/custom-instructions.md Organize instructions by importance, placing critical guidelines first. This example demonstrates how to structure instructions with sections like 'CRITICAL', 'IMPORTANT', and 'PREFERRED' to guide agent behavior effectively. ```python custom_instructions = """ CRITICAL: 1. Never share personally identifiable information 2. Always include safety disclaimers for medical content IMPORTANT: 3. Cite evidence-based sources 4. Acknowledge limitations and uncertainties PREFERRED: 5. Use clear, accessible language 6. Provide practical examples """ ``` -------------------------------- ### Prompt Customization Example Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/api/patterns.md Demonstrates how to customize prompts for agent patterns. This example shows setting a custom prompt directory, providing custom instructions, and defining programmatic prompt overrides. ```python agent = PatternAgent( llm_configs=..., prompt_dir="custom_prompts", # File-based custom_instructions="Domain context", # Instructions prompt_overrides={...} # Programmatic ) ``` -------------------------------- ### Example: Concise Style Customization Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/guides/prompt-customization.md Demonstrates creating a ReflectionAgent with prompt overrides for a concise response style. It includes example configurations for 'Generate' and 'Refine' actions and sets specific LLM configurations. ```python from agent_patterns.patterns import ReflectionAgent def example_style_customization(): """Example: Customize the style/tone of responses.""" # Create a variant that produces more concise outputs concise_overrides = { "Generate": { "system": """You are a concise assistant. Follow these rules: - Use bullet points instead of paragraphs - Maximum 3 sentences per point - No fluff or filler words - Get straight to the point""", "user": "Task: {task}\n\nProvide a concise, bulleted response." }, "Refine": { "system": """You are a ruthless editor. Make responses MORE concise: - Cut unnecessary words - Use shorter sentences - Remove redundancy - Keep only essential information""", "user": "Task: {task}\n\nCurrent response:\n{output}\n\nCritique:\n{reflection}\n\nMake it more concise:" } } agent = ReflectionAgent( llm_configs={ "documentation": {"provider": "openai", "model": "gpt-4"}, "reflection": {"provider": "openai", "model": "gpt-4"} }, prompt_overrides=concise_overrides, max_reflection_cycles=1 ) result = agent.run("Explain machine learning") return result ``` -------------------------------- ### Verify Package Installation and Functionality Source: https://github.com/osok/agent-patterns/blob/main/PYPI_PUBLISHING_CHECKLIST.md Commands to install the package from PyPI and verify that the ReActAgent module imports correctly. ```bash pip install agent-patterns ``` ```bash python -c "from agent_patterns.patterns import ReActAgent; print('Success!')" ``` -------------------------------- ### Reflection Agent Example Script Source: https://github.com/osok/agent-patterns/blob/main/docs/Design.md An example script demonstrating the usage of the ReflectionAgent. It loads environment variables, configures LLM settings for documentation and reflection, initializes the agent, and runs it with a sample prompt. ```python # examples/reflection_example.py import os from dotenv import load_dotenv from agent_patterns.patterns.reflection_agent import ReflectionAgent def main(): load_dotenv() llm_configs = { "documentation": { "provider": os.getenv("DOCUMENTATION_MODEL_PROVIDER"), "model_name": os.getenv("DOCUMENTATION_MODEL_NAME"), }, "reflection": { "provider": os.getenv("REFLECTION_MODEL_PROVIDER"), "model_name": os.getenv("REFLECTION_MODEL_NAME"), } } agent = ReflectionAgent(llm_configs=llm_configs) final_answer = agent.run("Write a short story about a robot dog.") print(final_answer) if __name__ == "__main__": main() ``` -------------------------------- ### STORM Agent Example Usage Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/api/patterns.md Provides an example of how to use the STORMAgent. It includes defining a simple search tool, initializing the agent with LLM configurations, and running it to generate a report on a given topic. ```python def search_tool(query: str) -> str: return f"Research data for: {query}" agent = STORMAgent( llm_configs={ "thinking": {"provider": "openai", "model_name": "gpt-4-turbo"}, "documentation": {"provider": "openai", "model_name": "gpt-4-turbo"} }, retrieval_tools={"search": search_tool} ) report = agent.run("Artificial Intelligence in Healthcare") ``` -------------------------------- ### Install agent-patterns from Source Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/faq.md Install the agent-patterns library in editable mode from source. Use this if you have cloned the repository and are making modifications. ```bash pip install -e . ``` -------------------------------- ### Minimal Installation with OpenAI Provider Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/installation.md Install only the core Agent Patterns library along with the OpenAI integration. Use this if you only need to work with OpenAI models. ```bash pip install agent-patterns langchain-openai ``` -------------------------------- ### Define Requirements Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/quickstart.md Example dependencies for the project. ```default agent-patterns>=0.2.0 python-dotenv>=1.0.0 ``` -------------------------------- ### Minimal Installation with Anthropic Provider Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/installation.md Install only the core Agent Patterns library along with the Anthropic integration. Use this if you only need to work with Anthropic models. ```bash pip install agent-patterns langchain-anthropic ``` -------------------------------- ### Structured Response Format Example Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/guides/best-practices.md Provide an example of a structured response format within prompt overrides to guide the agent's output. This includes defining sections like 'Summary', 'Details', and 'Conclusion' with specific formatting instructions. ```python prompt_override = { "Generate": { "system": """Generate structured responses. Example format: ## Summary - Key point 1 - Key point 2 ## Details Detailed explanation... ## Conclusion Final thoughts...""", "user": "Topic: {task}\n\nProvide structured response:" } } ``` -------------------------------- ### Placeholder Usage Progression Example Source: https://github.com/osok/agent-patterns/blob/main/agent_patterns/prompts/REWOOAgent/WorkerPlan/system.md Illustrates a logical flow of information retrieval using placeholders, starting from a broad search and narrowing down to specific details. ```text {search_results} -> {company_name} -> {ceo_name} -> {ceo_bio} ``` -------------------------------- ### Implement on_start Hook Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/api/base-agent.md Override this method to execute custom logic before agent execution begins. Example logs the input data and records the start time. ```python class MonitoredAgent(ReActAgent): def on_start(self, input_data): print(f"Starting: {input_data}") self.start_time = time.time() ``` -------------------------------- ### LLMCompiler Usage Example Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/api/patterns.md Demonstrates initializing the agent with specific LLM configurations and tools to run a task. ```python agent = LLMCompilerAgent( llm_configs={ "planning": {"provider": "openai", "model_name": "gpt-4-turbo"}, "synthesis": {"provider": "openai", "model_name": "gpt-3.5-turbo"} }, tools={ "search": search_tool, "weather": weather_tool, "calculator": calc_tool } ) result = agent.run("Compare weather in Paris and Tokyo, calculate difference") ``` -------------------------------- ### Initialize ReAct Agent Source: https://github.com/osok/agent-patterns/blob/main/README.md Example of configuring and running a ReAct agent with custom tools and LLM settings. ```python from agent_patterns.patterns import ReActAgent import os from dotenv import load_dotenv load_dotenv() # Configure LLMs llm_configs = { "thinking": { "provider": "openai", "model_name": "gpt-4-turbo", "temperature": 0.7, } } # Define tools def search_tool(query): # Your search implementation return f"Results for: {query}" tools = {"search": search_tool} # Create and run agent agent = ReActAgent( llm_configs=llm_configs, tools=tools, max_iterations=5 ) result = agent.run("What is the weather in Paris?") print(result) ``` -------------------------------- ### GitHub Actions Workflow for Testing Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/guides/testing.md Example GitHub Actions workflow for running tests on push and pull requests. It sets up Python, installs dependencies, and runs unit and integration tests. ```yaml # .github/workflows/test.yml name: Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.10' - name: Install dependencies run: | pip install -e ".[dev]" - name: Run unit tests run: | pytest tests/unit/ -v --cov=agent_patterns - name: Run integration tests run: | pytest tests/integration/ -v - name: Upload coverage uses: codecov/codecov-action@v2 ``` -------------------------------- ### Iterative Agent Configuration for Production Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/guides/best-practices.md This code demonstrates a phased approach to configuring an agent, starting from a simple proof-of-concept and progressing to an optimized production setup. It highlights the evolution of configuration parameters like `llm_configs`, `max_reflection_cycles`, and the addition of `custom_instructions` and `prompt_overrides`. ```python # Phase 1: Proof of Concept agent = ReflectionAgent( llm_configs=simple_config, max_reflection_cycles=1 ) # Phase 2: Production MVP agent = ReflectionAgent( llm_configs=production_config, max_reflection_cycles=2, custom_instructions=domain_guidelines ) # Phase 3: Optimized Production agent = ReflectionAgent( llm_configs=optimized_config, max_reflection_cycles=2, custom_instructions=domain_guidelines, prompt_overrides=tested_overrides ) ``` -------------------------------- ### Verify Editable Installation Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/troubleshooting.md Installs the package in editable mode and verifies the installation path. ```bash # Install in editable mode pip install -e . # Verify python -c "import agent_patterns; print(agent_patterns.__file__)" ``` -------------------------------- ### Instantiate Agent with Curated Module Library Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/patterns/self-discovery.md Demonstrates a recommended configuration using a focused and relevant module library with a reasonable `max_selected_modules` limit. ```python focused_library = [/* 6-8 most relevant modules */] agent = SelfDiscoveryAgent( llm_configs=llm_configs, reasoning_modules=focused_library, max_selected_modules=3 ) ``` -------------------------------- ### Initialize and Run ReflectionAgent Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/api/index.md Demonstrates basic instantiation and execution of a ReflectionAgent using a dictionary of LLM configurations. ```python from agent_patterns.patterns import ReflectionAgent # Configure LLM llm_configs = { "documentation": {"provider": "openai", "model": "gpt-4"}, "reflection": {"provider": "openai", "model": "gpt-4"} } # Create agent agent = ReflectionAgent(llm_configs=llm_configs) # Run result = agent.run("Your task here") ``` ```python agent = ReflectionAgent( llm_configs=llm_configs, max_reflection_cycles=2, custom_instructions="Domain-specific guidelines", prompt_overrides={"Generate": {"system": "...", "user": "..."}} ) ``` -------------------------------- ### TestPyPI Installation Source: https://github.com/osok/agent-patterns/blob/main/PUBLISHING.md Command to install the package from TestPyPI for verification. ```bash pip install --index-url https://test.pypi.org/simple/ agent-patterns ``` -------------------------------- ### ReAct Agent Example Usage Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/api/patterns.md Demonstrates how to set up and use the ReAct agent with custom tools. Includes defining search and calculator functions, initializing the agent with these tools, and running a query that utilizes them. ```python def search(query: str) -> str: return f"Search results for: {query}" def calculator(expression: str) -> str: return str(eval(expression)) agent = ReActAgent( llm_configs={ "thinking": { "provider": "openai", "model_name": "gpt-4-turbo", "temperature": 0.7, } }, tools={"search": search, "calculator": calculator}, max_iterations=5 ) result = agent.run("What is the population of Tokyo times 2?") ``` -------------------------------- ### Commit Message Examples Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/contributing.md Examples of descriptive commit messages. ```bash # Good git commit -m "Add STORM pattern implementation" git commit -m "Fix ReAct infinite loop on empty tool results" git commit -m "Update README with new pattern examples" # Bad git commit -m "fix bug" git commit -m "updates" git commit -m "WIP" ``` -------------------------------- ### Install to User Directory or Virtual Environment Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/installation.md Address permission denied errors during installation by installing the package to your user directory or by creating and activating a Python virtual environment. ```bash pip install --user agent-patterns ``` ```bash python -m venv venv && source venv/bin/activate ``` -------------------------------- ### Install pip Module Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/installation.md If 'pip' command is not found, use this command to install pip or directly install the agent-patterns package using Python's pip module. ```bash python -m ensurepip --default-pip ``` ```bash python -m pip install agent-patterns ``` -------------------------------- ### Verify Development Setup Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/contributing.md Commands to run tests, formatting checks, linting, and type checking. ```bash # Run tests pytest # Check formatting black --check agent_patterns tests examples # Check linting ruff check agent_patterns tests examples # Check types mypy agent_patterns ``` -------------------------------- ### Build and Serve Documentation Locally Source: https://github.com/osok/agent-patterns/blob/main/DOCUMENTATION_SUMMARY.md Commands to generate and host the documentation locally for previewing changes. ```bash cd usr-docs make html make serve ``` -------------------------------- ### Commit Message Example Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/contributing.md A concrete example of a formatted commit message. ```default feat: Add LATS pattern implementation Implements Language Agent Tree Search pattern with: - Tree node expansion - Evaluation and backpropagation - Best path extraction Closes #123 ``` -------------------------------- ### Install Test Dependencies Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/troubleshooting.md Installs the package in editable mode with development dependencies. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Initialize Development Environment Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/contributing.md Commands to create a virtual environment and install development dependencies. ```bash python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate ``` ```bash pip install -e ".[dev]" ``` -------------------------------- ### Good: Specific, Actionable Instructions Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/guides/custom-instructions.md Provide clear, actionable guidelines. This example demonstrates how to write specific instructions that an agent can easily follow, such as citing sources or using bullet points. ```python custom_instructions = """ 1. Cite sources for all factual claims 2. Use bullet points for lists of 3+ items 3. Define technical terms on first use 4. Include examples for abstract concepts """ ``` -------------------------------- ### Virtual Environment Setup using poetry Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/installation.md Instructions for setting up and managing Agent Patterns within a project using Poetry. This includes project initialization, adding dependencies, and running commands. ```bash # Initialize poetry project poetry init # Add Agent Patterns poetry add agent-patterns # Install dependencies poetry install # Run commands in poetry environment poetry run python your_script.py ``` -------------------------------- ### Initialize and run a basic ReflectionAgent Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/patterns/reflection.md Configures LLM providers for documentation and reflection roles, then executes the agent to generate content. ```python from agent_patterns.patterns import ReflectionAgent # Configure LLMs llm_configs = { "documentation": { "provider": "openai", "model": "gpt-4", "temperature": 0.7, }, "reflection": { "provider": "openai", "model": "gpt-4", "temperature": 0.3, # Lower temp for more consistent critique } } # Create agent agent = ReflectionAgent( llm_configs=llm_configs, max_reflection_cycles=1 ) # Generate and refine content result = agent.run(""" Write a technical blog post about the benefits of microservices architecture. Target audience: Senior developers and tech leads. """) print(result) # Output will be a refined blog post that has been self-critiqued and improved ``` -------------------------------- ### Resolve installation permission issues Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/troubleshooting.md Methods to install packages without system-wide permission errors. ```bash # Install to user directory pip install --user agent-patterns # Or use virtual environment (recommended) python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate pip install agent-patterns ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/osok/agent-patterns/blob/main/DOCUMENTATION_SUMMARY.md Build and serve the documentation locally for preview. The documentation will be accessible at http://localhost:8000. ```bash make serve ``` -------------------------------- ### Install agent-patterns via pip Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/troubleshooting.md Commands to resolve 'pip: command not found' errors during installation. ```bash # Use Python's pip module python -m pip install agent-patterns # Or install pip python -m ensurepip --default-pip # macOS with brew brew install python@3.10 ``` -------------------------------- ### Create a Basic ReAct Agent Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/quickstart.md Create your first agent using the ReAct pattern. This example uses the calculator tool to perform a mathematical operation. ```python from agent_patterns.patterns import ReActAgent from dotenv import load_dotenv # Load environment variables load_dotenv() # Configure the agent llm_configs = { "thinking": { "provider": "openai", "model_name": "gpt-4-turbo", "temperature": 0.7, } } # Define a simple tool def calculator(expression: str) -> str: """Evaluate a mathematical expression.""" try: result = eval(expression) return f"Result: {result}" except Exception as e: return f"Error: {str(e)}" # Create the agent with tools agent = ReActAgent( llm_configs=llm_configs, tools={"calculator": calculator}, max_iterations=3 ) # Run the agent result = agent.run("What is 156 * 234?") print(result) ``` -------------------------------- ### Install Dependencies Locally Source: https://github.com/osok/agent-patterns/blob/main/RTD_BUILD_FIX.md Installs the necessary Python packages listed in `usr-docs/requirements.txt` for local documentation builds. ```bash pip install -r usr-docs/requirements.txt ``` -------------------------------- ### Markdown Admonition Example Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/README.md Example of using MyST Markdown to create a note admonition for important information. ```markdown ```{note} This is a helpful note ``` ``` -------------------------------- ### Tool Call Sequence with Proper Dependencies Source: https://github.com/osok/agent-patterns/blob/main/agent_patterns/prompts/REWOOAgent/WorkerPlan/system.md Demonstrates a correctly ordered sequence of tool calls where each step provides necessary input for the subsequent step, ensuring logical information flow. ```text 1. Search company → {company_info} 2. Extract CEO from {company_info} → {ceo_name} 3. Search for {ceo_name} details → {ceo_details} ``` -------------------------------- ### Initialize Reflection Agent Source: https://github.com/osok/agent-patterns/blob/main/README.md Example of configuring a Reflection agent with separate LLM providers for documentation and reflection tasks. ```python from agent_patterns.patterns import ReflectionAgent llm_configs = { "documentation": { "provider": "openai", "model_name": "gpt-3.5-turbo", }, "reflection": { "provider": "openai", "model_name": "gpt-4-turbo", }, } agent = ReflectionAgent( llm_configs=llm_configs, max_reflection_cycles=1 ) result = agent.run("Write a short story about a robot dog") print(result) ``` -------------------------------- ### Markdown Cross-Reference Example Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/README.md Example of creating cross-references to other documentation pages using MyST Markdown syntax. ```markdown See [Pattern Comparison](patterns/comparison-matrix.md) See [API Reference](api/index.md) ``` -------------------------------- ### Install Compatible LangChain/LangGraph Versions Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/installation.md Ensure compatibility by installing specific versions of langgraph and langchain alongside agent-patterns. ```bash pip install langgraph==0.2.0 langchain==0.3.0 agent-patterns ``` -------------------------------- ### Install Agent Patterns Package Source: https://github.com/osok/agent-patterns/blob/main/examples/README.md Install the required package via pip, either for standard use or development. ```bash pip install agent-patterns # OR for development: pip install -e . ``` -------------------------------- ### Execute REWOOAgent Workflow Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/patterns/rewoo.md Complete example demonstrating tool definition, LLM configuration, and agent execution for a multi-step task. ```python from agent_patterns.patterns import REWOOAgent # Define tools def search_web(query: str) -> str: """Search the web for information""" import requests response = requests.get(f"https://api.search.com?q={query}") return response.json()["snippet"] def calculate(expression: str) -> float: """Evaluate a mathematical expression""" return eval(expression) # Use safe_eval in production def get_weather(location: str) -> str: """Get current weather""" # API call return f"Weather in {location}: Sunny, 72°F" # Configure LLMs llm_configs = { "thinking": { "provider": "openai", "model": "gpt-4", # Strong model for planning "temperature": 0.3, }, "solver": { "provider": "openai", "model": "gpt-3.5-turbo", # Cheaper model for simple tool use "temperature": 0, } } # Create agent agent = REWOOAgent( llm_configs=llm_configs, tools={ "search": search_web, "calculate": calculate, "weather": get_weather, } ) # Execute complex multi-tool workflow result = agent.run(""" Find the population of Tokyo, then the population of London, then calculate which is larger and by what percentage. Also get the current weather in both cities. """) print(result) # Agent will: # 1. PLAN: Create workflow with placeholders # {tokyo_pop}, {london_pop}, {percentage}, {tokyo_weather}, {london_weather} # 2. EXECUTE: Run all searches and calculations # 3. INTEGRATE: Combine results into final answer # Total LLM calls: 2 (plan + integrate) ``` -------------------------------- ### ReflectionAgent Example Source: https://context7.com/osok/agent-patterns/llms.txt Illustrates the Reflection agent's generate-reflect-refine cycle for output quality. Requires configuration for both documentation and reflection LLMs. ```python from agent_patterns.patterns import ReflectionAgent llm_configs = { "documentation": { "provider": "openai", "model_name": "gpt-3.5-turbo", "temperature": 0.7, }, "reflection": { "provider": "openai", "model_name": "gpt-4-turbo", "temperature": 0.5, }, } agent = ReflectionAgent( llm_configs=llm_configs, max_reflection_cycles=2, # Reflect and refine up to 2 times ) # Generate and refine a story result = agent.run("Write a short story about a robot dog discovering friendship") print(result) # Generate documentation with self-critique doc_result = agent.run(""" Write documentation for this function: def fibonacci(n): if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2) Include: purpose, parameters, return value, and usage example. """) print(doc_result) ``` -------------------------------- ### Prompt Overrides Example Source: https://github.com/osok/agent-patterns/blob/main/COMPLETE_UPDATE_SUMMARY.md Illustrates the usage of prompt overrides in Python. This is one of the example files provided in the project. ```python from langgraph.graph import StateGraph, END def main(): # ... (rest of the code for prompt_overrides_example.py) pass if __name__ == "__main__": main() ``` -------------------------------- ### Initialize Agent Pattern Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/api/base-agent.md Example of instantiating a concrete agent pattern with custom configurations. ```python from agent_patterns.patterns import ReActAgent agent = ReActAgent( llm_configs={ "thinking": { "provider": "openai", "model_name": "gpt-4-turbo", "temperature": 0.7, } }, prompt_dir="custom_prompts", custom_instructions="You are a helpful medical assistant.", prompt_overrides={ "ThoughtStep": { "system": "Think carefully about medical implications." } } ) ``` -------------------------------- ### Combine Configuration Methods for ReflectionAgent Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/guides/prompt-customization.md Demonstrates the integration of custom prompt directories, domain instructions, and step-specific overrides within a ReflectionAgent. ```python from agent_patterns.patterns import ReflectionAgent # 1. Start with custom prompts directory # 2. Add domain-specific instructions domain_instructions = """ DOMAIN: Software Architecture AUDIENCE: Senior engineers FORMAT: Include diagrams (described in text), code examples, and trade-offs """ # 3. Override specific steps for fine-tuning overrides = { "Generate": { "system": "You create structured, well-organized responses.", "user": "Task: {task}\n\nCreate a structured response with clear sections." } } # Combine all three agent = ReflectionAgent( llm_configs=llm_configs, prompt_dir="my_custom_prompts", # 1. Custom directory custom_instructions=domain_instructions, # 2. Add domain context prompt_overrides=overrides # 3. Override specific steps ) result = agent.run("Design a microservices architecture for an e-commerce platform") ``` -------------------------------- ### Install with Trusted Hosts Source: https://github.com/osok/agent-patterns/blob/main/usr-docs/installation.md Resolve SSL certificate verification failures by explicitly trusting the PyPI hosts during the pip installation process. ```bash pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org agent-patterns ``` -------------------------------- ### Custom Instructions Example (v0.2.0) Source: https://github.com/osok/agent-patterns/blob/main/COMPLETE_UPDATE_SUMMARY.md This note explains that in v0.2.0, custom instructions are appended to comprehensive, enterprise-grade system prompts. Users build upon a solid foundation that includes error handling and quality standards. ```python """ NOTE: In v0.2.0, all system prompts are enterprise-grade (150-300+ lines) with comprehensive sections including Role, Capabilities, Process, Examples, and more. Your custom_instructions are appended to these comprehensive prompts, building on a solid foundation that already includes error handling, quality standards, and edge case management. """ ```