
    6i!                        d Z ddlmZ ddlmZ ddlmZ 	 	 	 	 	 	 ddZddZ	 	 	 	 	 	 ddZ		 	 	 	 	 	 dd	Z
ej                  ee
d
ej                  ee	d
iZy)zCohere-specific utilities.

This module contains utilities specific to the Cohere provider,
including reask functions, response handlers, and message formatting.
    )annotations)Any   )Modec                   | j                  d      }t        |d      rd}|j                  }nt        |d      r~t        |j                  d      rhd}|j                  j                  }d}|r>|D ]9  }t        |d      s|j
                  dk(  s t        |d      s-|j                  } n |s*t        |      }nt        |      }|d	| v rd}n
d
| v sd| v rd}d| d| }|dk(  r| d	   j                  d|d       | S |dk(  r>| j                  dd      }d
| v r| d
   j                  d|d       n	d|dg| d
<   || d<   | S t        d| d      )a^  
    Handle reask for Cohere tools and JSON schema modes.
    Supports both V1 and V2 formats.

    V1 kwargs modifications:
    - Adds/Modifies: "chat_history" (appends prior message)
    - Modifies: "message" (user prompt describing validation errors)

    V2 kwargs modifications:
    - Modifies: "messages" (appends error correction message)
    _cohere_client_versiontextv1messagecontentv2 typemessageschat_historyzMCorrect the following JSON response, based on the errors given below:

JSON:
z

Exceptions:
userroler   r   r   #Unsupported Cohere client version: . Expected 'v1' or 'v2'.)	gethasattrr	   r   r   r   strappend
ValueError)	kwargsresponse	exceptionclient_versionresponse_textcontent_itemsitemcorrection_msgr   s	            l/root/.openclaw/workspace/visionaryfx/venv/lib/python3.12/site-packages/instructor/providers/cohere/utils.pyreask_cohere_toolsr&      s   " ZZ 89N x  	9	%'(2B2BI*N ((00% D&)		V+f-$(IIM MM H!V#!%6)Y&-@!%	 1)	> 
 z!!6n"MN& M% 
4	**Y+ V#>"))6g*NO/5'&J%KF>"*y M 1.1A B% &
 	
    c                   | j                         } | j                  d      }|dk(  r2d| v rd| vr| j                  d      | d<   | j                  dd       d| fS |dk(  rz| j                  dg       }g }|dd	 D ]  }|j                  |d
   |d   d        |d	   d   | d<   || d<   d| v rd| vr| j                  d      | d<   | j                  dd       d| fS t        d| d      )a  
    Convert OpenAI-style messages to Cohere format.
    Handles both V1 and V2 client formats.

    V1 format:
    - Removes: "messages"
    - Adds: "message" (last user message)
    - Adds: "chat_history" (prior messages)

    V2 format:
    - Keeps: "messages" (compatible with OpenAI format)

    Both versions:
    - Renames: "model_name" -> "model"
    - Removes: "strict"
    - Removes: "_cohere_client_version" (internal marker)
    r   r   
model_namemodelstrictNr
   r   r   r   r   r   r   r   r   )copypopr   r   )
new_kwargsr    r   r   r   s        r%   handle_cohere_modesr0   \   s:   $ "J^^$<=N :%'*C",..">Jwx&0 / 
4	>>*b1} 	G#FO&y1	 !)Y 7
9%1
>":%'*C",..">Jwx&  1.1A B% &
 	
r'   c                l    | t        |      S d| j                         d|d<   t        |      \  }}| |fS )a  
    Handle Cohere JSON schema mode.

    When response_model is None:
        - Converts messages from OpenAI format to Cohere format (message + chat_history)
        - No schema is added to the request

    When response_model is provided:
        - Converts messages from OpenAI format to Cohere format
        - Adds the model's JSON schema to response_format

    Kwargs modifications:
    - Removes: "messages" (converted to message + chat_history)
    - Adds: "message" (last message content)
    - Adds: "chat_history" (all messages except last)
    - Modifies: "model" (if "model_name" exists, renames to "model")
    - Removes: "strict"
    - Adds: "response_format" (with JSON schema) - only when response_model provided
    json_object)r   schemaresponse_format)r0   model_json_schema)response_modelr/   _s      r%   handle_cohere_json_schemar8      sN    , ":..  224%J ! (
3MAz:%%r'   c           	        | t        |      S t        |      \  }}d| j                   d| j                          d| j                   d| j                   d	}d|v r|d   j                  dd|d	       | |fS d|d
g|d   z   |d<   | |fS )aQ  
    Handle Cohere tools mode.

    When response_model is None:
        - Converts messages from OpenAI format to Cohere format (message + chat_history for V1, messages for V2)
        - No tools or schema instructions are added
        - Allows for unstructured responses from Cohere

    When response_model is provided:
        - Converts messages from OpenAI format to Cohere format
        - Prepends extraction instructions to the chat history (V1) or messages (V2)
        - Includes the model's JSON schema in the instructions
        - The model is instructed to extract a valid object matching the schema

    Kwargs modifications:
    - All modifications from handle_cohere_modes (message format conversion)
    - Modifies: "chat_history" (V1) or "messages" (V2) to prepend extraction instruction - only when response_model provided
    zExtract a valid z= object based on the chat history and the json schema below.
z=
The JSON schema was obtained by running:
```python
schema = zG.model_json_schema()
```

The output must be a valid JSON object that `z}.model_validate_json()` can successfully parse.
Respond with JSON only. Do not include code fences, markdown, or extra text.
r   r   r   r   r   r   )r0   __name__r5   insert)r6   r/   r7   instructions       r%   handle_cohere_toolsr=      s    * ":..'
3MAz(() *!!# $ %
 
!
!	" #. /=.E.E-F G
K Z:%%a&[)QR :%% 4&
~&&'
>" :%%r'   )reaskr   N)r   dict[str, Any]r   r   r   	Exception)r/   r?   returnztuple[None, dict[str, Any]])r6   ztype[Any] | Noner/   r?   rA   z'tuple[type[Any] | None, dict[str, Any]])__doc__
__future__r   typingr   moder   r&   r0   r8   r=   COHERE_TOOLSCOHERE_JSON_SCHEMACOHERE_HANDLERS r'   r%   <module>rJ      s    #  KKK K\2j &$ &2@ &, &F1&$1&2@1&,1&l 	#' 	#-	r'   