77 raise ModuleNotFoundError ("Please install OpenAI to use this feature: 'pip install openai'" )
88
99from posthog .client import Client as PostHogClient
10- from posthog .ai .utils import track_usage_async , get_model_params
10+ from posthog .ai .utils import call_llm_and_track_usage_async , get_model_params
1111
1212
1313class AsyncOpenAI :
@@ -29,6 +29,15 @@ def __init__(
2929 self ._openai_client = openai .AsyncOpenAI (** openai_config )
3030 self ._posthog_client = posthog_client
3131
32+ def __getattr__ (self , name : str ) -> Any :
33+ """
34+ Expose all attributes of the underlying openai.AsyncOpenAI instance except for the 'chat' property,
35+ which is replaced with a custom AsyncChatNamespace for usage tracking.
36+ """
37+ if name == "chat" :
38+ return self .chat
39+ return getattr (self ._openai_client , name )
40+
3241 @property
3342 def chat (self ) -> "AsyncChatNamespace" :
3443 return AsyncChatNamespace (self ._posthog_client , self ._openai_client )
@@ -71,11 +80,10 @@ async def create(
7180 async def call_async_method (** call_kwargs ):
7281 return await self ._openai_client .chat .completions .create (** call_kwargs )
7382
74- response = await track_usage_async (
83+ response = await call_llm_and_track_usage_async (
7584 distinct_id , self ._ph_client , posthog_trace_id , posthog_properties , call_async_method , ** kwargs
7685 )
7786 return response
78-
7987
8088 async def _create_streaming (
8189 self ,
@@ -106,7 +114,9 @@ async def async_generator():
106114 end_time = time .time ()
107115 latency = end_time - start_time
108116 output = "" .join (accumulated_content )
109- self ._capture_streaming_event (distinct_id , posthog_trace_id , posthog_properties , kwargs , usage_stats , latency , output )
117+ self ._capture_streaming_event (
118+ distinct_id , posthog_trace_id , posthog_properties , kwargs , usage_stats , latency , output
119+ )
110120
111121 return async_generator ()
112122
@@ -120,7 +130,7 @@ def _capture_streaming_event(
120130 latency : float ,
121131 output : str ,
122132 ):
123-
133+
124134 event_properties = {
125135 "$ai_provider" : "openai" ,
126136 "$ai_model" : kwargs .get ("model" ),
@@ -133,7 +143,7 @@ def _capture_streaming_event(
133143 "role" : "assistant" ,
134144 }
135145 ]
136- },
146+ },
137147 "$ai_http_status" : 200 ,
138148 "$ai_input_tokens" : usage_stats .get ("prompt_tokens" , 0 ),
139149 "$ai_output_tokens" : usage_stats .get ("completion_tokens" , 0 ),
@@ -148,4 +158,3 @@ def _capture_streaming_event(
148158 event = "$ai_generation" ,
149159 properties = event_properties ,
150160 )
151-
0 commit comments