Ë
    uPêju<  ã            
       óæ  — U d Z ddlZddlZddlmZmZmZ ddlmZm	Z	 ddl
Z
ddlmZmZmZ ddlmZmZ ddlmZmZmZmZmZmZ ddlmZmZmZmZmZmZm Z m!Z! dd	l"m#Z#m$Z$ dd
l%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ dede,e-ef   fd„Z.dede/e   fd„Z0dede-fd„Z1dee-e2f   de-fd„Z3de-eee-e2f      z  dz  de-fd„Z4dede-fd„Z5 ee,e-e2f   «      Z6e	e7d<   de-e,e-e2f   z  de,e-e2f   fd„Z8de$defd„Z9de/e#   de/e   fd„Z:de,e-ef   defd„Z;de,e-ef   de<defd „Z=d!ede,e-ef   fd"„Z>d#ee-ef   defd$„Z?d%eee-ef      de/e   fd&„Z@d'ee-ef   d(e-d)e(d*e
j‚                  de(f
d+„ZB	 	 d0d,ee-ef   d-e<d.e<de)fd/„ZCy)1u
  
OCI Generative AI â€” Cohere-specific chat transformation helpers.

Handles message history building, tool definition adaptation, non-streaming
response parsing, and streaming chunk parsing for models served with
``apiFormat="COHERE"`` (e.g. ``cohere.command-*``).
é    N)ÚIterableÚMappingÚSequence)ÚAnyÚFinal)Ú	JsonValueÚTypeAdapterÚValidationError)Ú_normalize_oci_finish_reasonÚ_synthesize_oci_tool_call_id)ÚOCI_JSON_TO_PYTHON_TYPESÚOCIErrorÚenrich_cohere_param_descriptionÚresolve_oci_schema_anyofÚresolve_oci_schema_refsÚsanitize_oci_schema)ÚCohereChatResultÚCohereMessageÚCohereParameterDefinitionÚCohereStreamChunkÚ
CohereToolÚCohereToolCallÚCohereToolMessageÚCohereToolResult)ÚAllMessageValuesÚChatCompletionAssistantToolCall)ÚChoicesÚDeltaÚModelResponseÚModelResponseStreamÚStreamingChoicesÚUsageÚvalueÚreturnc                 ó*   — t        | t        «      r| S i S ©N)Ú
isinstanceÚdict©r#   s    úa/home/oem/CyberBrain26-unified/.venv/lib/python3.12/site-packages/litellm/llms/oci/chat/cohere.pyÚ
_json_dictr+   2   ó   € Ü˜u¤dÔ+ˆ5Ð3°Ð3ó    c                 ó*   — t        | t        «      r| S g S r&   )r'   Úlistr)   s    r*   Ú
_json_listr0   6   r,   r-   c                 ó*   — t        | t        «      r| S dS )NÚ )r'   Ústrr)   s    r*   Ú	_json_strr4   :   s   € Ü˜u¤cÔ*ˆ5Ð2°Ð2r-   Úblockc                 ó˜   — t        | t        «      r| j                  d«      dk7  ry| j                  dd«      }t        |t        «      r|S dS )NÚtypeÚtextr2   )r'   r(   Úgetr3   )r5   r8   s     r*   Ú_content_block_textr:   >   sC   € Ü�eœTÔ" e§i¡i°Ó&7¸6Ò&AØØ—)‘)˜F BÓ'€DÜ˜d¤CÔ(ˆ4Ð0¨bÐ0r-   Úcontentc                 ó’   — | €yt        | t        «      r| S t        | t        «      rdj                  d„ | D «       «      S t        | «      S )Nr2   c              3   ó2   K  — | ]  }t        |«      –— Œ y ­wr&   )r:   )Ú.0r5   s     r*   ú	<genexpr>z _content_text.<locals>.<genexpr>K   s   è ø€ ÒG°eÔ*¨5×1ÑGùs   ‚)r'   r3   r/   Újoin©r;   s    r*   Ú_content_textrB   E   sB   € Ø€ØÜ�'œ3ÔØˆÜ�'œ4Ô Ø�w‰wÑG¸wÔGÓGÐGÜˆw‹<Ðr-   c                 ó   — t        | «      S )z@Return the plain-text representation of a message content value.)rB   rA   s    r*   Ú_extract_text_contentrD   O   s   € ä˜Ó!Ð!r-   Ú_TOOL_ARGUMENTS_ADAPTERÚraw_argumentsc                 ót   — t        | t        «      s| S 	 t        j                  | «      S # t        $ r i cY S w xY wr&   )r'   r3   rE   Úvalidate_jsonr
   )rF   s    r*   Ú_parsed_tool_argumentsrI   W   s<   € Ü�m¤SÔ)ØÐðÜ&×4Ñ4°]ÓCÐCøÜò ØŠ	ðús   ”) ©7¶7Ú	tool_callc           	      ó¤   — | j                  di «      }t        t        |j                  dd«      «      t        |j                  dd«      «      ¬«      S )NÚfunctionÚnamer2   Ú	argumentsz{}©rM   Ú
parameters)r9   r   r3   rI   )rJ   Úfunction_fieldss     r*   Ú_to_cohere_tool_callrR   `   sI   € Ø&Ÿ]™]¨:°rÓ:€OÜÜ�×$Ñ$ V¨RÓ0Ó1Ü)¨/×*=Ñ*=¸kÈ4Ó*PÓQôð r-   Úmessagesc           	      ó  ‡ — ‰ D ��ci c]D  }|j                  d«      dk(  r.d|v r*|d   xs g D ]  }|j                  dd«      t        |«      “Œ  ŒF }}}t        ˆ fd„t        t	        ‰ «      dz
  dd«      D «       d	«      }|€‰ n#t        ‰ «      D ��cg c]  \  }}||k7  sŒ|‘Œ c}}}g }|D �]B  }|j                  d«      }	t        |j                  d
«      «      }
|	dk(  r%d|v r!|d   r|d   D �cg c]  }t        |«      ‘Œ c}nd	}|	dk(  r|j                  t        d|
¬«      «       Œ}|	dk(  r|j                  t        d|
|¬«      «       Œ |	dk(  sŒ¦t        |j                  dd«      xs d«      }|j                  |t        di ¬«      «      }t        |d|
ig¬«      }|r3t        |d   t        «      r |d   j                  j                  |«       �Œ'|j                  t        |g¬«      «       �ŒE |S c c}}w c c}}w c c}w )uA  Build a Cohere ``chatHistory`` list from an OpenAI-format message array.

    - All messages except the *last user message* are included. The caller pulls
      the last user message into the request's top-level ``message`` field, so
      trailing tool results (the standard agentic continuation pattern) still
      appear in ``chatHistory`` and reach the model.
    - If no user message exists, every message is included (no slice).
    - System messages must be filtered out by the caller (they are routed into
      ``preambleOverride`` separately) â€” they are not represented in
      ``chatHistory``.
    - Tool results are expressed as OCI ``CohereToolMessage.toolResults`` entries,
      with the originating call's name and parameters resolved from the preceding
      assistant message via a ``tool_call_id`` lookup.
    ÚroleÚ	assistantÚ
tool_callsÚidr2   c              3   óR   •K  — | ]  }‰|   j                  d «      dk(  sŒ|–— Œ  y­w)rU   ÚuserN)r9   )r>   ÚirS   s     €r*   r?   z4adapt_messages_to_cohere_standard.<locals>.<genexpr>ƒ   s&   øè ø€ ÒZˆq¸À¹¿¹ÈÓ8OÐSYÓ8YŒÑZùs   ƒ' 'é   éÿÿÿÿNr;   rZ   ÚUSER)rU   ÚmessageÚCHATBOT)rU   r_   Ú	toolCallsÚtoolÚtool_call_idrO   Úoutput)ÚcallÚoutputs)ÚtoolResults)r9   rR   ÚnextÚrangeÚlenÚ	enumeraterD   Úappendr   r3   r   r   r'   r   rg   )rS   ÚmsgrJ   Útool_call_lookupÚlast_user_indexr[   ÚmÚhistory_sourceÚchat_historyrU   r;   rW   rc   Úcohere_callÚtool_results   `              r*   Ú!adapt_messages_to_cohere_standardru   h   s)  ø€ ð* ÷àØ�7‰7�6‹?˜kÒ)¨l¸cÑ.AØ˜\Ñ*Ò0¨bò	ð ð 	�‰�d˜BÓÔ!5°iÓ!@Ñ@ðØðÐñ ô "ÛZ”Eœ#˜h›-¨!Ñ+¨R°Ó4ÔZØó€Oð
 $Ð+‰Ä	È(Ó@S×1l¹¸¸1ÐWXÐ\kÓWk²!Ó1lð ð 02€LØó RˆØ�w‰w�v‹ˆÜ'¨¯©°	Ó(:Ó;ˆð �{Ò" |°sÑ':¸sÀ<Ò?Pð ?BÀ,Ñ>OÖP°Ô! )Õ,ÓPàð 	ð �6Š>Ø×Ñ¤°6À7Ô KÕLØ�[Ò Ø×Ñ¤°9ÀgÐYcÔ dÕeØ�V‹^Ü˜sŸw™w ~°rÓ:Ò@¸bÓAˆLØ*×.Ñ.¨|¼^ÐQSÐ`bÔ=cÓdˆKÜ*Ø Ø" GÐ,Ð-ôˆKñ ¤
¨<¸Ñ+;Ô=NÔ OØ˜RÑ ×,Ñ,×3Ñ3°KÖ@à×#Ñ#Ô$5À;À-Ô$PÖQð;Rð> Ðùó_ùó 2mùò Qs   ‡A	G3ÂG9ÂG9Ã/G?Úraw_parametersc                 ó<   — t        t        t        | «      «      «      S r&   )r   r   r   )rv   s    r*   Ú_resolved_oci_parameter_schemarx   ­   s   € ÜÔ7Ô8OÐP^Ó8_Ó`ÓaÐar-   Úparam_schemaÚis_requiredc           	      óÆ   — t        | j                  d«      «      xs d}t        t        t        | j                  d«      «      | «      t	        j                  ||«      |¬«      S )Nr7   ÚstringÚdescription)r}   r7   Ú
isRequired)r4   r9   r   r   r   )ry   rz   Ú	json_types      r*   Ú_cohere_parameter_definitionr€   ±   sW   € Ü  ×!1Ñ!1°&Ó!9Ó:ÒF¸h€IÜ$Ü3´I¸l×>NÑ>NÈ}Ó>]Ó4^Ð`lÓmÜ%×)Ñ)¨)°YÓ?Øôð r-   Úresolved_schemac           
      óú   — t        | «      }t        |j                  d«      «      }t        |j                  d«      «      j                  «       D ��ci c]  \  }}|t	        t        |«      ||v «      “Œ c}}S c c}}w )NÚrequiredÚ
properties)r+   r0   r9   Úitemsr€   )r�   Úschema_fieldsrƒ   Ú
param_namery   s        r*   Ú_cohere_parameter_definitionsrˆ   º   sx   € Ü% oÓ6€MÜ  ×!2Ñ!2°:Ó!>Ó?€Hô )3°=×3DÑ3DÀ\Ó3RÓ(S×(YÑ(YÓ([÷á$ˆJ˜ð 	Ô0´¸LÓ1IÈ:ÐYaÐKaÓbÑbóð ùó s   Á"A7rb   c                 ó  — t        | j                  d«      «      }t        t        |j                  d«      «      t        |j                  d«      «      t	        t        t        |j                  d«      «      «      «      ¬«      S )NrL   rM   r}   rP   )rM   r}   ÚparameterDefinitions)r+   r9   r   r4   rˆ   rx   )rb   Úfunction_defs     r*   Ú_to_cohere_toolrŒ   Ã   sh   € Ü$ T§X¡X¨jÓ%9Ó:€LÜÜ�|×'Ñ'¨Ó/Ó0Ü˜l×.Ñ.¨}Ó=Ó>Ü:Ü*¬:°l×6FÑ6FÀ|Ó6TÓ+UÓVó
ôð r-   Útoolsc                 ó>   — | D �cg c]  }t        |«      ‘Œ c}S c c}w )un  Adapt OpenAI-format tool definitions to the OCI Cohere format.

    - Resolves ``$ref``/``$defs`` and ``anyOf`` patterns that OCI rejects.
    - Maps JSON Schema type names to Python type names (``"string"`` â†’ ``"str"``).
    - Embeds unsupported constraints (enum, format, range, pattern) into the
      parameter description so the model can still see them.
    )rŒ   )r�   rb   s     r*   Ú)adapt_tool_definitions_to_cohere_standardr�   Î   s   € ð /4Ö4 dŒO˜DÕ!Ò4Ð4ùÒ4s   …Újson_responseÚmodelÚmodel_responseÚraw_responsec                 óê  — 	 t        j                  | «      }||_        t        t        j                  j                  «       j                  «       «      |_        |j                  j                  }t        |j                  j                  «      }d}|j                  j                   r“t#        |j                  j                   «      D �	�
cg c]i  \  }	}
t%        |	|
j&                  t)        j*                  |
j,                  d¬«      «      d|
j&                  t)        j*                  |
j,                  «      dœdœ‘Œk }}	}
|r|nd}d	|d
œ}|�||d<   t/        d||¬«      g|_        |j                  j2                  }|�3t5        |j6                  |j8                  |j:                  ¬«      |_        |S t5        ddd¬«      |_        |S # t        t        f$ r}t	        d|› �|j
                  ¬«      ‚d}~ww xY wc c}
}	w )zGParse a non-streaming Cohere OCI response into a LiteLLM ModelResponse.z/Response cannot be casted to CohereChatResult: )r_   Ústatus_codeNT©Ú	sort_keysrL   ©rM   rN   ©rX   r7   rL   rV   )rU   r;   rW   r   )Úindexr_   Úfinish_reason)Úprompt_tokensÚcompletion_tokensÚtotal_tokens)r   Úmodel_validateÚ	TypeErrorr
   r   r•   r‘   ÚintÚdatetimeÚnowÚ	timestampÚcreatedÚchatResponser8   r   ÚfinishReasonra   rk   r   rM   ÚjsonÚdumpsrP   r   ÚchoicesÚusager"   ÚpromptTokensÚcompletionTokensÚtotalTokens)r�   r‘   r’   r“   Úcohere_responseÚeÚresponse_textr›   rW   r[   Útcr;   r_   Ú
usage_infos                 r*   Úhandle_cohere_responser´   Û   sÜ  € ð
Ü!1×!@Ñ!@ÀÓ!Oˆð !€NÔÜ ¤×!2Ñ!2×!6Ñ!6Ó!8×!BÑ!BÓ!DÓE€NÔà*×7Ñ7×<Ñ<€MÜ7¸×8TÑ8T×8aÑ8aÓb€Mà15€JØ×#Ñ#×-Ò-ô # ?×#?Ñ#?×#IÑ#IÓJ÷

ñ ��2ô 3°1°b·g±g¼t¿z¹zÈ"Ï-É-ÐcgÔ?hÓiØ"àŸG™GÜ!%§¡¨B¯M©MÓ!:ñóð

ˆ
ñ 

ñ 3@¡ÀT€Gð 2=ÈÑ(Q€GØÐØ *ˆ�Ñô 	ØØØ'ô	
ð€NÔð (×4Ñ4×:Ñ:€JØÐÜ$Ø$×1Ñ1Ø(×9Ñ9Ø#×/Ñ/ô 
ˆÔð Ðô  %°1ÈÐXYÔZˆÔàÐøôo ”Ð'ò 
ÜØEÀaÀSÐIØ$×0Ñ0ô
ð 	
ûð
üó

s   ‚F> ÃA.G/Æ>G,ÇG'Ç'G,Ú
dict_chunkÚprior_tool_calls_emittedÚprior_text_emittedc                 óÄ  — 	 t        j                  | «      }|j
                  €d|_        |j                  duxr |j                  du}|r|rdn|j                  }|r|rdn|j                  }d}|rt        |«      D �	�
cg c]i  \  }	}
t        |	|
j                  t        j                  |
j                  d¬«      «      d|
j                  t        j                  |
j                  «      d	œd
œ‘Œk }}	}
t!        |j                  «      }t#        t%        |j
                  t'        ||ddd¬«      |¬«      g¬«      S # t        t        f$ r}t	        dd|› �¬«      ‚d}~ww xY wc c}
}	w )a“  Parse a single Cohere SSE chunk into a LiteLLM ModelResponseStream.

    ``prior_tool_calls_emitted`` lets the caller signal whether tool calls
    were already emitted in earlier chunks of the same stream. When set, the
    terminal consolidation chunk's tool calls are suppressed (they would
    duplicate prior deltas); otherwise they are passed through so a stream
    that delivers tool calls only on the terminal chunk doesn't silently
    drop them.

    ``prior_text_emitted`` plays the analogous role for the ``text`` field:
    when set, the terminal consolidation chunk's ``text`` is suppressed
    (it would re-emit the full assembled response on top of prior deltas);
    when unset (e.g. a degenerate stream that delivers the entire response
    in a single SSE event carrying both ``chatHistory`` and ``finishReason``),
    the text is passed through so the response content isn't silently lost.
    iô  z-Chunk cannot be parsed as CohereStreamChunk: )r•   r_   Nr   Tr–   rL   r˜   r™   )r;   rW   Úprovider_specific_fieldsÚthinking_blocksÚreasoning_content)rš   Údeltar›   )rª   )r   rŸ   r    r
   r   rš   ÚchatHistoryr§   r8   ra   rk   r   rM   r¨   r©   rP   r   r    r!   r   )rµ   r¶   r·   Útyped_chunkr°   Úis_terminal_consolidationr8   Úcohere_tool_callsrW   r[   r²   r›   s               r*   Úhandle_cohere_stream_chunkrÁ     sy  € ð*
Ü.×=Ñ=¸jÓIˆð ×ÑÐ ØˆÔð (3×'>Ñ'>ÀdÐ'JÒ'sÈ{×OgÑOgÐosÐOsÐñ (AÑEW™dÐ^i×^nÑ^n€Dñ ";Ñ?W™Ð^i×^sÑ^sÐà15€JÙô #Ð#4Ó5÷
ñ ��2ô 3°1°b·g±g¼t¿z¹zÈ"Ï-É-ÐcgÔ?hÓiØ"àŸG™GÜ!%§¡¨B¯M©MÓ!:ñóð
ˆ
ñ 
ô  8¸×8PÑ8PÓQ€MääØ!×'Ñ'ÜØ Ø)Ø-1Ø$(Ø&*ôð ,ô
ð
ôð øôs ”Ð'ò 
ÜØØCÀAÀ3ÐGô
ð 	
ûð
üóN
s   ‚D5 Á>A.EÄ5EÅEÅE)FF)DÚ__doc__r¢   r¨   Úcollections.abcr   r   r   Útypingr   r   ÚhttpxÚpydanticr   r	   r
   Úlitellm.llms.oci.chat.genericr   r   Úlitellm.llms.oci.common_utilsr   r   r   r   r   r   Úlitellm.types.llms.ocir   r   r   r   r   r   r   r   Úlitellm.types.llms.openair   r   Úlitellm.types.utilsr   r   r   r    r!   r"   r(   r3   r+   r/   r0   r4   Úobjectr:   rB   rD   rE   Ú__annotations__rI   rR   ru   rx   Úboolr€   rˆ   rŒ   r�   ÚResponser´   rÁ   © r-   r*   ú<module>rÑ      sœ  ðòó Û ß 7Ñ 7ß ã ß <Ñ <÷÷÷ ÷	÷ 	ó 	÷ X÷÷ ð4�ið 4 D¨¨i¨Ñ$8ó 4ð4�ið 4 D¨¡Oó 4ð3�Yð 3 3ó 3ð1˜w s¨F {Ñ3ð 1¸ó 1ð˜3 ¨'°#°v°+Ñ*>Ñ!?Ñ?À$ÑFð È3ó ð" 3ð "¨3ó "ñ
 "-¨T°#°v°+Ñ->Ó!?Ð ˜Ó ?ð¨#°°S¸&°[Ñ0AÑ*Að ÀdÈ3ÐPVÈ;ÑFWó ðÐ$Cð Èó ðBØÐ#Ñ$ðBà	ˆ-ÑóBðJb°4¸¸Y¸Ñ3Gð bÈIó bð¨t°C¸°NÑ/Cð ÐRVð Ð[tó ð°9ð ÀÀcÐKdÐFdÑAeó ð˜' # y .Ñ1ð °jó ð
5Ø�G˜C ˜NÑ+Ñ,ð
5à	ˆ*Ñó
5ð@Ø˜3 	˜>Ñ*ð@àð@ð "ð@ð —.‘.ð	@ð
 ó@ðJ &+Ø$ñ^Ø˜˜Y˜Ñ'ð^à"ð^ð ð^ð ô	^r-   