Ë
    ñÏjë%  ã                  ó  — d Z ddlmZ ddlZddlZddlmZmZ ddlm	Z	 ddl
mZmZmZ ddlmZ  ej                   e«      ZdZd	Zdd
„Zdd„Zdd„Zdd„Zdd„Zdd„Zdd„Zdd„Zdd„Z	 d	 	 	 	 	 	 	 dd„Zd d„Zd!d„Z d"d„Z!y)#u'  Small pure helpers for the LiveKit â†’ LangSmith span processor.

Split out of :mod:`langsmith.integrations.livekit.processor` to keep that module
focused on span dispatch and lifecycle: provider-slug normalization, LiveKit
span detection, and the tiny chat-message builders the handlers reuse.
é    )ÚannotationsN)ÚAnyÚOptional)ÚAttributeValue)Ú!build_assistant_tool_call_messageÚbuild_tool_messageÚtry_parse_json_object)ÚTranslatedSpanzlivekit-agents)
ÚopenaiÚ	anthropicÚgeminiÚgoogleÚdeepgramÚcartesiaÚ
elevenlabsÚcohereÚmistralÚgroqc                ó‚   — d|› �}|| j                   v r| j                   |   S | j                   j                  d|› �«      S )zàRead a LiveKit content field across the 1.7 ``lk.pii.*`` rename.

    A present new key is authoritative, even when empty: do not replace withheld
    content with an older value. ``name`` is the suffix without ``lk.``.
    zlk.pii.zlk.)Ú
attributesÚget)ÚtspanÚnameÚpii_keys      úd/var/www/html/gaurav-v2/venv/lib/python3.12/site-packages/langsmith/integrations/livekit/_helpers.pyÚget_content_attributer   )   sL   € ð ˜�vÐ€GØ�%×"Ñ"Ñ"Ø×Ñ Ñ(Ð(Ø×Ñ×Ñ # d V Ó-Ð-ó    c                óä   — | syt        | «      j                  «       j                  «       }|r|dk(  ryt        D ]
  }||v sŒ|c S  |j	                  dd«      d   j	                  dd«      d   xs dS )aš  Map a LiveKit provider (often an API host) to a LangSmith provider slug.

    Matches a known provider slug as a substring (so ``api.openai.com`` and
    ``beta.anthropic.com`` resolve to ``openai`` / ``anthropic``); otherwise
    returns the value's host, stripped of scheme/path. Returns ``None`` for
    empty input or LiveKit's ``"unknown"`` placeholder, so we never stamp a
    non-matching provider.
    NÚunknownz://é   éÿÿÿÿÚ/r   )ÚstrÚstripÚlowerÚ_PROVIDER_ALIASESÚsplit)ÚrawÚvalueÚaliass      r   Únormalize_providerr+   5   su   € ñ ØÜ�‹H�N‰NÓ×"Ñ"Ó$€EÙ�E˜YÒ&Øß"ˆØ�EŠ>ØŠLð #ð �;‰;�u˜aÓ  Ñ$×*Ñ*¨3°Ó2°1Ñ5Ò=¸Ð=r   c                óD   — t        | dd«      }t        |dd«      t        k(  S )a/  Whether a span came from LiveKit's tracer (its instrumentation scope).

    Used to gate root detection: only a parentless span emitted by LiveKit is
    the conversation root. Named LiveKit spans are matched by name above and
    don't need this; it guards the broad ``parent is None`` case alone.
    Úinstrumentation_scopeNr   )ÚgetattrÚ_LIVEKIT_INSTRUMENTATION_SCOPE)ÚspanÚscopes     r   Úis_livekit_spanr2   I   s(   € ô �DÐ1°4Ó8€EÜ�5˜& $Ó'Ô+IÑIÐIr   c                óâ   — g }| xs dD ]J  }t        |t        «      r	 t        j                  |«      }t        |t
        «      sŒ:|j                  |«       ŒL |S # t        j                  $ r Y Œdw xY w)z›Parse an event's ``tool_calls`` to OpenAI-shape dicts (JSON strings decoded).

    Entries that are neither dicts nor JSON-object strings are dropped.
    © )Ú
isinstancer#   ÚjsonÚloadsÚJSONDecodeErrorÚdictÚappend)Úraw_tool_callsÚ
tool_callsr(   s      r   Úparse_tool_callsr=   T   ss   € ð
  €JØÒ# Ò#ˆÜ�cœ3ÔðÜ—j‘j “o�ô �cœ4Õ Ø×Ñ˜cÕ"ð $ð Ðøô	 ×'Ñ'ò Ùðús   �AÁA.Á-A.c                ó‚   — t        | «      }t        |t        «      r$|j                  d«      xs i j                  d«      S y)uè   Read the provider (``metadata.model_provider``) from a LiveKit metrics blob.

    LiveKit reports it as the API-base-URL host (its OpenAI plugin â†’
    ``api.openai.com``); the caller normalizes it to a slug before setting it.
    ÚmetadataÚmodel_providerN©r	   r5   r9   r   ©ÚmetricsÚparseds     r   Ú extract_provider_from_lk_metricsrE   e   s;   € ô # 7Ó+€FÜ�&œ$ÔØ—
‘
˜:Ó&Ò,¨"×1Ñ1Ð2BÓCÐCØr   c                ó¨   — t        | «      }t        |t        «      r7|j                  d«      xs i j                  d«      xs |j                  d«      S y)zëRead the model name (``metadata.model_name`` or ``model_name``) from a blob.

    LiveKit doesn't always set ``gen_ai.request.model`` (notably on ``tts_request``),
    so the model is recovered from the metrics blob as a fallback.
    r?   Ú
model_nameNrA   rB   s     r   Úextract_model_from_lk_metricsrH   q   sR   € ô # 7Ó+€FÜ�&œ$ÔØ—
‘
˜:Ó&Ò,¨"×1Ñ1°,Ó?ò 
À6Ç:Á:ØóD
ð 	
ð r   c                óH   — t        | t        t        f«      rt        | «      S dS )zFCoerce a numeric metrics value to ``int``, or ``None`` if not numeric.N)r5   ÚintÚfloat)r)   s    r   Ú_as_intrL      s   € ä# E¬C´¨<Ô8Œ3ˆu‹:ÐB¸dÐBr   c                óP  — t        | «      }t        |t        «      si S i }t        |j	                  d«      «      x}�||d<   t        |j	                  d«      «      x}�||d<   t        |j	                  d«      «      x}�||d<   t        |j	                  d«      «      x}�d|i|d<   |S )	z:Parse a ``lk.llm_metrics`` blob into ``set_usage`` kwargs.Úprompt_tokensÚinput_tokensÚcompletion_tokensÚoutput_tokensÚtotal_tokensÚprompt_cached_tokensÚ
cache_readÚinput_token_details©r	   r5   r9   rL   r   )rC   rD   ÚusageÚvs       r   Úextract_llm_usagerY   „   s¹   € ä" 7Ó+€FÜ�fœdÔ#Øˆ	Ø€EÜ�V—Z‘Z Ó0Ó1Ð1ˆÐ>Ø !ˆˆnÑÜ�V—Z‘ZÐ 3Ó4Ó5Ð5ˆÐBØ!"ˆˆoÑÜ�V—Z‘Z Ó/Ó0Ð0ˆÐ=Ø !ˆˆnÑÜ�V—Z‘ZÐ 6Ó7Ó8Ð8ˆÐEØ(4°aÐ'8ˆÐ#Ñ$Ø€Lr   c                óö  — t        | «      }t        |t        «      si S i }dD ]$  }t        |j	                  |«      «      x}€Œ |||<   Œ& |j	                  d«      }i }t        |t        «      rBt        |j	                  d«      «      x}�||d<   t        |j	                  d«      «      x}�||d<   |r||d<   |j	                  d«      }	t        |	t        «      r#t        |	j	                  d«      «      x}�d|i|d<   |S )zEParse a ``lk.realtime_model_metrics`` blob into ``set_usage`` kwargs.)rO   rQ   rR   rU   Úaudio_tokensÚaudioÚcached_tokensrT   Úoutput_token_detailsrV   )
rC   rD   rW   ÚkeyÚcountÚ
in_detailsÚinput_detailr\   ÚcachedÚout_detailss
             r   Úextract_realtime_usagere   •   s  € ä" 7Ó+€FÜ�fœdÔ#Øˆ	Ø€EÛ@ˆÜ˜VŸZ™Z¨›_Ó-Ð-ˆEÑ:ØˆE�#ŠJð Að —‘Ð1Ó2€JØ#%€LÜ�*œdÔ#Ü˜ZŸ^™^¨NÓ;Ó<Ð<ˆEÐIØ$)ˆL˜Ñ!Ü˜jŸn™n¨_Ó=Ó>Ð>ˆFÐKØ)/ˆL˜Ñ&ÙØ'3ˆÐ#Ñ$à—*‘*Ð3Ó4€KÜ�+œtÔ$Ü˜[Ÿ_™_¨^Ó<Ó=Ð=ˆEÐJØ-4°eÐ,<ˆEÐ(Ñ)Ø€Lr   c           	     óx  — i }|dkD  r|S | j                  «       D ]�  \  }}|› d|› �}t        |t        «      r |j                  t	        |||dz   «      «       Œ=t        |t
        t        t        t        f«      r|||<   Œct        |t        t        f«      sŒz|sŒ}t        d„ |D «       «      sŒ�t        |«      ||<   ŒŸ |S )u'  Flatten a JSON-object blob's scalar leaves to ``{prefix_key: value}``.

    Recurses into nested dicts (capped at depth 4); keeps scalars and lists of
    scalars, dropping anything else. Returns a flat dict the caller stamps onto
    the span â€” so this stays agnostic to the span itself.
    é   Ú_r    c              3  ó\   K  — | ]$  }t        |t        t        t        t        f«      –— Œ& y ­w©N)r5   r#   rJ   rK   Úbool)Ú.0Úitems     r   Ú	<genexpr>z7flatten_lk_attributes_to_ls_metadata.<locals>.<genexpr>Å   s!   è ø€ ÐLÉ!À$”J˜t¤c¬3´´tÐ%<×=É!ùs   ‚*,)Úitemsr5   r9   ÚupdateÚ$flatten_lk_attributes_to_ls_metadatar#   rJ   rK   rk   ÚlistÚtupleÚall)ÚobjÚprefixÚ_depthÚflatÚkrX   r   s          r   rq   rq   °   s«   € ð €DØ�‚zØˆØ—	‘	–‰ˆˆ1Ø�˜˜1˜#ˆˆÜ�aœÔØ�K‰KÔ<¸QÀÀfÈqÁjÓQÕRÜ˜œC¤¤e¬TÐ2Ô3ØˆD�ŠJä�qœ4¤˜-Õ(ÚÜÑLÉ!ÓLÕLä˜a›ˆD�ŠJð ð €Kr   c                ó  — |j                   xs i }t        |j                  d«      xs d«      }| dk(  r,t        ||j                  d«      |j                  d«      ¬«      S | |dœ}t	        |j                  d«      «      }|r||d<   |S )	u  Build a chat message dict from a LiveKit ``gen_ai.*`` span event.

    ``role`` is authoritative (the caller derives it from the event name). Tool
    calls are forwarded in their OpenAI shape (JSON-string entries decoded) â€”
    LangSmith's ingester renders them directly.
    ÚcontentÚ ÚtoolÚidr   ©Útool_call_idr   ©Úroler{   r<   )r   r#   r   r   r=   )r‚   ÚeventÚattrsr{   Úmsgr<   s         r   Úbuild_message_from_eventr†   Ë   s‰   € ð ×ÑÒ" €EÜ�%—)‘)˜IÓ&Ò,¨"Ó-€GØˆv‚~Ü!Ø %§)¡)¨D£/¸¿	¹	À&Ó8Iô
ð 	
ð ¨'Ñ2€CÜ! %§)¡)¨LÓ"9Ó:€JÙØ&ˆˆLÑØ€Jr   c                ó2   — dj                  d„ | D «       «      S )zHFlatten a ``ChatMessage.content`` list to text, dropping non-text parts.Ú
c              3  óB   K  — | ]  }t        |t        «      sŒ|–— Œ y ­wrj   )r5   r#   )rl   Úparts     r   rn   z#_content_to_text.<locals>.<genexpr>á   s   è ø€ ÐG¡g˜d´¸DÄ#Õ1F”T¡gùs   ‚˜)Újoin)r{   s    r   Ú_content_to_textrŒ   ß   s   € à�9‰9ÑG¡gÓGÓGÐGr   c           	     ó²  — 	 | j                  dddd¬«      d   }g }|D ]Ž  }|d   }|dk(  r+|d	   }t	        |d
   «      }|sŒ#|j                  ||dœ«       Œ8|dk(  r&|j                  t        |d   |d   |d   «      «       Œc|dk(  sŒi|j                  t        |d   |d   |d   ¬«      «       Œ� |S # t        $ r t        j                  dd¬«       g cY S w xY w)a  Convert a LiveKit ``ChatContext`` into LangSmith chat messages.

    Keeps LiveKit's conversation order, including instructions, tool calls, and
    tool outputs. Returns ``[]`` if LiveKit cannot serialize the history, so
    export falls back to the span-derived transcript.
    FT)Úexclude_timestampÚexclude_function_callÚexclude_metricsÚexclude_config_updatero   zslangsmith voice: could not read the session report's chat history; falling back to the transcript built from spans.)Úexc_infoÚtypeÚmessager‚   r{   r�   Úfunction_callÚcall_idr   Ú	argumentsÚfunction_call_outputÚoutputr   )Úto_dictÚ	ExceptionÚloggerÚwarningrŒ   r:   r   r   )Úchat_historyro   Úmessagesrm   Úkindr‚   Útexts          r   Ú build_messages_from_chat_historyr¢   ä   s  € ðØ×$Ñ$Ø#Ø"'Ø Ø"&ð	 %ó 
ð
 ñˆð €HÛˆØ�F‰|ˆØ�9ÒØ˜‘<ˆDÜ# D¨¡OÓ4ˆDÚØ—‘¨¸$Ñ ?Õ@Ø�_Ò$Ø�O‰OÜ1Ø˜‘O T¨&¡\°4¸Ñ3Dóõð
 Ð+Ó+Ø�O‰OÜ"Ø˜‘NØ!% i¡Ø˜f™ôõð ð* €Oøô= ò Ü�‰ð?àð 	ô 	
ð
 Š	ðús   ‚B1 Â1"CÃC)r   r
   r   r#   ÚreturnzOptional[AttributeValue])r(   r   r£   úOptional[str])r0   r   r£   rk   )r;   r   r£   ú
list[dict])rC   r   r£   r¤   )r)   r   r£   zOptional[int])rC   r   r£   zdict[str, Any])r   )ru   r9   rv   r#   rw   rJ   r£   r9   )r‚   r#   rƒ   r   r£   r9   )r{   z	list[Any]r£   r#   )rž   r   r£   r¥   )"Ú__doc__Ú
__future__r   r6   ÚloggingÚtypingr   r   Úopentelemetry.util.typesr   Ú"langsmith._internal.voice._helpersr   r   r	   Ú)langsmith._internal.voice.translated_spanr
   Ú	getLoggerÚ__name__rœ   r/   r&   r   r+   r2   r=   rE   rH   rL   rY   re   rq   r†   rŒ   r¢   r4   r   r   Ú<module>r¯      s´   ðñõ #ã Û ß  å 3÷ñ õ
 Eà	ˆ×	Ñ	˜8Ó	$€à!1Ð ðÐ ó	.ó>ó(Jóó"	óóCó
ó"ð8 +,ðØ	ðØðØ$'ðà	óó6ó(Hô
,r   