
    jF                       U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dl	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Zd dlmZmZ d dlmZ ddlmZmZ ddlmZ eej<                  eeeej<                  ef      eeej<                  ef   d	f   f   Z i Z!d
e"d<   dZ#dZ$de"d<   dZ%de"d<   dZ&de"d<   dZ'de"d<   dZ(de"d<    ejR                  e*      Z+ G d dee      Z, G d dej*                        Z-ddZ.ddZ/y)     )annotationsN)	AnyDictFinalListLiteralOptionalTupleTypeUnion)BaseSettingsInitSettingsSource)ConfigFileSourceMixin   )
dict_utilsurl_helpers)opik_api_key.Dict[str, Any]_SESSION_CACHE_DICT   zhttps://www.comet.com/opik/api/z
Final[str]OPIK_URL_CLOUDzhttp://localhost:5173/api/OPIK_URL_LOCALzDefault ProjectOPIK_PROJECT_DEFAULT_NAMEdefaultOPIK_WORKSPACE_DEFAULT_NAMEz~/.opik.configCONFIG_FILE_PATH_DEFAULTc                  0     e Zd ZdZ	 	 d fdZddZ xZS )IniConfigSettingsSourcez=
    A source class that loads variables from a INI file
    c                D   t        j                  dt              }t        j                  |      j                         }|t        k7  r)|j                         st        j                  d| d       | j                  |      | _
        t        | 1  || j                         y )NOPIK_CONFIG_PATHz#Config file not found at the path 'z:' provided by the `OPIK_CONFIG_PATH` environment variable.)osgetenvr   pathlibPath
expanduserexistsLOGGERwarning_read_filesini_datasuper__init__)selfsettings_clsconfig_file_pathexpanded_path	__class__s       d/Users/manta/Documents/Projects/TheRoad-I1/backend/.venv/lib/python3.12/site-packages/opik/config.pyr,   z IniConfigSettingsSource.__init__-   s     99%79QR%56AAC77@T@T@VNN5m_D~ ((7t}}5    c           	         t        j                         }|j                  |       |j                         D ci c]  }|t	        |j                  |             }}d|v r|d   S i S c c}w )Nopik)configparserConfigParserreadsectionsdictitems)r-   	file_pathconfigsectionconfig_valuess        r2   
_read_filez"IniConfigSettingsSource._read_file;   sr    **,I@F@Q
@QWGT&,,w/00@Q 	 
 ]" ((	
s   "A')r.   zType[BaseSettings])r<   pathlib.Pathreturnr   )__name__
__module____qualname____doc__r,   r@   __classcell__)r1   s   @r2   r   r   (   s    6(6
r3   r   c                  *   e Zd ZU dZ ej
                  d      Ze	 	 	 	 	 	 	 	 	 	 	 	 dMd       Ze	Z
ded<   	 eZded<   	 eZded<   	 d	Zded
<   	 dZded<   	 dZded<   	 dZded<   	 dZded<   	 dZded<   	 dZded<   	 dZded<   	 dZded<   	 dZded<   	 d Zded!<   	 dZded"<   	 d#Zded$<   	 dZded%<   	 dZded&<   	 d'Zded(<   	 dZ ded)<   	 d*Z!ded+<   	 d,Z"ded-<   	 dZ#ded.<   	 d/Z$ded0<   	 dZ%ded1<   	 d,Z&d2ed3<   	 d4Z'd2ed5<   	 d6Z(ded7<   	 d8Z)d2ed9<   	 d:Z*d2ed;<   	 d<Z+d2ed=<   	 dZ,ded><   	 e-dNd?       Z.e-dOd@       Z/e-dOdA       Z0e-dOdB       Z1e-dPdC       Z2 e3jh                  dDE      dQdF       Z5dRdGZ6dSdHZ7	 dT	 	 	 dUdIZ8dVdJZ9dVdKZ:dVdLZ;y)W
OpikConfigaL  
    Initializes every configuration variable with the first
    found value. The order of sources used:
    1. User passed values
    2. Session config dict (can be populated by calling `update_session_config(...)`)
    3. Environment variables (they must start with "OPIK_" prefix)
    4. Load from file
    5. Default values
    opik_)
env_prefixc                n    |t        j                  t         j                  t              |t	        |       fS )N)r.   )pydantic_settingsr   r   r   r   )clsr.   init_settingsenv_settingsdotenv_settingsfile_secret_settingss         r2   settings_customise_sourcesz%OpikConfig.settings_customise_sourcesU   s8     00!..0C #5
 	
r3   strurl_overrideproject_name	workspacezopenai/gpt-5-nanodefault_llmNzOptional[str]api_keyzOptional[int]default_flush_timeout   intbackground_workers   file_upload_background_workersINFOz8Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']console_logging_levelzBOptional[Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']]file_logging_levelzopik.loglogging_fileTboolpytest_experiment_enabledcheck_tls_certificateFtrack_disablesentry_enablezUhttps://34bd6f9621ca2783be63f320e35de0dc@o168229.ingest.us.sentry.io/4508620148441088
sentry_dsn enable_litellm_models_monitoringenable_json_request_compression   guardrail_timeoutguardrails_url_overridei@B maximal_queue_size
   maximal_queue_size_batch_factorlog_start_trace_spani  #min_base64_embedded_attachment_sizeis_attachment_extraction_activefloat connection_monitor_ping_intervalr    connection_monitor_check_timeout2   replay_batch_sizeg      ?replay_batch_replay_delayg333333?replay_tick_intervalg      $@(unauthorized_message_type_retry_interval)unauthorized_message_type_max_retry_countc                |    t        j                  dt              }t        j                  |      j                         S )Nr    )r!   r"   r   r#   r$   r%   )r-   r/   s     r2   config_file_fullpathzOpikConfig.config_file_fullpath!  s.    99%79QR||,-88::r3   c                6    | j                   j                         S )zY
        Determines whether the configuration file exists at the specified path.
        )r   r&   r-   s    r2   config_file_existszOpikConfig.config_file_exists&  s    
 ((//11r3   c                t    t        j                  | j                        t        j                  t              k(  S )zM
        Determine if the installation type is a cloud installation.
        )r   get_base_urlrU   r   r   s    r2   is_cloud_installationz OpikConfig.is_cloud_installation-  s2    
 ''(9(9:k>V>V?
 
 	
r3   c                    d| j                   v S )N	localhost)rU   r   s    r2   is_localhost_installationz$OpikConfig.is_localhost_installation6  s    d////r3   c                v    | j                   | j                   S t        j                  | j                        dz   S )Nzguardrails/)rn   r   r   rU   r   s    r2   guardrails_backend_hostz"OpikConfig.guardrails_backend_host:  s6    ''3///''(9(9:]JJr3   after)modec                B   d| j                   vxs | j                  d u }| j                  d uxr |}|s| S | j                  J t        j                  | j                        }|;|j
                  /t        j                  j                  |j
                  d      | _        | S )NrU   z	opik/api/)	model_fields_setrU   rY   r   parse_api_keybase_urlurllibparseurljoin)r-   url_was_not_providedurl_needs_configurationopik_api_key_s       r2   _set_url_override_from_api_keyz)OpikConfig._set_url_override_from_api_key@  s     $"7"77T4;L;LPT;T 	 #',,d":"S?S&K||'''$224<<@$)?)?)K & 4 4&&!D r3   c                   t        j                         }| j                  | j                  d|d<   | j                  | j                  |d   d<   	 t        | j                  dd      5 }|j                  |       ddd       t        j                  d| j                          y# 1 sw Y   ,xY w# t        $ r}t        j                  d	|         d}~ww xY w)
z~
        Save configuration to a file

        Raises:
            OSError: If there is an issue writing to the file.
        )rU   rW   r5   NrY   zw+zutf-8)r   encodingzConfiguration saved to file: zFailed to save configuration: )r6   r7   rU   rW   rY   openr   writer'   infoOSErrorerror)r-   config_file_contentconfig_filees       r2   save_to_filezOpikConfig.save_to_fileT  s     +779 !--'
F#
 <<#59\\'	2	))w#))+6 KK78Q8Q7RST	 
  	LL9!=>	s0   B1 (B%:*B1 %B.*B1 1	C:CCc                V    | j                         }|j                  d      |rd|d<   |S )zT
        Retrieves the current configuration with the API key value masked.
        rY   z*** HIDDEN ***)
model_dumpget)r-   mask_api_keycurrent_valuess      r2   as_dictzOpikConfig.as_dicto  s3     *i(4(8N9%r3   c                    dt         j                  v ry| j                         \  }}|r&|r#t                t        j                  d| d       yy)a  
        Attempts to detects if Opik is misconfigured and optionally displays
        a corresponding error message.
        Works only for Opik cloud and OSS localhost installations.

        Parameters:
        show_misconfiguration_message : A flag indicating whether to display detailed error messages if the configuration
            is determined to be misconfigured. Defaults to False.
        pytestFz========================
z 
==============================
T)sysmodules&get_misconfiguration_detection_resultsprintr'   r   )r-   show_misconfiguration_messageis_misconfigured_flagerror_messages       r2   !check_for_known_misconfigurationsz,OpikConfig.check_for_known_misconfigurationsx  s^     s{{" 779 	-} !,0$o &77
 r3   c                h    | j                         \  }}|rd|fS | j                         \  }}|rd|fS y)a#  
        Tries detecting misconfigurations for either cloud or localhost environments.
        The detection will not work for any other kind of installation.

        Returns:
            Tuple[bool, Optional[str]]: A tuple where the first element indicates
            whether the configuration is misconfigured (True for misconfigured, False for valid).
            The second element is an optional string that contains
            an error message if there is a configuration issue, or None if the
            configuration is valid.
        TFN)_is_misconfigured_for_cloud_is_misconfigured_for_localhost)r-   is_misconfigured_for_cloud_flagr   #is_misconfigured_for_localhost_flags       r2   r   z1OpikConfig.get_misconfiguration_detection_results  sU     ,,. 	7' +&& 002 	;+] /&&r3   c                d    | j                   du}| j                  }| j                  r
|s|sd}d|fS y)a  
        Determines if the current Opik configuration is misconfigured for cloud logging.

        Returns:
            Tuple[bool, Optional[str]]: A tuple where the first element is a boolean indicating if
            the configuration is misconfigured for cloud logging, and the second element is either
            an error message indicating the reason for misconfiguration or None.
        Na  The API key must be specified to log data to https://www.comet.com/opik.
You can use `opik configure` CLI command to configure your environment for logging.
See the configuration details in the docs: https://www.comet.com/docs/opik/tracing/sdk_configuration.
Tr   )rY   rg   r   )r-   api_key_configuredtracking_disabledr   s       r2   r   z&OpikConfig._is_misconfigured_for_cloud  sK     "\\5 .. &&'&z 
 &&r3   c                n    | j                   t        k(  }| j                  }| j                  r
|s|sd}d|fS y)a  
        Determines if the current setup is misconfigured for a local open-source installation.

        Returns:
            Tuple[bool, Optional[str]]: A tuple where the first element is a boolean indicating if
            the configuration is misconfigured for local logging, and the second element is either
            an error message indicating the reason for misconfiguration or None.
        a  Open source installations do not support workspace specification. Only `default` is available.
See the configuration details in the docs: https://www.comet.com/docs/opik/tracing/sdk_configuration
If you need advanced workspace management - you may consider using our cloud offer (https://www.comet.com/site/pricing/)
or contact our team for purchasing and setting up a self-hosted installation.
Tr   )rW   r   rg   r   )r-   workspace_is_defaultr   r   s       r2   r   z*OpikConfig._is_misconfigured_for_localhost  sL      $~~1LL .. **)&b  &&r3   )r.   z$Type[pydantic_settings.BaseSettings]rO   ,pydantic_settings.PydanticBaseSettingsSourcerP   r   rQ   r   rR   r   rB   z8Tuple[pydantic_settings.PydanticBaseSettingsSource, ...])rB   rA   )rB   rd   )rB   rT   )rB   rI   )rB   None)r   rd   rB   r   )F)r   rd   rB   rd   )rB   zTuple[bool, Optional[str]])<rC   rD   rE   rF   rM   SettingsConfigDictmodel_configclassmethodrS   r   rU   __annotations__r   rV   r   rW   rX   rY   rZ   r]   r_   ra   rb   rc   re   rf   rg   rh   ri   rj   rk   rm   rn   ro   rq   rr   rs   rt   rv   rw   ry   rz   r{   r|   r}   propertyr   r   r   r   r   pydanticmodel_validatorr   r   r   r   r   r   r    r3   r2   rI   rI   H   sY    8$777KL
:
 D
 C	

 F
 K
 
B
 
& 'L#&1L#10Is0*K*_!G]!e+/=/	   +-"C,
 	 S  	    #L#" '+t* #'4&  M4  M4 nJm .2$d1 -1#T0  s .2]1
 (' ,.#S- "&$%
 07'6
 -1#T0 /1$e0 /0$e/  s (+u*
 #&%%
 7;,e:
 @D-}C
 ; ; 2 2 
 
 0 0 K K
 X7+ ,&6 5:-1	>44r3   rI   c                    |t         | <   y )N)r   )keyvalues     r2   update_session_configr     s    $r3   c                 B    t        j                  |       }t        di |S )z@
    Instantiates an OpikConfig using provided user inputs.
    r   )r   remove_none_from_dictrI   )user_inputscleaned_user_inputss     r2   get_from_user_inputsr     s$     %::;G,+,,r3   )r   rT   r   r   rB   r   )r   r   rB   rI   )0
__future__r   r6   loggingr!   r   r#   urllib.parser   typingr   r   r   r   r   r	   r
   r   r   r   rM   r   r   pydantic_settings.sourcesr    r   r   rY   r   r$   rT   PathTyper   r   MAX_BATCH_SIZE_MBr   r   r   r   r   	getLoggerrC   r'   r   rI   r   r   r   r3   r2   <module>r      s
   "   	 
   P P P   > ; % !LLw||S 	!"	%c!
"C
'(* ') ^ ( >
 >9
 9(9 : 9*3 Z 3'7 * 7			8	$02G @]"// ]@%-r3   