"""
ADDER+ Prompt Builder - Agent Orchestration Platform
This module provides utilities for constructing ADDER+ prompts with proper
formatting and agent context injection for multi-agent coordination.
Architecture Integration:
- Design Pattern: Builder pattern for flexible prompt construction
- Context Injection: Agent name and session context integration
- Performance Profile: O(1) prompt construction with template caching
Technical Decisions:
- Template-based approach for consistency
- Context-aware prompt customization
- Minimal prompt for reduced token usage
- Structured format for agent parsing
Author: ADDER_5 | Created: 2025-06-26 | Last Modified: 2025-06-26
"""
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Optional
from src.models.agent import AgentSpecialization
from src.models.session import SessionContext
from .contracts_shim import ensure, require
@dataclass
class ADDERPromptContext:
"""Context for ADDER+ prompt construction."""
agent_name: str
session_id: str
session_root: Path
specialization: Optional[AgentSpecialization] = None
priority: str = "MEDIUM"
sender: str = "Orchestration Controller"
additional_context: Dict[str, Any] = None
class ADDERPromptBuilder:
"""
Builder for ADDER+ system prompts and message formatting.
Constructs properly formatted ADDER+ prompts with agent context
injection for effective multi-agent coordination.
Contracts:
Preconditions:
- Agent name must be valid Agent_# format
- Context must contain required fields
Postconditions:
- Prompt includes agent identification
- Context properly injected
- Format parseable by agents
Invariants:
- Template structure maintained
- No injection vulnerabilities
- Consistent formatting
"""
# Base ADDER+ prompt template
BASE_PROMPT_TEMPLATE = """You are {agent_name}. Please execute the following task:
# ELITE CODE AGENT: ADDER+ Task Assignment
<task_metadata>
**Agent**: {agent_name}
**Session**: {session_id}
**Priority**: {priority}
**Timestamp**: {timestamp}
**Sender**: {sender}
**Working Directory**: {session_root}
{additional_metadata}
</task_metadata>
<task_context>
You are operating within the session context at: {session_root}
{specialization_context}
{additional_context}
</task_context>
<task_instruction>
{message}
</task_instruction>
<execution_requirements>
- Follow ADDER+ methodology for all implementations
- Update TODO.md and task files as you progress
- Use advanced techniques: contracts, defensive programming, type safety
- Maintain modularity with <250 lines per module
- Create comprehensive tests for all code
- Document architectural decisions
</execution_requirements>
Remember to track your progress in the task management system and coordinate with other agents as needed.
"""
# Minimal prompt template for simple messages
MINIMAL_PROMPT_TEMPLATE = """# Task for {agent_name}
**From**: {sender} | **Priority**: {priority} | **Time**: {timestamp}
{message}
---
Working directory: {session_root}
"""
# Specialization contexts
SPECIALIZATION_CONTEXTS = {
AgentSpecialization.FRONTEND: "You are specialized in frontend development with expertise in React, TypeScript, and modern UI/UX patterns.",
AgentSpecialization.BACKEND: "You are specialized in backend development with expertise in APIs, databases, and distributed systems.",
AgentSpecialization.TESTING: "You are specialized in testing with expertise in unit tests, integration tests, and property-based testing.",
AgentSpecialization.DEVOPS: "You are specialized in DevOps with expertise in CI/CD, containerization, and infrastructure as code.",
AgentSpecialization.SECURITY: "You are specialized in security with expertise in threat modeling, secure coding, and penetration testing.",
AgentSpecialization.DOCUMENTATION: "You are specialized in documentation with expertise in technical writing, API docs, and architecture diagrams.",
}
def __init__(self):
"""Initialize ADDER+ prompt builder."""
self._template_cache = {}
@require(lambda self, context, message: context.agent_name and message)
@ensure(lambda result, *args: isinstance(result, str) and len(result) > 0)
def build_task_prompt(
self, context: ADDERPromptContext, message: str, use_minimal: bool = False
) -> str:
"""
Build ADDER+ task prompt with context injection.
Args:
context: ADDER+ prompt context with agent details
message: Task message to deliver
use_minimal: Use minimal prompt format
Returns:
Formatted ADDER+ prompt ready for agent delivery
"""
template = (
self.MINIMAL_PROMPT_TEMPLATE if use_minimal else self.BASE_PROMPT_TEMPLATE
)
# Build additional metadata
additional_metadata = ""
if context.additional_context:
for key, value in context.additional_context.items():
additional_metadata += f"\n**{key}**: {value}"
# Build specialization context
specialization_context = ""
if context.specialization:
specialization_context = self.SPECIALIZATION_CONTEXTS.get(
context.specialization,
f"You are specialized in {context.specialization.value}.",
)
# Format additional context
additional_context = ""
if (
context.additional_context
and "task_dependencies" in context.additional_context
):
deps = context.additional_context["task_dependencies"]
additional_context = f"This task depends on: {', '.join(deps)}"
# Build prompt from template
prompt = template.format(
agent_name=context.agent_name,
session_id=context.session_id,
session_root=context.session_root,
priority=context.priority,
timestamp=datetime.utcnow().isoformat(),
sender=context.sender,
message=message,
additional_metadata=additional_metadata,
specialization_context=specialization_context,
additional_context=additional_context,
)
return prompt.strip()
def build_coordination_message(
self,
source_agent: str,
target_agent: str,
message: str,
coordination_type: str = "TASK_HANDOFF",
) -> str:
"""
Build inter-agent coordination message.
Args:
source_agent: Agent sending the message
target_agent: Agent receiving the message
message: Coordination message content
coordination_type: Type of coordination
Returns:
Formatted coordination message
"""
template = """# Inter-Agent Coordination
**Type**: {coordination_type}
**From**: {source_agent}
**To**: {target_agent}
**Time**: {timestamp}
## Message
{message}
---
Please acknowledge receipt and provide status update.
"""
return template.format(
coordination_type=coordination_type,
source_agent=source_agent,
target_agent=target_agent,
timestamp=datetime.utcnow().isoformat(),
message=message,
).strip()
def build_status_query(self, agent_name: str, query_type: str = "GENERAL") -> str:
"""
Build status query message for agent.
Args:
agent_name: Target agent name
query_type: Type of status query
Returns:
Formatted status query message
"""
queries = {
"GENERAL": "Please provide your current task status and progress.",
"DETAILED": "Please provide detailed status including: current task, completion percentage, blockers, and next steps.",
"HEALTH": "Please confirm you are operational and provide system resource usage.",
"TASK_LIST": "Please list all your assigned tasks and their current status.",
}
query = queries.get(query_type, queries["GENERAL"])
return f"""# Status Query for {agent_name}
{query}
Please respond in structured format."""
def extract_agent_name(self, prompt: str) -> Optional[str]:
"""
Extract agent name from ADDER+ prompt.
Args:
prompt: ADDER+ formatted prompt
Returns:
Agent name if found, None otherwise
"""
import re
# Try multiple patterns
patterns = [
r"You are (Agent_\d+)",
r"\*\*Agent\*\*: (Agent_\d+)",
r"# Task for (Agent_\d+)",
r"FOR (Agent_\d+)",
]
for pattern in patterns:
match = re.search(pattern, prompt)
if match:
return match.group(1)
return None
# Singleton instance
_prompt_builder = ADDERPromptBuilder()
def build_adder_task_prompt(
agent_name: str,
message: str,
session_id: str,
session_root: Path,
specialization: Optional[AgentSpecialization] = None,
priority: str = "MEDIUM",
additional_context: Optional[Dict[str, Any]] = None,
use_minimal: bool = False,
) -> str:
"""
Convenience function to build ADDER+ task prompt.
Args:
agent_name: Target agent name
message: Task message
session_id: Current session ID
session_root: Session root directory
specialization: Agent specialization
priority: Task priority
additional_context: Additional context
use_minimal: Use minimal format
Returns:
Formatted ADDER+ prompt
"""
context = ADDERPromptContext(
agent_name=agent_name,
session_id=session_id,
session_root=session_root,
specialization=specialization,
priority=priority,
additional_context=additional_context,
)
return _prompt_builder.build_task_prompt(context, message, use_minimal)
def build_coordination_message(
source_agent: str,
target_agent: str,
message: str,
coordination_type: str = "TASK_HANDOFF",
) -> str:
"""
Convenience function to build coordination message.
Args:
source_agent: Source agent name
target_agent: Target agent name
message: Coordination message
coordination_type: Type of coordination
Returns:
Formatted coordination message
"""
return _prompt_builder.build_coordination_message(
source_agent, target_agent, message, coordination_type
)
# Export public API
__all__ = [
"ADDERPromptBuilder",
"ADDERPromptContext",
"build_adder_task_prompt",
"build_coordination_message",
]