posthog 7.4.0__tar.gz → 7.4.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. {posthog-7.4.0/posthog.egg-info → posthog-7.4.2}/PKG-INFO +1 -1
  2. {posthog-7.4.0 → posthog-7.4.2}/posthog/__init__.py +27 -6
  3. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/openai/openai.py +27 -2
  4. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/openai/openai_async.py +27 -2
  5. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/utils.py +2 -2
  6. {posthog-7.4.0 → posthog-7.4.2}/posthog/client.py +30 -27
  7. {posthog-7.4.0 → posthog-7.4.2}/posthog/exception_utils.py +3 -3
  8. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_client.py +86 -1
  9. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_feature_flags.py +9 -55
  10. {posthog-7.4.0 → posthog-7.4.2}/posthog/version.py +1 -1
  11. {posthog-7.4.0 → posthog-7.4.2/posthog.egg-info}/PKG-INFO +1 -1
  12. {posthog-7.4.0 → posthog-7.4.2}/LICENSE +0 -0
  13. {posthog-7.4.0 → posthog-7.4.2}/MANIFEST.in +0 -0
  14. {posthog-7.4.0 → posthog-7.4.2}/README.md +0 -0
  15. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/__init__.py +0 -0
  16. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/anthropic/__init__.py +0 -0
  17. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/anthropic/anthropic.py +0 -0
  18. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/anthropic/anthropic_async.py +0 -0
  19. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/anthropic/anthropic_converter.py +0 -0
  20. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/anthropic/anthropic_providers.py +0 -0
  21. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/gemini/__init__.py +0 -0
  22. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/gemini/gemini.py +0 -0
  23. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/gemini/gemini_async.py +0 -0
  24. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/gemini/gemini_converter.py +0 -0
  25. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/langchain/__init__.py +0 -0
  26. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/langchain/callbacks.py +0 -0
  27. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/openai/__init__.py +0 -0
  28. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/openai/openai_converter.py +0 -0
  29. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/openai/openai_providers.py +0 -0
  30. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/sanitization.py +0 -0
  31. {posthog-7.4.0 → posthog-7.4.2}/posthog/ai/types.py +0 -0
  32. {posthog-7.4.0 → posthog-7.4.2}/posthog/args.py +0 -0
  33. {posthog-7.4.0 → posthog-7.4.2}/posthog/consumer.py +0 -0
  34. {posthog-7.4.0 → posthog-7.4.2}/posthog/contexts.py +0 -0
  35. {posthog-7.4.0 → posthog-7.4.2}/posthog/exception_capture.py +0 -0
  36. {posthog-7.4.0 → posthog-7.4.2}/posthog/feature_flags.py +0 -0
  37. {posthog-7.4.0 → posthog-7.4.2}/posthog/flag_definition_cache.py +0 -0
  38. {posthog-7.4.0 → posthog-7.4.2}/posthog/integrations/__init__.py +0 -0
  39. {posthog-7.4.0 → posthog-7.4.2}/posthog/integrations/django.py +0 -0
  40. {posthog-7.4.0 → posthog-7.4.2}/posthog/poller.py +0 -0
  41. {posthog-7.4.0 → posthog-7.4.2}/posthog/py.typed +0 -0
  42. {posthog-7.4.0 → posthog-7.4.2}/posthog/request.py +0 -0
  43. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/__init__.py +0 -0
  44. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_before_send.py +0 -0
  45. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_consumer.py +0 -0
  46. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_contexts.py +0 -0
  47. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_exception_capture.py +0 -0
  48. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_feature_flag.py +0 -0
  49. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_feature_flag_result.py +0 -0
  50. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_flag_definition_cache.py +0 -0
  51. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_module.py +0 -0
  52. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_request.py +0 -0
  53. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_size_limited_dict.py +0 -0
  54. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_types.py +0 -0
  55. {posthog-7.4.0 → posthog-7.4.2}/posthog/test/test_utils.py +0 -0
  56. {posthog-7.4.0 → posthog-7.4.2}/posthog/types.py +0 -0
  57. {posthog-7.4.0 → posthog-7.4.2}/posthog/utils.py +0 -0
  58. {posthog-7.4.0 → posthog-7.4.2}/posthog.egg-info/SOURCES.txt +0 -0
  59. {posthog-7.4.0 → posthog-7.4.2}/posthog.egg-info/dependency_links.txt +0 -0
  60. {posthog-7.4.0 → posthog-7.4.2}/posthog.egg-info/requires.txt +0 -0
  61. {posthog-7.4.0 → posthog-7.4.2}/posthog.egg-info/top_level.txt +0 -0
  62. {posthog-7.4.0 → posthog-7.4.2}/pyproject.toml +0 -0
  63. {posthog-7.4.0 → posthog-7.4.2}/setup.cfg +0 -0
  64. {posthog-7.4.0 → posthog-7.4.2}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: posthog
3
- Version: 7.4.0
3
+ Version: 7.4.2
4
4
  Summary: Integrate PostHog into any python application.
5
5
  Home-page: https://github.com/posthog/posthog-python
6
6
  Author: Posthog
@@ -1,25 +1,42 @@
1
1
  import datetime # noqa: F401
2
- from typing import Callable, Dict, Optional, Any # noqa: F401
2
+ from typing import Any, Callable, Dict, Optional # noqa: F401
3
+
3
4
  from typing_extensions import Unpack
4
5
 
5
- from posthog.args import OptionalCaptureArgs, OptionalSetArgs, ExceptionArg
6
+ from posthog.args import ExceptionArg, OptionalCaptureArgs, OptionalSetArgs
6
7
  from posthog.client import Client
8
+ from posthog.contexts import (
9
+ identify_context as inner_identify_context,
10
+ )
7
11
  from posthog.contexts import (
8
12
  new_context as inner_new_context,
13
+ )
14
+ from posthog.contexts import (
9
15
  scoped as inner_scoped,
10
- tag as inner_tag,
11
- set_context_session as inner_set_context_session,
12
- identify_context as inner_identify_context,
16
+ )
17
+ from posthog.contexts import (
13
18
  set_capture_exception_code_variables_context as inner_set_capture_exception_code_variables_context,
14
- set_code_variables_mask_patterns_context as inner_set_code_variables_mask_patterns_context,
19
+ )
20
+ from posthog.contexts import (
15
21
  set_code_variables_ignore_patterns_context as inner_set_code_variables_ignore_patterns_context,
16
22
  )
23
+ from posthog.contexts import (
24
+ set_code_variables_mask_patterns_context as inner_set_code_variables_mask_patterns_context,
25
+ )
26
+ from posthog.contexts import (
27
+ set_context_session as inner_set_context_session,
28
+ )
29
+ from posthog.contexts import (
30
+ tag as inner_tag,
31
+ )
17
32
  from posthog.exception_utils import (
18
33
  DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS,
19
34
  DEFAULT_CODE_VARIABLES_MASK_PATTERNS,
20
35
  )
21
36
  from posthog.feature_flags import (
22
37
  InconclusiveMatchError as InconclusiveMatchError,
38
+ )
39
+ from posthog.feature_flags import (
23
40
  RequiresServerEvaluation as RequiresServerEvaluation,
24
41
  )
25
42
  from posthog.flag_definition_cache import (
@@ -35,6 +52,8 @@ from posthog.request import (
35
52
  from posthog.types import (
36
53
  FeatureFlag,
37
54
  FlagsAndPayloads,
55
+ )
56
+ from posthog.types import (
38
57
  FeatureFlagResult as FeatureFlagResult,
39
58
  )
40
59
  from posthog.version import VERSION
@@ -201,6 +220,7 @@ default_client = None # type: Optional[Client]
201
220
  capture_exception_code_variables = False
202
221
  code_variables_mask_patterns = DEFAULT_CODE_VARIABLES_MASK_PATTERNS
203
222
  code_variables_ignore_patterns = DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS
223
+ in_app_modules = None # type: Optional[list[str]]
204
224
 
205
225
 
206
226
  # NOTE - this and following functions take unpacked kwargs because we needed to make
@@ -799,6 +819,7 @@ def setup() -> Client:
799
819
  capture_exception_code_variables=capture_exception_code_variables,
800
820
  code_variables_mask_patterns=code_variables_mask_patterns,
801
821
  code_variables_ignore_patterns=code_variables_ignore_patterns,
822
+ in_app_modules=in_app_modules,
802
823
  )
803
824
 
804
825
  # always set incase user changes it
@@ -124,14 +124,23 @@ class WrappedResponses:
124
124
  start_time = time.time()
125
125
  usage_stats: TokenUsage = TokenUsage()
126
126
  final_content = []
127
+ model_from_response: Optional[str] = None
127
128
  response = self._original.create(**kwargs)
128
129
 
129
130
  def generator():
130
131
  nonlocal usage_stats
131
132
  nonlocal final_content # noqa: F824
133
+ nonlocal model_from_response
132
134
 
133
135
  try:
134
136
  for chunk in response:
137
+ # Extract model from response object in chunk (for stored prompts)
138
+ if hasattr(chunk, "response") and chunk.response:
139
+ if model_from_response is None and hasattr(
140
+ chunk.response, "model"
141
+ ):
142
+ model_from_response = chunk.response.model
143
+
135
144
  # Extract usage stats from chunk
136
145
  chunk_usage = extract_openai_usage_from_chunk(chunk, "responses")
137
146
 
@@ -161,6 +170,7 @@ class WrappedResponses:
161
170
  latency,
162
171
  output,
163
172
  None, # Responses API doesn't have tools
173
+ model_from_response,
164
174
  )
165
175
 
166
176
  return generator()
@@ -177,6 +187,7 @@ class WrappedResponses:
177
187
  latency: float,
178
188
  output: Any,
179
189
  available_tool_calls: Optional[List[Dict[str, Any]]] = None,
190
+ model_from_response: Optional[str] = None,
180
191
  ):
181
192
  from posthog.ai.types import StreamingEventData
182
193
  from posthog.ai.openai.openai_converter import (
@@ -189,9 +200,12 @@ class WrappedResponses:
189
200
  formatted_input = format_openai_streaming_input(kwargs, "responses")
190
201
  sanitized_input = sanitize_openai_response(formatted_input)
191
202
 
203
+ # Use model from kwargs, fallback to model from response
204
+ model = kwargs.get("model") or model_from_response or "unknown"
205
+
192
206
  event_data = StreamingEventData(
193
207
  provider="openai",
194
- model=kwargs.get("model", "unknown"),
208
+ model=model,
195
209
  base_url=str(self._client.base_url),
196
210
  kwargs=kwargs,
197
211
  formatted_input=sanitized_input,
@@ -320,6 +334,7 @@ class WrappedCompletions:
320
334
  usage_stats: TokenUsage = TokenUsage()
321
335
  accumulated_content = []
322
336
  accumulated_tool_calls: Dict[int, Dict[str, Any]] = {}
337
+ model_from_response: Optional[str] = None
323
338
  if "stream_options" not in kwargs:
324
339
  kwargs["stream_options"] = {}
325
340
  kwargs["stream_options"]["include_usage"] = True
@@ -329,9 +344,14 @@ class WrappedCompletions:
329
344
  nonlocal usage_stats
330
345
  nonlocal accumulated_content # noqa: F824
331
346
  nonlocal accumulated_tool_calls
347
+ nonlocal model_from_response
332
348
 
333
349
  try:
334
350
  for chunk in response:
351
+ # Extract model from chunk (Chat Completions chunks have model field)
352
+ if model_from_response is None and hasattr(chunk, "model"):
353
+ model_from_response = chunk.model
354
+
335
355
  # Extract usage stats from chunk
336
356
  chunk_usage = extract_openai_usage_from_chunk(chunk, "chat")
337
357
 
@@ -376,6 +396,7 @@ class WrappedCompletions:
376
396
  accumulated_content,
377
397
  tool_calls_list,
378
398
  extract_available_tool_calls("openai", kwargs),
399
+ model_from_response,
379
400
  )
380
401
 
381
402
  return generator()
@@ -393,6 +414,7 @@ class WrappedCompletions:
393
414
  output: Any,
394
415
  tool_calls: Optional[List[Dict[str, Any]]] = None,
395
416
  available_tool_calls: Optional[List[Dict[str, Any]]] = None,
417
+ model_from_response: Optional[str] = None,
396
418
  ):
397
419
  from posthog.ai.types import StreamingEventData
398
420
  from posthog.ai.openai.openai_converter import (
@@ -405,9 +427,12 @@ class WrappedCompletions:
405
427
  formatted_input = format_openai_streaming_input(kwargs, "chat")
406
428
  sanitized_input = sanitize_openai(formatted_input)
407
429
 
430
+ # Use model from kwargs, fallback to model from response
431
+ model = kwargs.get("model") or model_from_response or "unknown"
432
+
408
433
  event_data = StreamingEventData(
409
434
  provider="openai",
410
- model=kwargs.get("model", "unknown"),
435
+ model=model,
411
436
  base_url=str(self._client.base_url),
412
437
  kwargs=kwargs,
413
438
  formatted_input=sanitized_input,
@@ -128,14 +128,23 @@ class WrappedResponses:
128
128
  start_time = time.time()
129
129
  usage_stats: TokenUsage = TokenUsage()
130
130
  final_content = []
131
+ model_from_response: Optional[str] = None
131
132
  response = await self._original.create(**kwargs)
132
133
 
133
134
  async def async_generator():
134
135
  nonlocal usage_stats
135
136
  nonlocal final_content # noqa: F824
137
+ nonlocal model_from_response
136
138
 
137
139
  try:
138
140
  async for chunk in response:
141
+ # Extract model from response object in chunk (for stored prompts)
142
+ if hasattr(chunk, "response") and chunk.response:
143
+ if model_from_response is None and hasattr(
144
+ chunk.response, "model"
145
+ ):
146
+ model_from_response = chunk.response.model
147
+
139
148
  # Extract usage stats from chunk
140
149
  chunk_usage = extract_openai_usage_from_chunk(chunk, "responses")
141
150
 
@@ -166,6 +175,7 @@ class WrappedResponses:
166
175
  latency,
167
176
  output,
168
177
  extract_available_tool_calls("openai", kwargs),
178
+ model_from_response,
169
179
  )
170
180
 
171
181
  return async_generator()
@@ -182,13 +192,17 @@ class WrappedResponses:
182
192
  latency: float,
183
193
  output: Any,
184
194
  available_tool_calls: Optional[List[Dict[str, Any]]] = None,
195
+ model_from_response: Optional[str] = None,
185
196
  ):
186
197
  if posthog_trace_id is None:
187
198
  posthog_trace_id = str(uuid.uuid4())
188
199
 
200
+ # Use model from kwargs, fallback to model from response
201
+ model = kwargs.get("model") or model_from_response or "unknown"
202
+
189
203
  event_properties = {
190
204
  "$ai_provider": "openai",
191
- "$ai_model": kwargs.get("model"),
205
+ "$ai_model": model,
192
206
  "$ai_model_parameters": get_model_params(kwargs),
193
207
  "$ai_input": with_privacy_mode(
194
208
  self._client._ph_client,
@@ -350,6 +364,7 @@ class WrappedCompletions:
350
364
  usage_stats: TokenUsage = TokenUsage()
351
365
  accumulated_content = []
352
366
  accumulated_tool_calls: Dict[int, Dict[str, Any]] = {}
367
+ model_from_response: Optional[str] = None
353
368
 
354
369
  if "stream_options" not in kwargs:
355
370
  kwargs["stream_options"] = {}
@@ -360,9 +375,14 @@ class WrappedCompletions:
360
375
  nonlocal usage_stats
361
376
  nonlocal accumulated_content # noqa: F824
362
377
  nonlocal accumulated_tool_calls
378
+ nonlocal model_from_response
363
379
 
364
380
  try:
365
381
  async for chunk in response:
382
+ # Extract model from chunk (Chat Completions chunks have model field)
383
+ if model_from_response is None and hasattr(chunk, "model"):
384
+ model_from_response = chunk.model
385
+
366
386
  # Extract usage stats from chunk
367
387
  chunk_usage = extract_openai_usage_from_chunk(chunk, "chat")
368
388
  if chunk_usage:
@@ -405,6 +425,7 @@ class WrappedCompletions:
405
425
  accumulated_content,
406
426
  tool_calls_list,
407
427
  extract_available_tool_calls("openai", kwargs),
428
+ model_from_response,
408
429
  )
409
430
 
410
431
  return async_generator()
@@ -422,13 +443,17 @@ class WrappedCompletions:
422
443
  output: Any,
423
444
  tool_calls: Optional[List[Dict[str, Any]]] = None,
424
445
  available_tool_calls: Optional[List[Dict[str, Any]]] = None,
446
+ model_from_response: Optional[str] = None,
425
447
  ):
426
448
  if posthog_trace_id is None:
427
449
  posthog_trace_id = str(uuid.uuid4())
428
450
 
451
+ # Use model from kwargs, fallback to model from response
452
+ model = kwargs.get("model") or model_from_response or "unknown"
453
+
429
454
  event_properties = {
430
455
  "$ai_provider": "openai",
431
- "$ai_model": kwargs.get("model"),
456
+ "$ai_model": model,
432
457
  "$ai_model_parameters": get_model_params(kwargs),
433
458
  "$ai_input": with_privacy_mode(
434
459
  self._client._ph_client,
@@ -285,7 +285,7 @@ def call_llm_and_track_usage(
285
285
 
286
286
  event_properties = {
287
287
  "$ai_provider": provider,
288
- "$ai_model": kwargs.get("model"),
288
+ "$ai_model": kwargs.get("model") or getattr(response, "model", None),
289
289
  "$ai_model_parameters": get_model_params(kwargs),
290
290
  "$ai_input": with_privacy_mode(
291
291
  ph_client, posthog_privacy_mode, sanitized_messages
@@ -396,7 +396,7 @@ async def call_llm_and_track_usage_async(
396
396
 
397
397
  event_properties = {
398
398
  "$ai_provider": provider,
399
- "$ai_model": kwargs.get("model"),
399
+ "$ai_model": kwargs.get("model") or getattr(response, "model", None),
400
400
  "$ai_model_parameters": get_model_params(kwargs),
401
401
  "$ai_input": with_privacy_mode(
402
402
  ph_client, posthog_privacy_mode, sanitized_messages
@@ -2,26 +2,36 @@ import atexit
2
2
  import logging
3
3
  import os
4
4
  import sys
5
+ import warnings
5
6
  from datetime import datetime, timedelta
6
7
  from typing import Any, Dict, Optional, Union
7
- from typing_extensions import Unpack
8
8
  from uuid import uuid4
9
9
 
10
10
  from dateutil.tz import tzutc
11
11
  from six import string_types
12
+ from typing_extensions import Unpack
12
13
 
13
- from posthog.args import OptionalCaptureArgs, OptionalSetArgs, ID_TYPES, ExceptionArg
14
+ from posthog.args import ID_TYPES, ExceptionArg, OptionalCaptureArgs, OptionalSetArgs
14
15
  from posthog.consumer import Consumer
16
+ from posthog.contexts import (
17
+ _get_current_context,
18
+ get_capture_exception_code_variables_context,
19
+ get_code_variables_ignore_patterns_context,
20
+ get_code_variables_mask_patterns_context,
21
+ get_context_distinct_id,
22
+ get_context_session_id,
23
+ new_context,
24
+ )
15
25
  from posthog.exception_capture import ExceptionCapture
16
26
  from posthog.exception_utils import (
27
+ DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS,
28
+ DEFAULT_CODE_VARIABLES_MASK_PATTERNS,
17
29
  exc_info_from_error,
30
+ exception_is_already_captured,
18
31
  exceptions_from_error_tuple,
19
32
  handle_in_app,
20
- exception_is_already_captured,
21
33
  mark_exception_as_captured,
22
34
  try_attach_code_variables_to_frames,
23
- DEFAULT_CODE_VARIABLES_MASK_PATTERNS,
24
- DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS,
25
35
  )
26
36
  from posthog.feature_flags import (
27
37
  InconclusiveMatchError,
@@ -45,15 +55,6 @@ from posthog.request import (
45
55
  get,
46
56
  remote_config,
47
57
  )
48
- from posthog.contexts import (
49
- _get_current_context,
50
- get_context_distinct_id,
51
- get_context_session_id,
52
- get_capture_exception_code_variables_context,
53
- get_code_variables_mask_patterns_context,
54
- get_code_variables_ignore_patterns_context,
55
- new_context,
56
- )
57
58
  from posthog.types import (
58
59
  FeatureFlag,
59
60
  FeatureFlagError,
@@ -196,6 +197,7 @@ class Client(object):
196
197
  capture_exception_code_variables=False,
197
198
  code_variables_mask_patterns=None,
198
199
  code_variables_ignore_patterns=None,
200
+ in_app_modules: list[str] | None = None,
199
201
  ):
200
202
  """
201
203
  Initialize a new PostHog client instance.
@@ -264,6 +266,7 @@ class Client(object):
264
266
  if code_variables_ignore_patterns is not None
265
267
  else DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS
266
268
  )
269
+ self.in_app_modules = in_app_modules
267
270
 
268
271
  if project_root is None:
269
272
  try:
@@ -679,15 +682,6 @@ class Client(object):
679
682
  f"[FEATURE FLAGS] Unable to get feature variants: {e}"
680
683
  )
681
684
 
682
- elif self.feature_flags and event != "$feature_flag_called":
683
- # Local evaluation is enabled, flags are loaded, so try and get all flags we can without going to the server
684
- feature_variants = self.get_all_flags(
685
- distinct_id,
686
- groups=(groups or {}),
687
- disable_geoip=disable_geoip,
688
- only_evaluate_locally=True,
689
- )
690
-
691
685
  for feature, variant in (feature_variants or {}).items():
692
686
  extra_properties[f"$feature/{feature}"] = variant
693
687
 
@@ -1006,6 +1000,7 @@ class Client(object):
1006
1000
  "values": all_exceptions_with_trace,
1007
1001
  },
1008
1002
  },
1003
+ in_app_include=self.in_app_modules,
1009
1004
  project_root=self.project_root,
1010
1005
  )
1011
1006
  all_exceptions_with_trace_and_in_app = event["exception"]["values"]
@@ -1797,7 +1792,7 @@ class Client(object):
1797
1792
  person_properties=None,
1798
1793
  group_properties=None,
1799
1794
  only_evaluate_locally=False,
1800
- send_feature_flag_events=True,
1795
+ send_feature_flag_events=False,
1801
1796
  disable_geoip=None,
1802
1797
  ):
1803
1798
  """
@@ -1811,7 +1806,7 @@ class Client(object):
1811
1806
  person_properties: A dictionary of person properties.
1812
1807
  group_properties: A dictionary of group properties.
1813
1808
  only_evaluate_locally: Whether to only evaluate locally.
1814
- send_feature_flag_events: Whether to send feature flag events.
1809
+ send_feature_flag_events: Deprecated. Use get_feature_flag() instead if you need events.
1815
1810
  disable_geoip: Whether to disable GeoIP for this request.
1816
1811
 
1817
1812
  Examples:
@@ -1827,6 +1822,14 @@ class Client(object):
1827
1822
  Category:
1828
1823
  Feature flags
1829
1824
  """
1825
+ if send_feature_flag_events:
1826
+ warnings.warn(
1827
+ "send_feature_flag_events is deprecated in get_feature_flag_payload() and will be removed "
1828
+ "in a future version. Use get_feature_flag() if you want to send $feature_flag_called events.",
1829
+ DeprecationWarning,
1830
+ stacklevel=2,
1831
+ )
1832
+
1830
1833
  feature_flag_result = self._get_feature_flag_result(
1831
1834
  key,
1832
1835
  distinct_id,
@@ -2182,9 +2185,9 @@ class Client(object):
2182
2185
  return None
2183
2186
 
2184
2187
  try:
2185
- from urllib.parse import urlparse, parse_qs
2188
+ from urllib.parse import parse_qs, urlparse
2186
2189
  except ImportError:
2187
- from urlparse import urlparse, parse_qs
2190
+ from urlparse import parse_qs, urlparse
2188
2191
 
2189
2192
  try:
2190
2193
  parsed = urlparse(cache_url)
@@ -14,23 +14,23 @@ import types
14
14
  from datetime import datetime
15
15
  from types import FrameType, TracebackType # noqa: F401
16
16
  from typing import ( # noqa: F401
17
+ TYPE_CHECKING,
17
18
  Any,
18
19
  Dict,
19
20
  Iterator,
20
21
  List,
21
22
  Literal,
22
23
  Optional,
24
+ Pattern,
23
25
  Set,
24
26
  Tuple,
25
27
  TypedDict,
26
28
  TypeVar,
27
29
  Union,
28
30
  cast,
29
- TYPE_CHECKING,
30
- Pattern,
31
31
  )
32
32
 
33
- from posthog.args import ExcInfo, ExceptionArg # noqa: F401
33
+ from posthog.args import ExceptionArg, ExcInfo # noqa: F401
34
34
 
35
35
  try:
36
36
  # Python 3.11
@@ -409,7 +409,9 @@ class TestClient(unittest.TestCase):
409
409
  )
410
410
  client.feature_flags = [multivariate_flag, basic_flag, false_flag]
411
411
 
412
- msg_uuid = client.capture("python test event", distinct_id="distinct_id")
412
+ msg_uuid = client.capture(
413
+ "python test event", distinct_id="distinct_id", send_feature_flags=True
414
+ )
413
415
  self.assertIsNotNone(msg_uuid)
414
416
  self.assertFalse(self.failed)
415
417
 
@@ -565,6 +567,7 @@ class TestClient(unittest.TestCase):
565
567
  "python test event",
566
568
  distinct_id="distinct_id",
567
569
  properties={"$feature/beta-feature-local": "my-custom-variant"},
570
+ send_feature_flags=True,
568
571
  )
569
572
  self.assertIsNotNone(msg_uuid)
570
573
  self.assertFalse(self.failed)
@@ -746,6 +749,88 @@ class TestClient(unittest.TestCase):
746
749
 
747
750
  self.assertEqual(patch_flags.call_count, 0)
748
751
 
752
+ @mock.patch("posthog.client.flags")
753
+ def test_capture_with_send_feature_flags_false_and_local_evaluation_doesnt_send_flags(
754
+ self, patch_flags
755
+ ):
756
+ """Test that send_feature_flags=False with local evaluation enabled does NOT send flags"""
757
+ patch_flags.return_value = {"featureFlags": {"beta-feature": "remote-variant"}}
758
+
759
+ multivariate_flag = {
760
+ "id": 1,
761
+ "name": "Beta Feature",
762
+ "key": "beta-feature-local",
763
+ "active": True,
764
+ "rollout_percentage": 100,
765
+ "filters": {
766
+ "groups": [
767
+ {
768
+ "rollout_percentage": 100,
769
+ },
770
+ ],
771
+ "multivariate": {
772
+ "variants": [
773
+ {
774
+ "key": "first-variant",
775
+ "name": "First Variant",
776
+ "rollout_percentage": 50,
777
+ },
778
+ {
779
+ "key": "second-variant",
780
+ "name": "Second Variant",
781
+ "rollout_percentage": 50,
782
+ },
783
+ ]
784
+ },
785
+ },
786
+ }
787
+ simple_flag = {
788
+ "id": 2,
789
+ "name": "Simple Flag",
790
+ "key": "simple-flag",
791
+ "active": True,
792
+ "filters": {
793
+ "groups": [
794
+ {
795
+ "rollout_percentage": 100,
796
+ }
797
+ ],
798
+ },
799
+ }
800
+
801
+ with mock.patch("posthog.client.batch_post") as mock_post:
802
+ client = Client(
803
+ FAKE_TEST_API_KEY,
804
+ on_error=self.set_fail,
805
+ personal_api_key=FAKE_TEST_API_KEY,
806
+ sync_mode=True,
807
+ )
808
+ client.feature_flags = [multivariate_flag, simple_flag]
809
+
810
+ msg_uuid = client.capture(
811
+ "python test event",
812
+ distinct_id="distinct_id",
813
+ send_feature_flags=False,
814
+ )
815
+ self.assertIsNotNone(msg_uuid)
816
+ self.assertFalse(self.failed)
817
+
818
+ # Get the enqueued message from the mock
819
+ mock_post.assert_called_once()
820
+ batch_data = mock_post.call_args[1]["batch"]
821
+ msg = batch_data[0]
822
+
823
+ self.assertEqual(msg["event"], "python test event")
824
+ self.assertEqual(msg["distinct_id"], "distinct_id")
825
+
826
+ # CRITICAL: Verify local flags are NOT included in the event
827
+ self.assertNotIn("$feature/beta-feature-local", msg["properties"])
828
+ self.assertNotIn("$feature/simple-flag", msg["properties"])
829
+ self.assertNotIn("$active_feature_flags", msg["properties"])
830
+
831
+ # CRITICAL: Verify the /flags API was NOT called
832
+ self.assertEqual(patch_flags.call_count, 0)
833
+
749
834
  @mock.patch("posthog.client.flags")
750
835
  def test_capture_with_send_feature_flags_true_and_local_evaluation_uses_local_flags(
751
836
  self, patch_flags
@@ -3062,6 +3062,7 @@ class TestLocalEvaluation(unittest.TestCase):
3062
3062
  "some-distinct-id",
3063
3063
  match_value=True,
3064
3064
  person_properties={"region": "USA"},
3065
+ send_feature_flag_events=True,
3065
3066
  ),
3066
3067
  300,
3067
3068
  )
@@ -4051,7 +4052,9 @@ class TestCaptureCalls(unittest.TestCase):
4051
4052
 
4052
4053
  self.assertEqual(
4053
4054
  client.get_feature_flag_payload(
4054
- "decide-flag-with-payload", "some-distinct-id"
4055
+ "decide-flag-with-payload",
4056
+ "some-distinct-id",
4057
+ send_feature_flag_events=True,
4055
4058
  ),
4056
4059
  {"foo": "bar"},
4057
4060
  )
@@ -4127,9 +4130,10 @@ class TestCaptureCalls(unittest.TestCase):
4127
4130
 
4128
4131
  @mock.patch.object(Client, "capture")
4129
4132
  @mock.patch("posthog.client.flags")
4130
- def test_capture_is_called_in_get_feature_flag_payload(
4133
+ def test_get_feature_flag_payload_does_not_send_feature_flag_called_events(
4131
4134
  self, patch_flags, patch_capture
4132
4135
  ):
4136
+ """Test that get_feature_flag_payload does NOT send $feature_flag_called events"""
4133
4137
  patch_flags.return_value = {
4134
4138
  "featureFlags": {"person-flag": True},
4135
4139
  "featureFlagPayloads": {"person-flag": 300},
@@ -4151,68 +4155,18 @@ class TestCaptureCalls(unittest.TestCase):
4151
4155
  "rollout_percentage": 100,
4152
4156
  }
4153
4157
  ],
4158
+ "payloads": {"true": '"payload"'},
4154
4159
  },
4155
4160
  }
4156
4161
  ]
4157
4162
 
4158
- # Call get_feature_flag_payload with match_value=None to trigger get_feature_flag
4159
- client.get_feature_flag_payload(
4160
- key="person-flag",
4161
- distinct_id="some-distinct-id",
4162
- person_properties={"region": "USA", "name": "Aloha"},
4163
- )
4164
-
4165
- # Assert that capture was called once, with the correct parameters
4166
- self.assertEqual(patch_capture.call_count, 1)
4167
- patch_capture.assert_called_with(
4168
- "$feature_flag_called",
4169
- distinct_id="some-distinct-id",
4170
- properties={
4171
- "$feature_flag": "person-flag",
4172
- "$feature_flag_response": True,
4173
- "locally_evaluated": True,
4174
- "$feature/person-flag": True,
4175
- },
4176
- groups={},
4177
- disable_geoip=None,
4178
- )
4179
-
4180
- # Reset mocks for further tests
4181
- patch_capture.reset_mock()
4182
- patch_flags.reset_mock()
4183
-
4184
- # Call get_feature_flag_payload again for the same user; capture should not be called again because we've already reported an event for this distinct_id + flag
4185
- client.get_feature_flag_payload(
4163
+ payload = client.get_feature_flag_payload(
4186
4164
  key="person-flag",
4187
4165
  distinct_id="some-distinct-id",
4188
4166
  person_properties={"region": "USA", "name": "Aloha"},
4189
4167
  )
4190
-
4168
+ self.assertIsNotNone(payload)
4191
4169
  self.assertEqual(patch_capture.call_count, 0)
4192
- patch_capture.reset_mock()
4193
-
4194
- # Call get_feature_flag_payload for a different user; capture should be called
4195
- client.get_feature_flag_payload(
4196
- key="person-flag",
4197
- distinct_id="some-distinct-id2",
4198
- person_properties={"region": "USA", "name": "Aloha"},
4199
- )
4200
-
4201
- self.assertEqual(patch_capture.call_count, 1)
4202
- patch_capture.assert_called_with(
4203
- "$feature_flag_called",
4204
- distinct_id="some-distinct-id2",
4205
- properties={
4206
- "$feature_flag": "person-flag",
4207
- "$feature_flag_response": True,
4208
- "locally_evaluated": True,
4209
- "$feature/person-flag": True,
4210
- },
4211
- groups={},
4212
- disable_geoip=None,
4213
- )
4214
-
4215
- patch_capture.reset_mock()
4216
4170
 
4217
4171
  @mock.patch("posthog.client.flags")
4218
4172
  def test_fallback_to_api_in_get_feature_flag_payload_when_flag_has_static_cohort(
@@ -1,4 +1,4 @@
1
- VERSION = "7.4.0"
1
+ VERSION = "7.4.2"
2
2
 
3
3
  if __name__ == "__main__":
4
4
  print(VERSION, end="") # noqa: T201
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: posthog
3
- Version: 7.4.0
3
+ Version: 7.4.2
4
4
  Summary: Integrate PostHog into any python application.
5
5
  Home-page: https://github.com/posthog/posthog-python
6
6
  Author: Posthog
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes