"""
Pattern 27: Team-Based Pattern
Agents organized into formal teams with defined roles and responsibilities.
Teams have leaders, members, and coordinate to achieve team goals.
"""
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
class TeamRole(Enum):
"""Role within a team."""
LEADER = "leader"
MEMBER = "member"
SPECIALIST = "specialist"
COORDINATOR = "coordinator"
@dataclass
class TeamMember:
"""Member of a team."""
name: str
role: TeamRole
skills: List[str]
availability: float = 1.0 # 0.0 to 1.0
tasks_assigned: List[str] = field(default_factory=list)
@dataclass
class TeamTask:
"""Task assigned to team."""
task_id: str
description: str
required_skills: List[str]
assigned_to: Optional[str] = None
status: str = "pending" # pending, in_progress, completed
priority: int = 5 # 1-10
@dataclass
class Team:
"""Team of agents."""
team_id: str
name: str
purpose: str
members: List[TeamMember] = field(default_factory=list)
tasks: List[TeamTask] = field(default_factory=list)
achievements: List[str] = field(default_factory=list)
class TeamAgent:
"""Agent that works as part of a team."""
def __init__(self, name: str, role: TeamRole, skills: List[str], model_name: str = "gpt-4"):
self.member = TeamMember(name=name, role=role, skills=skills)
self.llm = ChatOpenAI(model=model_name, temperature=0.7)
def work_on_task(self, task: TeamTask, team: Team) -> str:
"""Work on assigned task."""
prompt = ChatPromptTemplate.from_messages([
("system", f"You are {self.member.name}, a {self.member.role.value} with skills: {', '.join(self.member.skills)}. "
f"You're part of team '{team.name}' working on: {team.purpose}"),
("human", f"Task: {task.description}\n"
f"Required skills: {', '.join(task.required_skills)}\n"
f"Priority: {task.priority}/10\n\n"
f"Describe your approach to completing this task (2-3 sentences).")
])
chain = prompt | self.llm
response = chain.invoke({})
return str(response.content)[:200]
def collaborate_with(self, other_member: TeamMember, context: str) -> str:
"""Collaborate with another team member."""
prompt = ChatPromptTemplate.from_messages([
("system", f"You are {self.member.name} collaborating with {other_member.name}."),
("human", f"Context: {context}\n\nHow will you work together? (brief response)")
])
chain = prompt | self.llm
response = chain.invoke({})
return str(response.content)[:150]
class TeamBasedPattern:
"""
Team-Based Pattern - Structured team organization and coordination.
Agents are organized into teams with formal roles and responsibilities.
Teams have leaders, coordinate work, and achieve collective goals.
"""
def __init__(self):
self.teams: Dict[str, Team] = {}
self.agents: Dict[str, TeamAgent] = {}
def create_team(self, team_id: str, name: str, purpose: str) -> Team:
"""Create a new team."""
team = Team(team_id=team_id, name=name, purpose=purpose)
self.teams[team_id] = team
return team
def add_member_to_team(self, team_id: str, agent: TeamAgent):
"""Add agent to team."""
if team_id in self.teams:
self.teams[team_id].members.append(agent.member)
self.agents[agent.member.name] = agent
def assign_task(self, team_id: str, task: TeamTask) -> bool:
"""Assign task to appropriate team member."""
if team_id not in self.teams:
return False
team = self.teams[team_id]
team.tasks.append(task)
# Find best member for task based on skills
best_member = None
best_match_score = 0
for member in team.members:
# Count matching skills
matches = sum(1 for skill in task.required_skills if skill in member.skills)
if matches > best_match_score and member.availability > 0.3:
best_match_score = matches
best_member = member
if best_member:
task.assigned_to = best_member.name
task.status = "in_progress"
best_member.tasks_assigned.append(task.task_id)
return True
return False
def execute_team_work(self, team_id: str) -> Dict[str, Any]:
"""Execute work for team."""
if team_id not in self.teams:
return {"success": False, "error": "Team not found"}
team = self.teams[team_id]
results = []
print(f"\n Team '{team.name}' working on: {team.purpose}")
# Execute tasks
for task in team.tasks:
if task.assigned_to and task.assigned_to in self.agents:
agent = self.agents[task.assigned_to]
print(f" - {task.assigned_to} working on: {task.description}")
work_result = agent.work_on_task(task, team)
results.append({
"task": task.task_id,
"member": task.assigned_to,
"result": work_result
})
task.status = "completed"
team.achievements.append(f"Completed: {task.description}")
# Team collaboration
if len(team.members) >= 2:
member1 = team.members[0]
member2 = team.members[1]
if member1.name in self.agents and member2.name in self.agents:
agent1 = self.agents[member1.name]
collab = agent1.collaborate_with(member2, f"Team goal: {team.purpose}")
print(f" - Collaboration: {collab[:80]}...")
return {
"success": True,
"team": team.name,
"tasks_completed": sum(1 for t in team.tasks if t.status == "completed"),
"achievements": len(team.achievements),
"results": results
}
def run(self, scenario: str) -> Dict[str, Any]:
"""Execute team-based pattern."""
total_tasks = sum(len(team.tasks) for team in self.teams.values())
completed_tasks = sum(
sum(1 for t in team.tasks if t.status == "completed")
for team in self.teams.values()
)
return {
"pattern": "TeamBased",
"total_teams": len(self.teams),
"total_agents": len(self.agents),
"total_tasks": total_tasks,
"completed_tasks": completed_tasks,
"scenario": scenario
}
# Example usage
if __name__ == "__main__":
print("=== Team-Based Pattern Demo ===\n")
# Create pattern
pattern = TeamBasedPattern()
# Create teams
print("1. Creating teams...")
dev_team = pattern.create_team("dev1", "Development Team", "Build mobile app")
design_team = pattern.create_team("design1", "Design Team", "Create UI/UX designs")
# Add members to development team
print("\n2. Adding team members...")
dev_lead = TeamAgent("Alice", TeamRole.LEADER, ["python", "architecture", "testing"])
backend_dev = TeamAgent("Bob", TeamRole.MEMBER, ["python", "databases", "APIs"])
frontend_dev = TeamAgent("Carol", TeamRole.MEMBER, ["javascript", "react", "CSS"])
pattern.add_member_to_team("dev1", dev_lead)
pattern.add_member_to_team("dev1", backend_dev)
pattern.add_member_to_team("dev1", frontend_dev)
# Add members to design team
design_lead = TeamAgent("Dave", TeamRole.LEADER, ["UI_design", "prototyping"])
ux_specialist = TeamAgent("Eve", TeamRole.SPECIALIST, ["UX_research", "user_testing"])
pattern.add_member_to_team("design1", design_lead)
pattern.add_member_to_team("design1", ux_specialist)
# Assign tasks
print("\n3. Assigning tasks...")
task1 = TeamTask("t1", "Implement authentication system", ["python", "security"], priority=9)
task2 = TeamTask("t2", "Build REST API", ["python", "APIs"], priority=8)
task3 = TeamTask("t3", "Create responsive UI", ["javascript", "CSS"], priority=7)
task4 = TeamTask("t4", "Design app mockups", ["UI_design", "prototyping"], priority=9)
task5 = TeamTask("t5", "Conduct user research", ["UX_research"], priority=6)
pattern.assign_task("dev1", task1)
pattern.assign_task("dev1", task2)
pattern.assign_task("dev1", task3)
pattern.assign_task("design1", task4)
pattern.assign_task("design1", task5)
# Execute team work
print("\n4. Executing team work...")
dev_result = pattern.execute_team_work("dev1")
design_result = pattern.execute_team_work("design1")
# Summary
print("\n5. Team Performance Summary:")
summary = pattern.run("Multi-team software development")
print(f" Total Teams: {summary['total_teams']}")
print(f" Total Agents: {summary['total_agents']}")
print(f" Tasks Completed: {summary['completed_tasks']}/{summary['total_tasks']}")
print("\nā Team-based pattern organized agents into effective teams!")
Agentic Architecture Pattern: Team Based
Pattern 27: 27 Team Based – Line-by-Line Explanation
Overview
Pattern 27: Team-Based Pattern
Agents organized into formal teams with defined roles and responsibilities. Teams have leaders, members, and coordinate to achieve team goals.
Code Structure Analysis
File Information
- Pattern Number: 27
- Pattern Name: 27 Team Based
- File Path:
patterns\collaboration\27_team_based.py - Total Lines: 258
Detailed Code Explanation
Module Docstring
"""
Pattern 27: Team-Based Pattern
Agents organized into formal teams with defined roles and responsibilities.
Teams have leaders, members, and coordinate to achieve team goals.
"""
Explanation: This module docstring describes the purpose and key features of the 27 Team Based pattern.
Imports Section
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
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: 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 enum import Enum: Enumeration support for fixed sets of values
– from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration
– from langchain_openai import ChatOpenAI: LangChain framework integration
Enumerations
TeamRole (Line 16)
class TeamRole(Enum):
LEADER
MEMBER
SPECIALIST
COORDINATOR
Purpose: Role within a team.
Values:
– LEADER: Represents leader
– MEMBER: Represents member
– SPECIALIST: Represents specialist
– COORDINATOR: Represents coordinator
Classes
TeamRole (Line 16)
Description: Role within a team.
TeamMember (Line 25)
Description: Member of a team.
TeamTask (Line 35)
Description: Task assigned to team.
Team (Line 46)
Description: Team of agents.
TeamAgent (Line 56)
Description: Agent that works as part of a team.
Methods:
__init__ (Line 59)
def __init__(self, name, role, skills, model_name):
"""No method docstring."""
Purpose: No method docstring.
Parameters:
– self: Instance reference
– name: Identifier or label
– role: Parameter for role
– skills: Parameter for skills
– model_name: LLM model to use (e.g., “gpt-4”)
work_on_task (Line 63)
def work_on_task(self, task, team):
"""Work on assigned task."""
Purpose: Work on assigned task.
Parameters:
– self: Instance reference
– task: Parameter for task
– team: Parameter for team
collaborate_with (Line 78)
def collaborate_with(self, other_member, context):
"""Collaborate with another team member."""
Purpose: Collaborate with another team member.
Parameters:
– self: Instance reference
– other_member: Parameter for other_member
– context: Parameter for context
TeamBasedPattern (Line 90)
Description: Team-Based Pattern – Structured team organization and coordination.
Agents are organized into teams with formal roles and responsibilities. Teams have leaders, coordinate work, and achieve collective goals.
Methods:
__init__ (Line 98)
def __init__(self):
"""No method docstring."""
Purpose: No method docstring.
Parameters:
– self: Instance reference
create_team (Line 102)
def create_team(self, team_id, name, purpose):
"""Create a new team."""
Purpose: Create a new team.
Parameters:
– self: Instance reference
– team_id: Parameter for team_id
– name: Identifier or label
– purpose: Parameter for purpose
add_member_to_team (Line 108)
def add_member_to_team(self, team_id, agent):
"""Add agent to team."""
Purpose: Add agent to team.
Parameters:
– self: Instance reference
– team_id: Parameter for team_id
– agent: Parameter for agent
assign_task (Line 114)
def assign_task(self, team_id, task):
"""Assign task to appropriate team member."""
Purpose: Assign task to appropriate team member.
Parameters:
– self: Instance reference
– team_id: Parameter for team_id
– task: Parameter for task
execute_team_work (Line 141)
def execute_team_work(self, team_id):
"""Execute work for team."""
Purpose: Execute work for team.
Parameters:
– self: Instance reference
– team_id: Parameter for team_id
run (Line 184)
def run(self, scenario):
"""Execute team-based pattern."""
Purpose: Execute team-based pattern.
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 = TeamRole(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