o
    ưi2                     @   s   d Z ddlmZmZmZmZmZmZmZm	Z	m
Z
mZmZ ddlZddlmZ ddlmZ ddlm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mZm Z  ddl!m"Z"m#Z# ddl$m%Z% G dd de%Z&G dd deZ'dS )zQ
Translate from OpenAI's `/v1/chat/completions` to Groq's `/v1/chat/completions`
    )Any	CoroutineListLiteralOptionalTupleUnioncastoverloadIteratorAsyncIteratorN)$OpenAIChatCompletionStreamingHandler)OpenAIError)	BaseModel)verbose_logger)Loggingget_secret_str)AllMessageValuesChatCompletionAssistantMessageChatCompletionToolParam$ChatCompletionToolParamFunctionChunk)ModelResponseModelResponseStream   )OpenAILikeChatConfigc                       s  e Zd ZU dZee ed< dZeee	e
f  ed< dZee ed< dZee
 ed< dZee ed< dZee ed< dZee ed< dZeee	ef  ed	< dZee ed
< dZee ed< dZee
 ed< dZee ed< dZeee	e
f  ed< 													dAdee deee	e
f  dee dee
 dee dee dee d	eee	ef  d
ee dee dee
 dee deee	e
f  ddfddZedee	 fddZe fddZ	dBdeee	 ee	 ef dedee de fddZ!de	def fddZ"e#de$e% de	d e&d! de'e e e$e% f fd"d#Z(e#	dBde$e% de	d e&d de$e% fd$d#Z(	dBde$e% de	d edee$e% e'e e e$e% f f f fd%d#Z(d&ee	 d'ee	 de)ee	 ee	 f fd(d)Z*d*e
defd+d,Z+d-e
fd.d/Z,		dCd0e
d*e
de	d1ed2ede
f fd3d4Z-		dDde	d5e.j/d6ed7e0d8e
de$e% d*e
d9e
d:e d'ee	 dee def fd;d<Z1d=ee	 de&d> fd?d@Z2  Z3S )EGroqChatConfigNfrequency_penaltyfunction_call	functions
logit_bias
max_tokensnpresence_penaltystoptemperaturetop_presponse_formattoolstool_choicereturnc                 C   s>   t   }| D ]\}}|dkr|d urt| j|| q	d S )Nself)localscopyitemssetattr	__class__)r+   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   Zlocals_keyvalue r3   \/home/app/Keep/.python/lib/python3.10/site-packages/litellm/llms/groq/chat/transformation.py__init__9   s   
zGroqChatConfig.__init__c                 C   s   dS )Ngroqr3   )r+   r3   r3   r4   custom_llm_providerN   s   z"GroqChatConfig.custom_llm_providerc                    s
   t   S N)super
get_config)clsr0   r3   r4   r:   R   s   
zGroqChatConfig.get_configFstreaming_responsesync_stream	json_modec                 C   s   t |||dS )N)r=   r>   r?   )"GroqChatCompletionStreamingHandler)r+   r=   r>   r?   r3   r3   r4   get_model_response_iteratorV   s
   z*GroqChatConfig.get_model_response_iteratormodelc              
      s   t  |}z|d W n	 ty   Y nw ztj|| jdr(|d W |S W |S  tyE } zt	
d|  W Y d }~|S d }~ww )Nmax_retriesrB   r7   Zreasoning_effortz,Error checking if model supports reasoning: )r9   get_supported_openai_paramsremove
ValueErrorlitellmZsupports_reasoningr7   append	Exceptionr   debug)r+   rB   Zbase_paramser<   r3   r4   rE   b   s&   z*GroqChatConfig.get_supported_openai_paramsmessagesis_asyncTc                 C      d S r8   r3   r+   rM   rB   rN   r3   r3   r4   _transform_messagess   s   z"GroqChatConfig._transform_messagesc                 C   rO   r8   r3   rP   r3   r3   r4   rQ   y   s   c                    s   t |D ]4\}}	 t|tr| }n|}|ddk}|r8tdd}| D ]\}	}
|
d ur3|
||	< q'|||< q|rDt j||ddS t j||ddS )NroleZ	assistant)rR   T)rM   rB   rN   F)		enumerate
isinstancer   Z
model_dumpgetr   r.   r9   rQ   )r+   rM   rB   rN   idxmessage_messageZassistant_messageZnew_messagekvr<   r3   r4   rQ      s*   


api_baseapi_keyc                 C   s$   |pt dpd}|pt d}||fS )NZGROQ_API_BASEzhttps://api.groq.com/openai/v1ZGROQ_API_KEYr   )r+   r[   r\   Zdynamic_api_keyr3   r3   r4   $_get_openai_compatible_provider_info   s   z3GroqChatConfig._get_openai_compatible_provider_infooptional_paramsc                 C   s   | ddur	dS dS )zH
        Groq doesn't support 'response_format' while streaming
        r'   NTF)rU   )r+   r^   r3   r3   r4   _should_fake_stream   s   z"GroqChatConfig._should_fake_streamjson_schemac                 C   s   t dtd|ddS )a3  
        Handles creating a tool call for getting responses in JSON format.

        Args:
            json_schema (Optional[dict]): The JSON schema the response should be in

        Returns:
            AnthropicMessagesTool: The tool call to send to Anthropic API to get responses in JSON format
        functionjson_tool_call)name
parameterstypera   )r   r   )r+   r`   r3   r3   r4   *_create_json_tool_call_for_response_format   s   z9GroqChatConfig._create_json_tool_call_for_response_formatnon_default_paramsdrop_params-replace_max_completion_tokens_with_max_tokensc           
         s   | d}| |rd|d< |d urht|trhd }d|v r"|d }n
d|v r,|d d }	 |d urhtj|ddshd	|v rHtjd
| d|dddddid}| j|d}	|	g|d	< ||d< d|d< |dd  t	 
||||}|S )Nr'   TZfake_streamZresponse_schemar`   Zschemar6   rD   r(   zGroq model 'as  ' does not support native structured outputs. LiteLLM uses a tool-calling workaround for structured outputs on this model, which is incompatible with user-provided tools. Either use a model that supports native structured outputs (e.g., gpt-oss-120b, llama-4, kimi-k2), or remove the tools parameter. See: https://console.groq.com/docs/structured-outputs#supported-models)rW   rB   Zllm_providerra   rc   rb   re   )r`   r)   r?   )rU   r_   rT   dictrH   Zsupports_response_schemaZBadRequestErrorrg   popr9   map_openai_params)
r+   rh   r^   rB   ri   rj   Z_response_formatr`   Z_tool_choiceZ_toolr<   r3   r4   rm      sH   




z GroqChatConfig.map_openai_paramsraw_responsemodel_responselogging_objrequest_datalitellm_paramsencodingc                    sD   t  j|||||||||	|
|d}| jt|dd}t|d| |S )N)rB   rn   ro   rp   rq   rM   r^   rr   rs   r\   r?   Zservice_tier)original_service_tier)r9   transform_response_map_groq_service_tiergetattrr/   )r+   rB   rn   ro   rp   rq   rM   r^   rr   rs   r\   r?   Zmapped_service_tierr<   r3   r4   ru     s&   z!GroqChatConfig.transform_responsert   autodefaultZflexc                 C   s&   |du rdS |dvrdS t td |S )z@
        Ensure groq service tier is OpenAI compatible.
        Nry   rx   )r	   r   )r+   rt   r3   r3   r4   rv   0  s
   z%GroqChatConfig._map_groq_service_tier)NNNNNNNNNNNNN)F)FF)NN)4__name__
__module____qualname__r   r   int__annotations__r   r   strrk   r   listr    r!   r"   r#   r$   r%   r&   r'   r(   r)   r5   propertyr7   classmethodr:   r   r   r   boolr   rA   rE   r
   r   r   r   r   rQ   r   r]   r_   rg   rm   httpxResponseLiteLLMLoggingObjru   rv   __classcell__r3   r3   r<   r4   r   *   s@  
 	


	
	
O	
$r   c                       s&   e Zd Zdedef fddZ  ZS )r@   chunkr*   c                    sl   | d}|rt| d| d|d| dg }|D ]}| di }d|v r/|d|d< qt |S )	NerrorcoderW   )status_coderW   bodychoicesdeltaZ	reasoningZreasoning_content)rU   r   rl   r9   chunk_parser)r+   r   r   r   choicer   r<   r3   r4   r   ?  s   
z/GroqChatCompletionStreamingHandler.chunk_parser)r{   r|   r}   rk   r   r   r   r3   r3   r<   r4   r@   >  s    r@   )(__doc__typingr   r   r   r   r   r   r   r	   r
   r   r   r   Z+litellm.llms.openai.chat.gpt_transformationr   Z litellm.llms.openai.common_utilsr   Zpydanticr   rH   Zlitellm._loggingr   Z*litellm.litellm_core_utils.litellm_loggingr   r   Zlitellm.secret_managers.mainr   Zlitellm.types.llms.openair   r   r   r   Zlitellm.types.utilsr   r   Zopenai_like.chat.transformationr   r   r@   r3   r3   r3   r4   <module>   s"    4  