
    jP                     x   U d dl Z d dlZd dlZd dlmZmZ d dlZd dlZd dl	Z
d dlmZ 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  ej2                  e      Zd	Zee   ed
<   dZee   ed<    G d d      Z dee   dee   ddfdZ!dedee   fdZ"	 	 	 	 	 	 ddee   dee   dee   de#de#de#ddfdZ$y)    N)FinalOptional)get_client_cached)OPIK_WORKSPACE_DEFAULT_NAME)ask_user_for_approvalis_interactive)opik_rest_helpers)ConfigurationError)opik_api_keyzhttps://www.comet.com/OPIK_BASE_URL_CLOUDzhttp://localhost:5173/OPIK_BASE_URL_LOCALc                       e Zd Z	 	 	 	 	 	 	 ddee   dee   dee   dedededefd	ZddZddZddZ	d
efdZ
ddZd
efdZd
efdZddZdded
dfdZddZddZddZy)OpikConfiguratorNapi_key	workspaceurl	use_localforceself_hosted_cometautomatic_approvalsc                    || _         || _        || _        || _        t        j
                  j                         | _        || _        || _	        |$| j                  rt        | _        y t        | _        y t        j                  |      | _        y N)r   r   r   r   opikconfig
OpikConfigcurrent_configr   r   r   r   base_urlurl_helpersget_base_url)selfr   r   r   r   r   r   r   s           t/Users/manta/Documents/Projects/TheRoad-I1/backend/.venv/lib/python3.12/site-packages/opik/configurator/configure.py__init__zOpikConfigurator.__init__   s{     ""
"kk446!2#6  ;'+~~# M;N M (44S9DM    returnc                     t        j                         j                  dkD  rt        j	                  d       | j
                  du r| j                          y| j                          y)a  
        Create a local configuration file for the Python SDK. If a configuration file already exists,
        it will not be overwritten unless the `force` parameter is set to True.

        Raises:
            ConfigurationError
            ConnectionError
        r   zTExisting Opik clients will not use updated values for "url", "api_key", "workspace".FN)r   
cache_infocurrsizeLOGGERinfor   _configure_cloud_configure_local)r    s    r!   	configurezOpikConfigurator.configure9   sX     '')22Q6KKf
 >>U"!!# 	r#   c                 H   | j                         }| j                         }|s|r| j                          n]| j                  d       t        | j                  | j
                         t        j                  d| j                  j                         | j                          y)z
        Configure the non-local Opik instance by handling API key and workspace settings.
        Non-local means both cloud and onprem.
        Fsave_to_filer   r   zWOpik is already configured. You can check the settings by viewing the config file at %sN)_set_api_key_set_workspace_update_config+_set_environment_variables_for_integrationsr   r   r(   r)   r   config_file_fullpath"_log_project_configuration_message)r    update_config_with_api_keyupdate_config_with_workspaces      r!   r*   z!OpikConfigurator._configure_cloudR   s     &*%6%6%8" (,':':'<$ &)E!U37 KKi##88
 	//1r#   c                 `   d| _         t        | _        | j                  t        k(   }|st
        | _        |rLt        j                  | j                        r-| j                  | j                         | j                          yt        j                  t
              r| j                  sK| j                  j                  t
        k(  r.t        j                  dt
         d       | j                          yt               s| j                   st#        dt
         d      | j                   rdnt%        dt
         d	      }|r,t
        | _        | j                          | j                          yt               st#        d
      | j'                          | j                          | j                          y)z
        Configure the local Opik instance by setting the local URL and workspace.

        Raises:
            ConfigurationError: Raised if the Opik instance is not active or not found.
        Nr.   z0Opik is already configured to local instance at .zBOpik URL is not specified - A local Opik instance was detected at z, to use it set your URL using the environment variable OPIK_URL_OVERRIDE or provide it as an argument. For more details, refer to the documentation: https://www.comet.com/docs/opik/tracing/sdk_configuration.TzFound local Opik instance on: z, do you want to use it? (Y/n)zOpik URL is not specified - Please set your Opik instance URL using the environment variable OPIK_URL_OVERRIDE or provide it as an argument. For more details, refer to the documentation: https://www.comet.com/docs/opik/tracing/sdk_configuration.)r   r   r   r   r   r   r	   is_instance_activer3   r   r6   r   url_overrider(   r)   r   r   r
   r   _ask_for_url)r    url_was_provideduse_urls      r!   r+   z!OpikConfigurator._configure_locall   s    4 $1D DE/DM  1 D DT]] STZZ8335 //0CDJJ''448KKFGZF[[\] 779 "#D,D,D(XYlXm  n~    ++ *45H4IIgh   3##%779 $ H  	//1r#   c                    d}| j                   rt        | j                         }|| j                  r| j                          t	        j
                  | j                   |xs | j                        st        d      | j                          | j                  rd}|S d}|S | j                  r0| j                   $| j                          | j                          d}|S | j                   :| j                  j                   $| j                          | j                          d}|S | j                   A| j                  j                   +| j                  j                   | _         | j                          |S )z
        Determines and set the correct API key based on the current configuration, force flag, and user input.

        Returns:
            bool: a boolean indicating if the configuration file needs updating.
        Fr   API key is incorrect.T)r   _extract_base_url_from_api_keyr   r=   r	   is_api_key_correctr   r
   _try_set_url_from_api_keyr   _ask_for_api_keyr   )r    config_file_needs_updatingextracted_base_urls      r!   r1   zOpikConfigurator._set_api_key   sX    &+"<<!?!M!)d.D.D!!#$77"4"E ))@AA**,15&  *)! BG&  *) ZZDLL0!!#**,)-& *) \\!d&9&9&A&A&I!!#**,)-& *)	 \\!d&9&9&A&A&M..66DL**,))r#   c                    d}t         j                  j                  t        j                  | j
                        d      }| j
                  t        k(  }| j                  s/|rt        j                  d|       nt        j                  d|       t               st        d      |dkD  rt        j                  d      }t        |      }|| j                  r| j                          |xs | j
                  }t        j                   ||	      r|| _        yt        j%                  d
| d       |dz  }|dkD  rt        d      )a  
        Prompt the user for an Opik API key and verify its validity.
        Verification is done against:
            * cloud, if no url was provided, self_hosted_comet is false
            * provided url (if exists)
            * url, extracted from the smart API key
        The function retries up to 3 times if the API key is invalid.

        Raises:
            ConfigurationError: Raised if the API key provided by the user is invalid after 3 attempts.
           z/api/my/settings/zZYour Opik API key is available in your account settings, can be found at %s for Opik cloudzKYour Opik API key is available in your account settings, can be found at %szAPI key missing - Please set your API key using the environment variable OPIK_API_KEY or provide it as an argument. For more details, refer to the documentation: https://www.comet.com/docs/opik/tracing/sdk_configuration.r   zPlease enter your Opik API key:NrA   z%The API key provided is not valid on z. Please try again.   rB   )urllibparseurljoinr   r   r   r   r   r(   r)   r   r
   getpassrC   r=   r	   rD   r   error)r    retriessettings_urlurl_was_not_passeduser_input_api_keyrH   current_iteration_urls          r!   rF   z!OpikConfigurator._ask_for_api_key   s<    ||++$$T]]35H
 "]].AA%%!p 
 a 
 $ o  k!(1R!S!?@R!S!)d.D.D!!#$6$G$--! 33")  2;<Q;RRef 1' k( !!899r#   c                 "   | j                   _t        j                  | j                  | j                   | j                        st        d| j                    d      | j                  rdS dS d| j                  j                  v rE| j                  j                   t        k7  r(| j                  s| j                  j                   | _         y| j                         }| j                  rdnt        d| d      }|r|| _         y| j                          y)	a5  
        Determines and set the correct workspace based on current configuration, force flag, and user input.

        Returns:
            bool: a boolean indicating whether the configuration file needs updating.

        Raises:
            ConfigurationError: If the provided workspace is invalid.
        r   r   r   zWorkspace `z%` is incorrect for the given API key.TFr   zDo you want to use "z" workspace? (Y/n))r   r	   is_workspace_name_correctr   r   r
   r   r   model_fields_setr   _get_default_workspacer   r   _ask_for_workspace)r    default_workspaceuse_default_workspaces      r!   r2   zOpikConfigurator._set_workspace  s
    >>%$>>DMM )!$..!11VW   ::4050 4..???##--1LLJJ!00::DN !779 '' &&'8&99KL 	 !.DN  ##%r#   c                    | j                   st        d      	 t        j                         5 }|j                  j                  d| j                    i       |j                  t        j                  | j                              }ddd       j                  dk7  rt        d|j                         |j                         j                  d      }|st        d      |S # 1 sw Y   ^xY w# t        j                  $ r}t        d	t        |             d}~wt         $ r}t        d
t        |             d}~ww xY w)a  
        Retrieves the default Opik workspace name associated with the given API key.

        Returns:
            str: The default workspace name.

        Raises:
            ConnectionError: If there's an error while fetching the default workspace.
        zAPI key must be set.AuthorizationrA   N   z,Error while getting default workspace name: defaultWorkspaceNamez/defaultWorkspaceName not found in the response.zNetwork error occurred: zUnexpected error occurred: )r   r
   httpxClientheadersupdategetr   get_account_details_urlr   status_codeConnectionErrortextjsonRequestErrorstr	Exception)r    clientresponsedefault_workspace_namees        r!   rZ   z'OpikConfigurator._get_default_workspace6  s"    ||$%;<<	J6%%4<<.&JK!::#;;DMMJ &    ##s*%B8==/R  &.]]_%8%89O%P")%&WXX))  " !! 	G!$<SVH"EFF 	J!$?Ax"HII	Js<   C. AC"AC. "C+'C. .E DE $D;;E c                 <   d}| j                   st        d      t               st        d      |dkD  r_t        d      }t	        j
                  | j                   || j                        r|| _        yt        j                  d       |d	z  }|dkD  r_t        d
      )a  
        Prompt the user for an Opik instance workspace name and verify its validity.
        The function retries up to 3 times if the workspace name is invalid.

        Raises:
            ConfigurationError: Raised if the workspace name is invalid after 3 attempts.
        rJ   z,API key must be set to check workspace name.zWorkspace name missing - Please set your workspace name using the environment variable OPIK_WORKSPACE or provide it as an argument. For more details, refer to the documentation: https://www.comet.com/docs/opik/tracing/sdk_configuration.r   z0Please enter your Opik instance workspace name: rW   NzPThis workspace does not exist, please enter a workspace that you have access to.rK   z5User does not have access to the workspaces provided.)
r   r
   r   inputr	   rX   r   r   r(   rP   )r    rQ   user_input_workspaces      r!   r[   z#OpikConfigurator._ask_for_workspaceZ  s     ||$%STT$   k#(B$  !::0D$-- "6f 1 k !C
 	
r#   r/   c                    	 | j                   s*t        j                  j                  | j                  d      n)t        j                  j                  | j                  d      }|rFt
        j                  j                  | j                  || j                        }|j                          t
        j                  j                  d| j                         t
        j                  j                  d|       t
        j                  j                  d| j                         y	# t        $ r1}t        j                  dt        |              t!        d      d	}~ww xY w)
z
        Save changes to the config file and update the current session configuration.

        Raises:
            ConfigurationError: Raised if there is an issue saving the configuration or updating the session.
        z	opik/api/z/api/)r   r<   r   r   r<   r   zFailed to update config: zFailed to update configuration.N)r   rL   rM   rN   r   r   r   r   r   r   r/   update_session_configrn   r(   rP   rm   r
   )r    r/   r   
new_configrr   s        r!   r3   zOpikConfigurator._update_config~  s   	H ~~ $$T]]K@\\))$--A  ![[33 LL!$"nn 4 

 '') KK--iFKK--ncBKK--k4>>J 	HLL4SVH=>$%FGG	Hs   DD 	E(,EEc                 b    | j                   j                  }t        j                  d| d       y)z`
        Log an informative message about project configuration after successful setup.
        z@Configuration completed successfully. Traces will be logged to 'z' project. To change the destination project, see: https://www.comet.com/docs/opik/tracing/log_traces#configuring-the-project-nameN)r   project_namer(   r)   )r    rz   s     r!   r6   z3OpikConfigurator._log_project_configuration_message  s5     **77N|n ]F F	
r#   c                    d}|dkD  rwt        d      }|dk(  rt        d      t        j                  |      }t	        j
                  |      r|| _        yt        j                  d| dt                |d	z  }|dkD  rwt        d
      )a  
        Prompt the user for an Opik instance URL and check if it is accessible.
        The function retries up to 3 times if the URL is not accessible.

        Raises:
            ConfigurationError: Raised if the URL provided by the user is not accessible after 3 attempts.
        rJ   r   z$Please enter your Opik instance URL: zURL cannot be empty. Please enter a valid URL. For more details, refer to the documentation: https://www.comet.com/docs/opik/tracing/sdk_configuration.NzOpik is not accessible at z>. Please try again, the URL should follow a format similar to rK   zRCannot use the URL provided by the user. Opik instance is not active or not found.)
rt   r
   r   r   r	   r;   r   r(   rP   r   )r    rQ   user_input_opik_urls      r!   r=   zOpikConfigurator._ask_for_url  s     k"'(N"O"b(( n  #.":":;N"O 334GH 301D0E FSSfRgi 1% k& !`
 	
r#   c                    | j                   J t        | j                         }|y |t        j                  | j                        k7  r3| j                  t
        k7  r t        j                  d| j                         || _        y )NzyThe url provided in the configure (%s) method doesn't match the domain linked to the API key provided and will be ignored)r   rC   r   r   r   r   r(   warning)r    rH   s     r!   rE   z*OpikConfigurator._try_set_url_from_api_key  sr    ||''';DLLI% +":":4=="II!44NN L
 +r#   )NNNFFFF)r$   N)T)__name__
__module____qualname__r   rm   boolr"   r,   r*   r+   r1   rF   r2   rZ   r[   r3   r6   r=   rE    r#   r!   r   r      s     "&#'!"'$):#: C=: c]	:
 : :  : ":<224:2x#*d #*J8:t- -^"J "JH"
HH4 H4 H@	

@+r#   r   r   r   r$   c                 Z    | | t         j                  d<   ||t         j                  d<   yy)a  
    Environment variables are set for use by some integrations (liteLLM, etc.) when both the API key and workspace name
    are provided by the user. According to the current implementation logic, these values will not be
    saved to the OPIK configuration file. As a result, some third-party integrations will not be able to use them.
    This is a workaround for this issue: https://github.com/comet-ml/opik/issues/2118
    NOPIK_API_KEYOPIK_WORKSPACE)osenvironr0   s     r!   r4   r4     s2     %,

>"'0

#$ r#   c                 b    t        j                  |       }||j                  |j                  S y r   )r   parse_api_keyr   )r   opik_api_key_s     r!   rC   rC     s2     ..w7M ]%;%;%G%%%r#   r   r   r   r   c                 F    t        | |||||      }|j                          y)a  
    Create a local configuration file for the Python SDK. If a configuration file already exists,
    it will not be overwritten unless the `force` parameter is set to True.

    Args:
        api_key: The API key if using an Opik Cloud.
        workspace: The workspace name if using an Opik Cloud.
        url: The URL of the Opik instance if you are using a local deployment.
        use_local: Whether to use a local deployment.
        force: If true, the configuration file will be recreated and existing settings
               will be overwritten with passed parameters.
        automatic_approvals: if True, `yes` will automatically be answered whenever a user approval is required

    Raises:
        ConfigurationError
    )r   r   r   r   r   r   N)r   r,   )r   r   r   r   r   r   ro   s          r!   r,   r,     s.    0 /F r#   )NNNFFF)%rO   loggingr   typingr   r   rb   opik.configr   urllib.parserL   opik.api_objects.opik_clientr   r   %opik.configurator.interactive_helpersr   r   opik.configuratorr	   opik.exceptionsr
   opik.url_helpersr   opik.api_keyr   	getLoggerr   r(   r   rm   __annotations__r   r   r4   rC   r   r,   r   r#   r!   <module>r      s     	 "    : X / . & % 
		8	$": U3Z :": U3Z :+ +D1c]1'/}1	1C HSM  "# % c] }  
#  	 
     
 r#   