
    *`i:                        d dl mZ d dlmZmZ d dlmZ d dlmZ d dl	m
Z
 d dlmZmZmZmZ d dlmZmZ d dlmZmZmZ  G d	 d
ee          Z G d de          Z G d de
ee                   Z G d deeeef                   ZdS )    )Enum)AnyGeneric)Field)MistralBase)BaseCompletionRequest)_check_openai_fields_names_is_openai_field_nameconvert_openai_messagesconvert_openai_tools)ChatMessageChatMessageType)Tool
ToolChoiceToolTypec                       e Zd ZdZdZdZdS )ResponseFormatszEnum of the different formats of an instruct response.

    Attributes:
        text: The response is a plain text.
        json: The response is a JSON object.

    Examples:
        >>> response_format = ResponseFormats.text
    textjson_objectN)__name__
__module____qualname____doc__r   json     |/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/mistral_common/protocol/instruct/request.pyr   r      s$          DDDDr   r   c                   ,    e Zd ZU dZej        Zeed<   dS )ResponseFormatzThe format of the response.

    Attributes:
        type: The type of the response.

    Examples:
        >>> response_format = ResponseFormat(type=ResponseFormats.text)
    typeN)r   r   r   r   r   r   r    __annotations__r   r   r   r   r   $   s1           ,0D/00000r   r   c                      e Zd ZU dZdZedz  ed<   ee         ed<    e	e
          Ze
ed<   dZee         dz  ed<   ej        Zeed<   d	Zeed
<   d	Zeed<   dedeeeeeef                  f         fdZe	 	 ddeeeeeeeeeeef         z  f                  z  f                  deeeef                  dz  dededd f
d            ZdS )ChatCompletionRequesta  Request for a chat completion.

    Attributes:
        model: The model to use for the chat completion.
        messages: The messages to use for the chat completion.
        response_format: The format of the response.
        tools: The tools to use for the chat completion.
        tool_choice: The tool choice to use for the chat completion.
        truncate_for_context_length: Whether to truncate the messages for the context length.
        continue_final_message: Whether to continue the final message.

    Examples:
        >>> from mistral_common.protocol.instruct.messages import UserMessage, AssistantMessage
        >>> from mistral_common.protocol.instruct.tool_calls import ToolTypes, Function
        >>> request = ChatCompletionRequest(
        ...     messages=[
        ...         UserMessage(content="Hello!"),
        ...         AssistantMessage(content="Hi! How can I help you?"),
        ...     ],
        ...     response_format=ResponseFormat(type=ResponseFormats.text),
        ...     tools=[Tool(type=ToolTypes.function, function=Function(name="get_weather", parameters={}))],
        ...     tool_choice=ToolChoice.auto,
        ...     truncate_for_context_length=True,
        ... )
    Nmodelmessages)default_factoryresponse_formattoolstool_choiceFtruncate_for_context_lengthcontinue_final_messagekwargsreturnc                 *   |                      h dd          }|                    dd          }|||d<   | j        rt          d          |D ][}||v rt	          d|           |t
          j        v rt	          d	| d
          t          |          st	          d| d          \g }| j        D ])}|	                    |
                                           *||d<   | j        d | j        D             |d<   |                    |           |S )a	  Convert the request messages and tools into the OpenAI format.

        Args:
            kwargs: Additional parameters to be added to the request.

        Returns:
            The request in the OpenAI format.

        Examples:
            >>> from mistral_common.protocol.instruct.messages import UserMessage
            >>> from mistral_common.protocol.instruct.tool_calls import Tool, Function
            >>> request = ChatCompletionRequest(messages=[UserMessage(content="Hello, how are you?")], temperature=0.15)
            >>> request.to_openai(stream=True)
            {'temperature': 0.15, 'top_p': 1.0, 'response_format': {'type': 'text'}, 'tool_choice': 'auto', 'continue_final_message': False, 'messages': [{'role': 'user', 'content': 'Hello, how are you?'}], 'stream': True}
            >>> request = ChatCompletionRequest(messages=[UserMessage(content="Hello, how are you?")], tools=[
            ...     Tool(function=Function(
            ...         name="get_current_weather",
            ...         description="Get the current weather in a given location",
            ...         parameters={
            ...             "type": "object",
            ...             "properties": {
            ...                 "location": {
            ...                     "type": "string",
            ...                     "description": "The city and state, e.g. San Francisco, CA",
            ...                 },
            ...                 "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            ...             },
            ...             "required": ["location"],
            ...         },
            ...     ),
            ... )])
            >>> request.to_openai()
            {'temperature': 0.7, 'top_p': 1.0, 'response_format': {'type': 'text'}, 'tool_choice': 'auto', 'continue_final_message': False, 'messages': [{'role': 'user', 'content': 'Hello, how are you?'}], 'tools': [{'type': 'function', 'function': {'name': 'get_current_weather', 'description': 'Get the current weather in a given location', 'parameters': {'type': 'object', 'properties': {'location': {'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA'}, 'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}}, 'required': ['location']}}}]}
        >   r(   r%   r*   Texcludeexclude_nonerandom_seedNseedzETruncating for context length is not implemented for OpenAI requests.Duplicate keyword argument: Keyword argument  is already set in the request.Invalid keyword argument: $, it should be an OpenAI field name.r%   c                 6    g | ]}|                                 S r   	to_openai.0tools     r   
<listcomp>z3ChatCompletionRequest.to_openai.<locals>.<listcomp>   s"    &O&O&ODt~~'7'7&O&O&Or   r(   )
model_dumppopr*   NotImplementedError
ValueErrorr#   model_fieldsr
   r%   appendr;   r(   update)selfr,   openai_requestr3   kwargopenai_messagesmessages          r   r;   zChatCompletionRequest.to_openaiT   s{   J *.HHHW[ *9 *
 *

 !!-66%)N6"+ 	o%&mnnn 
	k 
	kE&& !G!G!GHHH /<<< ![U![![![\\\*511 k !ie!i!i!ijjjk } 	8 	8G""7#4#4#6#67777%4z":!&O&ODJ&O&O&ON7#f%%%r   c                    d|v rd|v rt          d          |                    dd          p|                    dd          }t          t          | j                                                  t          |                                                     t          |          }|t          |          nd} | d||||d|S )a  Create a chat completion request from the OpenAI format.

        Args:
            messages: The messages in the OpenAI format.
            tools: The tools in the OpenAI format.
            continue_final_message: Whether to continue the final message.
            **kwargs: Additional keyword arguments to pass to the constructor. These should be the same as the fields
                of the request class or the OpenAI API equivalent.


        Returns:
            The chat completion request.
        r3   r2   z-Cannot specify both `seed` and `random_seed`.N)r%   r(   r2   r+   r   )rC   rA   r	   setrD   keysr   r   )clsr%   r(   r+   r,   r2   converted_messagesconverted_toolss           r   from_openaiz!ChatCompletionRequest.from_openai   s    * V 7 7LMMMjj..Q&**]D2Q2Q"3s'7'<'<'>'>#?#?V[[]]ASASTTT0G0Q0Q9>9J.u555PTs 
'!##9	
 

 
 
 	
r   NF)r   r   r   r   r$   strr!   listr   r   r   r'   r(   r   r   autor)   r*   boolr+   r   dictr;   classmethodrR   r   r   r   r#   r#   1   s         4 E3:?####&+eN&K&K&KO^KKK#E4:###(oK---(----#(D(((G# G$sDc3h4H/H*I G G G GR  .2',	%
 %
tCtDcDcN6J1J,K'L!LLMN%
 DcN#d*%
 !%	%

 %
 
!%
 %
 %
 [%
 %
 %
r   r#   c                   d   e Zd ZU dZee         ed<   dZedz  ed<   dZ	ee
         dz  ed<   dZedz  ed<   dZeed<   d	ed
eeeeeef                  f         fdZe	 	 ddeeeeeeeeeeef         z  f                  z  f                  deeeef                  dz  ded	ed
d f
d            ZdS )InstructRequesta  A valid Instruct request to be tokenized.

    Attributes:
        messages: The history of the conversation.
        system_prompt: The system prompt to be used for the conversation.
        available_tools: The tools available to the assistant.
        truncate_at_max_tokens: The maximum number of tokens to truncate the conversation at.
        continue_final_message: Whether to continue the final message.

    Examples:
        >>> from mistral_common.protocol.instruct.messages import UserMessage, SystemMessage
        >>> request = InstructRequest(
        ...     messages=[UserMessage(content="Hello, how are you?")], system_prompt="You are a helpful assistant."
        ... )
    r%   Nsystem_promptavailable_toolstruncate_at_max_tokensFr+   r,   r-   c                 8   |                      h dd          }|D ][}||v rt          d|           |t          j        v rt          d| d          t	          |          st          d| d          \g }| j        |                    d
| j        d           | j        D ])}|                    |                                           *||d<   | j	        d | j	        D             |d<   | j
        t          d          |                    |           |S )a  Convert the request messages and tools into the OpenAI format.

        Args:
            kwargs: Additional parameters to be added to the request.

        Returns:
            The request in the OpenAI format.

        Examples:
            >>> from mistral_common.protocol.instruct.messages import UserMessage
            >>> from mistral_common.protocol.instruct.tool_calls import Tool, Function
            >>> request = InstructRequest(messages=[UserMessage(content="Hello, how are you?")])
            >>> request.to_openai(temperature=0.15, stream=True)
            {'continue_final_message': False, 'messages': [{'role': 'user', 'content': 'Hello, how are you?'}], 'temperature': 0.15, 'stream': True}
            >>> request = InstructRequest(
            ...     messages=[UserMessage(content="Hello, how are you?")],
            ...     available_tools=[
            ...     Tool(function=Function(
            ...         name="get_current_weather",
            ...         description="Get the current weather in a given location",
            ...         parameters={
            ...             "type": "object",
            ...             "properties": {
            ...                 "location": {
            ...                     "type": "string",
            ...                     "description": "The city and state, e.g. San Francisco, CA",
            ...                 },
            ...                 "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            ...             },
            ...             "required": ["location"],
            ...         },
            ...     ),
            ... )])
            >>> request.to_openai()
            {'continue_final_message': False, 'messages': [{'role': 'user', 'content': 'Hello, how are you?'}], 'tools': [{'type': 'function', 'function': {'name': 'get_current_weather', 'description': 'Get the current weather in a given location', 'parameters': {'type': 'object', 'properties': {'location': {'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA'}, 'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}}, 'required': ['location']}}}]}
        >   r%   r]   r^   Tr/   r4   r5   r6   r7   r8   Nsystem)rolecontentr%   c                 6    g | ]}|                                 S r   r:   r<   s     r   r?   z-InstructRequest.to_openai.<locals>.<listcomp>  s"    &Y&Y&YDt~~'7'7&Y&Y&Yr   r(   z@Truncating at max tokens is not implemented for OpenAI requests.)r@   rC   r[   rD   r
   r\   rE   r%   r;   r]   r^   rB   rF   )rG   r,   rH   rI   rJ   rK   s         r   r;   zInstructRequest.to_openai   s|   N *.MMM\` *9 *
 *
  
	k 
	kE&& !G!G!GHHH /666 ![U![![![\\\*511 k !ie!i!i!ijjjk 13)""HAS#T#TUUU} 	8 	8G""7#4#4#6#67777%4z"+&Y&YDDX&Y&Y&YN7#&2%&hiiif%%%r   r(   c                 Z   d|v r'||                     d          }nt          d          t          t          | j                                                  t          |                                                     t          |          }|t          |          nd} | d|||d|S )a  Create an instruct request from the OpenAI format.

        Args:
            messages: The messages in the OpenAI format.
            tools: The tools in the OpenAI format.
            continue_final_message: Whether to continue the final message.
            **kwargs: Additional keyword arguments to pass to the constructor. These should be the same as the fields
                of the request class or the OpenAI API equivalent.

        Returns:
            The instruct request.
        r]   Nz2Cannot specify both `tools` and `available_tools`.)r%   r]   r+   r   )rA   rC   r	   rM   rD   rN   r   r   )rO   r%   r(   r+   r,   rP   rQ   s          r   rR   zInstructRequest.from_openai'  s    , &&}

#455 !UVVV"3s'7'<'<'>'>#?#?V[[]]ASASTTT0G0Q0Q9>9J.u555PTs 
'+#9
 
 	
 
 	
r   rS   )r   r   r   r   rU   r   r!   r\   rT   r]   r   r^   intr+   rW   r   rX   r;   rY   rR   r   r   r   r[   r[      se           ?#### $M3:$$$-1OT(^d*111)-C$J---#(D(((H# H$sDc3h4H/H*I H H H HT  .2',	&
 &
tCtDcDcN6J1J,K'L!LLMN&
 DcN#d*&
 !%	&

 &
 
&
 &
 &
 [&
 &
 &
r   r[   N)enumr   typingr   r   pydanticr   mistral_common.baser   mistral_common.protocol.baser   +mistral_common.protocol.instruct.convertersr	   r
   r   r   )mistral_common.protocol.instruct.messagesr   r   +mistral_common.protocol.instruct.tool_callsr   r   r   rT   r   r   r#   r[   r   r   r   <module>rn      s                       + + + + + + > > > > > >                   S R R R R R R R R R    c4   
1 
1 
1 
1 
1[ 
1 
1 
1R
 R
 R
 R
 R
17?3K R
 R
 R
jH
 H
 H
 H
 H
k7?H+D#E H
 H
 H
 H
 H
r   