Skip to content

Commit 7a8b091

Browse files
Twixesk11kirky
andauthored
feat(llmo): Make it optional to pass posthog client (#291)
Co-authored-by: Peter Kirkham <[email protected]>
1 parent da09639 commit 7a8b091

File tree

10 files changed

+51
-31
lines changed

10 files changed

+51
-31
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
# 6.2.1 - 2025-06-21
2+
3+
- feat: make `posthog_client` an optional argument in PostHog AI providers wrappers (`posthog.ai.*`), intuitively using the default client as the default
4+
15
# 6.1.1 - 2025-07-16
26

37
- fix: correctly capture exceptions processed by Django from views or middleware

posthog/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -676,7 +676,7 @@ def shutdown():
676676
_proxy("join")
677677

678678

679-
def setup():
679+
def setup() -> Client:
680680
global default_client
681681
if not default_client:
682682
if not api_key:
@@ -706,6 +706,8 @@ def setup():
706706
default_client.disabled = disabled
707707
default_client.debug = debug
708708

709+
return default_client
710+
709711

710712
def _proxy(method, *args, **kwargs):
711713
"""Create an analytics client if one doesn't exist and send to it."""

posthog/ai/anthropic/anthropic.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
import time
1010
import uuid
11-
from typing import Any, Dict, Optional
11+
from typing import Any, Dict, Optional, cast
1212

1313
from posthog.ai.utils import (
1414
call_llm_and_track_usage,
@@ -17,6 +17,7 @@
1717
with_privacy_mode,
1818
)
1919
from posthog.client import Client as PostHogClient
20+
from posthog import setup
2021

2122

2223
class Anthropic(anthropic.Anthropic):
@@ -26,14 +27,14 @@ class Anthropic(anthropic.Anthropic):
2627

2728
_ph_client: PostHogClient
2829

29-
def __init__(self, posthog_client: PostHogClient, **kwargs):
30+
def __init__(self, posthog_client: Optional[PostHogClient] = None, **kwargs):
3031
"""
3132
Args:
3233
posthog_client: PostHog client for tracking usage
3334
**kwargs: Additional arguments passed to the Anthropic client
3435
"""
3536
super().__init__(**kwargs)
36-
self._ph_client = posthog_client
37+
self._ph_client = posthog_client or setup()
3738
self.messages = WrappedMessages(self)
3839

3940

posthog/ai/anthropic/anthropic_async.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import uuid
1111
from typing import Any, Dict, Optional
1212

13+
from posthog import setup
1314
from posthog.ai.utils import (
1415
call_llm_and_track_usage_async,
1516
get_model_params,
@@ -26,14 +27,14 @@ class AsyncAnthropic(anthropic.AsyncAnthropic):
2627

2728
_ph_client: PostHogClient
2829

29-
def __init__(self, posthog_client: PostHogClient, **kwargs):
30+
def __init__(self, posthog_client: Optional[PostHogClient] = None, **kwargs):
3031
"""
3132
Args:
3233
posthog_client: PostHog client for tracking usage
3334
**kwargs: Additional arguments passed to the Anthropic client
3435
"""
3536
super().__init__(**kwargs)
36-
self._ph_client = posthog_client
37+
self._ph_client = posthog_client or setup()
3738
self.messages = AsyncWrappedMessages(self)
3839

3940

posthog/ai/anthropic/anthropic_providers.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,12 @@
55
"Please install the Anthropic SDK to use this feature: 'pip install anthropic'"
66
)
77

8+
from typing import Optional
9+
810
from posthog.ai.anthropic.anthropic import WrappedMessages
911
from posthog.ai.anthropic.anthropic_async import AsyncWrappedMessages
1012
from posthog.client import Client as PostHogClient
13+
from posthog import setup
1114

1215

1316
class AnthropicBedrock(anthropic.AnthropicBedrock):
@@ -17,9 +20,9 @@ class AnthropicBedrock(anthropic.AnthropicBedrock):
1720

1821
_ph_client: PostHogClient
1922

20-
def __init__(self, posthog_client: PostHogClient, **kwargs):
23+
def __init__(self, posthog_client: Optional[PostHogClient] = None, **kwargs):
2124
super().__init__(**kwargs)
22-
self._ph_client = posthog_client
25+
self._ph_client = posthog_client or setup()
2326
self.messages = WrappedMessages(self)
2427

2528

@@ -30,9 +33,9 @@ class AsyncAnthropicBedrock(anthropic.AsyncAnthropicBedrock):
3033

3134
_ph_client: PostHogClient
3235

33-
def __init__(self, posthog_client: PostHogClient, **kwargs):
36+
def __init__(self, posthog_client: Optional[PostHogClient] = None, **kwargs):
3437
super().__init__(**kwargs)
35-
self._ph_client = posthog_client
38+
self._ph_client = posthog_client or setup()
3639
self.messages = AsyncWrappedMessages(self)
3740

3841

@@ -43,9 +46,9 @@ class AnthropicVertex(anthropic.AnthropicVertex):
4346

4447
_ph_client: PostHogClient
4548

46-
def __init__(self, posthog_client: PostHogClient, **kwargs):
49+
def __init__(self, posthog_client: Optional[PostHogClient] = None, **kwargs):
4750
super().__init__(**kwargs)
48-
self._ph_client = posthog_client
51+
self._ph_client = posthog_client or setup()
4952
self.messages = WrappedMessages(self)
5053

5154

@@ -56,7 +59,7 @@ class AsyncAnthropicVertex(anthropic.AsyncAnthropicVertex):
5659

5760
_ph_client: PostHogClient
5861

59-
def __init__(self, posthog_client: PostHogClient, **kwargs):
62+
def __init__(self, posthog_client: Optional[PostHogClient] = None, **kwargs):
6063
super().__init__(**kwargs)
61-
self._ph_client = posthog_client
64+
self._ph_client = posthog_client or setup()
6265
self.messages = AsyncWrappedMessages(self)

posthog/ai/gemini/gemini.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
"Please install the Google Gemini SDK to use this feature: 'pip install google-genai'"
1111
)
1212

13+
from posthog import setup
1314
from posthog.ai.utils import (
1415
call_llm_and_track_usage,
1516
get_model_params,
@@ -36,6 +37,8 @@ class Client:
3637
)
3738
"""
3839

40+
_ph_client: PostHogClient
41+
3942
def __init__(
4043
self,
4144
api_key: Optional[str] = None,
@@ -56,12 +59,14 @@ def __init__(
5659
posthog_groups: Default groups for all calls (can be overridden per call)
5760
**kwargs: Additional arguments (for future compatibility)
5861
"""
59-
if posthog_client is None:
62+
self._ph_client = posthog_client or setup()
63+
64+
if self._ph_client is None:
6065
raise ValueError("posthog_client is required for PostHog tracking")
6166

6267
self.models = Models(
6368
api_key=api_key,
64-
posthog_client=posthog_client,
69+
posthog_client=self._ph_client,
6570
posthog_distinct_id=posthog_distinct_id,
6671
posthog_properties=posthog_properties,
6772
posthog_privacy_mode=posthog_privacy_mode,
@@ -97,10 +102,10 @@ def __init__(
97102
posthog_groups: Default groups for all calls
98103
**kwargs: Additional arguments (for future compatibility)
99104
"""
100-
if posthog_client is None:
101-
raise ValueError("posthog_client is required for PostHog tracking")
105+
self._ph_client = posthog_client or setup()
102106

103-
self._ph_client = posthog_client
107+
if self._ph_client is None:
108+
raise ValueError("posthog_client is required for PostHog tracking")
104109

105110
# Store default PostHog settings
106111
self._default_distinct_id = posthog_distinct_id

posthog/ai/openai/openai.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
with_privacy_mode,
1616
)
1717
from posthog.client import Client as PostHogClient
18+
from posthog import setup
1819

1920

2021
class OpenAI(openai.OpenAI):
@@ -24,16 +25,15 @@ class OpenAI(openai.OpenAI):
2425

2526
_ph_client: PostHogClient
2627

27-
def __init__(self, posthog_client: PostHogClient, **kwargs):
28+
def __init__(self, posthog_client: Optional[PostHogClient] = None, **kwargs):
2829
"""
2930
Args:
3031
api_key: OpenAI API key.
31-
posthog_client: If provided, events will be captured via this client instead
32-
of the global posthog.
32+
posthog_client: If provided, events will be captured via this client instead of the global `posthog`.
3333
**openai_config: Any additional keyword args to set on openai (e.g. organization="xxx").
3434
"""
3535
super().__init__(**kwargs)
36-
self._ph_client = posthog_client
36+
self._ph_client = posthog_client or setup()
3737

3838
# Store original objects after parent initialization (only if they exist)
3939
self._original_chat = getattr(self, "chat", None)

posthog/ai/openai/openai_async.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import time
22
import uuid
3-
from typing import Any, Dict, List, Optional
3+
from typing import Any, Dict, List, Optional, cast
44

55
try:
66
import openai
@@ -9,6 +9,7 @@
99
"Please install the OpenAI SDK to use this feature: 'pip install openai'"
1010
)
1111

12+
from posthog import setup
1213
from posthog.ai.utils import (
1314
call_llm_and_track_usage_async,
1415
get_model_params,
@@ -24,7 +25,7 @@ class AsyncOpenAI(openai.AsyncOpenAI):
2425

2526
_ph_client: PostHogClient
2627

27-
def __init__(self, posthog_client: PostHogClient, **kwargs):
28+
def __init__(self, posthog_client: Optional[PostHogClient] = None, **kwargs):
2829
"""
2930
Args:
3031
api_key: OpenAI API key.
@@ -33,7 +34,7 @@ def __init__(self, posthog_client: PostHogClient, **kwargs):
3334
**openai_config: Any additional keyword args to set on openai (e.g. organization="xxx").
3435
"""
3536
super().__init__(**kwargs)
36-
self._ph_client = posthog_client
37+
self._ph_client = posthog_client or setup()
3738

3839
# Store original objects after parent initialization (only if they exist)
3940
self._original_chat = getattr(self, "chat", None)

posthog/ai/openai/openai_providers.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@
1515
from posthog.ai.openai.openai_async import WrappedChat as AsyncWrappedChat
1616
from posthog.ai.openai.openai_async import WrappedEmbeddings as AsyncWrappedEmbeddings
1717
from posthog.ai.openai.openai_async import WrappedResponses as AsyncWrappedResponses
18+
from typing import Optional
19+
1820
from posthog.client import Client as PostHogClient
21+
from posthog import setup
1922

2023

2124
class AzureOpenAI(openai.AzureOpenAI):
@@ -25,7 +28,7 @@ class AzureOpenAI(openai.AzureOpenAI):
2528

2629
_ph_client: PostHogClient
2730

28-
def __init__(self, posthog_client: PostHogClient, **kwargs):
31+
def __init__(self, posthog_client: Optional[PostHogClient] = None, **kwargs):
2932
"""
3033
Args:
3134
api_key: Azure OpenAI API key.
@@ -34,7 +37,7 @@ def __init__(self, posthog_client: PostHogClient, **kwargs):
3437
**openai_config: Any additional keyword args to set on Azure OpenAI (e.g. azure_endpoint="xxx").
3538
"""
3639
super().__init__(**kwargs)
37-
self._ph_client = posthog_client
40+
self._ph_client = posthog_client or setup()
3841

3942
# Store original objects after parent initialization (only if they exist)
4043
self._original_chat = getattr(self, "chat", None)
@@ -63,7 +66,7 @@ class AsyncAzureOpenAI(openai.AsyncAzureOpenAI):
6366

6467
_ph_client: PostHogClient
6568

66-
def __init__(self, posthog_client: PostHogClient, **kwargs):
69+
def __init__(self, posthog_client: Optional[PostHogClient] = None, **kwargs):
6770
"""
6871
Args:
6972
api_key: Azure OpenAI API key.
@@ -72,7 +75,7 @@ def __init__(self, posthog_client: PostHogClient, **kwargs):
7275
**openai_config: Any additional keyword args to set on Azure OpenAI (e.g. azure_endpoint="xxx").
7376
"""
7477
super().__init__(**kwargs)
75-
self._ph_client = posthog_client
78+
self._ph_client = posthog_client or setup()
7679

7780
# Store original objects after parent initialization (only if they exist)
7881
self._original_chat = getattr(self, "chat", None)

posthog/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
VERSION = "6.1.1"
1+
VERSION = "6.2.1"
22

33
if __name__ == "__main__":
44
print(VERSION, end="") # noqa: T201

0 commit comments

Comments
 (0)