
    gK                       d dl mZ d dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
 d dlmZ d dlmZmZ d dlZd dlmZmZ d dlZdd	lmZmZ dd
lmZmZmZ ddlmZ ddlmZmZ  G d de      Z  G d de      Z! G d de
      Z" e"       Z#d dZ$	 d!	 	 	 	 	 	 	 	 	 d"dZ%ed#d       Z&d$dZ'd%dZ( G d de)      Z*d&dZ+ G d de,      Z- G d de.      Z/d'dZ0y)(    )annotationsN)	lru_cache)	Formatter)CodeType)AnyLiteral)NotRequired	TypedDict   )ATTRIBUTES_SCRUBBED_KEY$MESSAGE_FORMATTED_VALUE_LENGTH_LIMIT)NOOP_SCRUBBERBaseScrubberScrubbedNote)warn_at_user_stacklevel)log_internal_errortruncate_stringc                  "    e Zd ZU ded<   ded<   y)LiteralChunkzLiteral['lit']tstrvN__name__
__module____qualname____annotations__     P/var/www/openai/venv/lib/python3.12/site-packages/logfire/_internal/formatter.pyr   r      s    
Fr   r   c                  ,    e Zd ZU ded<   ded<   ded<   y)ArgChunkzLiteral['arg']r   r   r   zNotRequired[str]specNr   r   r   r    r"   r"      s    
F
r   r"   c                  l    e Zd Zdd	 	 	 	 	 	 	 	 	 d	dZ	 	 	 	 	 	 	 	 d
dZdd	 	 	 	 	 	 	 	 	 ddZddZy)ChunksFormatterN)fstring_framec               l    |r| j                  |||      }|r|S | j                  |||      \  }}|||fS )N)kwargsscrubber)_fstring_chunks_vformat_chunks)selfformat_stringr(   r)   r&   resultchunksextra_attrss           r    r/   zChunksFormatter.chunks$   sU     ))&(MJF"22 3 
 {M11r   c           	     .   |j                   }|j                  }|J t        j                  j                  |      }|j                  }||j
                  j                  st        dt        |             y d}t        j                  d d dk  r|dz  }g }|j                  D ]=  }	t        |	t        j                        r||	j                  z  }-|j!                  |	       ? |D 
cg c]P  }
t        j"                  |
      D ]6  }t        |t        j$                        r|j&                  s|j(                  r|8 R }}
}t+        |      dk7  rt        |t        |             y |\  }t        |t        j$                        st        dt        |             y |t,        j.                  j0                  j2                  k(  rlt+        |j&                        dk\  r|j&                  d   }nv|j(                  D ]  }|j4                  dk(  s|j6                  } nI t        d	t        |             y |j&                  r|j&                  d
   }nt        d	t        |             y t        |t        j8                        sy |j:                  }i |j<                  |}g }d}i }g }|j>                  D ]  }t        |t        j@                        r&|j6                  }|j!                  |dd       ||z  }Ct        |t        jB                        sJ tE        ||j
                        \  }}}|d|z   dz   z  }tG        |||      }|||<   tG        ||i |d|i      }| jI                  |||      \  }}||z  }|j!                  |dd        |r	||tJ        <   |||fS c c}}
w )NzNo source code available. This happens when running in an interactive shell, using exec(), or running .pyc files without the source .py files.z"`executing` failed to find a node.   )      zM This may be caused by a combination of using Python < 3.11 and auto-tracing.r   z4`executing` unexpectedly identified a non-Call node.msg_templatez:Couldn't identify the `msg_template` argument in the call.r    litr   r   {}@fvaluearg)&f_codef_back	executingSourcenodesourcetextwarn_inspect_argumentsget_stacklevelsysversion_info
statements
isinstanceastWithitemsappendwalkCallargskeywordslenlogfireLogfirelog__code__r<   value	JoinedStr	f_globalsf_localsvaluesConstantFormattedValuecompile_formatted_valueeval_clean_valuer   )r,   r(   r)   framecalled_codeex	call_nodemsg
main_nodes	statement	main_noderA   
call_nodesarg_nodekeywordglobal_vars
local_varsr.   new_templater0   scrubbed
node_valuerW   rB   
value_codeformatted_code	formattedvalue_scrubbeds                               r    r*   zChunksFormatter._fstring_chunks?   s    ll    ''.GG	 99>> 'X #5)	 6C#g-
 ff )+J]]	i2)//1J%%i0 + ",!+IHHY/DdCHH-99	 / !+   :!#&sN5,AB$KY)SXX."Fu% '//--666 9>>"a'$>>!,  )11G{{n4#*==  2
 +T&u-  ^^ ~~a(H #Lu% (CMM2  oo11&1
 13
 &(')"//J*cll3'--E67% "*c.@.@AAA 6MZY[YbYb5c2
N fs 22 ZjA&+F# !>^>^YX]>^_	,0,=,=fiQY,Z)	>N*IE:;9 *< 3;K/0{L00Is   'ANr2   )recursion_depthc          
        |dk  rt        d      g }d}g }| j                  |      D ]+  \  }}	}
}|r|j                  |dd       |	"|	dk(  rt        d      |	j                  d	      r7|r|d
   d   dk(  r|d
   dxx   |	z  cc<   n|j                  |	dd       |	dd
 }		 | j	                  |	||      \  }}|	 | j                  ||      }| j                  |
xs d|t        |dz
        \  }}dj                  d |D              }
	 | j                  ||
      }| j                  |	||      \  }}||z  }|dd}|
r|
|d<   |j                  |       . |rt         |ini }||fS # t
        $ r t        d      t        $ r]}t        |      t        |	      k(  rt        d|	 d      |	 ||	   }n$# t        $ r}t        d| d| d      |d}~ww xY wY d}~"d}~wt        $ r}t        d|	 d|       |d}~ww xY w# t        $ r}t        d|	 d|       |d}~ww xY w# t        $ r}t        d|	 d|       |d}~ww xY w)z|Copied from `string.Formatter._vformat` https://github.com/python/cpython/blob/v3.11.4/Lib/string.py#L198-L247 then altered.r   z"Max format spec recursion exceededr   r7   r8   Nr6   zDEmpty curly brackets `{}` are not allowed. A field name is required.=r   r   z$Numeric field names are not allowed.zThe field {z} is not defined.zThe fields z and z are not defined.zError getting field {z}: zError converting field {r   )r)   ru   c              3  &   K   | ]	  }|d      ywr   Nr   .0chunks     r    	<genexpr>z2ChunksFormatter._vformat_chunks.<locals>.<genexpr>  s     %Q>PUeCj>P   zError formatting field {r<   r#   )KnownFormattingErrorparserM   endswith	get_field
IndexErrorKeyErrorr   repr	Exceptionconvert_fieldr+   r   joinformat_fieldr`   r   )r,   r-   r(   r)   ru   r.   rP   ro   literal_text
field_nameformat_spec
conversionobj	_arg_usedexc1exc2excformat_spec_chunks_rW   rt   dr0   s                          r    r+   zChunksFormatter._vformat_chunks   s    Q&'KLL02')AEMAZ=L*k:Lu=> % #./uvv &&s+&*S/U":r
3:5JU&CD!+CRJh%)^^Jf%MNC& )o"00jA
 )-(<(<%2vWfijWj )= )%"A !gg%Q>P%QQk --c;?E )-(9(9*eX(V%~N*$)6 +AfIa  B[B >F.92{""U " W./UVV o4yD$442\*M_3`agkko %Z0# o2[eD6Qb3cdjnno  ! h.1G
|SWX[W\/]^dggh % o25NzlZ^_b^c3deknno ! k.1J:,VZ[^Z_/`agjjksx   #E'<H
H$'G>'G+F10G1	G:GGGG>'G99G>	H!
HH!$	I-H??Ic                v    g }||j                   vr|j                  d|f|      \  }}t        |t              |fS )Nmessage)
max_length)	SAFE_KEYSscrub_valuer   r   )r,   r   rW   r)   ro   s        r    r`   zChunksFormatter._clean_value(  sF     (*X///&22Iz3JEROE8u1UVX```r   )
r-   r   r(   dict[str, Any]r)   r   r&   types.FrameType | Nonereturnz9tuple[list[LiteralChunk | ArgChunk], dict[str, Any], str])r(   r   r)   r   ra   types.FrameTyper   z@tuple[list[LiteralChunk | ArgChunk], dict[str, Any], str] | None)
r-   r   r(   r   r)   r   ru   intr   z4tuple[list[LiteralChunk | ArgChunk], dict[str, Any]])r   r   rW   r   r)   r   r   ztuple[str, list[ScrubbedNote]])r   r   r   r/   r*   r+   r`   r   r   r    r%   r%   #   s     1522 2
 2 .2 
C26T1T1 T1 	T1
 
JT1x  !Q#Q# Q#
 Q# Q# 
>Q#far   r%   c                (    t        | ||      \  }}}|S N)logfire_format_with_magic)r-   r(   r)   r.   _extra_attrs_new_templates         r    logfire_formatr   5  s#    *C+'FL-
 Mr   c                (   	 t         j                  | |||      \  }}}dj                  d |D              ||fS # t        $ r5}t	        t        |      xs t        |j                               Y d }~nd }~wt        $ r t                Y nw xY w| i | fS )N)r)   r&   r6   c              3  &   K   | ]	  }|d      ywrz   r   r{   s     r    r~   z,logfire_format_with_magic.<locals>.<genexpr>P  s     6veuSzvr   )	chunks_formatterr/   r   r   warn_formattingr   	__cause__r   r   )r-   r(   r)   r&   r/   r0   rn   es           r    r   r   >  s    ,<,C,C'	 -D -
)\ ww6v66\QQ 4A2#akk"233  	 "m++s   7: 	B+A33BBc                   t        | j                  |      }t        |dd      }t        j                  t        j
                  t        j                  t        j                  dt        j                               | j                  | j                        g            }t        j                  |       t        |dd      }|||fS )a  Returns three things that can be expensive to compute.

    1. Source code corresponding to the node value (excluding the format spec).
    2. A compiled code object which can be evaluated to calculate the value.
    3. Another code object which formats the value.
    z	<fvalue1>r_   r;   )idctx)rW   r   r   )r[   z	<fvalue2>)get_node_source_textrW   compilerJ   
ExpressionrX   r]   NameLoadr   r   fix_missing_locations)rA   	ex_sourcerB   rq   exprrr   s         r    r^   r^   \  s     "$**i8Ff5J>> ""((iSXXZ@# $ 0 0	
D$ d#T;7N:~--r   c                    t        j                  |       }t        j                  |j                  |       xs d}	 t        j                  t        j                  |d            }||k(  r|S |S # t
        $ r d}Y w xY w)a]  Returns some Python source code representing `node`.

    Preferably the actual original code given by `ast.get_source_segment`,
    but falling back to `ast.unparse(node)` if the former is incorrect.
    This happens sometimes due to Python bugs (especially for older Python versions)
    in the source positions of AST nodes inside f-strings.
    r6   r_   )mode)rJ   unparseget_source_segmentrC   r   r   )rA   r   source_unparsedsource_segmentsource_segment_unparseds        r    r   r   }  sx     kk$'O++INNDAGRN%"%++ciiV.T"U -0GG>\_\  %"$%s   *A. .A<;A<c                n    t        j                         }d}|r|| k(  r	 |S |dz  }|j                  }|r|S )Nr   r   )inspectcurrentframer>   )ra   current_frame
stacklevels      r    rE   rE     sP     ((*MJ
E!  	a
%,,	 
 r   c                      e Zd Zy)InspectArgumentsFailedWarningNr   r   r   r   r   r    r   r         r   r   c                r    d| z   } t        j                  | t        |       t        j                  d|        y )Na  Failed to introspect calling code. Please report this issue to Logfire. Falling back to normal message formatting which may result in loss of information if using an f-string. Set inspect_arguments=False in logfire.configure() to suppress this warning. The problem was:
)r   warn)warningsr   r   rS   rU   )re   r   s     r    rD   rD     s4    	 	C MM#4LKKr   c                      e Zd ZdZy)r   a.  An error raised when there's something wrong with a format string or the field values.

    In other words this should correspond to errors that would be raised when using `str.format`,
    and generally indicate a user error, most likely that they weren't trying to pass a template string at all.
    N)r   r   r   __doc__r   r   r    r   r     s    r   r   c                      e Zd Zy)FormattingFailedWarningNr   r   r   r    r   r     r   r   r   c                ,    t        d|  t               y )NaO  
    Ensure you are either:
      (1) passing an f-string directly, with inspect_arguments enabled and working, or
      (2) passing a literal `str.format`-style template, not a preformatted string.
    See https://logfire.pydantic.dev/docs/guides/onboarding-checklist/add-manual-tracing/#messages-and-span-names.
    The problem was: )category)r   r   )re   s    r    r   r     s      
 !$u	& )r   )r-   r   r(   r   r)   r   r   r   r   )
r-   r   r(   r   r)   r   r&   r   r   ztuple[str, dict[str, Any], str])rA   zast.FormattedValuer   executing.Sourcer   ztuple[str, CodeType, CodeType])rA   zast.ASTr   r   )ra   r   )re   r   r   r   )re   r   )1
__future__r   rJ   r   rF   typesr   	functoolsr   stringr   r   typingr   r   r?   typing_extensionsr	   r
   rS   	constantsr   r   	scrubbingr   r   r   
stack_infor   utilsr   r   r   r"   r%   r   r   r   r^   r   rE   Warningr   rD   r   r   UserWarningr   r   r   r   r    <module>r      s    " 
  
        4  T @ @ / 69 
y Lai La^ #$  -1	,,, , *	,
 %,< . .@]&
	G 	
9 	k 		r   