Agentic Architecture Pattern: Community

Written by

in


    """
Pattern 37: Community Pattern

Agents form communities based on shared interests, goals, or characteristics.
Social structures with norms, reputation, and collective identity emerge organically.
"""

from typing import Dict, Any, List, Optional, Set
from dataclasses import dataclass, field
from datetime import datetime
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI


@dataclass
class CommunityMember:
    """Member of a community."""
    name: str
    interests: List[str]
    reputation: float = 0.5  # 0.0-1.0
    contributions: int = 0
    communities: Set[str] = field(default_factory=set)


@dataclass
class Community:
    """A community of agents."""
    name: str
    focus: str
    members: Set[str] = field(default_factory=set)
    norms: List[str] = field(default_factory=list)
    events: List[Dict[str, Any]] = field(default_factory=list)


class CommunityPattern:
    """
    Community Pattern - Social organization around shared interests.
    
    Features:
    - Interest-based clustering
    - Reputation systems
    - Community norms
    - Collective activities
    - Inter-community connections
    """
    
    def __init__(self, model_name: str = "gpt-4"):
        self.llm = ChatOpenAI(model=model_name, temperature=0.7)
        self.members: Dict[str, CommunityMember] = {}
        self.communities: Dict[str, Community] = {}
    
    def add_member(self, member: CommunityMember):
        """Add member to the system."""
        self.members[member.name] = member
        print(f"✓ Added member: {member.name} - Interests: {', '.join(member.interests)}")
    
    def create_community(self, name: str, focus: str, norms: List[str]) -> Community:
        """Create a new community."""
        community = Community(name, focus, norms=norms)
        self.communities[name] = community
        print(f"✓ Created community: {name} (Focus: {focus})")
        return community
    
    def join_community(self, member_name: str, community_name: str) -> bool:
        """Member joins a community."""
        if member_name in self.members and community_name in self.communities:
            self.members[member_name].communities.add(community_name)
            self.communities[community_name].members.add(member_name)
            print(f"✓ {member_name} joined {community_name}")
            return True
        return False
    
    def suggest_communities(self, member_name: str) -> List[str]:
        """Suggest communities based on interests."""
        if member_name not in self.members:
            return []
        
        member = self.members[member_name]
        suggestions = []
        
        for comm_name, comm in self.communities.items():
            if comm_name not in member.communities:
                # Check interest overlap
                if any(interest.lower() in comm.focus.lower() 
                      for interest in member.interests):
                    suggestions.append(comm_name)
        
        return suggestions
    
    def contribute(self, member_name: str, community_name: str, contribution: str):
        """Member contributes to community."""
        if member_name in self.members and community_name in self.communities:
            member = self.members[member_name]
            community = self.communities[community_name]
            
            member.contributions += 1
            member.reputation = min(1.0, member.reputation + 0.05)
            
            event = {
                "type": "contribution",
                "member": member_name,
                "description": contribution,
                "timestamp": datetime.now()
            }
            community.events.append(event)
            
            print(f"✓ {member_name} contributed to {community_name}: {contribution}")
            print(f"  Reputation: {member.reputation:.2f}")
    
    def organize_event(self, community_name: str, event_description: str) -> Dict[str, Any]:
        """Community organizes an event."""
        if community_name not in self.communities:
            return {}
        
        community = self.communities[community_name]
        event = {
            "type": "event",
            "community": community_name,
            "description": event_description,
            "participants": list(community.members),
            "timestamp": datetime.now()
        }
        community.events.append(event)
        
        return event
    
    def get_top_contributors(self, community_name: str, n: int = 3) -> List[Dict[str, Any]]:
        """Get top contributors in a community."""
        if community_name not in self.communities:
            return []
        
        community = self.communities[community_name]
        members = [self.members[m] for m in community.members if m in self.members]
        members.sort(key=lambda x: (x.contributions, x.reputation), reverse=True)
        
        return [
            {"name": m.name, "contributions": m.contributions, "reputation": m.reputation}
            for m in members[:n]
        ]
    
    def run(self, scenario: str) -> Dict[str, Any]:
        """Execute community scenario."""
        total_events = sum(len(c.events) for c in self.communities.values())
        avg_community_size = sum(len(c.members) for c in self.communities.values()) / len(self.communities) if self.communities else 0
        
        return {
            "pattern": "Community",
            "scenario": scenario,
            "members": len(self.members),
            "communities": len(self.communities),
            "total_events": total_events,
            "avg_community_size": avg_community_size
        }


# Example usage
if __name__ == "__main__":
    print("=== Community Pattern Demo ===\n")
    
    pattern = CommunityPattern()
    
    # Add members
    print("--- Adding Members ---")
    members = [
        CommunityMember("Alice", ["Python", "AI", "Open Source"]),
        CommunityMember("Bob", ["Design", "UX", "Open Source"]),
        CommunityMember("Carol", ["Python", "Data Science", "Research"]),
        CommunityMember("David", ["AI", "Research", "Ethics"]),
    ]
    
    for member in members:
        pattern.add_member(member)
    
    # Create communities
    print("\n--- Creating Communities ---")
    pattern.create_community("PythonDevs", "Python Programming", 
                            ["Share knowledge", "Help beginners", "Code quality"])
    pattern.create_community("AIResearchers", "AI and Machine Learning",
                            ["Peer review", "Reproducibility", "Ethical AI"])
    pattern.create_community("OpenSourceContributors", "Open Source Development",
                            ["Collaboration", "Documentation", "Community-first"])
    
    # Members join communities
    print("\n--- Members Joining Communities ---")
    pattern.join_community("Alice", "PythonDevs")
    pattern.join_community("Alice", "OpenSourceContributors")
    pattern.join_community("Carol", "PythonDevs")
    pattern.join_community("David", "AIResearchers")
    
    # Suggest communities
    print("\n--- Community Suggestions ---")
    for member_name in ["Bob", "Carol"]:
        suggestions = pattern.suggest_communities(member_name)
        if suggestions:
            print(f"{member_name} might like: {', '.join(suggestions)}")
    
    # Member contributions
    print("\n--- Member Contributions ---")
    pattern.contribute("Alice", "PythonDevs", "Wrote tutorial on async programming")
    pattern.contribute("Carol", "PythonDevs", "Fixed bugs in pandas integration")
    pattern.contribute("David", "AIResearchers", "Published ethics framework")
    pattern.contribute("Alice", "PythonDevs", "Mentored 3 new members")
    
    # Organize community events
    print("\n--- Community Events ---")
    event = pattern.organize_event("PythonDevs", "Weekly coding meetup")
    print(f"✓ Event in {event['community']}: {event['description']}")
    print(f"  Participants: {', '.join(event['participants'])}")
    
    # Top contributors
    print("\n--- Top Contributors ---")
    top = pattern.get_top_contributors("PythonDevs")
    for i, contributor in enumerate(top, 1):
        print(f"{i}. {contributor['name']}: {contributor['contributions']} contributions, "
              f"reputation {contributor['reputation']:.2f}")
    
    # Summary
    print("\n--- Summary ---")
    result = pattern.run("Developer communities")
    print(f"Total Members: {result['members']}")
    print(f"Total Communities: {result['communities']}")
    print(f"Total Events: {result['total_events']}")
    print(f"Avg Community Size: {result['avg_community_size']:.1f}")
    result = pattern.run("Test input")
    print(f"Result: {result}")

    

Agentic Architecture Pattern: Community

Pattern 37: 37 Community – Line-by-Line Explanation

Overview

Pattern 37: Community Pattern

Agents form communities based on shared interests, goals, or characteristics. Social structures with norms, reputation, and collective identity emerge organically.


Code Structure Analysis

File Information

  • Pattern Number: 37
  • Pattern Name: 37 Community
  • File Path: patterns\organizational\37_community.py
  • Total Lines: 226

Detailed Code Explanation

Module Docstring

"""
Pattern 37: Community Pattern

Agents form communities based on shared interests, goals, or characteristics.
Social structures with norms, reputation, and collective identity emerge organically.
"""

Explanation: This module docstring describes the purpose and key features of the 37 Community pattern.


Imports Section

from typing import Dict, Any, List, Optional, Set
from dataclasses import dataclass, field
from datetime import datetime
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI  # First 20 imports shown

Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional, Set: 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_core.prompts import ChatPromptTemplate: LangChain framework integration – from langchain_openai import ChatOpenAI: LangChain framework integration


Classes

CommunityMember (Line 16)

Description: Member of a community.

Community (Line 26)

Description: A community of agents.

CommunityPattern (Line 35)

Description: Community Pattern – Social organization around shared interests.

Features: – Interest-based clustering – Reputation systems – Community norms – Collective activities – Inter-community connections

Methods:

__init__ (Line 47)
def __init__(self, model_name):
    """No method docstring."""

Purpose: No method docstring.

Parameters: – self: Instance reference – model_name: LLM model to use (e.g., “gpt-4”)

add_member (Line 52)
def add_member(self, member):
    """Add member to the system."""

Purpose: Add member to the system.

Parameters: – self: Instance reference – member: Parameter for member

create_community (Line 57)
def create_community(self, name, focus, norms):
    """Create a new community."""

Purpose: Create a new community.

Parameters: – self: Instance reference – name: Identifier or label – focus: Parameter for focus – norms: Parameter for norms

join_community (Line 64)
def join_community(self, member_name, community_name):
    """Member joins a community."""

Purpose: Member joins a community.

Parameters: – self: Instance reference – member_name: Parameter for member_name – community_name: Parameter for community_name

suggest_communities (Line 73)
def suggest_communities(self, member_name):
    """Suggest communities based on interests."""

Purpose: Suggest communities based on interests.

Parameters: – self: Instance reference – member_name: Parameter for member_name

contribute (Line 90)
def contribute(self, member_name, community_name, contribution):
    """Member contributes to community."""

Purpose: Member contributes to community.

Parameters: – self: Instance reference – member_name: Parameter for member_name – community_name: Parameter for community_name – contribution: Parameter for contribution

organize_event (Line 110)
def organize_event(self, community_name, event_description):
    """Community organizes an event."""

Purpose: Community organizes an event.

Parameters: – self: Instance reference – community_name: Parameter for community_name – event_description: Parameter for event_description

get_top_contributors (Line 127)
def get_top_contributors(self, community_name, n):
    """Get top contributors in a community."""

Purpose: Get top contributors in a community.

Parameters: – self: Instance reference – community_name: Parameter for community_name – n: Parameter for n

run (Line 141)
def run(self, scenario):
    """Execute community scenario."""

Purpose: Execute community scenario.

Parameters: – self: Instance reference – scenario: Parameter for scenario


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 = CommunityMember(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

Comments

Leave a Reply

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