
    >'hO                    2   d dl mZ 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Zd dlmZ d dlmZmZ d dlmZmZmZmZ d dlmZ d dlmZ d dlmZ d d	lmZmZm Z m!Z! d d
l"m#Z#m$Z$m%Z% erd dl&m'Z' d dl(m)Z)  ejT                  d      Z+ ejX                   e       dz        Z-ej\                   G d d             Z/	 d	 	 	 	 	 	 	 ddZ0	 d	 	 	 	 	 	 	 ddZ1	 	 	 	 	 	 	 	 	 	 ddZ2	 	 	 	 	 	 	 	 d dZ3d!dZ4	 	 	 	 d"dZ5d#dZ6	 d$	 	 	 	 	 d%dZ7	 	 	 	 	 	 d&dZ8y)'    )annotationsN)	cpu_count)EmptyQueue)TYPE_CHECKINGOptionalUnioncast)schemas)utils)CompressedTraces)_AUTO_SCALE_DOWN_NEMPTY_TRIGGER_AUTO_SCALE_UP_NTHREADS_LIMIT_AUTO_SCALE_UP_QSIZE_TRIGGER	_BOUNDARY)SerializedFeedbackOperationSerializedRunOperation#combine_serialized_queue_operations)Context)Clientzlangsmith.client   )max_workersc                  ^    e Zd ZU dZded<   ded<   ded<   dZ	 d	 	 	 	 	 	 	 dd
ZddZddZy	)TracingQueueItemzAn item in the tracing queue.

    Attributes:
        priority (str): The priority of the item.
        action (str): The action associated with the item.
        item (Any): The item itself.
    strpriority:Union[SerializedRunOperation, SerializedFeedbackOperation]itemOptional[Context]otel_contextr   r   r    Nc                .    || _         || _        || _        y Nr!   )selfr   r   r    s       m/home/kushmeetdev/Regenta/Chatbot/venv/lib/python3.12/site-packages/langsmith/_internal/_background_thread.py__init__zTracingQueueItem.__init__=   s     !	(    c                    | j                   | j                  j                  f|j                   |j                  j                  fk  S r#   )r   r   	__class__r$   others     r%   __lt__zTracingQueueItem.__lt__G   s;    tyy223NNJJ  7
 
 	
r'   c                    t        |t              xrE | j                  | j                  j                  f|j                  |j                  j                  fk(  S r#   )
isinstancer   r   r   r)   r*   s     r%   __eq__zTracingQueueItem.__eq__M   sM    %!12 4MMII8
 nnejj22384 	4r'   r#   )r   r   r   r   r    r   returnNone)r+   r   r0   bool)r+   objectr0   r2   )	__name__
__module____qualname____doc____annotations__	__slots__r&   r,   r/    r'   r%   r   r   -   sZ     M
DD##4I +/	)) I) (	)
 
)
4r'   r   c                   g }	 | j                  |d      x}r|j                  |       | j                  |d      x}r:|j                  |       |rt        |      |k\  r	 |S | j                  |d      x}r:|S # t        $ r Y |S w xY w)Ng      ?)blocktimeout皙?)getappendlenr   )tracing_queuelimitr<   
next_batchr   s        r%   _tracing_thread_drain_queuerE   T   s     *,J !$$5$$??4?d##''eT'BBdBd#ZE1  $''eT'BBdB   s   AA; #A; ;	BBc                   	 | j                   y| j                   j                  5  | j                   j                  j                          | j                   j                  j                         }| j                   j                  }||dk  rt        d|       ||dk  rt        d|       |||k  r%|| j                   j                  |k  r
	 d d d        y| j                   j                  j                  dt         dj                                | j                   j                  j                          | j                   j                  }| j                   j                  |_        ||f}| j                   j                          d d d        j!                  d       |fS # 1 sw Y   xY w# t"        $ r t$        j'                  dd	       Y yw xY w)
N)NNr   z!size_limit must be positive; got z*size_limit_bytes must be nonnegative; got z--z--
uLangSmith tracing error: Failed to submit trace data.
This does not affect your application's runtime.
Error details:Texc_info)compressed_traceslockcompressor_writerflushbuffertelluncompressed_size
ValueErrortrace_countwriter   encodeclose_contextcontextresetseek	Exceptionloggererror)client
size_limitsize_limit_bytescurrent_sizepre_compressed_sizefilled_buffercompressed_traces_infos          r%   '_tracing_thread_drain_compressed_bufferrd   i   s   -##+%%** 	-$$66<<>!33::??AL"(":":"L"L%*/ #DZL!QRR+0@10D @AQ@RS  !(L;K,K"f&>&>&J&JZ&W!!	- 	-& $$66<<YKv&--/ $$66<<>"44;;M$*$<$<$E$EM!&9<%H"$$**,;	-> 	1566A	- 	-B  	 	 	 	
 	s;   F1 F1 B,F%F1 B.F%F1 %F.*F1 1 GGc                   	 t        |D cg c]  }|j                   c}      }|r| j                  |       nmt        d |D              r5t        j                  d       |D cg c]  }t        |t              r| }}| j                  t        t        t           |             |D ]  }|j                           y c c}w c c}w # t        $ r t        j                  dd       Y Dw xY w# |D ]  }|j                           w xY w)Nc              3  <   K   | ]  }t        |t                y wr#   )r.   r   ).0ops     r%   	<genexpr>z/_tracing_thread_handle_batch.<locals>.<genexpr>   s     M2:b"=>Ms   z;Feedback operations are not supported in non-multipart moderG   TrH   )r   r   _multipart_ingest_opsanyr[   warnr.   r   _batch_ingest_run_opsr
   listr   rZ   r\   	task_done)r]   rB   batchuse_multipartr   opsrh   _s           r%   _tracing_thread_handle_batchrt      s   &12O4992OP((-MMMQ "%Jr;V,WB  ((d3I.JC)PQ  	&A##%	&1 3P
  	 	 	 	
 		  	&A##%	&sF   	C B>AC $C:C>(C >
C  C+(C. *C++C. .Dc                l   	 t        |D cg c]  }|j                   c}      }|D cg c]  }t        |t              s| }}|D ci c]=  }t        |j                  t              r!|j                  j                  |j
                  ? }}|r>| j                  | j                  j                  ||       nt        j                  d       |D ]  }|j                           yc c}w c c}w c c}w # t        $ r t        j                  dd       Y Iw xY w# |D ]  }|j                           w xY w)z@Handle a batch of tracing queue items by exporting them to OTEL.NzLangSmith tracing error: Failed to submit OTEL trace data.
This does not affect your application's runtime.
Error details: client.otel_exporter is NonezzLangSmith tracing error: Failed to submit OTEL trace data.
This does not affect your application's runtime.
Error details:TrH   )r   r   r.   r   idr    otel_exporterexport_batchr[   r\   rZ   ro   )	r]   rB   rp   r   rr   rh   run_opsotel_context_maprs   s	            r%   !_otel_tracing_thread_handle_batchr{      s.   &12O4992OP #N"z"6L'M2NN 
$))%;< IILL$+++
 

 ##/$$11';KLB"  	&A##%	&; 3PN
  
 	 	 	

  	&A##%	&sQ   	C4 C%C4 C*C*C4 	AC/AC4 %C4 4 DD DD D3c                     t        j                  d      } | 	 t        |       S y # t        $ r t        j                  d|  d       Y y w xY w)NBATCH_INGEST_SIZE_LIMITz+Invalid value for BATCH_INGEST_SIZE_LIMIT: z, continuing with default)ls_utilsget_env_varintrQ   r[   warning)size_limit_strs    r%   get_size_limit_from_envr      sg    ))!N !	~&&   	NN=n=M N* * 	s   
% "A
	A
c                    t        j                  dd dt        t        t              }| s|S 	 | j
                  s|S t               }||| j
                  d<   | j
                  S # t        $ r |cY S w xY w)NFd   )use_multipart_endpointr_   r^   scale_up_nthreads_limitscale_up_qsize_triggerscale_down_nempty_triggerr^   )
ls_schemasBatchIngestConfigr   r   r   batch_ingest_configr   BaseException)infodefault_configenv_size_limits      r%   _ensure_ingest_configr      s      11$ =;"AN ''!!02%5CD$$\2''' s   A" &A" "A0/A0c                >    |        y j                   }|J t        j                        }|d   }|d   }|d   }|j                  dd      }g dt	        j
                  t	        j                  d            xs j                  d u}|s|rÉj                  j                  xs i j                  dd      st        j                  d	       nt        j                         _        t               _        t!        j"                         _        t!        j&                  t(        t        j*                        f
      j-                          dz  dfd} |       rډD ]$  }	|	j/                         rj1                  |	       & t3              |k  rd|j5                         |kD  rQt!        j&                  t6        t        j*                        |f
      }
j9                  |
       |
j-                          t;        ||      x}r(j                  t=        ||       nt?        |||        |       rt;        ||d      x}r9j                  t=        ||       nt?        |||       t;        ||d      x}r9t        jA                  d       y )Nr^   r   r   r   Fr   DISABLE_RUN_COMPRESSIONzstd_compression_enabledz~Run compression is not enabled. Please update to the latest version of LangSmith. Falling back to regular multipart ingestion.)targetargs   c                 p   rt        d      r"j                  rt        j                  d       yt	        j
                         j                         st        j                  d       yt        t        d      r=t        j                        t              z   kD  } | st        j                  d       | S y)N_manual_cleanupz3Client is being cleaned up, stopping tracing threadFz,Main thread is dead, stopping tracing threadgetrefcountzeClient refs count indicates we're the only remaining reference to the client, stopping tracing threadT)
hasattrr   r[   debug	threadingmain_threadis_alivesysr   rA   )should_keep_threadr]   num_known_refssub_threadss    r%   keep_thread_activez7tracing_control_thread_func.<locals>.keep_thread_active6  s    F-.63I3ILLNO$$&//1LLGH3& "%!8>CM < " &= &% r'   rC   rC   r<   z'Tracing control thread is shutting downr0   r2   )!rB   r   r   r?   r~   	is_truishr   rw   instance_flagsr[   r   weakrefWeakSet_futuresr   rJ   r   Event_data_available_eventThread-tracing_control_thread_func_compress_parallelrefstartr   removerA   qsize_tracing_sub_thread_funcr@   rE   r{   rt   r   )
client_refrB   r   r^   r   r   rq   disable_compressionr   thread
new_threadrD   r]   r   r   s               @@@r%   tracing_control_thread_funcr     s   \F~((M$$$/<),7J#67P#Q"56N"O'++,DeLM*,KN 	8//0IJK 	,t+  =**0b55&
 NNU
 &oo/FO'7'9F$+4??+<F(Dkk&)+ egaN< 
! 	+F??$""6*	+ 66##%(>>"))/kk&)=9J z*4]*UU:U##/1&-T,M:}% 
. 4Zu *  +-fmZP(z= 4Zu *  LL:;r'   c                0    |        y j                   j                  j                  t        j	                  d       y t        j                        }|d   }|j                  dd      }ddfd}t        j                         }	 j                  j                  d	      } |       sn|r~j                  j                          t        ||      \  }}	|=	 t        j                  j                  ||	      }
j                  j!                  |
       t        j                         }nwt        j                         |z
  |k\  r]t        d
d
      \  }}	|6	 t%        j                  t        j                  j                  ||	      g       t        j                         }	 t        d
d
      \  }}	|6	 t%        j                  t        j                  j                  ||	      g       t        j)                  d       y # t"        $ r j                  ||	       Y w xY w# t"        $ r j                  ||	       Y w xY w# t"        $ r j                  ||	       Y vw xY w# t&        $ r t        j	                  dd       Y w xY w)NzLangSmith tracing error: Required compression attributes not initialized.
This may affect trace submission but does not impact your application's runtime.r^   r_     @   c                 X   rt        d      r"j                  rt        j                  d       yt	        j
                         j                         st        j                  d       yt        t        d      r1t        j                        kD  } | st        j                  d       | S y)Nr   z7Client is being cleaned up, stopping compression threadFz0Main thread is dead, stopping compression threadr   ziClient refs count indicates we're the only remaining reference to the client, stopping compression threadT)	r   r   r[   r   r   r   r   r   r   )r   r]   r   s    r%   r   zItracing_control_thread_func_compress_parallel.<locals>.keep_thread_active  s    F-.63I3ILLRS$$&//1LLKL3& "%!8>!I%A &% r'   Tr>   )r=   r   )r^   r_   zuLangSmith tracing error: Failed during final cleanup.
This does not affect your application's runtime.
Error details:rH   z1Compressed traces control thread is shutting downr   )rJ   r   r   r[   r\   r   r   r?   time	monotonicwaitclearrd   HTTP_REQUEST_THREAD_POOLsubmit_send_compressed_multipart_reqaddRuntimeErrorcfrZ   r   )r   flush_intervalr   r^   r_   r   last_flush_time	triggereddata_streamrc   futurefinal_data_streamr]   r   s               @@r%   r   r   w  s    \F~ 	  (''/??"1	

 	/<),7J*../A:N N4 nn&O
0055d5C	!# ((..0 8j"234/K/ &5<<==#.F
 OO''/ #nn.O  ?2~E;1q 43
 * 8 ? ?$*$I$I$/$:!" #'.."2g l
31q 	21
 (077"AA-2, LLDE $ 99#.2 ( =='22   55%*  
 	 	 	

sT   $<H #5H0 /I2 5I H-,H-0III/,I2 .I//I2 2 JJc                    |        }|y 	 |j                   sy 	 |j                  }|J t        |j                         }|j                  dd      }d}t        j                         j                         rr||d   k  rjt        ||      x}r+d}|j                  t        |||       nt        ||||       n|dz  }t        j                         j                         r	||d   k  rjt        ||d	      x}r9|j                  t        |||       nt        ||||       t        ||d	      x}r9t        j                  d
       y # t        $ r }t        j                  d|       Y d }~y d }~ww xY w)Nz#Error in tracing control thread: %sr^   r   r   r   r   r   Fr   z+Tracing control sub-thread is shutting down)r   r   r[   r   rB   r   r?   r   r   r   rE   rw   r{   rt   )	r   rq   r]   erB   r   r^   seen_successive_empty_queuesrD   s	            r%   r   r     s    \F~{{ 
 ((M$$$/<$((s;J#$ 
 	((*(:;< 5]*UU:U+,(##/1&-T,M:} )A-( 	((*(:;< 4Zu *  +-fmZP(z= 4Zu *  LL>?M  :A>s   E 	E/E**E/)r   T)rB   r   rC   r   r<   r2   r0   list[TracingQueueItem])r   r   )r]   r   r^   r   r_   z
int | Noner0   z6tuple[Optional[io.BytesIO], Optional[tuple[int, int]]])
r]   r   rB   r   rp   r   rq   r2   r0   r1   )r]   r   rB   r   rp   r   r0   r1   )r0   zOptional[int])r   zls_schemas.LangSmithInfor0   zls_schemas.BatchIngestConfig)r   weakref.ref[Client]r0   r1   )g      ?)r   r   r   floatr0   r1   )r   r   rq   r2   r0   r1   )9
__future__r   concurrent.futuresfuturesr   	functoolsiologgingr   r   r   r   multiprocessingr   queuer   r   typingr   r   r	   r
   	langsmithr   r   r   r~   &langsmith._internal._compressed_tracesr   langsmith._internal._constantsr   r   r   r   langsmith._internal._operationsr   r   r   opentelemetry.context.contextr   langsmith.clientr   	getLoggerr[   ThreadPoolExecutorr   total_orderingr   rE   rd   rt   r{   r   r   r   r   r   r:   r'   r%   <module>r      s   "   	  
    %   , ' C   5'			-	.0200Y[1_M  #4 #4 #4N ;?!$37, KU00 #0=G0;0f & & & " & 	 &
 
 &F%&%&%& "%& 
	%&P
"!0f<T >AJF#JF5:JF	JFZ0@#0@0@ 
0@r'   