API Reference
Complete API reference for the Agent Patterns library.
Overview
The Agent Patterns library is organized into three main modules:
agent_patterns.core- Base classes and core infrastructureagent_patterns.patterns- All 9 agent pattern implementationsagent_patterns.prompts- Prompt templates for each pattern
Quick Links
BaseAgent - Abstract base class for all patterns
Pattern APIs - Complete reference for all 9 patterns
Type Definitions - Type hints and data structures
Import Structure
# Import specific patterns
from agent_patterns.patterns import (
ReActAgent,
ReflectionAgent,
SelfDiscoveryAgent,
STORMAgent,
PlanAndSolveAgent,
ReflexionAgent,
REWOOAgent,
LATSAgent,
LLMCompilerAgent
)
# Import base classes (for extending)
from agent_patterns.core import BaseAgent, MultiAgentBase
Common Patterns
Basic Usage
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")
With Customization
agent = ReflectionAgent(
llm_configs=llm_configs,
max_reflection_cycles=2,
custom_instructions="Domain-specific guidelines",
prompt_overrides={"Generate": {"system": "...", "user": "..."}}
)
Core Classes
BaseAgent
Abstract base class for all agent patterns.
class BaseAgent(ABC):
def __init__(
self,
llm_configs: Dict[str, Dict[str, Any]],
prompt_dir: str = "prompts",
custom_instructions: Optional[str] = None,
prompt_overrides: Optional[Dict[str, Dict[str, str]]] = None
)
@abstractmethod
def build_graph(self) -> None:
"""Build the LangGraph state graph"""
@abstractmethod
def run(self, input_data: Any) -> Any:
"""Execute the pattern"""
Pattern Classes
All pattern classes inherit from BaseAgent and implement the same interface:
Class |
LLM Roles |
Key Parameters |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
None |
|
|
|
|
|
|
|
|
|
|
|
|
See: Pattern APIs
Type Definitions
LLM Configuration
from typing import Dict, Any
LLMConfig = Dict[str, Any]
# Example:
{
"provider": "openai", # or "anthropic"
"model": "gpt-4",
"temperature": 0.7,
"max_tokens": 2000,
"api_key": "...", # optional, reads from env
}
LLMConfigs = Dict[str, LLMConfig]
# Example:
{
"thinking": {"provider": "openai", "model": "gpt-4"},
"execution": {"provider": "openai", "model": "gpt-3.5-turbo"}
}
Prompt Overrides
from typing import Dict, Optional
PromptOverrides = Optional[Dict[str, Dict[str, str]]]
# Example:
{
"StepName": {
"system": "System prompt content",
"user": "User prompt template with {placeholders}"
}
}
Tool Definition
from typing import Callable
Tool = Callable[[str], str]
# Tools must:
# - Take string parameters
# - Return string results
# - Have clear docstrings
Tools = Dict[str, Tool]
See: Type Definitions
Common Parameters
All patterns support these parameters:
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
Yes |
LLM configuration for each role |
|
|
No |
Custom prompt directory (default: “prompts”) |
|
|
No |
Instructions appended to system prompts |
|
|
No |
Override specific prompts |
LLM Providers
OpenAI
llm_config = {
"provider": "openai",
"model": "gpt-4", # or gpt-3.5-turbo, gpt-4-turbo, etc.
"temperature": 0.7,
"max_tokens": 2000,
"api_key": "sk-...", # optional, defaults to OPENAI_API_KEY env var
}
Anthropic
llm_config = {
"provider": "anthropic",
"model": "claude-3-opus-20240229", # or claude-3-sonnet, etc.
"temperature": 0.7,
"max_tokens": 2000,
"api_key": "sk-ant-...", # optional, defaults to ANTHROPIC_API_KEY env var
}
Error Handling
All patterns may raise:
ValueError- Invalid configuration or parametersRuntimeError- Execution errorsProvider-specific exceptions (OpenAI, Anthropic)
from agent_patterns.patterns import ReflectionAgent
try:
agent = ReflectionAgent(llm_configs=llm_configs)
result = agent.run("task")
except ValueError as e:
print(f"Configuration error: {e}")
except RuntimeError as e:
print(f"Execution error: {e}")
Lifecycle Hooks
BaseAgent provides lifecycle hooks for monitoring:
class CustomAgent(BaseAgent):
def on_start(self, input_data: Any) -> None:
"""Called before execution starts"""
print(f"Starting with: {input_data}")
def on_finish(self, result: Any) -> None:
"""Called after successful completion"""
print(f"Finished with: {result}")
def on_error(self, error: Exception) -> None:
"""Called when an error occurs"""
print(f"Error: {error}")
Advanced Usage
Custom Pattern Creation
from agent_patterns.core import BaseAgent
from langgraph.graph import StateGraph, END
class MyCustomAgent(BaseAgent):
def build_graph(self) -> None:
workflow = StateGraph(dict)
# Build your graph
self.graph = workflow.compile()
def run(self, input_data: str) -> str:
if self.graph is None:
raise ValueError("Graph not built")
result = self.graph.invoke({"input": input_data})
return result.get("output")
Pattern Composition
# Sequential composition
storm_agent = STORMAgent(...)
reflection_agent = ReflectionAgent(...)
research = storm_agent.run("Topic")
polished = reflection_agent.run(f"Polish this: {research}")
See: Best Practices Guide
Next Steps
BaseAgent API - Detailed base class documentation
Pattern APIs - All pattern class references
Type Definitions - Type hints and structures
Configuration Guide - LLM setup
Extending Patterns - Create custom patterns