Skip to main content

scripts-llm-abstractions

#!/usr/bin/env python3 """

title: "Convenience function for quick prompt building" component_type: script version: "1.0.0" audience: contributor status: stable summary: "LLM Abstractions Module" keywords: ['abstractions', 'generation', 'llm'] tokens: ~500 created: 2025-12-22 updated: 2025-12-22 script_name: "llm_abstractions.py" language: python executable: true usage: "python3 scripts/llm_abstractions.py [options]" python_version: "3.10+" dependencies: [] modifies_files: false network_access: false requires_auth: false

LLM Abstractions Module

CODITECT Framework - Common abstractions for LLM interactions including framework knowledge retrieval and system prompt building.

Author: CODITECT Framework Version: 1.0.0 """

import json import logging from pathlib import Path from typing import Any, Dict, List, Optional from dataclasses import dataclass, field

logger = logging.getLogger(name)

@dataclass class FrameworkKnowledge: """Container for framework knowledge and context."""

name: str
version: str
description: str
capabilities: List[str] = field(default_factory=list)
components: Dict[str, Any] = field(default_factory=dict)
metadata: Dict[str, Any] = field(default_factory=dict)

def get_framework_knowledge( framework_path: Optional[Path] = None, include_components: bool = True ) -> FrameworkKnowledge: """ Retrieve framework knowledge from CODITECT configuration.

Args:
framework_path: Path to framework root (defaults to coditect-core)
include_components: Whether to include component registry data

Returns:
FrameworkKnowledge object with framework details
"""
if framework_path is None:
# Default to coditect-core
framework_path = Path(__file__).parent.parent

knowledge = FrameworkKnowledge(
name="CODITECT",
version="1.0.0",
description="AI-powered development framework with distributed intelligence"
)

# Load capabilities from CLAUDE.md if available
claude_md = framework_path / 'CLAUDE.md'
if claude_md.exists():
content = claude_md.read_text()
knowledge.metadata['claude_md'] = True
knowledge.metadata['claude_md_size'] = len(content)

# Load component registry if requested
if include_components:
registry_path = framework_path / '.coditect' / 'component-activation-status.json'
if registry_path.exists():
try:
with open(registry_path) as f:
registry = json.load(f)
knowledge.components = {
'total': registry.get('activation_summary', {}).get('total_components', 0),
'activated': registry.get('activation_summary', {}).get('activated', 0),
}

# Count by type
type_counts = {}
for comp in registry.get('components', []):
t = comp.get('type', 'unknown')
type_counts[t] = type_counts.get(t, 0) + 1
knowledge.components['by_type'] = type_counts

except Exception as e:
logger.warning(f"Failed to load component registry: {e}")

# Set capabilities
knowledge.capabilities = [
"Multi-agent orchestration",
"Component activation management",
"Session context preservation",
"Distributed intelligence via symlinks",
"Production-ready code generation",
]

return knowledge

class SystemPromptBuilder: """Builder for constructing system prompts with framework context."""

def __init__(self, base_prompt: str = ""):
"""
Initialize the system prompt builder.

Args:
base_prompt: Initial base prompt text
"""
self.sections: List[str] = []
if base_prompt:
self.sections.append(base_prompt)
self._framework_knowledge: Optional[FrameworkKnowledge] = None

def add_section(self, title: str, content: str) -> "SystemPromptBuilder":
"""Add a titled section to the prompt."""
self.sections.append(f"## {title}\n\n{content}")
return self

def add_framework_context(
self,
framework_path: Optional[Path] = None
) -> "SystemPromptBuilder":
"""Add CODITECT framework context to the prompt."""
self._framework_knowledge = get_framework_knowledge(framework_path)

context = f"""## CODITECT Framework Context

Framework: {self._framework_knowledge.name} v{self._framework_knowledge.version} Description: {self._framework_knowledge.description}

Components:

  • Total: {self._framework_knowledge.components.get('total', 'N/A')}
  • Activated: {self._framework_knowledge.components.get('activated', 'N/A')}

Capabilities: {chr(10).join(f'- {cap}' for cap in self._framework_knowledge.capabilities)} """ self.sections.append(context) return self

def add_role(self, role: str, responsibilities: List[str]) -> "SystemPromptBuilder":
"""Add role definition to the prompt."""
resp_text = "\n".join(f"- {r}" for r in responsibilities)
self.sections.append(f"## Role: {role}\n\n**Responsibilities:**\n{resp_text}")
return self

def add_constraints(self, constraints: List[str]) -> "SystemPromptBuilder":
"""Add constraints/rules to the prompt."""
constraints_text = "\n".join(f"- {c}" for c in constraints)
self.sections.append(f"## Constraints\n\n{constraints_text}")
return self

def add_examples(self, examples: List[Dict[str, str]]) -> "SystemPromptBuilder":
"""Add examples to the prompt."""
examples_text = []
for i, ex in enumerate(examples, 1):
examples_text.append(f"### Example {i}")
if 'input' in ex:
examples_text.append(f"**Input:** {ex['input']}")
if 'output' in ex:
examples_text.append(f"**Output:** {ex['output']}")
examples_text.append("")

self.sections.append("## Examples\n\n" + "\n".join(examples_text))
return self

def build(self) -> str:
"""Build the final system prompt."""
return "\n\n".join(self.sections)

@property
def framework_knowledge(self) -> Optional[FrameworkKnowledge]:
"""Get the loaded framework knowledge if available."""
return self._framework_knowledge

Convenience function for quick prompt building

def build_agent_prompt( agent_name: str, description: str, capabilities: List[str], include_framework: bool = True ) -> str: """ Build a standard agent system prompt.

Args:
agent_name: Name of the agent
description: Agent description
capabilities: List of agent capabilities
include_framework: Whether to include framework context

Returns:
Complete system prompt string
"""
builder = SystemPromptBuilder()

builder.add_section("Agent Identity", f"You are **{agent_name}**.\n\n{description}")
builder.add_section("Capabilities", "\n".join(f"- {c}" for c in capabilities))

if include_framework:
builder.add_framework_context()

builder.add_constraints([
"Follow CODITECT standards and patterns",
"Maintain production-ready code quality",
"Document decisions and rationale",
"Use appropriate tools for each task",
])

return builder.build()