Agentic Design Pattern: Contextual Adaptation

Written by

in


    """
Pattern 113: Contextual Adaptation

Description:
    Contextual Adaptation enables agents to dynamically adjust their behavior,
    communication style, and strategies based on the detected context. The
    pattern monitors multiple context dimensions (user preferences, environment,
    task type, constraints) and adapts agent behavior accordingly.
    
    This pattern is essential for creating flexible, user-friendly agents that
    can operate effectively across diverse situations and user needs. It combines
    context detection, preference learning, and dynamic behavior adjustment.

Key Components:
    1. Context Detector: Identifies current context dimensions
    2. Preference Learner: Learns user/situation preferences
    3. Behavior Adapter: Adjusts agent behavior
    4. Style Adapter: Modifies communication style
    5. Strategy Selector: Chooses appropriate strategies
    6. Constraint Manager: Handles situational constraints

Context Dimensions:
    - User: Experience level, preferences, goals
    - Environment: Location, time, available resources
    - Task: Type, complexity, urgency, importance
    - Social: Formality, relationship, cultural context
    - Technical: Device, bandwidth, capabilities
    - Domain: Field-specific conventions and norms

Use Cases:
    - Personalized assistants
    - Adaptive learning systems
    - Multi-domain chatbots
    - Context-aware recommendations
    - International applications

LangChain Implementation:
    Uses dynamic prompting, context tracking, and conditional routing to
    adapt agent behavior based on detected context.
"""

import os
from typing import List, Dict, Any, Optional
from dotenv import load_dotenv
from datetime import datetime
from enum import Enum

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
from langchain.memory import ConversationBufferMemory

load_dotenv()


class UserExperience(Enum):
    """User experience levels"""
    BEGINNER = "beginner"
    INTERMEDIATE = "intermediate"
    ADVANCED = "advanced"
    EXPERT = "expert"


class Formality(Enum):
    """Communication formality levels"""
    CASUAL = "casual"
    NEUTRAL = "neutral"
    FORMAL = "formal"
    VERY_FORMAL = "very_formal"


class TaskUrgency(Enum):
    """Task urgency levels"""
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"


class Context:
    """Represents current context"""
    
    def __init__(self):
        # User context
        self.user_experience = UserExperience.INTERMEDIATE
        self.user_preferences = {}
        self.user_goals = []
        
        # Environment context
        self.time_of_day = "morning"
        self.location = "office"
        self.available_resources = []
        
        # Task context
        self.task_type = "general"
        self.task_complexity = "medium"
        self.task_urgency = TaskUrgency.MEDIUM
        
        # Social context
        self.formality = Formality.NEUTRAL
        self.relationship = "professional"
        
        # Technical context
        self.device = "desktop"
        self.bandwidth = "high"
        
        # Domain context
        self.domain = "general"
        self.domain_conventions = {}
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert context to dictionary"""
        return {
            "user": {
                "experience": self.user_experience.value,
                "preferences": self.user_preferences,
                "goals": self.user_goals
            },
            "environment": {
                "time": self.time_of_day,
                "location": self.location,
                "resources": self.available_resources
            },
            "task": {
                "type": self.task_type,
                "complexity": self.task_complexity,
                "urgency": self.task_urgency.value
            },
            "social": {
                "formality": self.formality.value,
                "relationship": self.relationship
            },
            "technical": {
                "device": self.device,
                "bandwidth": self.bandwidth
            },
            "domain": {
                "name": self.domain,
                "conventions": self.domain_conventions
            }
        }
    
    def summarize(self) -> str:
        """Generate human-readable context summary"""
        return f"""
Current Context:
- User: {self.user_experience.value} level, wants {', '.join(self.user_goals) if self.user_goals else 'assistance'}
- Environment: {self.time_of_day} at {self.location}
- Task: {self.task_type} ({self.task_complexity} complexity, {self.task_urgency.value} urgency)
- Communication: {self.formality.value} style, {self.relationship} relationship
- Technical: {self.device} with {self.bandwidth} bandwidth
- Domain: {self.domain}
"""


class ContextualAdaptationAgent:
    """Agent that adapts behavior based on context"""
    
    def __init__(self, model_name: str = "gpt-4"):
        self.llm = ChatOpenAI(model=model_name, temperature=0.7)
        self.context = Context()
        self.memory = ConversationBufferMemory(return_messages=True)
        
        # Adaptive response generation
        self.adaptive_prompt = ChatPromptTemplate.from_messages([
            ("system", """You are an adaptive AI assistant that adjusts your behavior based on context.

{context_summary}

Adaptation Guidelines:
- For beginners: Use simple language, explain concepts, provide examples
- For experts: Be concise, use technical terms, assume background knowledge
- For casual contexts: Be friendly and conversational
- For formal contexts: Be professional and structured
- For urgent tasks: Be direct and action-oriented
- For complex tasks: Break down steps and provide detailed guidance

Adapt your response to match the context appropriately."""),
            ("human", "{query}")
        ])
        
        # Context detection prompt
        self.context_detector = ChatPromptTemplate.from_messages([
            ("system", """Analyze the user's query and extract context information.

Determine:
1. User experience level (beginner/intermediate/advanced/expert)
2. Formality expected (casual/neutral/formal/very_formal)
3. Task urgency (low/medium/high/critical)
4. Task type and complexity

Return JSON with: experience, formality, urgency, task_type, complexity"""),
            ("human", "{query}")
        ])
        
        self.response_chain = self.adaptive_prompt | self.llm | StrOutputParser()
        self.detector_chain = self.context_detector | self.llm | JsonOutputParser()
    
    def detect_context(self, query: str) -> Dict[str, Any]:
        """Detect context from user query"""
        try:
            detected = self.detector_chain.invoke({"query": query})
            
            # Update context based on detection
            if "experience" in detected:
                exp_map = {
                    "beginner": UserExperience.BEGINNER,
                    "intermediate": UserExperience.INTERMEDIATE,
                    "advanced": UserExperience.ADVANCED,
                    "expert": UserExperience.EXPERT
                }
                self.context.user_experience = exp_map.get(
                    detected["experience"], UserExperience.INTERMEDIATE
                )
            
            if "formality" in detected:
                form_map = {
                    "casual": Formality.CASUAL,
                    "neutral": Formality.NEUTRAL,
                    "formal": Formality.FORMAL,
                    "very_formal": Formality.VERY_FORMAL
                }
                self.context.formality = form_map.get(
                    detected["formality"], Formality.NEUTRAL
                )
            
            if "urgency" in detected:
                urg_map = {
                    "low": TaskUrgency.LOW,
                    "medium": TaskUrgency.MEDIUM,
                    "high": TaskUrgency.HIGH,
                    "critical": TaskUrgency.CRITICAL
                }
                self.context.task_urgency = urg_map.get(
                    detected["urgency"], TaskUrgency.MEDIUM
                )
            
            if "task_type" in detected:
                self.context.task_type = detected["task_type"]
            
            if "complexity" in detected:
                self.context.task_complexity = detected["complexity"]
            
            return detected
        except Exception as e:
            print(f"Context detection error: {e}")
            return {}
    
    def update_context(self, updates: Dict[str, Any]):
        """Manually update context"""
        for key, value in updates.items():
            if hasattr(self.context, key):
                setattr(self.context, key, value)
    
    def respond(self, query: str, auto_detect: bool = True) -> Dict[str, Any]:
        """Generate context-adapted response"""
        print(f"\n{'='*60}")
        print(f"Query: {query}")
        print(f"{'='*60}")
        
        # Auto-detect context if enabled
        if auto_detect:
            detected = self.detect_context(query)
            print(f"\nDetected context: {detected}")
        
        # Show current context
        print(self.context.summarize())
        
        # Generate adapted response
        response = self.response_chain.invoke({
            "context_summary": self.context.summarize(),
            "query": query
        })
        
        print(f"\nAdapted Response:")
        print(response)
        
        return {
            "query": query,
            "context": self.context.to_dict(),
            "response": response,
            "timestamp": datetime.now().isoformat()
        }
    
    def demonstrate_adaptation(self, query: str, contexts: List[Dict[str, Any]]):
        """Demonstrate how response changes with different contexts"""
        print(f"\n{'='*70}")
        print(f"Demonstrating Context Adaptation")
        print(f"Query: {query}")
        print(f"{'='*70}")
        
        responses = []
        for i, context_updates in enumerate(contexts, 1):
            print(f"\n--- Context {i}: {context_updates.get('description', '')} ---")
            
            # Reset context
            self.context = Context()
            
            # Apply updates
            for key, value in context_updates.items():
                if key != "description" and hasattr(self.context, key):
                    setattr(self.context, key, value)
            
            # Generate response
            result = self.respond(query, auto_detect=False)
            responses.append(result)
        
        return responses


def demonstrate_contextual_adaptation():
    """Demonstrate contextual adaptation pattern"""
    print("\n" + "="*70)
    print("CONTEXTUAL ADAPTATION DEMONSTRATION")
    print("="*70)
    
    agent = ContextualAdaptationAgent()
    
    # Example 1: Auto-detection of context
    print("\n" + "="*70)
    print("Example 1: Auto-Detection of Context")
    print("="*70)
    
    query1 = "I'm new to Python. Can you explain what a variable is?"
    result1 = agent.respond(query1, auto_detect=True)
    
    query2 = "Explain the time complexity of quicksort's partitioning scheme"
    result2 = agent.respond(query2, auto_detect=True)
    
    # Example 2: Adaptation to different user levels
    print("\n" + "="*70)
    print("Example 2: Adapting to User Experience Level")
    print("="*70)
    
    query = "How does machine learning work?"
    
    contexts = [
        {
            "description": "Beginner",
            "user_experience": UserExperience.BEGINNER,
            "formality": Formality.CASUAL
        },
        {
            "description": "Expert",
            "user_experience": UserExperience.EXPERT,
            "formality": Formality.NEUTRAL
        }
    ]
    
    responses = agent.demonstrate_adaptation(query, contexts)
    
    # Example 3: Adaptation to urgency
    print("\n" + "="*70)
    print("Example 3: Adapting to Task Urgency")
    print("="*70)
    
    query_urgent = "My server is down! How do I restart it?"
    
    contexts_urgent = [
        {
            "description": "Critical Urgency",
            "task_urgency": TaskUrgency.CRITICAL,
            "task_type": "troubleshooting"
        },
        {
            "description": "Low Urgency",
            "task_urgency": TaskUrgency.LOW,
            "task_type": "learning"
        }
    ]
    
    responses_urgent = agent.demonstrate_adaptation(query_urgent, contexts_urgent)
    
    # Example 4: Adaptation to formality
    print("\n" + "="*70)
    print("Example 4: Adapting to Formality Level")
    print("="*70)
    
    query_formal = "What are your capabilities?"
    
    contexts_formal = [
        {
            "description": "Casual",
            "formality": Formality.CASUAL,
            "relationship": "friendly"
        },
        {
            "description": "Very Formal",
            "formality": Formality.VERY_FORMAL,
            "relationship": "professional"
        }
    ]
    
    responses_formal = agent.demonstrate_adaptation(query_formal, contexts_formal)
    
    # Summary
    print("\n" + "="*70)
    print("SUMMARY")
    print("="*70)
    print("""
Contextual Adaptation Pattern demonstrated:

Key Features:
1. Context Detection - Automatically detect context from input
2. Multi-Dimensional Adaptation - Adapt across multiple context dimensions
3. Dynamic Behavior - Adjust communication style and strategy
4. User Personalization - Adapt to user experience and preferences
5. Situational Awareness - Respond appropriately to urgency and formality

Context Dimensions Handled:
- User experience level (beginner to expert)
- Communication formality (casual to very formal)
- Task urgency (low to critical)
- Task complexity and type
- Environment and technical constraints
- Domain-specific conventions

Applications:
- Personalized assistants adapting to user expertise
- Customer service bots adjusting tone
- Educational systems matching student level
- Multi-domain chatbots switching contexts
- International applications respecting cultural norms

Contextual adaptation makes agents more natural, effective, and user-friendly
by tailoring their behavior to the specific situation and user needs.
    """)


if __name__ == "__main__":
    demonstrate_contextual_adaptation()

    

Agentic Design Pattern: Contextual Adaptation

Pattern 113: Contextual Adaptation – Line-by-Line Explanation

Overview

This document provides a detailed line-by-line explanation of the Contextual Adaptation pattern implementation.


Pattern Description

Pattern 113: Contextual Adaptation

Description: Contextual Adaptation enables agents to dynamically adjust their behavior, communication style, and strategies based on the detected context. The pattern monitors multiple context dimensions (user preferences, environment, task type, constraints) and adapts agent behavior accordingly.

This pattern is essential for creating flexible, user-friendly agents that
can operate effectively across diverse situations and user needs. It combines
context detection, preference learning, and dynamic behavior adjustment.

Key Components: 1. Context Detector: Identifies current context dimensions 2. Preference Learner: Learns user/situation preferences 3. Behavior Adapter: Adjusts agent behavior 4. Style Adapter: Modifies communication style 5. Strategy Selector: Chooses appropriate strategies 6. Constraint Manager: Handles situational constraints

Context Dimensions: – User: Experience level, preferences, goals – Environment: Location, time, available resources – Task: Type, complexity, urgency, importance – Social: Formality, relationship, cultural context – Technical: Device, bandwidth, capabilities – Domain: Field-specific conventions and norms

Use Cases: – Personalized assistants – Adaptive learning systems – Multi-domain chatbots – Context-aware recommendations – International applications

LangChain Implementation: Uses dynamic prompting, context tracking, and conditional routing to adapt agent behavior based on detected context.


File Statistics

  • Total Lines: 432
  • Classes: 5
  • Functions: 1
  • Constants: 0

Module Documentation

"""
Pattern 113: Contextual Adaptation

Description:
    Contextual Adaptation enables agents to dynamically adjust their behavior,
    communication style, and strategies based on the detected context. The
    pattern monitors multiple context dimensions (user preferences, environment,
    task type, constraints) and adapts agent behavior accordingly.

    This pattern is essential for creating flexible, user-friendly agents that
    can operate effectively across diverse situations and user needs. It combines
    context detection, preference learning, and dynamic behavior adjustment.

Key Components:
    1. Context Detector: Identifies current context dimensions
    2. Preference Learner: Learns user/situation preferences
    3. Behavior Adapter: Adjusts agent behavior
    4. Style Adapter: Modifies communication style
    5. Strategy Selector: Chooses appropriate strategies
    6. Constraint Manager: Handles situational constraints

Context Dimensions:
    - User: Experience level, preferences, goals
    - Environment: Location, time, available resources
    - Task: Type, complexity, urgency, importance
    - Social: Formality, relationship, cultural context
    - Technical: Device, bandwidth, capabilities
    - Domain: Field-specific conventions and norms

Use Cases:
    - Personalized assistants
    - Adaptive learning systems
    - Multi-domain chatbots
    - Context-aware recommendations
    - International applications

LangChain Implementation:
    Uses dynamic prompting, context tracking, and conditional routing to
    adapt agent behavior based on detected context.
"""

Purpose: This module implements the Contextual Adaptation pattern, providing a structured approach to agent design and implementation.


Import Statements

Standard Library Imports

import datetime.datetime
import enum.Enum
import langchain_core.output_parsers.JsonOutputParser
import langchain_core.output_parsers.StrOutputParser
import langchain_core.prompts.ChatPromptTemplate
import os
import typing.Any
import typing.Dict
import typing.List
import typing.Optional

Purpose: Core Python functionality: – datetime.datetime: Date and time handling – enum.Enum: Enumeration support – langchain_core.output_parsers.JsonOutputParser: Regular expression operations – langchain_core.output_parsers.StrOutputParser: Regular expression operations – langchain_core.prompts.ChatPromptTemplate: Regular expression operations – os: Environment variable access and system operations – typing.Any: Type hints for better code documentation (List, Dict, Any, Optional) – typing.Dict: Type hints for better code documentation (List, Dict, Any, Optional) – typing.List: Type hints for better code documentation (List, Dict, Any, Optional) – typing.Optional: Type hints for better code documentation (List, Dict, Any, Optional)

LangChain Imports

from langchain.memory.ConversationBufferMemory
from langchain_openai.ChatOpenAI

Purpose: LangChain framework components: – LLM Interface: Wrapper for OpenAI models – Chains: Composable building blocks for complex workflows – Memory: State management across interactions

Other Imports

from dotenv.load_dotenv

Purpose: Additional dependencies for specialized functionality.


Classes

Class: UserExperience

Lines 56-61

Inherits from: Enum

Purpose:

User experience levels

Class: Formality

Lines 64-69

Inherits from: Enum

Purpose:

Communication formality levels

Class: TaskUrgency

Lines 72-77

Inherits from: Enum

Purpose:

Task urgency levels

Class: Context

Lines 80-153

Purpose:

Represents current context

Methods:

__init__(self)

Lines 83-109

Purpose: Initialize the class instance with required parameters.

Parameters:

to_dict(self)

Lines 111-141

Purpose:

Convert context to dictionary

Parameters:

Returns: <ast.Subscript object at 0x000001A06D798F90>

summarize(self)

Lines 143-153

Purpose:

Generate human-readable context summary

Parameters:

Returns: str


Class: ContextualAdaptationAgent

Lines 156-308

Purpose:

Agent that adapts behavior based on context

Methods:

__init__(self, model_name)

Lines 159-197

Purpose: Initialize the class instance with required parameters.

Parameters: – model_name: Language model instance

detect_context(self, query)

Lines 199-247

Purpose:

Detect context from user query

Parameters: – query: Input query or question

Returns: <ast.Subscript object at 0x000001A06D125F50>

update_context(self, updates)

Lines 249-253

Purpose:

Manually update context

Parameters: – updates: Updates

respond(self, query, auto_detect)

Lines 255-283

Purpose:

Generate context-adapted response

Parameters: – query: Input query or question – auto_detect: Auto detect

Returns: <ast.Subscript object at 0x000001A06D7FF950>

demonstrate_adaptation(self, query, contexts)

Lines 285-308

Purpose:

Demonstrate how response changes with different contexts

Parameters: – query: Input query or question – contexts: Contexts


Functions

demonstrate_contextual_adaptation()

Lines 311-427

Purpose:

Demonstrate contextual adaptation pattern

Key Concepts Summary

Pattern Overview

The Contextual Adaptation pattern provides a structured approach to building AI agents with specific capabilities and behaviors. This implementation leverages LangChain’s composable components to create a robust and maintainable solution.

Core Components

  1. Agent Class: Main implementation of the pattern logic
  2. Prompt Engineering: Carefully crafted prompts to guide LLM behavior
  3. Tool Integration: Optional tools for extended functionality
  4. Memory Management: State handling across interactions
  5. Output Parsing: Structured response processing

When to Use

✅ Good for: – Scenarios requiring this specific pattern’s strengths – Applications needing structured agent behavior – Systems where explainability is important – Production environments requiring reliability

❌ Not ideal for: – Simple single-prompt tasks – Scenarios requiring different pattern characteristics – Resource-constrained environments (if computationally intensive)


Best Practices Demonstrated

1. Environment Configuration

  • ✅ Use .env files for API keys
  • ✅ Never hardcode credentials
  • ✅ Validate environment variables on startup

2. Error Handling

  • ✅ Graceful degradation on failures
  • ✅ Informative error messages
  • ✅ Logging for debugging

3. Prompt Engineering

  • ✅ Clear, specific instructions
  • ✅ Structured output formats
  • ✅ Few-shot examples when beneficial

4. Code Organization

  • ✅ Separation of concerns (class-based design)
  • ✅ Type hints for clarity
  • ✅ Docstrings for documentation

5. Performance Optimization

  • ✅ Appropriate temperature settings
  • ✅ Token budget management
  • ✅ Caching where applicable

LangChain Components Used

  • ChatOpenAI: OpenAI model interface
  • Chains: Sequential component composition
  • Memory: Conversation state management

Why LangChain? – Composable abstractions for LLM applications – Rich ecosystem of integrations – Production-ready patterns – Active community and development


Execution Flow

1. Initialize agent with configuration
   ↓
2. Load environment and dependencies
   ↓
3. Prepare prompt with input data
   ↓
4. Invoke LLM through LangChain
   ↓
5. Parse and validate response
   ↓
6. Return formatted result

Key Decision Points: – Model selection (temperature, model type) – Prompt structure (few-shot vs zero-shot) – Error handling strategy – Output format validation


Performance Considerations

Computational Cost

  • LLM Calls: Primary cost factor (based on tokens)
  • Latency: Depends on model and input size
  • Memory: Minimal for most patterns

Optimization Strategies

  1. Prompt Optimization: Minimize tokens while maintaining clarity
  2. Caching: Cache repeated queries/responses
  3. Model Selection: Use smaller models when appropriate
  4. Batch Processing: Group similar requests
  5. Streaming: For long responses, stream tokens

Cost Estimates (Approximate)

  • GPT-3.5-turbo: ~$0.002 per request
  • GPT-4: ~$0.03 per request
  • GPT-4-turbo: ~$0.01 per request

Actual costs vary based on input/output token counts


Common Pitfalls to Avoid

1. Prompt Design Issues

❌ Vague or ambiguous instructions
✅ Clear, specific, testable prompts

2. Error Handling

❌ Ignoring API errors or rate limits
✅ Implement retry logic and graceful degradation

3. Token Management

❌ Exceeding model token limits
✅ Truncate inputs, chunk processing

4. Security

❌ Exposing API keys in code
✅ Use environment variables

5. Testing

❌ Only testing happy paths
✅ Test edge cases, failures, malformed inputs

6. Cost Management

❌ Unmonitored API usage
✅ Implement budgets, alerts, and monitoring


Further Improvements

Production Enhancements

  1. Monitoring: Add logging, metrics, tracing
  2. Validation: Input/output schema validation
  3. Rate Limiting: Implement request throttling
  4. Caching: Redis or in-memory cache for responses
  5. Async Support: Non-blocking operations for scalability

Feature Extensions

  1. Multi-Model Support: Switch between providers
  2. Fallback Models: Graceful degradation strategy
  3. Custom Tools: Domain-specific function calling
  4. Advanced Memory: Vector stores for long-term memory
  5. Evaluation: Automated testing and benchmarking

Code Quality

  1. Testing: Unit tests, integration tests
  2. Documentation: API docs, usage examples
  3. Type Safety: Stricter type hints
  4. Configuration: Externalized config files

Related Patterns

  • Pattern 112
  • Pattern 114

Pattern Families: – Reasoning Patterns (001-011) – Multi-Agent Patterns (012-019) – Tool Use Patterns (020-025) – Memory Patterns (026-031) – And many more…


Summary

The Contextual Adaptation pattern provides a powerful approach to building AI agents with specific capabilities. This implementation demonstrates:

✅ Key Strengths: – Clean, maintainable code structure – LangChain integration for composability – Type hints and documentation – Production-ready patterns

🎯 Best Use Cases: – Applications requiring this pattern’s characteristics – Systems needing structured agent behavior – Production environments requiring reliability

📚 Learning Resources: – LangChain Documentation: https://python.langchain.com/ – Pattern Documentation: See related patterns – OpenAI API Reference: https://platform.openai.com/docs/


File: 113_contextual_adaptation.py
Total Lines: 432
Pattern Category: AI Agent Design Pattern #113


Generated from actual implementation code
For educational and reference purposes

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *