Skip to main content
Cedar’s useSubscribeStateToAgentContext function allows you to automatically make any Cedar-registered state available to AI agents as context. This enables agents to understand your app’s current state and provide more relevant, contextual responses.
Prerequisite – The state you want to subscribe must first be registered in Cedar using either useCedarState or useRegisterState.

useSubscribeStateToAgentContext Overview

The useSubscribeStateToAgentContext function subscribes to local state changes and automatically updates the agent’s input context whenever the state changes. This means your AI agent always has access to the most up-to-date information from your application, including any Zod schemas defined for the state.

Function Signature

Parameters

  • stateKey: string - The registered state key that we want to subscribe to
  • mapFn: (state: T) => Record<string, any> - Function that maps your state to context entries
  • options (optional) - Configuration for visual representation and label extraction:
    • icon?: ReactNode | ((item: ElementType<T>) => ReactNode) - Icon to display for this context. Can be a static React element or a function that returns an icon based on each item
    • color?: string - Hex color for visual styling
    • labelField?: string | ((item: ElementType<T>) => string) - How to extract labels from your data. Can be a field name or a function
    • order?: number - Display order for context badges (lower numbers appear first)
    • showInChat?: boolean | ((entry: ContextEntry) => boolean) - Whether to show context badges in chat. Can be a boolean or a function to filter specific entries (default = true)
    • collapse?: boolean | number | { threshold: number; label?: string; icon?: ReactNode } - Collapse multiple entries into a single badge. Can be boolean (default threshold 5), number (custom threshold), or object with full configuration

Basic Usage Example

Here’s a simple example with a todo list:

Complex State Example

Here’s a more advanced example from the Product Roadmap demo:

Using the labelField Option

The labelField option allows you to specify how labels should be extracted from your data. This is especially useful when your data has custom field names or when you need custom label logic.

labelField as a String

Specify which field to use as the label:

labelField as a Function

Use a function for custom label generation:

Dynamic Icons and Conditional Display

Cedar supports dynamic behavior for both icons and chat display through function-based options. This allows you to customize the appearance and visibility of context entries based on their actual data.

Dynamic Icon Functions

The icon option can accept a function that receives each item and returns an appropriate icon:

Conditional Chat Display with showInChat

The showInChat option can be a function that determines whether specific entries should appear as badges in the chat UI:

Advanced Dynamic Configuration Example

Here’s a comprehensive example combining dynamic icons, conditional display, and collapsing from the Product Roadmap demo:

Function Parameter Types

When using function-based options, the parameters are strongly typed:
  • item - Individual item from your data array (or the single item if not an array)
  • Returns - Any valid React node (JSX element, string, emoji, etc.)

Best Practices for Dynamic Options

  1. Performance: Dynamic functions are called for each item, so keep them lightweight
  2. Consistency: Use consistent logic patterns across your application
  3. Fallbacks: Always provide fallback values for unexpected data
  4. Type Safety: Leverage TypeScript for better development experience

Single Values Support

useSubscribeInputContext now supports single values (not just arrays):

Controlling Display Order

The order property allows you to control the display order of context badges in the UI. This is useful when you have multiple context subscriptions and want to prioritize their visibility.

How Order Works

  • Lower numbers appear first: order: 1 will appear before order: 10
  • Default behavior: Items without an order are treated as having the maximum order value
  • Stable sorting: Items with the same order maintain their original relative position

Basic Order Example

Complex Order Example with Mention Providers

When combining useSubscribeInputContext with mention providers, you can create a well-organized context display:

Order Best Practices

  1. Use consistent spacing: Leave gaps between order values (1, 10, 20) to allow for future insertions
  2. Group related contexts: Give similar contexts adjacent order values
  3. Prioritize by importance: Most relevant context should have lower order values
  4. Document your ordering: Comment why certain items have specific orders

Collapsing Multiple Entries

The collapse option allows you to automatically collapse multiple context entries into a single badge when the number of entries exceeds a threshold. This is particularly useful for managing UI clutter when dealing with large datasets.

Collapse Configuration Types

The collapse option supports three different configuration formats:
Set to true to enable collapsing with default settings:
When collapse: true, items will collapse into a single badge when more than 5 entries are present.

Collapse Label Templates

When using the object format, the label field supports template variables:
  • {count} - Replaced with the actual number of entries
  • Static text - Any other text is displayed as-is

Real-World Collapse Examples

Dynamic Collapse Behavior

The collapse feature is dynamic and responsive to state changes:
Performance Tip: Collapsing is particularly useful for performance when dealing with large datasets, as it reduces the number of DOM elements rendered in the chat UI while still providing all the data to the agent.

Default Label Extraction

When no labelField is specified, the function looks for labels in this order:
  1. title field
  2. label field
  3. name field
  4. id field
  5. String representation of the value
When using useSubscribeInputContext, entries are automatically marked with source: 'subscription'.

Output Behavior and Structure

What Gets Sent to the Agent

When the agent receives context from useSubscribeStateToAgentContext, it gets a simplified structure containing only the essential data:
The agent only receives the source and data fields. Visual metadata like icon, color, and label are used only for UI display and are not sent to the agent.

Array Behavior

The output structure depends on how you pass data to useSubscribeStateToAgentContext:
When your mapFn returns a single non-array value, it’s stored as a single context entry:

Practical Examples

Here are real-world examples showing the input and output:
Why preserve array structure? This allows the agent to understand whether you’re working with a single item or a collection, even when that collection has only one item. This distinction can be important for generating appropriate responses.

Multiple Context Keys

When you return multiple keys from your mapFn, each follows the same behavior rules:

Multiple State Subscriptions

You can subscribe multiple pieces of state:

Best Practices

1. Transform Sensitive Data

Don’t expose sensitive information to the agent:

2. Use Meaningful Keys

Choose descriptive keys for your context:

3. Optimize Large Data Sets

For large data sets, consider filtering or summarizing:

Visual Customization

The options parameter allows you to customize how the context appears in the UI:

Integration with Chat Input

The subscribed context automatically becomes available to your AI agent when using Cedar’s chat components:
The agent will receive the context in a structured format and can reference it when generating responses, making the conversation more contextual and relevant to your application’s current state.