The context manager
The context manager is the second most important component of the Leclerk system, orchestrating all memory, state management, and conversation flow throughout the Clerk’s agentic loop.Context in the Clerk Loop
The context manager works hand-in-hand with the Clerk, managing the complete lifecycle of conversation state from initialization to cleanup.Step-by-Step Context Usage in Clerk Loop
1. Context Initialization
- Payload - Conversation and customer data
- Nexus Client - API communication
- Redis Client - State persistence
- Settings - Configuration parameters
2. Context Building (await context.build())
Key operations:
- Loads conversation history from database
- Builds system prompts with business rules
- Integrates customer preferences and order state
- Prepares tool definitions and guidelines
- Creates the complete message array for LLM
3. Loop Control Methods
context.restart_count()
Resets iteration counters at the start of each conversation turn:
_count = 0- Total iterations_tool_call_count = 0- Tool execution count_consecutive_tool_calls = {}- Per-tool consecutive calls
context.increment_count()
Increments counters for each iteration:
- Tracks loop iterations for stopping conditions
- Monitors tool usage patterns
- Enables loop termination logic
context.stopping_condition()
Determines when to exit the agentic loop based on:
- Maximum iteration limits (
_max_iterations = 10) - Consecutive tool call limits (
_max_consecutive_calls = 4) - Tool execution patterns
- Error conditions
4. Message Management During Iterations
Context message operations:context.messages- Current conversation threadadd_assistant_message_to_context()- Adds LLM responsesadd_tool_result_to_context()- Adds tool execution results- Messages accumulate throughout the loop for context continuity
5. Tool Registration and Tracking
Tool Call Registration
- Tool execution frequency
- Consecutive calls per tool type
- Tool arguments for audit trail
- Nexus integration for persistence
Tool Result Registration
- Result persistence to database
- Change detection for duplicate results
- Nexus instruction processing
- Error state management
6. Response Registration
- Extracts customer-facing content from LLM response
- Registers assistant messages with Nexus
- Handles XML tag parsing for clean customer communication
- Updates conversation state
7. Context Synchronization
- Fetches new messages from Redis queue
- Handles concurrent message scenarios
- Updates conversation state
- Manages race condition resolution
8. Context Cleanup
- Removes Redis conversation locks
- Persists final conversation state
- Returns formatted customer response
- Handles cleanup errors gracefully
Context State Management
Local Context (context.messages)
Maintains the current conversation thread including:
- System prompts and instructions
- User messages and responses
- Assistant responses with tool calls
- Tool execution results
- Nexus instructions
Persistent Context (via Nexus)
Manages long-term conversation data:- Customer profiles and preferences
- Order drafts and transaction state
- Conversation history across sessions
- Business context and settings
Concurrent Context (via Redis)
Handles real-time synchronization:- Message queuing for concurrent requests
- Conversation locking mechanisms
- State synchronization across instances
- Race condition prevention
Error Handling and Recovery
LLM Error Handling
- Logs LLM failures for debugging
- Maintains conversation continuity
- Enables graceful degradation
- Preserves context state
Tool Error Handling
- Individual tool failures don’t break the loop
- Tool results include error information
- Context continues with error responses
- Failed tools are tracked and logged
Context Performance Optimization
Message History Management
- Intelligent message truncation for token limits
- Context compression for long conversations
- Strategic message selection for relevance
- Memory-efficient state management
Caching and Persistence
- Redis for session-level caching
- Database for permanent state
- Context serialization optimization
- Lazy loading of business context