o
    mi5                     @   s,  d dl Z d dlmZ d dl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 e eZdeeef dee deeef fd	d
Zdeeeef  dee deee eee  f fddZ	ddeeef dededeeef fddZdeeeef  deeee f fddZG dd dZdS )    N)datetime)AnyDictListOptionalSequenceTuple)Response)generate_idoriginal_dictkeys_subsetreturnc                    s    fdd|D S )zCreate a subset of a dictionary using a subset of keys.

    :param original_dict: The original dictionary.
    :param keys_subset: The subset of keys to extract.
    :return: A dictionary containing only the specified keys.
    c                    s   i | ]}| v r| | qS  r   .0keyr   r   _/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/wandb/integration/cohere/resolver.py
<dictcomp>   s    zsubset_dict.<locals>.<dictcomp>r   )r   r   r   r   r   subset_dict   s   	r   dataorderc                 C   s   g }t  }|D ]}||vr|| || q| D ]}|D ]}||vr.|| || qqg }| D ]}g }|D ]}|||d q:|| q4||fS )a  Convert a list of dictionaries to a pair of column names and corresponding values, with the option to order specific dictionaries.

    :param data: A list of dictionaries.
    :param order: A list of keys specifying the desired order for specific dictionaries. The remaining dictionaries will be ordered based on their original order.
    :return: A pair of column names and corresponding values.
    N)setappendaddget)r   r   final_columnskeys_presentr   dvaluesrowr   r   r   &reorder_and_convert_dict_list_to_table   s*   	



r!    -
dictionary
parent_keysepc                 C   sZ   i }|   D ]$\}}|r| | | n|}t|tr&|t|||d q|||< q|S )a  Flatten a nested dictionary, joining keys using a specified separator.

    :param dictionary: The dictionary to flatten.
    :param parent_key: The base key to prepend to each key.
    :param sep: The separator to use when joining keys.
    :return: A flattened dictionary.
    )r&   )items
isinstancedictupdateflatten_dict)r$   r%   r&   flattened_dictr   valuenew_keyr   r   r   r+   <   s   


r+   list_of_dictsc                 C   sH   t jtt |  }dd |D }| D ]}|D ]}|| ||  qq|S )a3  Collect the common keys of a list of dictionaries. For each common key, put its values into a list in the order they appear in the original dictionaries.

    :param list_of_dicts: The list of dictionaries to inspect.
    :return: A dictionary with each common key and its corresponding list of values.
    c                 S   s   i | ]}|g qS r   r   r   r   r   r   r   W   s    z'collect_common_keys.<locals>.<dictcomp>)r   intersectionmapr   )r/   common_keyscommon_dictr   r   r   r   r   collect_common_keysP   s   r4   c                   @   sT  e Zd ZdZdee deeef dede	de	de
eeef  fdd	Zdedeeeef  fd
dZdedeeeef  fddZdedeeeef  fddZdeeef deeef fddZdedeeeef  fddZdedeeeef  fddZdee deeef deeeef  de	de	dedee dedeeef fddZdS )CohereRequestResponseResolverzlClass to resolve the request/response from the Cohere API and convert it to a dictionary that can be logged.argskwargsresponse
start_timetime_elapsedr   c              
   C   s0  z|t t|dd dd }d}|dkr#| |}g d}d}	nM|d	kr3| |}g d
}d}	n=|dkrH| |}| |}g d}d}	n(|dkrX| |}g d}d}	n|dkrh| |}g d}d}	nt	
d|  | ||||||||	W S  ty }
 zt	d|
  W Y d}
~
dS d}
~
ww )a  Process the response from the Cohere API and convert it to a dictionary that can be logged.

        :param args: The arguments of the original function.
        :param kwargs: The keyword arguments of the original function.
        :param response: The response from the Cohere API.
        :param start_time: The start time of the request.
        :param time_elapsed: The time elapsed for the request.
        :return: A dictionary containing the parsed response and timing information.
        '   .NGenerations)	r9   query_idmodelprompttexttoken_likelihoods
likelihoodtime_elapsed_(seconds)end_timecommandChat)r9   r@   rA   conversation_idresponse_idqueryrC   rB   preamblechat_historychatlogrF   rG   Classifications)	r9   r@   rA   idinput
prediction
confidencerF   rG   zembed-english-v2.0SummarizeResponse)r9   r@   rA   rK   rC   additional_commandsummaryrF   rG   lengthformatzsummarize-xlarge	Reranking)r9   r@   rA   rQ   rL   top_nzdocument-textrelevance_scoreindexrF   rG   zrerank-english-v2.0z$Unsupported Cohere response object: z$Failed to resolve request/response: )strtypesplit_resolve_generate_response_resolve_chat_response_resolve_classify_response_resolve_classify_kwargs_resolve_summarize_response_resolve_rerank_responseloggerinfo_resolve	Exceptionwarning)selfr6   r7   r8   r9   r:   response_typeparsed_responsetable_column_orderdefault_modeler   r   r   __call__a   sP    






z&CohereRequestResponseResolver.__call__c              
   C   sR   g }|D ]"}|  }zt|d |d< W n ttfy    Y nw || q|S )NrD   )_visualize_helperwandbHtmlKeyError
ValueErrorr   )rl   r8   return_list	_response_response_dictr   r   r   ra      s   z8CohereRequestResponseResolver._resolve_generate_responsec                 C   s   t |jg dgS )N)rK   generation_idrL   rC   rJ   rB   rO   rM   )r   __dict__rl   r8   r   r   r   rb      s
   z4CohereRequestResponseResolver._resolve_chat_responsec                 C   s   dd |D S )Nc                 S      g | ]}t |jqS r   r+   r|   r   ry   r   r   r   
<listcomp>  s    zLCohereRequestResponseResolver._resolve_classify_response.<locals>.<listcomp>r   r}   r   r   r   rc      s   z8CohereRequestResponseResolver._resolve_classify_responsec                 C   sL   g }g }|d D ]}| |j | |j q|d ||d< ||d< |S )Nexamplesexample_textsexample_labels)r   rC   labelpop)rl   r7   r   r   exampler   r   r   rd     s   
z6CohereRequestResponseResolver._resolve_classify_kwargsc                 C   s   |j |jdgS )N)rK   rW   )rQ   rW   r}   r   r   r   re     s   z9CohereRequestResponseResolver._resolve_summarize_responsec                 C   s&   dd |D }t |}|j|d< |gS )Nc                 S   r~   r   r   r   r   r   r   r     s    
zJCohereRequestResponseResolver._resolve_rerank_response.<locals>.<listcomp>rQ   )r4   rQ   )rl   r8   flattened_response_dictsreturn_dictr   r   r   rf     s   
z6CohereRequestResponseResolver._resolve_rerank_responsern   rm   ro   rp   c	                 C   s   t dd}	t|d jg d}
t|}t|| }|||d}g }|D ]}d|	i||||
}d|vr;||d< || q%t||\}}tj||d}| |iS )	a  Convert a list of dictionaries to a pair of column names and corresponding values, with the option to order specific dictionaries.

        :param args: The arguments passed to the API client.
        :param kwargs: The keyword arguments passed to the API client.
        :param parsed_response: The parsed response from the API.
        :param start_time: The start time of the API request.
        :param time_elapsed: The time elapsed during the API request.
        :param response_type: The type of the API response.
        :param table_column_order: The desired order of columns in the resulting table.
        :param default_model: The default model to use if not specified in the response.
        :return: A dictionary containing the formatted response.
           )rX   r   )api_version
batch_sizemax_retriesnum_workerstimeout)r9   rG   rF   r@   rA   )r   columns)	r
   r   r|   r   fromtimestampr   r!   rt   Table)rl   r6   r7   rn   r9   r:   rm   ro   rp   r@   parsed_argsstart_time_dtend_time_dttimingspacked_data_parsed_response_packed_dictr   r   request_response_tabler   r   r   ri   !  s>   


z&CohereRequestResponseResolver._resolveN)__name__
__module____qualname____doc__r   r   r   r^   r	   floatr   rr   r   ra   rb   rc   rd   re   rf   ri   r   r   r   r   r5   ^   sP    

"
	

r5   )r"   r#   )loggingr   typingr   r   r   r   r   r   rt   (wandb.sdk.integration_utils.auto_loggingr	   wandb.sdk.lib.runidr
   	getLoggerr   rg   r^   r   r!   r+   r4   r5   r   r   r   r   <module>   sB     




%


*