or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ai-integrations.mdclient-management.mdcontext-management.mdevent-tracking.mdfeature-flags.mdindex.mduser-group-management.md

index.mddocs/

0

# PostHog Python SDK

1

2

A comprehensive Python SDK for PostHog, providing developer-friendly integration of event tracking, feature flags, user identification, exception capture, and context management. The SDK offers both synchronous and asynchronous APIs with support for automatic session tracking, AI/LLM integrations (including OpenAI, Anthropic, Langchain), and comprehensive error handling with automatic retries, batching, offline queuing, and Django integration.

3

4

## Package Information

5

6

- **Package Name**: posthog

7

- **Language**: Python

8

- **Installation**: `pip install posthog`

9

- **Python Version**: 3.9+

10

11

## Core Imports

12

13

```python

14

import posthog

15

```

16

17

For direct client usage:

18

19

```python

20

from posthog import Posthog

21

```

22

23

For AI integrations:

24

25

```python

26

from posthog.ai.openai import OpenAI

27

from posthog.ai.anthropic import Anthropic

28

from posthog.ai.gemini import Client as GeminiClient, genai

29

from posthog.ai.langchain import CallbackHandler

30

```

31

32

For Django integration:

33

34

```python

35

from posthog.integrations.django import PosthogContextMiddleware

36

```

37

38

## Basic Usage

39

40

```python

41

import posthog

42

43

# Configure PostHog

44

posthog.api_key = 'phc_your_project_api_key'

45

posthog.host = 'https://app.posthog.com' # or your self-hosted instance

46

47

# Track events

48

posthog.capture('user123', 'button_clicked', {

49

'button_name': 'signup',

50

'page': 'landing'

51

})

52

53

# Set user properties

54

posthog.set('user123', {

55

'email': 'user@example.com',

56

'plan': 'premium'

57

})

58

59

# Use feature flags

60

if posthog.feature_enabled('new-checkout', 'user123'):

61

# Show new checkout flow

62

pass

63

64

# Context-based tracking

65

with posthog.new_context():

66

posthog.identify_context('user123')

67

posthog.tag('session_type', 'premium')

68

posthog.capture('purchase_completed', {'amount': 99.99})

69

```

70

71

## Architecture

72

73

PostHog Python SDK follows a context-aware architecture:

74

75

- **Global Module Interface**: Simplified API for quick integration using module-level functions

76

- **Client Instance**: Direct client instantiation for advanced configuration and multi-tenant usage

77

- **Context Management**: Thread-safe context system for automatic user identification and tagging

78

- **AI Integrations**: Wrapper clients for popular LLM providers with automatic usage tracking

79

- **Feature Flag System**: Local and remote evaluation with caching and fallback mechanisms

80

81

The SDK supports both fire-and-forget event tracking and comprehensive analytics workflows, with automatic batching, retry logic, and offline support for production deployments.

82

83

## Capabilities

84

85

### Event Tracking

86

87

Core event capture functionality for tracking user actions, system events, and custom analytics data with support for properties, timestamps, and automatic context enrichment.

88

89

```python { .api }

90

def capture(event: str, **kwargs: OptionalCaptureArgs) -> Optional[str]: ...

91

def capture_exception(exception: Optional[ExceptionArg] = None, **kwargs: OptionalCaptureArgs): ...

92

```

93

94

[Event Tracking](./event-tracking.md)

95

96

### User and Group Management

97

98

User identification, property management, and group associations for organizing users and tracking organizational-level data with support for both user and group properties.

99

100

```python { .api }

101

def set(**kwargs: OptionalSetArgs) -> Optional[str]: ...

102

def set_once(**kwargs: OptionalSetArgs) -> Optional[str]: ...

103

def group_identify(group_type: str, group_key: str, properties: Optional[Dict], timestamp: Optional[datetime], uuid: Optional[str], disable_geoip: Optional[bool]) -> Optional[str]: ...

104

def alias(previous_id: str, distinct_id: str, timestamp: Optional[datetime], uuid: Optional[str], disable_geoip: Optional[bool]) -> Optional[str]: ...

105

```

106

107

[User and Group Management](./user-group-management.md)

108

109

### Feature Flags

110

111

Feature flag evaluation system supporting boolean flags, multivariate testing, remote configuration, and both local and remote evaluation with caching and fallback support.

112

113

```python { .api }

114

def feature_enabled(key: str, distinct_id: str, groups: Optional[dict] = None, person_properties: Optional[dict] = None, group_properties: Optional[dict] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None) -> bool: ...

115

def get_feature_flag(key: str, distinct_id: str, groups: Optional[dict] = None, person_properties: Optional[dict] = None, group_properties: Optional[dict] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None) -> Optional[FeatureFlag]: ...

116

def get_all_flags(distinct_id: str, groups: Optional[dict] = None, person_properties: Optional[dict] = None, group_properties: Optional[dict] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None) -> Optional[dict[str, FeatureFlag]]: ...

117

```

118

119

[Feature Flags](./feature-flags.md)

120

121

### Context Management

122

123

Thread-safe context system for automatic user identification, session tracking, and property tagging with support for nested contexts and exception capture.

124

125

```python { .api }

126

def new_context(fresh: bool = False, capture_exceptions: bool = True): ...

127

def scoped(fresh: bool = False, capture_exceptions: bool = True): ...

128

def identify_context(distinct_id: str): ...

129

def set_context_session(session_id: str): ...

130

def tag(name: str, value: Any): ...

131

```

132

133

[Context Management](./context-management.md)

134

135

### Client Management

136

137

Client lifecycle management including initialization, configuration, batching control, and graceful shutdown with support for both global and instance-based usage.

138

139

```python { .api }

140

class Client:

141

def __init__(self, project_api_key: str, host: Optional[str] = None, debug: bool = False, max_queue_size: int = 10000, send: bool = True, on_error: Optional[Callable] = None, flush_at: int = 100, flush_interval: float = 0.5, gzip: bool = False, max_retries: int = 3, sync_mode: bool = False, timeout: int = 15, thread: int = 1, poll_interval: int = 30, personal_api_key: Optional[str] = None, disabled: bool = False, disable_geoip: bool = True, historical_migration: bool = False, feature_flags_request_timeout_seconds: int = 3, super_properties: Optional[Dict] = None, enable_exception_autocapture: bool = False, log_captured_exceptions: bool = False, project_root: Optional[str] = None, privacy_mode: bool = False, before_send: Optional[Callable] = None, flag_fallback_cache_url: Optional[str] = None, enable_local_evaluation: bool = True): ...

142

143

def flush(): ...

144

def join(): ...

145

def shutdown(): ...

146

```

147

148

[Client Management](./client-management.md)

149

150

### AI Integrations

151

152

LLM provider integrations with automatic usage tracking, cost monitoring, and performance analytics for OpenAI, Anthropic, Gemini, and Langchain with support for both sync and async operations.

153

154

```python { .api }

155

# OpenAI Integration

156

class OpenAI: ...

157

class AsyncOpenAI: ...

158

class AzureOpenAI: ...

159

class AsyncAzureOpenAI: ...

160

161

# Anthropic Integration

162

class Anthropic: ...

163

class AsyncAnthropic: ...

164

class AnthropicBedrock: ...

165

class AsyncAnthropicBedrock: ...

166

167

# Gemini Integration

168

class Client: ... # Via posthog.ai.gemini

169

genai: _GenAI # Module compatibility

170

171

# Langchain Integration

172

class CallbackHandler: ...

173

```

174

175

[AI Integrations](./ai-integrations.md)

176

177

### Django Integration

178

179

Django middleware for automatic request tracking with context management, session identification, and exception capture.

180

181

```python { .api }

182

class PosthogContextMiddleware:

183

"""

184

Django middleware for automatic PostHog integration.

185

186

Automatically wraps requests with PostHog contexts and extracts:

187

- Session ID from X-POSTHOG-SESSION-ID header

188

- Distinct ID from X-POSTHOG-DISTINCT-ID header

189

- Request URL and method as properties

190

- Automatic exception capture (configurable)

191

192

Configurable via Django settings:

193

- POSTHOG_MW_CAPTURE_EXCEPTIONS: Enable/disable exception capture

194

- POSTHOG_MW_CLIENT: Custom client instance

195

- POSTHOG_MW_EXTRA_TAGS: Function for additional context tags

196

- POSTHOG_MW_REQUEST_FILTER: Function to filter requests

197

- POSTHOG_MW_TAG_MAP: Function to modify tags before context

198

"""

199

```

200

201

## Types

202

203

### Core Types

204

205

```python { .api }

206

# Type aliases

207

FlagValue = Union[bool, str]

208

BeforeSendCallback = Callable[[dict[str, Any]], Optional[dict[str, Any]]]

209

ID_TYPES = Union[numbers.Number, str, UUID, int]

210

ExceptionArg = Union[BaseException, ExcInfo]

211

212

# Feature flag types

213

@dataclass(frozen=True)

214

class FeatureFlag:

215

key: str

216

enabled: bool

217

variant: Optional[str]

218

reason: Optional[FlagReason]

219

metadata: Union[FlagMetadata, LegacyFlagMetadata]

220

221

def get_value(self) -> FlagValue: ...

222

223

@dataclass(frozen=True)

224

class FeatureFlagResult:

225

key: str

226

enabled: bool

227

variant: Optional[str]

228

payload: Optional[Any]

229

reason: Optional[str]

230

231

def get_value(self) -> FlagValue: ...

232

233

@dataclass(frozen=True)

234

class FlagReason:

235

code: str

236

condition_index: Optional[int]

237

description: str

238

239

@dataclass(frozen=True)

240

class FlagMetadata:

241

id: int

242

payload: Optional[str]

243

version: int

244

description: str

245

246

# Argument types

247

class OptionalCaptureArgs(TypedDict):

248

distinct_id: NotRequired[Optional[ID_TYPES]]

249

properties: NotRequired[Optional[Dict[str, Any]]]

250

timestamp: NotRequired[Optional[Union[datetime, str]]]

251

uuid: NotRequired[Optional[str]]

252

groups: NotRequired[Optional[Dict[str, str]]]

253

send_feature_flags: NotRequired[Optional[Union[bool, SendFeatureFlagsOptions]]]

254

disable_geoip: NotRequired[Optional[bool]]

255

256

class OptionalSetArgs(TypedDict):

257

distinct_id: NotRequired[Optional[ID_TYPES]]

258

properties: NotRequired[Optional[Dict[str, Any]]]

259

timestamp: NotRequired[Optional[Union[datetime, str]]]

260

uuid: NotRequired[Optional[str]]

261

disable_geoip: NotRequired[Optional[bool]]

262

263

class SendFeatureFlagsOptions(TypedDict, total=False):

264

should_send: bool

265

only_evaluate_locally: Optional[bool]

266

person_properties: Optional[dict[str, Any]]

267

group_properties: Optional[dict[str, dict[str, Any]]]

268

flag_keys_filter: Optional[list[str]]

269

```

270

271

## Global Configuration

272

273

```python { .api }

274

# Core configuration

275

api_key: Optional[str]

276

host: Optional[str]

277

debug: bool

278

send: bool

279

sync_mode: bool

280

disabled: bool

281

282

# Advanced configuration

283

personal_api_key: Optional[str]

284

project_api_key: Optional[str]

285

poll_interval: int

286

disable_geoip: bool

287

feature_flags_request_timeout_seconds: int

288

super_properties: Optional[Dict]

289

290

# Exception handling

291

enable_exception_autocapture: bool

292

log_captured_exceptions: bool

293

project_root: Optional[str]

294

295

# Privacy and evaluation

296

privacy_mode: bool

297

enable_local_evaluation: bool

298

299

# Error handling

300

on_error: Optional[Callable]

301

```