Skip to main content

Context Injection

Enhance your AI agent’s awareness with automatic contextual information
Context injection is a powerful system that automatically provides relevant information to your AI agent during conversations. This includes page metadata, user preferences, memories from previous interactions, and user click events—all injected seamlessly into the conversation flow.
Context injection is enabled by default to provide the best user experience. You can configure or disable specific features based on your needs.

Why Context Injection?

Traditional AI agents operate without awareness of their environment. Context injection solves this by:

Environmental Awareness

Automatically tracks page navigation and provides URL, title, and domain context

Memory Retrieval

Searches and injects relevant memories from previous interactions

User Interaction Tracking

Monitors and summarizes click events for proactive guidance

Quick Start

Context injection works out of the box with sensible defaults:
import { SammyAgentProvider } from '@sammy-labs/sammy-three';

// Context injection is enabled by default
<SammyAgentProvider config={config}>
  {children}
</SammyAgentProvider>

Configuration

The contextInjection prop accepts either a boolean for simple on/off control or an object for granular configuration:

Boolean Configuration

The simplest way to control context injection:
contextInjection: true   // Enable all features (default)
contextInjection: false  // Disable all features

Object Configuration

For fine-grained control over individual features:
enabled
boolean
default:"true"
required
Master switch that controls whether any context injection occurs. When false, all other settings are ignored.
Enables searching and injecting relevant memories from training data and previous interactions.
pageTracking
boolean
default:"true"
Tracks current page URL, title, domain, and path. Updates automatically on navigation.
clickTracking
boolean
default:"true"
Monitors user click events and injects summaries for proactive guidance.

Features in Detail

Memory Search & Injection

When enabled, the system automatically searches for relevant memories after user turns and injects them before the agent responds.
1

User Input Detection

System detects when user completes their turn (minimum 20 characters)
2

Memory Search

Searches memory backend for relevant context based on user input
3

Context Injection

Top 3 most relevant memories are formatted and injected into the conversation
4

Agent Response

Agent responds with awareness of the injected memories
Configuration:
contextInjection: {
  enabled: true,
  memorySearch: true  // Enable memory features
}
Memory injection only occurs after user turns to prevent infinite loops. The system tracks injected memories to avoid duplicates.

Page Context Tracking

Automatically tracks and injects page navigation context:
Page Context Structure
{
  url: "https://app.example.com/dashboard",
  title: "Dashboard - My App",
  domain: "app.example.com",
  path: "/dashboard"
}
The system injects this information:
  • Immediately when navigation occurs (URL changes)
  • Formatted as a navigation event similar to click events
  • Tracked in observability events
Navigation events are now injected as [NAVIGATION_EVENT] messages when the URL changes, providing a more consistent experience with click events. The agent receives contextual information about the new page to provide appropriate assistance.
Configuration:
contextInjection: {
  enabled: true,
  pageTracking: true  // Enable page tracking
}

Click Event Tracking

Monitors and aggregates user click events to provide interaction context:
  • How It Works
  • Injection Timing
  • Event Format
  1. Detection: Captures click events on truly interactive elements (buttons, links, forms, etc.)
  2. Filtering: By default, only processes clicks on interactable elements
  3. Aggregation: Groups related clicks within 500ms windows
  4. Summarization: Creates human-readable summaries
  5. Smart Timing: Injects at optimal moments based on conversation state
Configuration:
contextInjection: {
  enabled: true,
  clickTracking: true  // Enable click tracking
}
Advanced Click Detection Configuration: You can pass additional configuration to fine-tune click detection behavior:
const config = {
  auth: { /* ... */ },
  contextInjection: true,  // Uses default click detection settings
  clickDetection: {
    interactableOnly: true,    // Only track truly interactive elements (default: true)
    debugLogs: false,          // Enable debug logging (default: false)
    clickDebounceMs: 250,      // Minimum time between clicks (default: 250ms)
    aggregationWindowMs: 500,  // Time window to group clicks (default: 500ms)
    maxClicksPerWindow: 3,     // Max clicks per aggregation window (default: 3)
    significantClicksOnly: false // Only track significant clicks (default: false)
  }
};
The interactableOnly setting ensures only meaningful clicks are tracked. It filters clicks to elements like buttons, links, inputs, and elements with click handlers or ARIA roles. This reduces noise and improves the quality of context provided to the AI.
What Elements Are Considered Interactable? When interactableOnly is true (default), the system tracks clicks on:

HTML Elements

  • <a>, <button>, <input>
  • <select>, <textarea>, <label>
  • <details>, <summary>, <menu>
  • <embed>, <object>, <menuitem>

ARIA Roles

  • button, link, checkbox, radio
  • tab, menuitem, option, switch
  • slider, textbox, combobox
  • progressbar, scrollbar, tree
Additional criteria for interactable elements:
  • Elements with tabindex (except -1)
  • Elements with click handlers (onclick, @click, ng-click, etc.)
  • Elements with ARIA properties (aria-expanded, aria-pressed, etc.)
  • Draggable elements (draggable="true")
  • Content-editable elements (contenteditable)
The system also traverses up the DOM tree to find interactable parent elements, so clicks on button text or icons are properly captured.

Use Cases

Customer Support Agent

Full context awareness for comprehensive support:
const config = {
  auth: { /* ... */ },
  contextInjection: true  // All features enabled
};
Benefits:
  • Access to product knowledge through memories
  • Awareness of user’s current page
  • Understanding of user interactions

Documentation Helper

Page context only for documentation navigation:
const config = {
  auth: { /* ... */ },
  contextInjection: {
    enabled: true,
    memorySearch: false,   // No memory needed
    pageTracking: true,    // Track doc pages
    clickTracking: false   // No click tracking
  }
};
Benefits:
  • Knows which documentation page user is viewing
  • Can provide page-specific guidance
  • Lightweight without unnecessary features

Interactive Tutorial

Click and page tracking for guided experiences:
const config = {
  auth: { /* ... */ },
  contextInjection: {
    enabled: true,
    memorySearch: false,   // No memories needed
    pageTracking: true,    // Track progress
    clickTracking: true    // Monitor interactions
  },
  clickDetection: {
    interactableOnly: true,   // Focus on meaningful interactions
    significantClicksOnly: false // Track all interactive elements
  }
};
Benefits:
  • Tracks tutorial progression
  • Responds to user interactions
  • Provides contextual hints

Debugging User Interactions

For troubleshooting UI issues, you might want to track ALL clicks:
const config = {
  auth: { /* ... */ },
  contextInjection: true,
  clickDetection: {
    interactableOnly: false,  // Track ALL clicks, even on non-interactive elements
    debugLogs: true,          // Enable detailed logging
    aggregationWindowMs: 1000 // Longer window to catch related clicks
  }
};
Benefits:
  • Captures all user interactions for debugging
  • Helps identify dead zones or broken elements
  • Provides complete interaction telemetry

Simple Q&A Bot

Minimal configuration for basic interactions:
const config = {
  auth: { /* ... */ },
  contextInjection: false  // No context needed
};
Benefits:
  • Reduced latency
  • Lower resource usage
  • Simpler conversation flow

Programmatic Access

You can interact with the context system programmatically:

Checking Context Status

// Get context managers
const contextManager = agent.getContextStateManager();
const contextInjector = agent.getContextInjector();

// Check if enabled and ready
if (contextManager && contextInjector?.isReady()) {
  console.log('Context injection is active');
}

Manual Context Injection

Even with automatic injection enabled, you can inject custom context:
// Inject custom context
await agent.injectContext('User is reviewing Q4 reports', {
  source: 'custom',
  metadata: { reportId: 'q4-2024' }
});

// Update user preferences
agent.updateUserContext({
  name: 'Alice Johnson',
  preferences: {
    theme: 'dark',
    language: 'TypeScript'
  }
});

// Update page context manually
await agent.updatePageContext({
  url: window.location.href,
  title: document.title,
  domain: window.location.hostname,
  path: window.location.pathname
});

React Hook Integration

Use the useContextUpdater hook for automatic page tracking:
import { useContextUpdater } from '@sammy-labs/sammy-three';

function MyApp() {
  const { 
    startMonitoring, 
    updateUserContext, 
    setCustomContext 
  } = useContextUpdater({
    updateInterval: 1000,
    includeTitle: true,
    includeDomain: true,
    includePath: true
  });

  useEffect(() => {
    if (agentRef.current) {
      startMonitoring(agentRef.current);
    }
  }, [agentRef.current]);
  
  // Manual updates when needed
  const handleUserLogin = (user) => {
    updateUserContext({
      name: user.name,
      preferences: user.preferences
    });
  };
}

Performance Considerations

When to Disable

Consider disabling context injection for:
Performance-Critical Applications
  • Each injection adds processing overhead
  • Memory searches require API calls
  • Consider disabling for high-frequency interactions
Privacy-Sensitive Environments
  • No data collection when disabled
  • URLs and interactions not tracked
  • Memories not searched or stored
Simple Use Cases
  • Basic chatbots without context needs
  • Static help systems
  • Single-purpose tools

Impact Analysis

When context injection is disabled:
FeatureImpact
System PromptNo context instructions included
Memory SearchSkipped entirely
Page UpdatesNot tracked or injected
Click EventsNot processed
API CallsSignificantly reduced
LatencyLower response times

Advanced Configuration

Memory Search Settings

The memory search system has internal configuration:
Memory Search Defaults
{
  userInputThreshold: 20,      // Min chars to trigger search
  agentOutputThreshold: 50,    // Min chars for agent context
  searchLimit: 3,              // Max memories to return
  similarityThreshold: 0.5,    // Min relevance score
  searchDebounceMs: 2000       // Prevent excessive searches
}

Context Formatting

Context is injected using XML-style tags for clarity:
Example Injected Context
<page_context>
  url: "https://app.example.com/dashboard"
  title: "Dashboard"
  domain: "app.example.com"
  path: "/dashboard"
  instruction: "User is on the dashboard page"
</page_context>

<live_context>
  type: "related_knowledge"
  source: "user"
  memories:
    - memory: "User prefers TypeScript"
      relevance: 0.95
    - memory: "User works with React"
      relevance: 0.87
  instruction: "Use this context to provide relevant assistance"
</live_context>

Debugging

Console Logs

Monitor context injection activity in the console:
📝 [SAMMY-AGENT-CORE] Enabled context system augmentation
💉 [CONTEXT-INJECTOR] Successfully injected context (256 chars)
🔍 [Agent] Searching memories after user turn
💭 [CONTEXT-MEMORY-MANAGER] Found 3 memories
📍 [SAMMY-AGENT-CORE] Updated page context
🖱️ [SAMMY-AGENT-CORE] Click event detected
✅ [Agent] Successfully injected 2 memories

Observability Events

All context operations are tracked for monitoring:
// Context injection event
{
  type: 'context.injection',
  data: {
    source: 'memory',
    contextLength: 256,
    latencyMs: 12
  }
}

// Memory search event
{
  type: 'memory.search',
  data: {
    query: 'user input...',
    resultsFound: 3,
    searchDurationMs: 45
  }
}

Migration Guide

From Previous Versions

If upgrading from a version where context was always enabled:
1

Review Current Usage

Identify which context features your application uses
2

Update Configuration

// Old (context always on)
const config = {
  auth: { /* ... */ },
  observability: true
};

// New (explicit control)
const config = {
  auth: { /* ... */ },
  observability: true,
  contextInjection: true  // Maintain previous behavior
};
3

Test and Optimize

Gradually disable unused features:
contextInjection: {
  enabled: true,
  memorySearch: true,
  pageTracking: true,
  clickTracking: false  // Start by disabling least used
}

Best Practices

Troubleshooting

Common Issues

  • Context Not Injecting
  • Memory Search Not Working
  • Performance Issues
Symptoms: Agent seems unaware of contextCheck:
  • Verify contextInjection is not set to false
  • Ensure specific features are enabled
  • Check console for injection logs
  • Verify connection status: contextInjector?.isReady()
Solution:
// Enable and verify
contextInjection: true

// Check status
const ready = agent.getContextInjector()?.isReady();
console.log('Injector ready:', ready);

API Reference

Configuration Types

interface ContextInjectionConfig {
  enabled: boolean;        // Master switch
  clickTracking?: boolean; // Click event tracking
  pageTracking?: boolean;  // Page context tracking  
  memorySearch?: boolean;  // Memory search and injection
}

interface ClickDetectionConfig {
  aggregationWindowMs?: number;      // Time window to aggregate clicks (default: 500ms)
  clickDebounceMs?: number;          // Minimum time between clicks (default: 250ms)
  debugLogs?: boolean;               // Enable debug logging (default: false)
  interactableOnly?: boolean;        // Only track interactable elements (default: true)
  maxClicksPerWindow?: number;       // Max clicks per window (default: 3)
  significantClicksOnly?: boolean;   // Only track significant clicks (default: false)
}

// Usage
config: {
  contextInjection?: boolean | ContextInjectionConfig,
  clickDetection?: ClickDetectionConfig
}

Context Manager Methods

// Get managers
getContextStateManager(): ContextStateManager | null
getContextInjector(): ContextInjector | null

// Manual injection
injectContext(context: string, options?: ContextInjectionOptions): Promise<boolean>
injectMemoryContext(memories: Memory[], source: string): Promise<boolean>

// Update context
updatePageContext(metadata: PageMetadata): Promise<void>
updateUserContext(preferences: UserPreferences): void

Summary

Context injection provides intelligent, automatic context management that enhances your AI agent’s responses. With flexible configuration options, you can optimize for your specific use case—whether you need full contextual awareness for complex interactions or a lightweight setup for simple queries.
Remember: Context injection is enabled by default because it significantly improves the quality of AI responses. Only disable features that you’re certain you don’t need.
I