Template Method Pattern
Why Template Method for LLM?
Key LLM Use Cases
1. AI Agent Workflow Template
from abc import ABC, abstractmethod
class AIAgentTemplate(ABC):
"""Template for AI agent processing workflow"""
def process_request(self, user_input):
"""The template method defining the algorithm structure"""
# Step 1: Preprocess input
processed_input = self.preprocess_input(user_input)
# Step 2: Analyze and understand the request
analysis = self.analyze_request(processed_input)
# Step 3: Generate response using LLM
response = self.generate_response(analysis)
# Step 4: Post-process and validate response
final_response = self.postprocess_response(response)
# Step 5: Log and monitor
self.log_interaction(user_input, final_response)
return final_response
def preprocess_input(self, user_input):
"""Default preprocessing - can be overridden"""
return user_input.strip().lower()
@abstractmethod
def analyze_request(self, input_text):
"""Must be implemented by subclasses"""
pass
@abstractmethod
def generate_response(self, analysis):
"""Must be implemented by subclasses"""
pass
def postprocess_response(self, response):
"""Default post-processing - can be overridden"""
return response
def log_interaction(self, input_text, response):
"""Default logging - can be overridden"""
print(f"Input: {input_text[:50]}...")
print(f"Output: {response[:50]}...")
class CodeAssistantAgent(AIAgentTemplate):
def analyze_request(self, input_text):
# Analyze if it's a coding question
return {
"type": "coding",
"language": self.detect_language(input_text),
"complexity": self.assess_complexity(input_text)
}
def generate_response(self, analysis):
prompt = f"""
You are a coding assistant. Help with this {analysis['language']} question.
Complexity level: {analysis['complexity']}
Question: {analysis['input']}
Provide code examples and explanations.
"""
return self.llm.generate(prompt)
def detect_language(self, text):
# Language detection logic
return "python" # simplified
def assess_complexity(self, text):
# Complexity assessment logic
return "medium" # simplified
class MathTutorAgent(AIAgentTemplate):
def analyze_request(self, input_text):
return {
"type": "math",
"topic": self.identify_math_topic(input_text),
"level": self.assess_difficulty(input_text)
}
def generate_response(self, analysis):
prompt = f"""
You are a math tutor. Help with this {analysis['topic']} problem.
Difficulty level: {analysis['level']}
Problem: {analysis['input']}
Provide step-by-step solution and explanation.
"""
return self.llm.generate(prompt)2. RAG Pipeline Template
3. Multi-Modal Processing Template
4. Evaluation and Testing Template
Implementation Advantages
1. Code Reuse
2. Maintainability
3. Extensibility
4. Quality Assurance
Real-World Impact
Last updated