
    KiP[                     0   S SK r S SKrS SKJrJrJrJr   S SKrS SK
JrJrJr  S SKJr   " S S\R"                  5      r " S S	5      r " S
 S5      r " S S5      r " S S5      r " S S5      r " S S5      r " S S5      rg! \ a	    \	" S5      ef = f)    N)AnyDictListOptionalzGPlease install the OpenAI SDK to use this feature: 'pip install openai')call_llm_and_track_usageget_model_paramswith_privacy_mode)Clientc                   @   ^  \ rS rSr% Sr\\S'   S\4U 4S jjrSrU =r	$ )OpenAI   zW
A wrapper around the OpenAI SDK that automatically sends LLM usage events to PostHog.

_ph_clientposthog_clientc                   > [         TU ]  " S0 UD6  Xl        [        U SS5      U l        [        U SS5      U l        [        U SS5      U l        [        U SS5      U l        U R                  b  [        X R                  5      U l	        U R
                  b  [        X R
                  5      U l        U R                  b  [        X R                  5      U l        U R                  b  [        X R                  5      U l        gg)z
Args:
    api_key: OpenAI API key.
    posthog_client: If provided, events will be captured via this client instead
                    of the global posthog.
    **openai_config: Any additional keyword args to set on openai (e.g. organization="xxx").
chatN
embeddingsbeta	responses )super__init__r   getattr_original_chat_original_embeddings_original_beta_original_responsesWrappedChatr   WrappedEmbeddingsr   WrappedBetar   WrappedResponsesr   )selfr   kwargs	__class__s      Z/var/www/html/dynamic-report/venv/lib/python3.13/site-packages/posthog/ai/openai/openai.pyr   OpenAI.__init__   s     	"6"( &dFD9$+D,$E!%dFD9#*4d#C  *#D*=*=>DI$$0/6O6OPDO*#D*=*=>DI##/-d4L4LMDN 0    )	r   r   r   r   r   r   r   r   r   )
__name__
__module____qualname____firstlineno____doc__PostHogClient__annotations__r   __static_attributes____classcell__)r#   s   @r$   r   r      s$     N} N Nr&   r   c                      \ rS rSrSrS\4S jrS r     SS\\	   S\\	   S	\\
\	\4      S
\S\\
\	\4      S\4S jjrS\\	   S\\	   S	\\
\	\4      S
\S\\
\	\4      S\4S jr SS\\	   S\\	   S	\\
\	\4      S
\S\\
\	\4      S\
\	\4   S\
\	\4   S\S\S\\\
\	\4         4S jjr     SS\\	   S\\	   S	\\
\	\4      S
\S\\
\	\4      S\4S jjrSrg)r    :   z:Wrapper for OpenAI responses that tracks usage in PostHog.clientc                     Xl         X l        g N_client	_original)r!   r2   original_responsess      r$   r   WrappedResponses.__init__=       +r&   c                 .    [        U R                  U5      $ )zQFallback to original responses object for any methods we don't explicitly handle.r   r7   r!   names     r$   __getattr__WrappedResponses.__getattr__A       t~~t,,r&   Nposthog_distinct_idposthog_trace_idposthog_propertiesposthog_privacy_modeposthog_groupsr"   c                 @   Uc  [        [        R                  " 5       5      nUR                  SS5      (       a  U R                  " UUUUU40 UD6$ [        UU R                  R                  SUUUUU R                  R                  U R                  R                  4	0 UD6$ NstreamFopenaistruuiduuid4get_create_streamingr   r6   r   base_urlr7   creater!   rB   rC   rD   rE   rF   r"   s          r$   rR   WrappedResponses.createE        #"4::<0::h&&))# "$   (LL## LL!!NN!!
 
 	
r&   c                    ^ ^^^^^^^^	^
^ [         R                   " 5       m
0 m/ mT R                  R                  " S0 TD6m	UUUUUUUU	U U
U4S jnU" 5       $ )Nc               3   $  >#     T GH  n [        U S5      (       ad  U R                  S:X  aT  U R                  nUR                  (       a7  [	        UR                  5      S:  a  TR                  UR                  S   5        [        U S5      (       Ga   U R                  (       a  S Vs0 s H  nU[        U R                  US5      _M     snm[        U R                  S5      (       aH  [        U R                  R                  S5      (       a#  U R                  R                  R                  TS'   [        U R                  S5      (       aH  [        U R                  R                  S	5      (       a#  U R                  R                  R                  TS
'   U v   GM     [        R                  " 5       nUT-
  nTnTR                  TTTT
T	TTUU5	        g s  snf ! [        R                  " 5       nUT-
  nTnTR                  TTTT
T	TTUU5	        f = f7f)Ntypezresponse.completedr   usage)input_tokensoutput_tokenstotal_tokensoutput_tokens_detailsreasoning_tokensinput_tokens_detailscached_tokenscache_read_input_tokens)hasattrrX   responseoutputlenappendrY   r   r]   r^   r_   r`   time_capture_streaming_event)chunkreskend_timelatencyrd   final_contentr"   rB   rF   rE   rD   rC   rc   r!   
start_timeusage_statss         r$   	generator5WrappedResponses._create_streaming.<locals>.generatorv   s    0%Euf--%**@T2T#nn::#cjj/A*=)00A?ug..5;;&'& wu{{Aq99&' #5;;0GHHW!KK==?QN N !& A A R R ((:; #5;;0FGGG!KK<<oM M !& @ @ N N ((AB  K? &D  99;"Z/&--'$&("
='6  99;"Z/&--'$&("
s0   HB"G '"G	CG 6HG 7HHr   rg   r7   rR   )r!   rB   rC   rD   rE   rF   r"   rq   rn   rc   ro   rp   s   ``````` @@@@r$   rP   "WrappedResponses._create_streamingh   sG     YY[
&(>>((2624	 4	l {r&   rp   rm   rd   
tool_callsc                    Uc  [        [        R                  " 5       5      nSUR                  S5      [	        U5      [        U R                  R                  XFR                  S5      5      [        U R                  R                  UU	5      SUR                  SS5      UR                  SS5      UR                  SS5      UR                  S	S5      UU[        U R                  R                  5      S
.U=(       d    0 EnU
(       a$  [        U R                  R                  UU
5      US'   Uc  SUS'   [        U R                  R                  S5      (       a0  U R                  R                  R                  U=(       d    USUUS9  g g )NrJ   modelinput   rZ   r   r[   ra   r^   $ai_provider	$ai_modelz$ai_model_parameters	$ai_inputz$ai_output_choices$ai_http_status$ai_input_tokensz$ai_output_tokensz$ai_cache_read_input_tokensz$ai_reasoning_tokens$ai_latency$ai_trace_id$ai_base_url	$ai_toolsF$process_person_profilecapture$ai_generationdistinct_idevent
propertiesgroupsrL   rM   rN   rO   r   r	   r6   r   rQ   rb   r   r!   rB   rC   rD   rE   rF   r"   rp   rm   rd   ru   event_propertiess               r$   rh   )WrappedResponses._capture_streaming_event   sk    #"4::<0 %G,$4V$<*'')=zz'?R #4''$#
  # + B!,!!D+6??)1, %0OO4F$J", 5 56+
, "'R-
2 ,=''$-[) &:?674<<**I66LL##++/C3C&+%	 ,  7r&   c                     [        UU R                  R                  SUUUUU R                  R                  U R                  R
                  4	0 UD6$ )ah  
Parse structured output using OpenAI's 'responses.parse' method, but also track usage in PostHog.

Args:
    posthog_distinct_id: Optional ID to associate with the usage event.
    posthog_trace_id: Optional trace UUID for linking events.
    posthog_properties: Optional dictionary of extra properties to include in the event.
    posthog_privacy_mode: Whether to anonymize the input and output.
    posthog_groups: Optional dictionary of groups to associate with the event.
    **kwargs: Any additional parameters for the OpenAI Responses Parse API.

Returns:
    The response from OpenAI's responses.parse call.
rJ   r   r6   r   rQ   r7   parserS   s          r$   r   WrappedResponses.parse   sT    . (LL## LL!!NN  
 
 	
r&   r5   NNNFNr4   )r'   r(   r)   r*   r+   r   r   r?   r   rL   r   r   boolrR   rP   intfloatr   rh   r   r.   r   r&   r$   r    r    :   s   D,v ,- .2*.7;%*37!
%c]!
 #3-!
 %T#s(^4	!

 #!
 !c3h0!
 !
FD%c]D #3-D %T#s(^4	D
 #D !c3h0D Db 6:9%c]9 #3-9 %T#s(^4	9
 #9 !c3h09 S#X9 #s(^9 9 9 T$sCx.129z .2*.7;%*37"
%c]"
 #3-"
 %T#s(^4	"

 #"
 !c3h0"
 "
 "
r&   r    c                   <    \ rS rSrSrS\4S jrS r\S 5       r	Sr
g)	r   i  z5Wrapper for OpenAI chat that tracks usage in PostHog.r2   c                     Xl         X l        g r4   r5   )r!   r2   original_chats      r$   r   WrappedChat.__init__      &r&   c                 .    [        U R                  U5      $ )zLFallback to original chat object for any methods we don't explicitly handle.r<   r=   s     r$   r?   WrappedChat.__getattr__  rA   r&   c                 V    [        U R                  U R                  R                  5      $ r4   )WrappedCompletionsr6   r7   completionsr!   s    r$   r   WrappedChat.completions  s    !$,,0J0JKKr&   r5   Nr'   r(   r)   r*   r+   r   r   r?   propertyr   r.   r   r&   r$   r   r     s,    ?'v '- L Lr&   r   c                   d   \ rS rSrSrS\4S jrS r     SS\\	   S\\	   S	\\
\	\4      S
\S\\
\	\4      S\4S jjrS\\	   S\\	   S	\\
\	\4      S
\S\\
\	\4      S\4S jr SS\\	   S\\	   S	\\
\	\4      S
\S\\
\	\4      S\
\	\4   S\
\	\4   S\S\S\\\
\	\4         4S jjrSrg)r   i  zAWrapper for OpenAI chat completions that tracks usage in PostHog.r2   c                     Xl         X l        g r4   r5   )r!   r2   original_completionss      r$   r   WrappedCompletions.__init__!  s    -r&   c                 .    [        U R                  U5      $ )zSFallback to original completions object for any methods we don't explicitly handle.r<   r=   s     r$   r?   WrappedCompletions.__getattr__%  rA   r&   NrB   rC   rD   rE   rF   r"   c                 @   Uc  [        [        R                  " 5       5      nUR                  SS5      (       a  U R                  " UUUUU40 UD6$ [        UU R                  R                  SUUUUU R                  R                  U R                  R                  4	0 UD6$ rH   rK   rS   s          r$   rR   WrappedCompletions.create)  rU   r&   c                    ^ ^^^^^^^^	^
^^ [         R                   " 5       m0 m/ m0 m	ST;  a  0 TS'   STS   S'   T R                  R                  " S0 TD6m
UU	UUUUUUU
U UU4S jnU" 5       $ )Nstream_optionsTinclude_usagec               3     >#     T GH  n [        U S5      (       Ga   U R                  (       a  S Vs0 s H  nU[        U R                  US5      _M     snm[        U R                  S5      (       aH  [        U R                  R                  S5      (       a#  U R                  R                  R                  TS'   [        U R                  S5      (       aH  [        U R                  R
                  S5      (       a#  U R                  R
                  R                  TS'   [        U S	5      (       Ga`  U R                  (       GaN  [        U R                  5      S:  Ga4  U R                  S   R                  (       ac  U R                  S   R                  R                  (       a;  U R                  S   R                  R                  nU(       a  T
R                  U5        [        U R                  S   R                  S
S 5      nU(       a  U H  nUR                  nUT;  a  UTU'   M  [        US5      (       d  M/  [        UR                  S5      (       d  ML  TU   R                  =R                  UR                  R                  -  sl        M     U v   GM     [        R                  " 5       nUT-
  nSR!                  T
5      nT(       a  [#        TR%                  5       5      OS n	TR'                  TTTTTTTUUU	5
        g s  snf ! [        R                  " 5       nUT-
  nSR!                  T
5      nT(       a  [#        TR%                  5       5      OS n	TR'                  TTTTTTTUUU	5
        f = f7f)NrY   )prompt_tokenscompletion_tokensr\   r   prompt_tokens_detailsr`   ra   r]   r^   choicesru   function	arguments )rb   rY   r   r   r`   r]   r^   r   re   deltacontentrf   indexr   r   rg   joinlistvaluesrh   )ri   rk   r   ru   	tool_callr   rl   rm   rd   toolsaccumulated_contentaccumulated_toolsr"   rB   rF   rE   rD   rC   rc   r!   ro   rp   s             r$   rq   7WrappedCompletions._create_streaming.<locals>.generator^  s
    
I%Eug..5;;&'& wu{{Aq99&' #5;;0GHHW!KK==N N !& A A O O ((AB #5;;0GHHW!KK==?QN N !& A A R R ((:;
  y11!MMM.2 ==+11emmA6F6L6L6T6T&+mmA&6&<&<&D&DG& 3 : :7 C &-U]]1-=-C-C\SW%X
%-7	(1#(0A#A?H$5e$< (/y*'E'E'(1(:(:KK& K& ):,1)**2()=3<9,5,>,>,H,H)*3< .8  Km &r  99;"Z/!45<M.5578SW--'$&("w'n  99;"Z/!45<M.5578SW--'$&("s=   M1-L "L G L 8L AL A(M1 L A)M..M1r   rs   )r!   rB   rC   rD   rE   rF   r"   rq   r   r   rc   ro   rp   s   ``````` @@@@@r$   rP   $WrappedCompletions._create_streamingL  sy     YY[
&( 6)')F#$48 1>>((262N	 N	 N	` {r&   rp   rm   rd   ru   c                    Uc  [        [        R                  " 5       5      nSUR                  S5      [	        U5      [        U R                  R                  XFR                  S5      5      [        U R                  R                  UU	SS./5      SUR                  SS5      UR                  S	S5      UR                  S
S5      UR                  SS5      UU[        U R                  R                  5      S.U=(       d    0 EnU
(       a$  [        U R                  R                  UU
5      US'   Uc  SUS'   [        U R                  R                  S5      (       a0  U R                  R                  R                  U=(       d    USUUS9  g g )NrJ   rw   messages	assistant)r   rolery   r   r   r   ra   r^   rz   r   Fr   r   r   r   r   r   s               r$   rh   +WrappedCompletions._capture_streaming_event  st    #"4::<0 %G,$4V$<*'')=zz*?U #4''$#[9:#
  # + C!,1Da!H+6??)1, %0OO4F$J", 5 56+
, "'R-
2 ,=''$-[) &:?674<<**I66LL##++/C3C&+%	 ,  7r&   r5   r   r4   )r'   r(   r)   r*   r+   r   r   r?   r   rL   r   r   r   rR   rP   r   r   r   rh   r.   r   r&   r$   r   r     s   K.v .- .2*.7;%*37!
%c]!
 #3-!
 %T#s(^4	!

 #!
 !c3h0!
 !
Fb%c]b #3-b %T#s(^4	b
 #b !c3h0b b^ 6:9%c]9 #3-9 %T#s(^4	9
 #9 !c3h09 S#X9 #s(^9 9 9 T$sCx.129 9r&   r   c                       \ rS rSrSrS\4S jrS r     SS\\	   S\\	   S	\\
\	\4      S
\S\\
\	\4      S\4S jjrSrg)r   i  z;Wrapper for OpenAI embeddings that tracks usage in PostHog.r2   c                     Xl         X l        g r4   r5   )r!   r2   original_embeddingss      r$   r   WrappedEmbeddings.__init__  s    ,r&   c                 .    [        U R                  U5      $ )zRFallback to original embeddings object for any methods we don't explicitly handle.r<   r=   s     r$   r?   WrappedEmbeddings.__getattr__  rA   r&   NrB   rC   rD   rE   rF   r"   c           
      8   Uc  [        [        R                  " 5       5      n[        R                  " 5       nU R                  R
                  " S0 UD6n[        R                  " 5       n	0 n
[        US5      (       a@  UR                  (       a/  [        UR                  SS5      [        UR                  SS5      S.n
X-
  nSUR                  S5      [        U R                  R                  XFR                  S5      5      S	U
R                  SS5      UU[        U R                  R                  5      S
.U=(       d    0 EnUc  SUS'   [        U R                  R                  S5      (       a/  U R                  R                  R                  U=(       d    USUUS9  U$ )ac  
Create an embedding using OpenAI's 'embeddings.create' method, but also track usage in PostHog.

Args:
    posthog_distinct_id: Optional ID to associate with the usage event.
    posthog_trace_id: Optional trace UUID for linking events.
    posthog_properties: Optional dictionary of extra properties to include in the event.
    posthog_privacy_mode: Whether to anonymize the input and output.
    posthog_groups: Optional dictionary of groups to associate with the event.
    **kwargs: Any additional parameters for the OpenAI Embeddings API.

Returns:
    The response from OpenAI's embeddings.create call.
rY   r   r   r\   )r   r\   rJ   rw   rx   ry   )r{   r|   r}   r~   r   r   r   r   Fr   r   z$ai_embeddingr   r   )rL   rM   rN   rg   r7   rR   rb   rY   r   rO   r	   r6   r   rQ   r   )r!   rB   rC   rD   rE   rF   r"   ro   rc   rl   rp   rm   r   s                r$   rR   WrappedEmbeddings.create  sj   . #"4::<0YY[
>>((26299; 8W%%(..!(!!L ' JK
 ' %G,*'')=zz'?R  # + C", 5 56
 "'R
 &:?67 4<<**I66LL##++/C3C%+%	 ,  r&   r5   r   )r'   r(   r)   r*   r+   r   r   r?   r   rL   r   r   r   rR   r.   r   r&   r$   r   r     s    E-v -- .2*.7;%*37C%c]C #3-C %T#s(^4	C
 #C !c3h0C C Cr&   r   c                   <    \ rS rSrSrS\4S jrS r\S 5       r	Sr
g)	r   i=  z>Wrapper for OpenAI beta features that tracks usage in PostHog.r2   c                     Xl         X l        g r4   r5   )r!   r2   original_betas      r$   r   WrappedBeta.__init__@  r   r&   c                 .    [        U R                  U5      $ )zLFallback to original beta object for any methods we don't explicitly handle.r<   r=   s     r$   r?   WrappedBeta.__getattr__D  rA   r&   c                 V    [        U R                  U R                  R                  5      $ r4   )WrappedBetaChatr6   r7   r   r   s    r$   r   WrappedBeta.chatH  s    t||T^^-@-@AAr&   r5   N)r'   r(   r)   r*   r+   r   r   r?   r   r   r.   r   r&   r$   r   r   =  s,    H'v '- B Br&   r   c                   <    \ rS rSrSrS\4S jrS r\S 5       r	Sr
g)	r   iM  z:Wrapper for OpenAI beta chat that tracks usage in PostHog.r2   c                     Xl         X l        g r4   r5   )r!   r2   original_beta_chats      r$   r   WrappedBetaChat.__init__P  r:   r&   c                 .    [        U R                  U5      $ )zQFallback to original beta chat object for any methods we don't explicitly handle.r<   r=   s     r$   r?   WrappedBetaChat.__getattr__T  rA   r&   c                 V    [        U R                  U R                  R                  5      $ r4   )WrappedBetaCompletionsr6   r7   r   r   s    r$   r   WrappedBetaChat.completionsX  s    %dllDNN4N4NOOr&   r5   Nr   r   r&   r$   r   r   M  s,    D,v ,- P Pr&   r   c                       \ rS rSrSrS\4S jrS r     SS\\	   S\\	   S	\\
\	\4      S
\S\\
\	\4      S\4S jjrSrg)r   i]  zFWrapper for OpenAI beta chat completions that tracks usage in PostHog.r2   c                     Xl         X l        g r4   r5   )r!   r2   original_beta_completionss      r$   r   WrappedBetaCompletions.__init__`  s    2r&   c                 .    [        U R                  U5      $ )zXFallback to original beta completions object for any methods we don't explicitly handle.r<   r=   s     r$   r?   "WrappedBetaCompletions.__getattr__d  rA   r&   NrB   rC   rD   rE   rF   r"   c                     [        UU R                  R                  SUUUUU R                  R                  U R                  R
                  4	0 UD6$ )NrJ   r   rS   s          r$   r   WrappedBetaCompletions.parseh  sT     (LL## LL!!NN  
 
 	
r&   r5   r   )r'   r(   r)   r*   r+   r   r   r?   r   rL   r   r   r   r   r.   r   r&   r$   r   r   ]  s    P3v 3- .2*.7;%*37
%c]
 #3-
 %T#s(^4	

 #
 !c3h0
 
 
r&   r   )rg   rM   typingr   r   r   r   rJ   ImportErrorModuleNotFoundErrorposthog.ai.utilsr   r   r	   posthog.clientr
   r,   r   r    r   r   r   r   r   r   r   r&   r$   <module>r      s      , , 
 3#NV]] #NLQ
 Q
hL L K K\N NbB B P P 
 
m  
Q s   B B