
    jT"                     F   d dl Z d dlmZmZmZmZmZmZ d dlm	Z	 d dl
mZmZmZmZ d dlmZ d dlmZmZmZmZ d dlmZ dd	lmZmZ dd
lmZ deej8                     fdZdeej<                     fdZdefdZ 	 	 	 	 	 	 	 	 	 	 	 	 	 d#dee!   deee!ef      deee!ef      deee!ef      deee!      deeee!ef   e	jD                  f      deee      dee!   deee!ef      dee#   deee      dee   deeejH                        ddfdZ%	 	 	 	 	 	 	 	 	 d$dee!   deee!ef      deee!ef      deee!ef      deee!      deee      dee!   deee      deeejH                        ddfdZ&e jN                  dej<                  d ejP                  ded   fd!       Z)g d"Z*y)%    N)AnyDictListOptionalIteratorUnion)	llm_usage)spantraceopik_clientprompt)
Attachment)DistributedTraceHeadersDictFeedbackScoreDictLLMProviderErrorInfoDict)tracing_runtime_config   )context_storage
exceptions)error_info_collectorreturnc                  n    t        j                         } | yt        j                  di | j                  S )z]
    Returns the current span created by track() decorator or None if no span was found.
    N )r   top_span_datar
   SpanData__dict__)	span_datas    j/Users/manta/Documents/Projects/TheRoad-I1/backend/.venv/lib/python3.12/site-packages/opik/opik_context.pyget_current_span_datar       s3      --/I==.9--..    c                  n    t        j                         } | yt        j                  di | j                  S )z_
    Returns the current trace created by track() decorator or None if no trace was found.
    Nr   )r   get_trace_datar   	TraceDatar   )
trace_datas    r   get_current_trace_datar&      s3     !//1J??1Z0011r!   c                      t        j                         } | t        j                  d      t	        | j
                  | j                        S )z
    Returns headers' dictionary to be passed into tracked function on remote node.
    Requires an existing span in the context, otherwise raises an error.
     There is no span in the context.)opik_trace_idopik_parent_span_id)r   r   r   OpikExceptionr   trace_idid)current_span_datas    r   get_distributed_trace_headersr/   *   sJ    
 (557 &&'IJJ&'00-00 r!   nameinputoutputmetadatatagsusagefeedback_scoresmodelprovider
total_costattachments
error_infopromptsc                    t        j                         sy||D cg c]  }|j                          }}| |||||||||	|
||d}t        j                         }|t        j                  d       |j                  di | yc c}w )a  
    Update the current span with the provided parameters. This method is usually called within a tracked function.

    Args:
        name: The name of the span.
        input: The input data of the span.
        output: The output data of the span.
        metadata: The metadata of the span.
        tags: The tags of the span.
        usage: Usage data for the span. In order for input, output, and total tokens to be visible in the UI,
            the usage must contain OpenAI-formatted keys (they can be passed additionally to the original usage on the top level of the dict): prompt_tokens, completion_tokens, and total_tokens.
            If OpenAI-formatted keys were not found, Opik will try to calculate them automatically if the usage
            format is recognized (you can see which provider's formats are recognized in opik.LLMProvider enum), but it is not guaranteed.
        feedback_scores: The feedback scores of the span.
        model: The name of LLM (in this case type parameter should be == llm)
        provider: The provider of LLM. You can find providers officially supported by Opik for cost tracking
            in `opik.LLMProvider` enum. If your provider is not here, please open an issue in our GitHub - https://github.com/comet-ml/opik.
            If your provider is not in the list, you can still specify it, but the cost tracking will not be available
        total_cost: The cost of the span in USD. This value takes priority over the cost calculated by Opik from the usage.
        attachments: The list of attachments to be uploaded to the span.
        error_info: The error information of the span.
        prompts: The list of prompts used in the span.
    N)r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r(   r   )r   is_tracing_active__internal_api__to_info_dict__r   r   r   r+   update)r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   p
new_paramsr.   s                   r   update_current_spanrC   :   s    L "335?FGw!1335wG * " J (557 &&'IJJ*z*+ Hs   B	thread_idc	           
         t        j                         sy||D 	cg c]  }	|	j                          }}	| ||||||||d	}
t        j                         }|t        j                  d       |j                  di |
 yc c}	w )a  
    Update the current trace with the provided parameters. This method is usually called within a tracked function.

    Args:
        name: The name of the trace.
        input: The input data of the trace.
        output: The output data of the trace.
        metadata: The metadata of the trace.
        tags: The tags of the trace.
        feedback_scores: The feedback scores of the trace.
        thread_id: Used to group multiple traces into a thread.
            The identifier is user-defined and has to be unique per project.
        attachments: The list of attachments to be uploaded to the trace.
        prompts: The list of prompts used in the trace.
    N)	r0   r1   r2   r3   r4   r6   rD   r:   r<   z!There is no trace in the context.r   )r   r>   r?   r   r#   r   r+   r@   )r0   r1   r2   r3   r4   r6   rD   r:   r<   rA   rB   current_trace_datas               r   update_current_tracerG   |   s    4 "335?FGw!1335wG *"
J )779!&&'JKK+
+# Hs   A?r%   clientc              #   6  K   |j                   j                  r |j                  di | j                   d}	 t	        j
                  |        d 	 t	        j                         } | J ||| _
        | j                           |j                  di | j                   y# t        $ r}t        j                  |      } d}~ww xY w# t	        j                         } | J ||| _
        | j                           |j                  di | j                   w xY ww)a  
    Provides a context manager to handle trace data within an execution context.

    This function sets up trace data for the current context, ensuring it is
    properly cleaned up and processed during the lifecycle of the context. It also
    handles exceptions by collecting error information and associating it with
    the trace data before raising the exception further. At the end of the context,
    it finalizes the trace and logs it using the provided client.

    Args:
        trace_data: An instance of trace.TraceData containing information
            about the current trace context, such as start time, end time, and
            any relevant metadata for tracking execution.
        client: An object of type opik_client.Opik used to report the trace
            data, typically communicating with an external tracing or monitoring
            system.

    Yields:
        None: The context manager yields control back to the caller, allowing
            code execution within the defined trace context.

    Raises:
        Exception: The function raises any exceptions encountered within the
            context after collecting error information and associating it with the
            trace data.
    Nr   )configlog_start_trace_spanr   as_start_parametersr   set_trace_data	Exceptionr   collectpop_trace_datar;   init_end_timeas_parameters)r%   rH   r;   	exceptions       r   trace_contextrT      s    > }}))6z556*.J1&&z2
 %335
%%%!$.J!  "0z//0  )11)<
 %335
%%%!$.J!  "0z//0s6   5DB  AD 	C)B??CC ADD)r    r&   rC   rG   r/   rT   )NNNNNNNNNNNNN)	NNNNNNNNN)+
contextlibtypingr   r   r   r   r   r   opikr	   opik.api_objectsr
   r   r   r   opik.api_objects.attachmentr   
opik.typesr   r   r   r   r    r   r   	decoratorr   r   r    r$   r&   r/   str	OpikUsagefloat
BasePromptrC   rG   contextmanagerOpikrT   __all__r   r!   r   <module>rd      s    = =  = = 2  ( ) +/x6 /2 9 2'B " &*'+)- $BF9=26"&.2*.15?+
3-?+DcN#?+ T#s(^$?+ tCH~&	?+
 49
?+ E$sCx.)*=*==>??+ d#456?+ C=?+ uS+-./?+ ?+ $z*+?+ '?+ d6,,-.?+ 
?+F &*'+)- $9=#.215/,
3-/,DcN#/, T#s(^$/, tCH~&	/,
 49
/, d#456/, }/, $z*+/, d6,,-./, 
/,d 212121 d^21 21jr!   