UserContext provides user-specific information during graph execution. It consists of user attributes (key-value pairs) and a targeting key that determines which graph variant a user receives.
Why Use UserContext?
- A/B Testing: Enable sophisticated targeting rules for experiments
- Session Consistency: User context’s targeting key ensures the same user always gets the same experience across sessions
- Personalization: Pass user attributes to customize graph behavior
What Happens Without UserContext?
If running A/B experiments, always pass UserContext with a unique targeting key. Otherwise, all users get the same variant regardless of your split percentages.
How to Use UserContext
Basic Usage
import { Graph, UserContext } from '@inworld/runtime';
import { v4 } from 'uuid';
// Create UserContext
const userContext = new UserContext(
  {
    user_id: 'user_12345',
    age: '25',
    country: 'US',
    user_tier: 'premium'
  },
  'user_12345' // targeting key
);
// Execute graph with context
const outputStream = graph.start(inputData, userContext);
Schema
new UserContext(
  attributes: { [key: string]: string }, // Required if creating UserContext
  targetingKey: string                   // Required if creating UserContext
)
Common Attributes
Attributes are flexible key-value pairs. Common examples:
- user_id: Primary user identifier
- age: User age for demographic targeting
- country: Country code (‘US’, ‘CA’, ‘UK’)
- user_tier: Subscription level (‘free’, ‘premium’)
- app_version: Version of your application
Next Steps