### Installation and Setup Source: https://agent-patterns.readthedocs.io/en/latest/_sources/examples/index.md.txt Commands to install dependencies and configure environment variables. ```bash # Install dependencies pip install agent-patterns # Set up API keys cp .env.example .env # Edit .env with your keys ``` -------------------------------- ### Custom Instructions Example Setup Source: https://agent-patterns.readthedocs.io/en/latest/_sources/examples/index.md.txt Demonstrates adding domain-specific context to prompts using the ReAct agent. This example is a setup for custom instructions. ```python from agent_patterns.patterns import ReActAgent ``` -------------------------------- ### Example with Custom Instructions Source: https://agent-patterns.readthedocs.io/en/latest/_sources/patterns/reflexion.md.txt Illustrates how to use `custom_instructions` to guide the agent's behavior. ```APIDOC ## With Custom Instructions ### Description This example demonstrates how to provide `custom_instructions` to tailor the agent's problem-solving approach, particularly useful for tasks like debugging. ### Request Example ```python # Add domain-specific learning guidance debugging_instructions = """ You are debugging code by trial and error. Follow these principles: PLANNING WITH MEMORY: - Review what you've tried before - Don't repeat failed approaches - Build on partial successes - Try systematic variations EXECUTION: - Be precise in implementing the plan - Document what you're testing EVALUATION: - Check if code runs without errors - Verify output matches expected results - Identify specific failure points REFLECTION: - Analyze why the approach failed - Identify what worked and what didn't - Generate specific, actionable insights - Propose concrete changes for next trial """ agent = ReflexionAgent( llm_configs=llm_configs, max_trials=5, # Allow more trials for complex debugging custom_instructions=debugging_instructions ) result = agent.run(""" Debug this Python function that should find the longest palindromic substring: def longest_palindrome(s): result = "" for i in range(len(s)): for j in range(i, len(s)): if s[i:j] == s[i:j][::-1]: result = max(result, s[i:j]) return result Test cases: - longest_palindrome("babad") should return "bab" or "aba" - longest_palindrome("cbbd") should return "bb" The function has bugs. Fix them. """) ``` ``` -------------------------------- ### Environment Variables Setup Source: https://agent-patterns.readthedocs.io/en/latest/_sources/guides/configuration.md.txt Example of setting up environment variables in a .env file for API keys and default model parameters. ```bash # API Keys OPENAI_API_KEY=sk-... ANTHROPIC_API_KEY=sk-ant-... # Default Models THINKING_MODEL_PROVIDER=openai THINKING_MODEL_NAME=gpt-4 THINKING_TEMPERATURE=0.7 THINKING_MAX_TOKENS=2000 DOCUMENTATION_MODEL_PROVIDER=openai DOCUMENTATION_MODEL_NAME=gpt-3.5-turbo DOCUMENTATION_TEMPERATURE=0.7 # Pattern Defaults MAX_ITERATIONS=5 MAX_REFLECTION_CYCLES=2 MAX_TRIALS=3 ``` -------------------------------- ### Running Examples Source: https://agent-patterns.readthedocs.io/en/latest/_sources/examples/index.md.txt Commands to execute example scripts from the repository. ```bash # From repository root python examples/react_example.py # Or specific example python examples/reflection_example.py ``` -------------------------------- ### Set up Project with Poetry Source: https://agent-patterns.readthedocs.io/en/latest/_sources/installation.md.txt Guide to initializing a new project with Poetry, adding Agent Patterns as a dependency, and installing all project dependencies. Poetry is a dependency management and packaging tool. ```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 ``` -------------------------------- ### Configure and Run LATSAgent Source: https://agent-patterns.readthedocs.io/en/latest/patterns/lats.html Example setup for the LATSAgent with specific LLM providers and search iteration settings. ```python from agent_patterns.patterns import LATSAgent # Configure LLMs llm_configs = { "thinking": { "provider": "openai", "model": "gpt-4", "temperature": 0.7, }, "evaluation": { "provider": "openai", "model": "gpt-4", "temperature": 0.3, # More consistent evaluation } } # Create agent agent = LATSAgent( llm_configs=llm_configs, max_iterations=15, # More iterations for thorough exploration num_expansions=3 # Generate 3 children per expansion ) ``` -------------------------------- ### Run an Example Script Source: https://agent-patterns.readthedocs.io/en/latest/examples/index.html Executes an example Python script from the repository root. Use specific paths for individual examples. ```bash # From repository root python examples/react_example.py # Or specific example python examples/reflection_example.py ``` -------------------------------- ### Basic Usage Example Source: https://agent-patterns.readthedocs.io/en/latest/patterns/plan-and-solve.html A practical example demonstrating how to initialize and use the PlanAndSolveAgent with specific LLM configurations. ```APIDOC ## Complete Examples ### Basic Usage ```python from agent_patterns.patterns import PlanAndSolveAgent # Configure LLMs llm_configs = { "planning": { "provider": "openai", "model": "gpt-4", "temperature": 0.3, # Lower temp for consistent planning }, "execution": { "provider": "openai", "model": "gpt-4", "temperature": 0.7, }, "documentation": { "provider": "openai", "model": "gpt-4", "temperature": 0.7, } } # Create agent agent = PlanAndSolveAgent(llm_configs=llm_configs) ``` ``` -------------------------------- ### Basic Usage Example Source: https://agent-patterns.readthedocs.io/en/latest/patterns/llm-compiler.html A simple example demonstrating how to initialize and use the LLMCompilerAgent with basic tools and LLM configurations. ```APIDOC ## Basic Usage Example ### Description This example shows the fundamental setup of the LLMCompilerAgent, including defining tools, configuring LLMs, and running a complex workflow. ### Method POST (Conceptual - this is a method call, not a direct HTTP endpoint) ### Endpoint N/A (Instance method) ### Parameters See LLMCompilerAgent Initialization and Methods sections. ### Request Example ```python from agent_patterns.patterns import LLMCompilerAgent # Define tools def search_tool(query: str) -> str: """Search for information""" return f"Search results for: {query}" def calculate_tool(expression: str) -> float: """Evaluate mathematical expression""" return eval(expression) def get_price(product: str) -> float: """Get product price""" prices = {"laptop": 999, "phone": 699, "tablet": 499} return prices.get(product, 0) # Configure LLMs llm_configs = { "thinking": { "provider": "openai", "model": "gpt-4", "temperature": 0.3, }, "documentation": { "provider": "openai", "model": "gpt-4", "temperature": 0.7, } } # Create agent agent = LLMCompilerAgent( llm_configs=llm_configs, tools={ "search": search_tool, "calculate": calculate_tool, "get_price": get_price, } ) # Execute complex workflow result = agent.run(""" Find the prices of laptop, phone, and tablet. Calculate the total cost if I buy one of each. Also search for information about each product's warranty. Provide a summary with total cost and warranty info. """) print(result) ``` ### Response #### Success Response (200) - **result** (str) - The synthesized summary of the task execution. #### Response Example ``` "The total cost for a laptop, phone, and tablet is $2197. The laptop costs $999, the phone costs $699, and the tablet costs $499. [Warranty information would be included here if the search tool was implemented to provide it.]" ``` ``` -------------------------------- ### Custom ReAct Prompts Example Source: https://agent-patterns.readthedocs.io/en/latest/patterns/llm-compiler.html Provides an example of creating custom prompt directories and templates for the ReAct pattern. ```python from typing import List, Dict, Any from langchain_core.tools import tool from langchain_experimental.agents.react.agent import ReactAgent from langchain_experimental.agents.react.prompt import PromptTemplate @tool def search(query: str) -> Dict[str, Any]: """Searches for information about a given query.""" return {"query": query, "results": [f"Results for {query}"]} @tool def lookup(term: str) -> Dict[str, Any]: """Looks up a term in a dictionary.""" return {"term": term, "definition": f"Definition of {term}"} async def run_custom_react_prompts(): agent = ReactAgent(tools=[search, lookup]) # Assuming 'custom_prompts' directory exists with 'react_prompt.json' # and 'react_tool_prompt.json' files. # This part of the code would typically involve loading these files. # For demonstration, we'll simulate the effect. print("Simulating custom prompt usage for ReAct agent.") # In a real scenario, you would load and pass the custom prompts here. # Example: agent = ReactAgent(tools=[search, lookup], prompt_directory="custom_prompts") # result = await agent.astream_to_runnable("What is the capital of France?") # print(await result.ainvoke({})) if __name__ == "__main__": import asyncio asyncio.run(run_custom_react_prompts()) ``` -------------------------------- ### Set Up API Keys Source: https://agent-patterns.readthedocs.io/en/latest/examples/index.html Copies the example .env file to .env for API key configuration. Edit the .env file with your specific keys. ```bash # Set up API keys cp .env.example .env # Edit .env with your keys ``` -------------------------------- ### LATSAgent with Custom Instructions Example Source: https://agent-patterns.readthedocs.io/en/latest/_sources/patterns/lats.md.txt Example demonstrating how to provide custom instructions to guide the agent's behavior. ```APIDOC ## With Custom Instructions ### Description This example illustrates how to inject custom instructions to influence the agent's node expansion, evaluation criteria, and final output formatting. ### Method POST ### Endpoint `/run` (Conceptual endpoint for method execution) ### Parameters None (Assumes agent is already initialized) ### Request Example ```python from agent_patterns.patterns import LATSAgent llm_configs = { "thinking": { "provider": "openai", "model": "gpt-4", "temperature": 0.7, }, "evaluation": { "provider": "openai", "model": "gpt-4", "temperature": 0.3, } } problem_solving_instructions = """ You are solving complex problems through systematic exploration. NODE EXPANSION: - Generate diverse approaches (don't just vary small details) - Each child should represent meaningfully different strategy - Be creative but logical in generating alternatives NODE EVALUATION: - Score based on: * Logical soundness (0.4 weight) * Completeness of approach (0.3 weight) * Efficiency (0.2 weight) * Clarity (0.1 weight) - Use scale 0.0 to 1.0 - Be discriminating (don't give everything 0.5) FINAL OUTPUT: - Present the winning strategy clearly - Explain why this approach is optimal - Address potential objections """ agent = LATSAgent( llm_configs=llm_configs, max_iterations=20, num_expansions=4, custom_instructions=problem_solving_instructions ) result = agent.run("Design an algorithm to find the median of two sorted arrays of different lengths in O(log(min(m,n))) time complexity. Explain the approach and prove the time complexity.") print(result) ``` ### Response #### Success Response (200) - **result** (str) - The algorithm design, explanation, and complexity proof, guided by custom instructions. #### Response Example ```json { "result": "Detailed explanation of the median of two sorted arrays algorithm..." } ``` ``` -------------------------------- ### LLM Invocation Example Source: https://agent-patterns.readthedocs.io/en/latest/_sources/concepts/architecture.md.txt Demonstrates how to get an LLM for a specific role, prepare messages including system and human prompts, and invoke the LLM to get a response. ```python # Get LLM for role llm = self._get_llm("thinking") # Prepare messages messages = [ SystemMessage(content=system_prompt), HumanMessage(content=user_prompt), ] # Invoke LLM response = llm.invoke(messages) result = response.content ``` -------------------------------- ### Plan and Solve Usage Example Source: https://agent-patterns.readthedocs.io/en/latest/_sources/api/patterns.md.txt Demonstrates initializing the agent with specific provider configurations and executing a task. ```python agent = PlanAndSolveAgent( llm_configs={ "planning": { "provider": "openai", "model_name": "gpt-4-turbo", }, "execution": { "provider": "openai", "model_name": "gpt-3.5-turbo", }, "documentation": { "provider": "openai", "model_name": "gpt-3.5-turbo", } } ) result = agent.run("Create a marketing strategy for AI language learning app") ``` -------------------------------- ### Additional Resources Source: https://agent-patterns.readthedocs.io/en/latest/index.html Links to supplementary resources like examples, FAQs, and troubleshooting guides. ```APIDOC ## Additional Resources ### Examples Index Provides a collection of examples demonstrating various agent pattern use cases. ### Frequently Asked Questions (FAQ) Answers to common questions about agent patterns. ### Troubleshooting Guide Guidance on diagnosing and resolving issues encountered with agent patterns. ### Changelog Lists changes and updates made to the agent-patterns library. ### Contributing to Agent Patterns Information for developers interested in contributing to the project. ``` -------------------------------- ### Complete Example: Custom Instructions Source: https://agent-patterns.readthedocs.io/en/latest/guides/extending-patterns.html Provides a full, runnable example demonstrating the use of custom instructions in an agent, likely for domain-specific tasks. ```python # This is a placeholder for a complete example file. # The actual code would involve setting up an agent (e.g., ReAct, LLMCompiler, STORM) # and providing custom instructions during its initialization or invocation. # Example structure: # from langchain_core.prompts import ChatPromptTemplate # from langchain_core.runnables import RunnablePassthrough # from langchain_core.tools import tool # from langchain_experimental.agents import AgentExecutor # Or specific agent type # @tool # def some_tool(input: str) -> str: # """A sample tool.""" # return f"Processed: {input}" # Define custom instructions # custom_instructions = "You are a legal assistant. Always cite relevant precedents if possible." # Define the agent's prompt template, incorporating instructions # prompt = ChatPromptTemplate.from_messages([ # ("system", "{instructions}\n\n{template}"), # ("human", "{input}"), # # ]) # Initialize the agent with the prompt and tools # agent_executor = AgentExecutor(agent=..., tools=[some_tool], prompt=prompt, ...) # Run the agent with the instructions embedded in the prompt or passed separately # result = agent_executor.invoke({"input": "Draft a clause regarding confidentiality.", "instructions": custom_instructions}) # print(result) print("This section would contain a complete Python script demonstrating custom instructions.") print("It would typically involve defining an agent, its tools, and passing specific instructions to guide its behavior, potentially for domain-specific applications like legal or financial compliance.") ``` -------------------------------- ### Prompt with Example Format Override Source: https://agent-patterns.readthedocs.io/en/latest/guides/best-practices.html Configures prompt overrides to include a system message that specifies a desired response format with examples. Useful for guiding the agent's output structure. ```python prompt_override = { "Generate": { "system": "Generate structured responses.\n\nExample format:\n## Summary\n- Key point 1\n- Key point 2\n\n## Details\nDetailed explanation...\n\n## Conclusion\nFinal thoughts...", "user": "Topic: {task}\n\nProvide structured response:" } } ``` -------------------------------- ### Configure API keys via .env Source: https://agent-patterns.readthedocs.io/en/latest/troubleshooting.html Initialize the environment configuration file from the provided example. ```bash cp .env.example .env # Edit .env and add: OPENAI_API_KEY=your-key-here ``` -------------------------------- ### Initialize and Run a ReAct Agent Source: https://agent-patterns.readthedocs.io/en/latest/_sources/patterns/react.md.txt Demonstrates the basic setup of a ReAct agent with defined tools and LLM configuration. ```python from agent_patterns.patterns import ReActAgent import requests # Define tools def search_web(query: str) -> str: """Search the web for information""" # Simplified - use actual search API in production response = requests.get(f"https://api.search.com/search?q={query}") return response.json()["results"] def get_weather(location: str) -> str: """Get current weather for a location""" response = requests.get(f"https://api.weather.com/current?loc={location}") return f"Weather in {location}: {response.json()['condition']}" def calculate(expression: str) -> str: """Evaluate a mathematical expression""" try: result = eval(expression) # Use safe_eval in production! return f"Result: {result}" except Exception as e: return f"Error: {str(e)}" # Configure LLM llm_configs = { "thinking": { "provider": "openai", "model": "gpt-4", "temperature": 0.7, } } # Create agent with tools tools = { "search": search_web, "weather": get_weather, "calculate": calculate, } agent = ReActAgent( llm_configs=llm_configs, tools=tools, max_iterations=5 ) # Run agent result = agent.run("What is the weather in the capital of France?") print(result) # Expected: Agent searches for "capital of France", gets "Paris", # then calls weather("Paris") to get the weather ``` -------------------------------- ### Role-Based Configuration Example Source: https://agent-patterns.readthedocs.io/en/latest/patterns/plan-and-solve.html Configures specific purposes for different roles within an agent pattern, guiding behavior. ```yaml roles: - role: "system" purpose: "You are a helpful assistant that answers questions." - role: "user" purpose: "Provide the user's query." ``` -------------------------------- ### Complete Style Customization Example Source: https://agent-patterns.readthedocs.io/en/latest/_sources/guides/prompt-customization.md.txt A full implementation example showing the import, configuration, and execution of a ReflectionAgent with custom prompt overrides. ```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 ``` -------------------------------- ### Structured Response Prompt Override Example Source: https://agent-patterns.readthedocs.io/en/latest/_sources/guides/best-practices.md.txt Provides a `prompt_override` configuration for generating structured responses. This example defines system and user prompts to guide the agent in formatting its output with specific sections like 'Summary', 'Details', and 'Conclusion'. ```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:" } } ``` -------------------------------- ### LATSAgent with Custom Instructions Source: https://agent-patterns.readthedocs.io/en/latest/_sources/patterns/lats.md.txt Example showing how to inject custom system instructions to guide node expansion and evaluation logic. ```python problem_solving_instructions = """ You are solving complex problems through systematic exploration. NODE EXPANSION: - Generate diverse approaches (don't just vary small details) - Each child should represent meaningfully different strategy - Be creative but logical in generating alternatives NODE EVALUATION: - Score based on: * Logical soundness (0.4 weight) * Completeness of approach (0.3 weight) * Efficiency (0.2 weight) * Clarity (0.1 weight) - Use scale 0.0 to 1.0 - Be discriminating (don't give everything 0.5) FINAL OUTPUT: - Present the winning strategy clearly - Explain why this approach is optimal - Address potential objections """ agent = LATSAgent( llm_configs=llm_configs, max_iterations=20, num_expansions=4, custom_instructions=problem_solving_instructions ) result = agent.run(""" Design an algorithm to find the median of two sorted arrays of different lengths in O(log(min(m,n))) time complexity. Explain the approach and prove the time complexity. """) ``` -------------------------------- ### Compare ReAct and Plan & Solve Approaches Source: https://agent-patterns.readthedocs.io/en/latest/_sources/examples/index.md.txt Shows the initialization patterns for different agent strategies. ```python # Best for: Questions needing external data agent = ReActAgent( llm_configs={...}, tools={"search": search_tool} ) result = agent.run("What is the capital of France?") ``` -------------------------------- ### Configure Environment Variables Source: https://agent-patterns.readthedocs.io/en/latest/_sources/contributing.md.txt Copy the example environment file to initialize local configuration. ```bash cp .env.example .env # Edit .env and add your API keys ``` -------------------------------- ### Usage with Custom Instructions Source: https://agent-patterns.readthedocs.io/en/latest/patterns/llm-compiler.html Example demonstrating how to provide custom instructions to guide the agent's behavior, such as for data pipeline orchestration. ```APIDOC ## Usage with Custom Instructions ### Description This example illustrates how to use the `custom_instructions` parameter to tailor the agent's behavior for specific tasks, like orchestrating data processing pipelines. ### Method POST (Conceptual - this is a method call, not a direct HTTP endpoint) ### Endpoint N/A (Instance method) ### Parameters - **custom_instructions** (str) - Required - Detailed instructions for the agent's role and task execution. See LLMCompilerAgent Initialization and Methods sections for other parameters. ### Request Example ```python # Define custom instructions for data pipeline orchestration data_pipeline_instructions = """ You are orchestrating data processing pipelines. DAG CONSTRUCTION: - Identify all data sources (parallel) - Identify processing steps (sequential when dependent) - Identify aggregation steps (after all data ready) - Maximize parallelism where safe TOOL EXECUTION: - Respect all dependencies - Never execute before dependencies ready - Handle errors gracefully SYNTHESIS: - Present data clearly - Highlight key insights - Show data lineage """ # Assuming llm_configs and tools are defined as in the basic example agent = LLMCompilerAgent( llm_configs=llm_configs, tools=tools, custom_instructions=data_pipeline_instructions ) result = agent.run(""" Analyze sales data: 1. Fetch sales from Q1, Q2, Q3, Q4 (parallel) 2. Calculate total annual sales 3. Calculate quarter-over-quarter growth rates 4. Identify best and worst performing quarters 5. Generate executive summary """) print(result) ``` ### Response #### Success Response (200) - **result** (str) - The synthesized executive summary based on the data analysis and custom instructions. #### Response Example ``` "Executive Summary: Total annual sales: [Calculated Value] Performance by Quarter: Q1: [Value], Growth: [Rate]% Q2: [Value], Growth: [Rate]% Q3: [Value], Growth: [Rate]% Q4: [Value], Growth: [Rate]% Best Performing Quarter: [Quarter Name] Worst Performing Quarter: [Quarter Name]" ``` ``` -------------------------------- ### Test Fixtures and Utilities: Shared Fixtures Source: https://agent-patterns.readthedocs.io/en/latest/patterns/plan-and-solve.html Example of using shared fixtures in testing frameworks like pytest for common setup. ```python import pytest @pytest.fixture def sample_agent(): # Setup code for a reusable agent instance agent = Agent() agent.setup_dependencies() return agent def test_with_fixture(sample_agent): # Use the fixture in your test response = sample_agent.query("test") assert response is not None ``` -------------------------------- ### Copy Example Environment File Source: https://agent-patterns.readthedocs.io/en/latest/_sources/installation.md.txt Create a local .env file by copying the provided example configuration file. This file will be used to store your API keys and other environment-specific settings. ```bash cp .env.example .env ``` -------------------------------- ### ReAct Agent with Custom Instructions Example Source: https://agent-patterns.readthedocs.io/en/latest/troubleshooting.html Shows how to use the ReAct agent with custom instructions to guide its behavior. The custom_instructions parameter accepts a string. ```python from langgraph.graph.agent.react import ReActAgent agent = ReActAgent() agent.invoke("What is the capital of France?", custom_instructions="Always answer in French.") ``` -------------------------------- ### Instantiate and Run SimpleReasonerAgent Source: https://agent-patterns.readthedocs.io/en/latest/guides/extending-patterns.html Demonstrates how to create an instance of the SimpleReasonerAgent with specified LLM configurations and maximum reasoning steps, then run it with an input query. ```python # Create agent agent = SimpleReasonerAgent( llm_configs={ "thinking": {"provider": "openai", "model": "gpt-4"}, "execution": {"provider": "openai", "model": "gpt-4"} }, max_reasoning_steps=3 ) # Run agent result = agent.run("What is 15% of 80?") print(result) ``` -------------------------------- ### Docker Compose for Multi-Container Setup Source: https://agent-patterns.readthedocs.io/en/latest/index.html Example of a docker-compose.yml file to define and run multi-container Docker applications. Useful for orchestrating agents with databases or other services. ```yaml version: '3.8' services: agent: build: . ports: - "8000:8000" environment: - OPENAI_API_KEY=${OPENAI_API_KEY} redis: image: redis:alpine ports: - "6379:6379" ``` -------------------------------- ### Prompt Customization Guide - Method 2: Custom Instructions Source: https://agent-patterns.readthedocs.io/en/latest/guides/setting-goals.html Details the use of custom instructions for prompt customization, including when to use them, basic usage, and domain-specific examples. ```APIDOC ## Method 2: Custom Instructions ### What Are Custom Instructions? [Definition and purpose of custom instructions] ### When to Use Custom Instructions [Scenarios where custom instructions are beneficial] ### Basic Usage [Example of basic custom instruction implementation] ### Domain-Specific Examples #### Legal Domain [Example of custom instructions for the legal domain] #### Financial Compliance [Example of custom instructions for financial compliance] #### Educational Content [Example of custom instructions for educational content] #### Cultural Sensitivity [Example of custom instructions for cultural sensitivity] ### Best Practices for Custom Instructions [Guidelines for effective use of custom instructions] ### Complete Example from examples/custom_instructions_example.py [Link or snippet of the example file] ``` -------------------------------- ### Basic ReActAgent Usage Example Source: https://agent-patterns.readthedocs.io/en/latest/patterns/react.html Demonstrates how to set up and run the ReActAgent with custom tools (search, weather, calculate) and LLM configurations to answer a question. ```python from agent_patterns.patterns import ReActAgent import requests # Define tools def search_web(query: str) -> str: """Search the web for information""" # Simplified - use actual search API in production response = requests.get(f"https://api.search.com/search?q={query}") return response.json()["results"] def get_weather(location: str) -> str: """Get current weather for a location""" response = requests.get(f"https://api.weather.com/current?loc={location}") return f"Weather in {location}: {response.json()['condition']}" def calculate(expression: str) -> str: """Evaluate a mathematical expression""" try: result = eval(expression) # Use safe_eval in production! return f"Result: {result}" except Exception as e: return f"Error: {str(e)}" # Configure LLM llm_configs = { "thinking": { "provider": "openai", "model": "gpt-4", "temperature": 0.7, } } # Create agent with tools tools = { "search": search_web, "weather": get_weather, "calculate": calculate, } agent = ReActAgent( llm_configs=llm_configs, tools=tools, max_iterations=5 ) # Run agent result = agent.run("What is the weather in the capital of France?") print(result) # Expected: Agent searches for "capital of France", gets "Paris", # then calls weather("Paris") to get the weather ``` -------------------------------- ### Basic ReflectionAgent Usage Source: https://agent-patterns.readthedocs.io/en/latest/_sources/patterns/reflection.md.txt Demonstrates the basic setup and execution of the ReflectionAgent. Configure LLMs, create an agent instance, and run it with a task. Ensure LLM configurations are correctly defined. ```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 ``` -------------------------------- ### Plan & Solve Agent with Custom Instructions Example Source: https://agent-patterns.readthedocs.io/en/latest/troubleshooting.html Demonstrates using the Plan & Solve agent with custom instructions. The custom_instructions parameter accepts a string to guide the agent's planning and solving process. ```python from langgraph.graph.agent.plan_and_solve import PlanAndSolveAgent agent = PlanAndSolveAgent() agent.invoke("Create a detailed itinerary for a 7-day trip to Japan.", custom_instructions="Prioritize cultural experiences and minimize travel time between cities.") ``` -------------------------------- ### Instantiate ReActAgent Source: https://agent-patterns.readthedocs.io/en/latest/_sources/guides/configuration.md.txt Example of how to instantiate the ReActAgent with specified configurations, tools, and parameters. ```python from agent_patterns.patterns import ReActAgent agent = ReActAgent( llm_configs=configs, tools=tools, max_iterations=5, prompt_dir="prompts", custom_instructions=None, prompt_overrides=None ) ``` -------------------------------- ### Initialize REWOO Agent with Custom Instructions (Efficiency Focus) Source: https://agent-patterns.readthedocs.io/en/latest/patterns/rewoo.html Use custom instructions to guide the agent's planning and execution towards efficiency. This setup prioritizes parallel execution and minimizing tool calls. ```python agent = REWOOAgent( llm_configs=llm_configs, tools=tools, custom_instructions=""" EFFICIENCY FOCUS: - Plan for maximum parallel execution - Minimize total tool calls - Identify dependencies explicitly QUALITY FOCUS: - Ensure plan covers all task requirements - Create clear placeholders - Provide comprehensive final synthesis """ ) ``` -------------------------------- ### Verify Development Setup Source: https://agent-patterns.readthedocs.io/en/latest/_sources/contributing.md.txt 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 ``` -------------------------------- ### Install agent-patterns Package Source: https://agent-patterns.readthedocs.io/en/latest/_sources/faq.md.txt Command to install the agent-patterns library using pip. Use the editable install option if installing from source. ```bash pip install agent-patterns ``` ```bash pip install -e . ``` -------------------------------- ### Reflection Agent Example Usage Source: https://agent-patterns.readthedocs.io/en/latest/_sources/api/patterns.md.txt Example of initializing and running the Reflection agent to generate and refine a product description. Requires separate LLM configurations for documentation and reflection. ```python agent = ReflectionAgent( llm_configs={ "documentation": { "provider": "openai", "model_name": "gpt-3.5-turbo", }, "reflection": { "provider": "openai", "model_name": "gpt-4-turbo", } }, max_reflection_cycles=2 ) result = agent.run("Write a product description for smart water bottle") ``` -------------------------------- ### Install Dependencies Source: https://agent-patterns.readthedocs.io/en/latest/examples/index.html Installs the agent-patterns library using pip. Ensure you have Python and pip installed. ```bash # Install dependencies pip install agent-patterns ``` -------------------------------- ### Basic LLMCompilerAgent Usage Example Source: https://agent-patterns.readthedocs.io/en/latest/_sources/patterns/llm-compiler.md.txt A complete example showing how to set up tools, configure LLMs, instantiate the LLMCompilerAgent, and run a complex workflow involving multiple steps like searching, calculating, and summarizing. ```python from agent_patterns.patterns import LLMCompilerAgent # Define tools def search_tool(query: str) -> str: """Search for information""" # API call return f"Search results for: {query}" def calculate_tool(expression: str) -> float: """Evaluate mathematical expression""" return eval(expression) # Use safe_eval in production def get_price(product: str) -> float: """Get product price""" prices = {"laptop": 999, "phone": 699, "tablet": 499} return prices.get(product, 0) # Configure LLMs llm_configs = { "thinking": { "provider": "openai", "model": "gpt-4", "temperature": 0.3, }, "documentation": { "provider": "openai", "model": "gpt-4", "temperature": 0.7, } } # Create agent agent = LLMCompilerAgent( llm_configs=llm_configs, tools={ "search": search_tool, "calculate": calculate_tool, "get_price": get_price, } ) # Execute complex workflow result = agent.run(""" Find the prices of laptop, phone, and tablet. Calculate the total cost if I buy one of each. Also search for information about each product's warranty. Provide a summary with total cost and warranty info. """) print(result) # Agent will: # 1. PLAN: Create DAG with parallel price lookups and searches # 2. EXECUTE: Run get_price and search calls in parallel # Then calculate total (depends on prices) # 3. SYNTHESIZE: Combine all results into summary ``` -------------------------------- ### Install Agent Patterns from PyPI Source: https://agent-patterns.readthedocs.io/en/latest/_sources/installation.md.txt Use this command to install the latest stable version of Agent Patterns with all necessary dependencies. This is the recommended installation method. ```bash pip install agent-patterns ``` -------------------------------- ### Initialize Development Environment Source: https://agent-patterns.readthedocs.io/en/latest/_sources/contributing.md.txt 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]" ``` -------------------------------- ### STORM Agent Initialization with Retrieval Tool Source: https://agent-patterns.readthedocs.io/en/latest/examples/index.html Demonstrates initializing a STORMAgent with LLM configurations and a custom retrieval tool for generating multi-perspective reports. The `search_tool` function simulates a research lookup. ```python from agent_patterns.patterns import STORMAgent def search_tool(query: str) -> str: """Research tool.""" return f"[Research findings for: {query}]" agent = STORMAgent( llm_configs={ "thinking": {"provider": "openai", "model_name": "gpt-4o"}, "documentation": {"provider": "openai", "model_name": "gpt-4o-mini"} }, retrieval_tools={"search": search_tool} ) result = agent.run("Create a comprehensive report on quantum computing applications in cryptography") ``` -------------------------------- ### Provider Configuration Example Source: https://agent-patterns.readthedocs.io/en/latest/patterns/plan-and-solve.html Shows how to configure specific providers like OpenAI or Anthropic for LLM interactions. ```yaml llm: provider: "anthropic" model: "claude-3-opus-20240229" ``` -------------------------------- ### Commit Message Example Source: https://agent-patterns.readthedocs.io/en/latest/_sources/contributing.md.txt A complete example of a formatted commit message. ```text feat: Add LATS pattern implementation Implements Language Agent Tree Search pattern with: - Tree node expansion - Evaluation and backpropagation - Best path extraction Closes #123 ``` -------------------------------- ### Customization Guides Source: https://agent-patterns.readthedocs.io/en/latest/index.html Guides on customizing agent prompts, instructions, and goals. ```APIDOC ## Customization Guides ### Prompt Customization Guide #### Overview Explains how to customize prompts for agent patterns. #### Method N/A (Guide Overview) #### Endpoint N/A (Guide Overview) #### Parameters N/A (Guide Overview) #### Request Body N/A (Guide Overview) #### Response N/A (Guide Overview) ### Custom Instructions Deep Dive #### Overview In-depth guide on using and implementing custom instructions. #### How Custom Instructions Work Details the mechanism by which custom instructions influence agent behavior. ### Prompt Overrides Deep Dive #### Overview Explains how to override default prompt behavior. #### Finding Step Names Provides methods for identifying the names of steps within patterns for targeted overrides. ### Setting Agent Goals #### Overview Guide on defining and managing agent goals. #### Goal-Setting Methods Describes various approaches to setting goals for agents. ### Configuration Guide #### Overview Instructions on configuring agent patterns and LLM providers. #### LLM Configuration Structure Details the structure of the configuration dictionary for LLM providers. #### Model Parameters Lists and describes available parameters for configuring LLM models. ``` -------------------------------- ### Initialize ReActAgent with Customizations Source: https://agent-patterns.readthedocs.io/en/latest/api/base-agent.html Example of initializing a ReActAgent with custom LLM configurations, prompt directory, instructions, and prompt overrides. ```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." } } ) ``` -------------------------------- ### Ensure Pip is Installed or Use Python's Pip Module Source: https://agent-patterns.readthedocs.io/en/latest/installation.html Troubleshooting command to install pip if it's not found or to use the python -m pip command for package installation. ```bash python -m ensurepip --default-pip # or python -m pip install agent-patterns ``` -------------------------------- ### Example LLM Configuration Source: https://agent-patterns.readthedocs.io/en/latest/api/types.html Instantiate `LLMConfig` with specific provider and model details. Ensure all required fields are present. ```python llm_config: LLMConfig = { "provider": "openai", "model_name": "gpt-4-turbo", "temperature": 0.7, "max_tokens": 2000, } ``` -------------------------------- ### ReAct Agent Initialization and Invocation Example Source: https://agent-patterns.readthedocs.io/en/latest/concepts/architecture.html An example demonstrating the lifecycle of a ReAct agent, from initialization with LLM configurations and tools to invocation with a user query and the resulting internal execution flow. ```python # 1. User creates agent agent = ReActAgent( llm_configs={"thinking": {...}}, tools={"search": search_fn}, max_iterations=5 ) # → build_graph() called automatically # 2. User invokes agent result = agent.run("What is the weather in Paris?") # 3. Internal execution: initial_state = { "input": "What is the weather in Paris?", "thought": "", "action": {}, "observation": None, "intermediate_steps": [], "final_answer": None, "iteration_count": 0, "max_iterations": 5, } # Graph executes: # thought_step → action_step → observation_step → decision # ↑ ↓ # └──────────────────┘ # (loop if continue) # 4. Result extracted result = final_state["final_answer"] # → "The weather in Paris is..." ```