> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sammylabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Context Injection

> Automatically provide relevant context to enhance AI agent responses with page metadata, user preferences, memories, and interaction events

# 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.

<Info>
  Context injection is enabled by default to provide the best user experience. You can configure or disable specific features based on your needs.
</Info>

## Why Context Injection?

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

<Columns cols={3}>
  <Card title="Environmental Awareness" icon="location-dot">
    Automatically tracks page navigation and provides URL, title, and domain context
  </Card>

  <Card title="Memory Retrieval" icon="brain">
    Searches and injects relevant memories from previous interactions
  </Card>

  <Card title="User Interaction Tracking" icon="hand-pointer">
    Monitors and summarizes click events for proactive guidance
  </Card>
</Columns>

## Quick Start

Context injection works out of the box with sensible defaults:

<CodeGroup>
  ```typescript Default Configuration theme={null}
  import { SammyAgentProvider } from '@sammy-labs/sammy-three';

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

  ```typescript Disable All Context theme={null}
  // Completely disable context injection
  <SammyAgentProvider 
    config={{
      ...config,
      contextInjection: false
    }}
  >
    {children}
  </SammyAgentProvider>
  ```

  ```typescript Selective Configuration theme={null}
  // Fine-tune specific features
  <SammyAgentProvider 
    config={{
      ...config,
      contextInjection: {
        enabled: true,           // Master switch
        memorySearch: true,      // Memory retrieval
        pageTracking: false,     // Page context
        clickTracking: true      // Click events
      }
    }}
  >
    {children}
  </SammyAgentProvider>
  ```
</CodeGroup>

## 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:

```typescript theme={null}
contextInjection: true   // Enable all features (default)
contextInjection: false  // Disable all features
```

### Object Configuration

For fine-grained control over individual features:

<ResponseField name="enabled" type="boolean" default="true" required>
  Master switch that controls whether any context injection occurs. When false, all other settings are ignored.
</ResponseField>

<ResponseField name="memorySearch" type="boolean" default="true">
  Enables searching and injecting relevant memories from training data and previous interactions.
</ResponseField>

<ResponseField name="pageTracking" type="boolean" default="true">
  Tracks current page URL, title, domain, and path. Updates automatically on navigation.
</ResponseField>

<ResponseField name="clickTracking" type="boolean" default="true">
  Monitors user click events and injects summaries for proactive guidance.
</ResponseField>

## 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.

<Steps>
  <Step title="User Input Detection">
    System detects when user completes their turn (minimum 20 characters)
  </Step>

  <Step title="Memory Search">
    Searches memory backend for relevant context based on user input
  </Step>

  <Step title="Context Injection">
    Top 3 most relevant memories are formatted and injected into the conversation
  </Step>

  <Step title="Agent Response">
    Agent responds with awareness of the injected memories
  </Step>
</Steps>

**Configuration:**

```typescript theme={null}
contextInjection: {
  enabled: true,
  memorySearch: true  // Enable memory features
}
```

<Note>
  Memory injection only occurs after user turns to prevent infinite loops. The system tracks injected memories to avoid duplicates.
</Note>

### Page Context Tracking

Automatically tracks and injects page navigation context:

```typescript Page Context Structure theme={null}
{
  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

<Info>
  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.
</Info>

**Configuration:**

```typescript theme={null}
contextInjection: {
  enabled: true,
  pageTracking: true  // Enable page tracking
}
```

### Click Event Tracking

Monitors and aggregates user click events to provide interaction context:

<Tabs>
  <Tab title="How It Works">
    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
  </Tab>

  <Tab title="Injection Timing">
    The system uses intelligent timing strategies:

    * **Agent Speaking**: Buffers clicks until agent finishes
    * **User Speaking**: Waits for pause in speech
    * **Neither Speaking**: Injects after short delay (800ms for significant clicks)
  </Tab>

  <Tab title="Event Format">
    ```typescript theme={null}
    {
      summary: "User clicked 'Submit' button",
      isSignificant: true,
      timestamp: "2024-01-15T10:30:00Z",
      element: {
        type: "button",
        text: "Submit",
        selector: "#submit-btn"
      }
    }
    ```
  </Tab>
</Tabs>

**Configuration:**

```typescript theme={null}
contextInjection: {
  enabled: true,
  clickTracking: true  // Enable click tracking
}
```

**Advanced Click Detection Configuration:**

You can pass additional configuration to fine-tune click detection behavior:

```typescript theme={null}
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)
  }
};
```

<Note>
  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.
</Note>

**What Elements Are Considered Interactable?**

When `interactableOnly` is `true` (default), the system tracks clicks on:

<Columns cols={2}>
  <Card title="HTML Elements" icon="code">
    * `<a>`, `<button>`, `<input>`
    * `<select>`, `<textarea>`, `<label>`
    * `<details>`, `<summary>`, `<menu>`
    * `<embed>`, `<object>`, `<menuitem>`
  </Card>

  <Card title="ARIA Roles" icon="universal-access">
    * `button`, `link`, `checkbox`, `radio`
    * `tab`, `menuitem`, `option`, `switch`
    * `slider`, `textbox`, `combobox`
    * `progressbar`, `scrollbar`, `tree`
  </Card>
</Columns>

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:

```typescript theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
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

```typescript theme={null}
// 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:

```typescript theme={null}
// 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:

```typescript theme={null}
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:

<Warning>
  **Performance-Critical Applications**

  * Each injection adds processing overhead
  * Memory searches require API calls
  * Consider disabling for high-frequency interactions
</Warning>

<Warning>
  **Privacy-Sensitive Environments**

  * No data collection when disabled
  * URLs and interactions not tracked
  * Memories not searched or stored
</Warning>

<Tip>
  **Simple Use Cases**

  * Basic chatbots without context needs
  * Static help systems
  * Single-purpose tools
</Tip>

### Impact Analysis

When context injection is disabled:

| Feature       | Impact                           |
| ------------- | -------------------------------- |
| System Prompt | No context instructions included |
| Memory Search | Skipped entirely                 |
| Page Updates  | Not tracked or injected          |
| Click Events  | Not processed                    |
| API Calls     | Significantly reduced            |
| Latency       | Lower response times             |

## Advanced Configuration

### Memory Search Settings

The memory search system has internal configuration:

```typescript Memory Search Defaults theme={null}
{
  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:

```xml Example Injected Context theme={null}
<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:

<CodeGroup>
  ```text Context Enabled theme={null}
  📝 [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
  ```

  ```text Context Disabled theme={null}
  📝 [SAMMY-AGENT-CORE] Disabled context system augmentation
  ```
</CodeGroup>

### Observability Events

All context operations are tracked for monitoring:

```typescript theme={null}
// 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:

<Steps>
  <Step title="Review Current Usage">
    Identify which context features your application uses
  </Step>

  <Step title="Update Configuration">
    ```typescript theme={null}
    // Old (context always on)
    const config = {
      auth: { /* ... */ },
      observability: true
    };

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

  <Step title="Test and Optimize">
    Gradually disable unused features:

    ```typescript theme={null}
    contextInjection: {
      enabled: true,
      memorySearch: true,
      pageTracking: true,
      clickTracking: false  // Start by disabling least used
    }
    ```
  </Step>
</Steps>

## Best Practices

<Cards>
  <Card title="Start with Defaults" icon="play">
    Context injection is enabled by default for good reason. Test with full context before disabling features.
  </Card>

  <Card title="Measure Impact" icon="chart-line">
    Use observability to understand which context features provide value before disabling them.
  </Card>

  <Card title="Disable Selectively" icon="sliders">
    Turn off only the features you don't need rather than disabling everything.
  </Card>

  <Card title="Test Thoroughly" icon="flask">
    Ensure your use case works without context before deploying with it disabled.
  </Card>
</Cards>

## Troubleshooting

### Common Issues

<Tabs>
  <Tab title="Context Not Injecting">
    **Symptoms:** Agent seems unaware of context

    **Check:**

    * Verify `contextInjection` is not set to `false`
    * Ensure specific features are enabled
    * Check console for injection logs
    * Verify connection status: `contextInjector?.isReady()`

    **Solution:**

    ```typescript theme={null}
    // Enable and verify
    contextInjection: true

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

  <Tab title="Memory Search Not Working">
    **Symptoms:** No memories being found or injected

    **Check:**

    * Ensure `memorySearch` is enabled
    * Verify input meets minimum length (20 chars)
    * Check API connection to memory service
    * Look for duplicate memory filtering logs

    **Solution:**

    ```typescript theme={null}
    contextInjection: {
      enabled: true,
      memorySearch: true  // Must be enabled
    }
    ```
  </Tab>

  <Tab title="Performance Issues">
    **Symptoms:** Slow response times or high latency

    **Check:**

    * Consider disabling unused features
    * Monitor injection event frequency
    * Check memory search result counts

    **Solution:**

    ```typescript theme={null}
    // Optimize for performance
    contextInjection: {
      enabled: true,
      memorySearch: false,  // Disable if not needed
      pageTracking: true,
      clickTracking: false  // Disable if not needed
    }
    ```
  </Tab>
</Tabs>

## API Reference

### Configuration Types

```typescript theme={null}
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

```typescript theme={null}
// 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.

<Note>
  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.
</Note>
