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

# User Context

> Pass user information for session consistency and A/B testing

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?

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

**Without UserContext:** The system uses a single default targeting key for all requests, causing 100% of users to get assigned to the same variant instead of distributing according to your configured splits (50/50, 30/70, etc.).

## How to Use UserContext

### Basic Usage

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

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

<CardGroup cols={2}>
  <Card title="Experiments" icon="flask" href="/portal/graph-registry">
    Learn how to register your graphs and run A/B experiments
  </Card>

  <Card title="Experiments" icon="lightbulb" href="/portal/graph-registry">
    Learn best practices for A/B experiments
  </Card>
</CardGroup>
