Skip to content

Latest commit

 

History

History
425 lines (304 loc) · 13.8 KB

File metadata and controls

425 lines (304 loc) · 13.8 KB

Specialized Agents

Overview

Beyond the core orchestration and pipeline agents, ISC-CodeConnect employs several specialized agents that handle specific system functions, advanced analysis tasks, and support operations. These agents provide crucial functionality for code analysis, error handling, conversation management, and system optimization.

Code Analysis Agents

Context Analyzer Agent

Location: src/agents/analysis_agents.py:429
Function: analyze_context_needs()

Purpose

Decomposes complex Salesforce implementation queries into logical, executable steps with targeted retrieval strategies.

Key Capabilities

Query Decomposition
  • Step-Based Analysis: Breaks queries into implementation phases
  • Collection Mapping: Maps requirements to specific code collections
  • Priority Assignment: Assigns search priorities (high/medium/low)
  • Test Context Filtering: Automatically filters test-related content for non-test queries
Structured Output Processing
class ContextAnalysisResult(BaseModel):
    steps: List[AnalysisStep] = Field(
        description="List of implementation steps with their queries"
    )

class AnalysisStep(BaseModel):
    step: str = Field(description="Description of the implementation step")
    queries: List[QueryInfo] = Field(description="List of queries for this step")

Implementation Strategy

  • LLM-Driven Decomposition: Uses structured LLM output for consistent query generation
  • Deduplication Logic: Prevents redundant search queries
  • Fallback Mechanisms: Provides default queries when decomposition fails
  • Context Awareness: Considers conversation history and query patterns

LWC Context Analyzer Agent

Location: src/agents/analysis_agents.py:575
Function: analyze_lwc_context_needs()

Purpose

Specialized analyzer for Lightning Web Component requests with Carbon Design System awareness.

Key Features

Carbon Component Detection
def identify_carbon_components(query: str) -> List[str]:
    """Enhanced Carbon Design System component identification"""
    carbon_components = {
        "table": "c-carbon-data-table",
        "button": "c-carbon-button",
        "form": "c-carbon-form",
        "dropdown": "c-carbon-dropdown",
        # ... comprehensive mapping
    }
Multi-Layer Analysis
  • HTML Template Patterns: Identifies UI structure requirements
  • JavaScript Controller Needs: Determines event handling and data management
  • Apex Backend Dependencies: Analyzes server-side integration requirements
  • Carbon Pattern Matching: Maps UI elements to Carbon Design System components

Output Structure

class LWCContextAnalysisResult(BaseModel):
    steps: List[LWCAnalysisStep] = Field(
        description="List of implementation steps with their queries"
    )

class LWCAnalysisStep(BaseModel):
    step: str = Field(description="Description of the implementation step")
    queries: List[LWCQueryInfo] = Field(description="List of queries for this step")

Code Explanation Agent

Location: src/agents/analysis_agents.py:2014
Function: explain_code()

Purpose

Provides comprehensive code explanations with context-aware analysis for both Apex and LWC components.

Key Capabilities

Multi-Platform Support
  • Apex Code Analysis: Deep analysis of classes, triggers, and test classes
  • LWC Component Analysis: Comprehensive component breakdown (HTML, JS, Apex)
  • Carbon Design Integration: Explains Carbon pattern usage and implementation
Context Processing Pipeline
# Context building strategy
if analysis["is_lwc"]:
    # Process LWC chunks with Carbon awareness
    primary_chunks = chunks.get("primary_chunks", {})

    # Process JS chunks
    if primary_chunks.get("js"):
        js_context = await _process_lwc_chunks({"js": primary_chunks["js"]})

    # Process HTML chunks
    if primary_chunks.get("html"):
        html_context = await _process_lwc_chunks({"html": primary_chunks["html"]})

    # Process Apex dependencies
    if primary_chunks.get("apex_dependencies"):
        apex_context = await _process_apex_chunks(primary_chunks["apex_dependencies"])
Advanced Features
  • Continuation Support: Handles interrupted explanations
  • Implementation Guide Integration: Uses comprehensive prompts for architectural guidance
  • Performance Metrics: Tracks context processing efficiency
  • Multi-Collection Awareness: Processes related code from multiple collections

System Support Agents

Error Handler Agent

Location: src/agents/error_agent.py
Function: handle_error()

Purpose

Provides intelligent error recovery with fallback mechanisms and user-friendly error messaging.

Error Recovery Strategy

Loop Prevention System
# Check for loop prevention - track error handler invocations
error_count = state.get("error_handler_count", 0) + 1
max_error_attempts = 3  # Maximum allowed error handler attempts

# If we've exceeded maximum error attempts, end gracefully
if error_count >= max_error_attempts:
    friendly_error_message = await generate_llm_error_response(
        error_location, error_message, config
    )
    return {
        "messages": friendly_error_message,
        "current_agent": "end",
        "error_handler_count": error_count,
    }
Intelligent Fallback
  • General Query Processor Routing: Routes to general processor for error recovery
  • Context Preservation: Maintains original query and error context
  • Loop Detection: Prevents infinite error cycles between agents
  • LLM Error Translation: Converts technical errors to user-friendly messages
Error Message Generation
async def generate_llm_error_response(error_location: str, error_message: str, config=RunnableConfig) -> str:
    """Use LLM to generate friendly, informative error message"""
    prompt = f"""Create a friendly, concise error message that:
    1. Acknowledges the error in simple terms
    2. Briefly explains what might have gone wrong
    3. Suggests 1-2 specific actions the user could take
    4. Maintains a helpful, supportive tone"""

Chat Handler Agent

Location: src/agents/chat_handler.py
Function: handle_chat_query()

Purpose

Manages conversational interactions, distinguishing between casual chat and technical queries.

Chat Analysis System

Query Classification
class ChatAnalysisResult(BaseModel):
    type: str
    requires_query_extraction: bool = False
    history_analysis_type: Optional[str] = None
    technical_context: Optional[Dict] = None
Interaction Types
  • Regular Chat: Greetings, thanks, casual conversation
  • Technical Queries: Salesforce-specific development questions
  • History Analysis: Questions about previous conversation context
Intelligent Routing
# Check if we need to reroute to technical handler
if analysis["type"] == "technical":
    if analysis.get("technical_context"):
        tech_context = analysis["technical_context"]
        # Update state analysis with technical context
        state["analysis"].update({
            "query_type": "technical",
            "is_apex": tech_context.get("is_apex", False),
            "is_lwc": tech_context.get("is_lwc", False),
            "is_test_class": tech_context.get("is_test", False),
            "operation_type": tech_context.get("operation", "query"),
        })
        return {
            "current_agent": "router",  # Return to router for technical handling
            "requires_reanalysis": True,
        }

General Query Processor Agent

Location: src/agents/query_processor.py
Function: process_general_query()

Purpose

Handles general code queries with multi-collection retrieval and error fallback support.

Advanced Features

Collection Intelligence
COLLECTION_CONTEXT = {
    "apex": {
        "collections": ["apex_code", "apex_test_code"],
        "keywords": ["class", "trigger", "apex", "test class", "handler", "service"]
    },
    "lwc": {
        "collections": ["lwc_js_code", "lwc_html_code", "lwc_test_code"],
        "keywords": ["lwc", "component", "lightning", "template", "javascript"]
    }
}

def _identify_collections(query: str, conversation_history: List = None) -> List[str]:
    """Identify required collections based on query and conversation context"""
Error Fallback Integration
  • Error Context Handling: Processes queries routed from error handler
  • Continuation Support: Handles interrupted or incomplete responses
  • Multi-Collection Search: Searches across relevant code collections
  • Conversation Context: Maintains conversation flow and context

Continuation Handler Agent

Location: src/agents/continuation_handler.py
Function: is_continuation_request()

Purpose

Intelligently detects genuine continuation requests versus modification or enhancement requests.

Detection Strategy

Pattern Analysis
async def is_continuation_request(query: str) -> bool:
    """Enhanced detection of genuine continuation requests"""

    # Preprocessing to check for strong continuation indicators
    explicit_continue_phrases = [
        "you were cut off",
        "got cut off",
        "continue from where",
        "finish generating",
        "complete the rest",
        "proceed with the remaining"
    ]

    # Check for modification indicators that should return False
    modification_indicators = [
        "add", "modify", "update", "change",
        "enhance", "improve", "refine", "refactor"
    ]
LLM-Powered Classification
  • Context-Aware Analysis: Distinguishes continuation from modification
  • Intent Recognition: Identifies genuine interruption vs enhancement requests
  • Binary Classification: Returns clear true/false decisions
  • Fallback Logic: Handles edge cases with explicit pattern matching

Advanced Retrieval Agents

Multi-Collection Retrieval Agent

Location: src/agents/retrieval_agents.py
Functions: Multiple specialized retrieval functions

Purpose

Provides sophisticated, context-aware retrieval across multiple code collections with intelligent chunking and ranking.

Specialized Retrieval Functions

Apex Retrieval (retrieve_apex_chunks)
  • Context-Aware Search: Searches across apex_code and apex_test_code collections
  • Parallel Processing: Executes multiple queries simultaneously
  • Intelligent Ranking: Uses FlashRank for result optimization
  • Chunk Processing: Applies contextual chunk management
LWC Retrieval (retrieve_lwc_chunks)
  • Multi-Layer Retrieval: Searches HTML, JS, and Apex dependency collections
  • Carbon Pattern Integration: Includes Carbon Design System patterns
  • Component-Aware Processing: Understands LWC component structure
  • Cross-Reference Analysis: Links related component files
Test Context Retrieval (retrieve_apex_test_context)
  • Test-Specific Search: Focuses on test implementation patterns
  • Coverage Analysis: Identifies test coverage strategies
  • Mock Pattern Retrieval: Finds stubbing and mocking examples
  • Assertion Pattern Matching: Locates appropriate assertion strategies

Evaluation Agent

Location: src/agents/evaluation_agent.py
Function: evaluate_response()

Purpose

Evaluates generated responses for quality, completeness, and production readiness with improvement recommendations.

Evaluation Framework

Quality Metrics
"evaluation": {
    "correctness": 0-10,
    "completeness": 0-10,
    "best_practices": 0-10,
    "error_handling": 0-10,
    "documentation": 0-10
}
Improvement Analysis
  • Gap Identification: Identifies missing components or patterns
  • Additional Context Needs: Determines what additional information is required
  • Collection Targeting: Specifies which collections to query for improvements
  • Query Generation: Creates specific search queries for enhancement
Production Readiness Assessment
  • Code Quality Verification: Checks adherence to best practices
  • Error Handling Review: Evaluates exception management
  • Documentation Completeness: Assesses code documentation quality
  • Security Pattern Analysis: Reviews security implementation

Agent Integration Patterns

State Management

All specialized agents follow consistent state management patterns:

# Input state processing
original_query = state["query"] or state.get("original_query")
analysis = state.get("analysis", {})
chunks = state.get("retrieved_chunks", {})

# Output state updates
return {
    "current_agent": "next_agent",
    "processed_data": result,
    "error_context": error_info,  # if applicable
}

Error Handling

  • Graceful Degradation: All agents provide fallback mechanisms
  • Context Preservation: Maintains state through error scenarios
  • User Experience: Converts technical errors to friendly messages
  • Recovery Paths: Routes to appropriate recovery agents

Performance Optimization

  • Async Processing: All agents use async/await patterns
  • Parallel Execution: Multiple queries processed simultaneously
  • Context Caching: Intelligent caching of processed content
  • Memory Management: Efficient handling of large code chunks

Communication Protocols

  • Progress Events: Real-time progress updates via adispatch_custom_event
  • Logging Integration: Comprehensive logging with log_agent_step
  • State Updates: Structured state updates with log_state_update
  • Metrics Collection: Performance metrics gathering and reporting

These specialized agents form the backbone of ISC-CodeConnect's advanced functionality, providing intelligent analysis, robust error handling, sophisticated retrieval capabilities, and seamless user interactions that enhance the overall system performance and user experience.