"""
Pattern 81: Interface Agent Pattern
Purpose: Agent that provides interface to external systems
"""
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from datetime import datetime
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
@dataclass
class InterfaceRequest:
"""A request through interface."""
id: str
system: str
operation: str
parameters: Dict[str, Any]
timestamp: datetime = field(default_factory=datetime.now)
@dataclass
class InterfaceResponse:
"""Response from interface."""
request_id: str
status: str
data: Any
error: Optional[str] = None
timestamp: datetime = field(default_factory=datetime.now)
class InterfaceAgent:
"""
Interface Agent - Bridges AI agents and external systems
Provides standardized interface to external systems,
handles protocol translation, and manages communication.
"""
def __init__(self, name: str, systems: List[str], model_name: str = "gpt-4"):
self.name = name
self.systems = systems
self.llm = ChatOpenAI(model=model_name, temperature=0.5)
self.requests: List[InterfaceRequest] = []
self.responses: List[InterfaceResponse] = []
def can_interface(self, system: str) -> bool:
"""Check if agent can interface with system."""
return system in self.systems
def send_request(self, request: InterfaceRequest) -> InterfaceResponse:
"""Send request to external system."""
self.requests.append(request)
if not self.can_interface(request.system):
response = InterfaceResponse(
request_id=request.id,
status="error",
data=None,
error=f"Cannot interface with {request.system}"
)
self.responses.append(response)
return response
# Simulate interfacing with LLM
prompt = ChatPromptTemplate.from_messages([
("system", f"You are interfacing with {request.system}. Translate and execute request."),
("human", "Operation: {operation}\nParameters: {parameters}")
])
chain = prompt | self.llm
result = chain.invoke({
"operation": request.operation,
"parameters": str(request.parameters)
})
response = InterfaceResponse(
request_id=request.id,
status="success",
data=str(result.content)
)
self.responses.append(response)
return response
def get_stats(self) -> Dict[str, Any]:
"""Get interface statistics."""
success_count = sum(1 for r in self.responses if r.status == "success")
return {
"agent": self.name,
"systems": self.systems,
"total_requests": len(self.requests),
"successful": success_count,
"success_rate": success_count / len(self.responses) if self.responses else 0
}
class InterfaceAgentPattern:
"""Interface Agent Pattern - Manages interface agents."""
def __init__(self):
self.agents: Dict[str, InterfaceAgent] = {}
def register_agent(self, agent: InterfaceAgent):
"""Register interface agent."""
self.agents[agent.name] = agent
print(f"✓ Registered: {agent.name} (systems: {', '.join(agent.systems)})")
def find_agent_for_system(self, system: str) -> Optional[InterfaceAgent]:
"""Find agent that can interface with system."""
for agent in self.agents.values():
if agent.can_interface(system):
return agent
return None
def execute_request(self, system: str, operation: str, parameters: Dict[str, Any]) -> InterfaceResponse:
"""Execute request on external system."""
agent = self.find_agent_for_system(system)
if not agent:
return InterfaceResponse(
request_id="no_agent",
status="error",
data=None,
error=f"No agent for system {system}"
)
request = InterfaceRequest(
id=f"req_{len(agent.requests) + 1}",
system=system,
operation=operation,
parameters=parameters
)
return agent.send_request(request)
def run(self, requests: List[tuple]) -> Dict[str, Any]:
"""Execute multiple interface requests."""
results = []
for system, operation, parameters in requests:
response = self.execute_request(system, operation, parameters)
results.append({
"system": system,
"operation": operation,
"status": response.status,
"data": response.data[:100] if response.data else None,
"error": response.error
})
return {
"pattern": "InterfaceAgent",
"total_requests": len(requests),
"results": results
}
if __name__ == "__main__":
print("=== Interface Agent Pattern Demo ===\n")
pattern = InterfaceAgentPattern()
# Register interface agents
pattern.register_agent(InterfaceAgent("DatabaseAgent", ["PostgreSQL", "MongoDB"]))
pattern.register_agent(InterfaceAgent("APIAgent", ["REST", "GraphQL"]))
pattern.register_agent(InterfaceAgent("FileAgent", ["S3", "FileSystem"]))
print("\nExecuting requests...\n")
requests = [
("PostgreSQL", "query", {"sql": "SELECT * FROM users"}),
("REST", "get", {"endpoint": "/api/users"}),
("S3", "upload", {"bucket": "data", "file": "report.pdf"}),
]
summary = pattern.run(requests)
print(f"Pattern: {summary['pattern']}")
print(f"Total Requests: {summary['total_requests']}\n")
print("Results:")
for result in summary['results']:
status_icon = "✓" if result['status'] == "success" else "✗"
print(f" {status_icon} {result['system']}.{result['operation']}: {result['data'] or result['error']}")
Agentic Architecture Pattern: Interface Agent
Pattern 81: 81 Interface Agent – Line-by-Line Explanation
Overview
Pattern 81: Interface Agent Pattern Purpose: Agent that provides interface to external systems
Code Structure Analysis
File Information
- Pattern Number: 81
- Pattern Name: 81 Interface Agent
- File Path:
patterns\specialized_agent\81_interface_agent.py - Total Lines: 186
Detailed Code Explanation
Module Docstring
"""
Pattern 81: Interface Agent Pattern
Purpose: Agent that provides interface to external systems
"""
Explanation: This module docstring describes the purpose and key features of the 81 Interface Agent pattern.
Imports Section
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from datetime import datetime
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate # First 20 imports shown
Explanation: The module imports necessary dependencies:
– from typing import Dict, Any, List, Optional: Type hints for better code documentation
– from dataclasses import dataclass, field: Data class decorators for clean data structures
– from datetime import datetime: Date and time utilities
– from langchain_openai import ChatOpenAI: LangChain framework integration
– from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration
Classes
InterfaceRequest (Line 14)
Description: A request through interface.
InterfaceResponse (Line 24)
Description: Response from interface.
InterfaceAgent (Line 33)
Description: Interface Agent – Bridges AI agents and external systems
Provides standardized interface to external systems, handles protocol translation, and manages communication.
Methods:
__init__ (Line 41)
def __init__(self, name, systems, model_name):
"""No method docstring."""
Purpose: No method docstring.
Parameters:
– self: Instance reference
– name: Identifier or label
– systems: Parameter for systems
– model_name: LLM model to use (e.g., “gpt-4”)
can_interface (Line 48)
def can_interface(self, system):
"""Check if agent can interface with system."""
Purpose: Check if agent can interface with system.
Parameters:
– self: Instance reference
– system: Parameter for system
send_request (Line 52)
def send_request(self, request):
"""Send request to external system."""
Purpose: Send request to external system.
Parameters:
– self: Instance reference
– request: Parameter for request
get_stats (Line 87)
def get_stats(self):
"""Get interface statistics."""
Purpose: Get interface statistics.
Parameters:
– self: Instance reference
InterfaceAgentPattern (Line 100)
Description: Interface Agent Pattern – Manages interface agents.
Methods:
__init__ (Line 103)
def __init__(self):
"""No method docstring."""
Purpose: No method docstring.
Parameters:
– self: Instance reference
register_agent (Line 106)
def register_agent(self, agent):
"""Register interface agent."""
Purpose: Register interface agent.
Parameters:
– self: Instance reference
– agent: Parameter for agent
find_agent_for_system (Line 111)
def find_agent_for_system(self, system):
"""Find agent that can interface with system."""
Purpose: Find agent that can interface with system.
Parameters:
– self: Instance reference
– system: Parameter for system
execute_request (Line 118)
def execute_request(self, system, operation, parameters):
"""Execute request on external system."""
Purpose: Execute request on external system.
Parameters:
– self: Instance reference
– system: Parameter for system
– operation: Parameter for operation
– parameters: Parameter for parameters
run (Line 139)
def run(self, requests):
"""Execute multiple interface requests."""
Purpose: Execute multiple interface requests.
Parameters:
– self: Instance reference
– requests: Parameter for requests
Design Patterns Used
- Strategy Pattern: Different execution strategies for various scenarios
- State Pattern: Managing different states in the workflow
- Chain of Responsibility: Sequential processing through workflow nodes
- Observer Pattern: Tracking and monitoring pattern execution
- Factory Pattern: Creating instances with proper configuration
Usage Example
# Initialize the pattern
pattern = InterfaceRequest(name="example", model_name="gpt-4")
# Configure and execute
result = pattern.execute(data={"key": "value"})
# Check results
print(result)
Key Concepts
- LLM Integration: Uses LangChain/OpenAI for intelligent decision-making
- Workflow Orchestration: LangGraph manages execution flow through nodes
- State Management: TypedDict defines workflow state structure
- Error Handling: Comprehensive error handling and fallback mechanisms
- Extensibility: Designed for easy customization and extension
Extension Points
This pattern can be extended by: 1. Adding custom workflow nodes 2. Implementing additional validation logic 3. Integrating with external services 4. Customizing LLM prompts and responses 5. Adding monitoring and logging capabilities
Leave a Reply