
    j(              	          d dl Z d dlZd dlmZmZ d dlmZmZmZm	Z	m
Z
 d dlZd dlmZ  ej                  e      Z G d de j"                        Zededeeeef      d	ed
efd       Zededeeeef      d	ed
efd       Zde	e   d
efdZy)    N)contextmanagerasynccontextmanager)AnyListDictOptionalType)
exceptionsc            
          e Zd ZdZdefdZej                  	 ddedee	e
j                        dedefd	       Zej                  d
eeeef      dedefd       Z	 ddedee	e
j                        dedefdZd
eeeef      dedefdZy)OpikBaseModelz
    This class serves as an interface to LLMs.

    If you want to implement a custom LLM provider in evaluation metrics,
    you should inherit from this class.
    
model_namec                     || _         y)z
        Initializes the base model with a given model name.

        Args:
            model_name: The name of the LLM to be used.
        N)r   )selfr   s     z/Users/manta/Documents/Projects/TheRoad-I1/backend/.venv/lib/python3.12/site-packages/opik/evaluation/models/base_model.py__init__zOpikBaseModel.__init__   s     %    Ninputresponse_formatkwargsreturnc                      y)aV  
        Simplified interface to generate a string output from the model.

        Args:
            input: The input string based on which the model will generate the output.
            kwargs: Additional arguments that may be used by the model for string generation.

        Returns:
            str: The generated string output.
        N r   r   r   r   s       r   generate_stringzOpikBaseModel.generate_string       " 	r   messagesc                      y)ak  
        Do not use this method directly. It is intended to be used within `get_provider_response()` method.

        Generate a provider-specific response. Can be used to interface with
        the underlying model provider (e.g., OpenAI, Anthropic) and get raw output.

        Args:
            messages: A list of messages to be sent to the model, should be a list of dictionaries with the keys
            kwargs: arguments required by the provider to generate a response.

        Returns:
            Any: The response from the model provider, which can be of any type depending on the use case and LLM.
        Nr   r   r   r   s      r   generate_provider_responsez(OpikBaseModel.generate_provider_response1   r   r   c                     K   t        d      w)ae  
        Simplified interface to generate a string output from the model. Async version.

        Args:
            input: The input string based on which the model will generate the output.
            kwargs: Additional arguments that may be used by the model for string generation.

        Returns:
            str: The generated string output.
        2Async generation not implemented for this providerNotImplementedErrorr   s       r   agenerate_stringzOpikBaseModel.agenerate_stringD   s       ""VWW   c                     K   t        d      w)a  
        Do not use this method directly. It is intended to be used within `aget_provider_response()` method.

        Generate a provider-specific response. Can be used to interface with
        the underlying model provider (e.g., OpenAI, Anthropic) and get raw output.
        Async version.

        Args:
            messages: A list of messages to be sent to the model, should be a list of dictionaries with the keys
                "content" and "role".
            kwargs: arguments required by the provider to generate a response.

        Returns:
            Any: The response from the model provider, which can be of any type depending on the use case and LLM.
        r!   r"   r   s      r   agenerate_provider_responsez)OpikBaseModel.agenerate_provider_responseV   s     $ ""VWWr%   )N)__name__
__module____qualname____doc__strr   abcabstractmethodr   r	   pydantic	BaseModelr   r   r   r   r   r$   r'   r   r   r   r   r      s   %3 % 	 ?C "$x'9'9":; 	
 
 $ 	T#s(^,8;	 * ?CXX "$x'9'9":;X 	X
 
X$XT#s(^,X8;X	Xr   r   model_providerr   r   r   c              +      K   	  | j                   |fi | y# t        $ r9}t        j                  d|       t	        j
                  t        |            d}~ww xY ww)a  
    Provides a context manager for getting and managing the response from a
    model provider. Ensures that errors during the interaction with the model
    provider are handled appropriately and logged.

    Args:
        model_provider: Instance of a class derived from `OpikBaseModel`
            responsible for interfacing with the model.
        messages: List of dictionaries containing the messages or inputs to be
            passed to the model.
        **kwargs: Additional keyword arguments to customize the generation of
            the model responses.

    Yields:
        Any: The response generated by the model provider.

    Raises:
        exceptions.BaseLLMError: If the response generation from the model provider
            fails due to an exception.
    z'Failed to call LLM provider, reason: %sN)r   	ExceptionLOGGERerrorr
   BaseLLMErrorr,   )r1   r   r   es       r   get_provider_responser8   k   sV     0.7n77KFKK .>B%%c!f--.s$   A A	A4AAAc                   K   	  | j                   dd|i| d{   }| y7 
# t        $ r9}t        j                  d|       t	        j
                  t        |            d}~ww xY ww)a  
    Asynchronous context manager for getting a response from a model provider.

    This function asynchronously interacts with the specified `model_provider` to
    generate a response based on the given list of `messages` and additional
    optional keyword arguments. If an error occurs during this process, it is
    logged, and a custom exception is raised.

    Args:
        model_provider: The model provider from which to request
            the response.
        messages: A list of dictionaries containing the
            messages for the model provider to process.
        **kwargs: Additional keyword arguments passed to the model provider's
            response generation method.

    Yields:
        Any: The response generated asynchronously by the model provider.

    Raises:
        exceptions.BaseLLMError: If there is an error during the asynchronous
            interaction with the model provider.
    r   Nz6Failed to call LLM provider asynchronously, reason: %sr   )r'   r3   r4   r5   r
   r6   r,   )r1   r   r   responser7   s        r   aget_provider_responser;      ss     6.CCC 

!'
 
 
  .MqQ%%c!f--.s0   A-( &	( A-( 	A*4A%%A**A-outputc                 4    | t        j                  d      | S )a  
    Checks the output of a model and verifies that it is not None.

    This function ensures that the output returned from a language model (LLM) has a valid, non-null value.
    If the output is found to be None, an error is raised with a detailed message. This can help in
    debugging issues related to incorrect environment configuration or missing API keys.

    Args:
        output: The output string generated by the language model to be validated.

    Returns:
        The output of the language model that was validated.

    Raises:
        exceptions.BaseLLMError: Raised if the output is evaluated to None. The error message contains suggestions to
        verify environment configurations and check model API key availability.
    zReceived None as the output from the LLM. Please verify your environment configuration and ensure that the API keys for the models in use (e.g., OPENAI_API_KEY) are set correctly.)r
   r6   )r<   s    r   check_model_output_stringr>      s)    $ ~%%k
 	

 Mr   )r-   logging
contextlibr   r   typingr   r   r   r   r	   r/   opikr
   	getLoggerr(   r4   ABCr   r,   r8   r;   r>   r   r   r   <module>rE      s    
  : 2 2   
		8	$[XCGG [X| .!.-1$sCx.-A.MP.. .< !.!!.-1$sCx.-A!.MP!.!. !.Hhsm  r   