
    f3fi$                    |    d Z ddlmZ ddlZddlZddlZddlZ G d dej                        Z G d de      Z	ddgZ
y)z;Interface for a rate limiter and an in-memory rate limiter.    )annotationsNc                  h    e Zd ZdZej
                  dddd       Zej
                  dddd       Zy)BaseRateLimiteray  Base class for rate limiters.

    Usage of the base limiter is through the acquire and aacquire methods depending
    on whether running in a sync or async context.

    Implementations are free to add a timeout parameter to their initialize method
    to allow users to specify a timeout for acquiring the necessary tokens when
    using a blocking call.

    Current limitations:

    - Rate limiting information is not surfaced in tracing or callbacks. This means
        that the total time it takes to invoke a chat model will encompass both
        the time spent waiting for tokens and the time spent making the request.
    Tblockingc                    yao  Attempt to acquire the necessary tokens for the rate limiter.

        This method blocks until the required tokens are available if `blocking`
        is set to `True`.

        If `blocking` is set to `False`, the method will immediately return the result
        of the attempt to acquire the tokens.

        Args:
            blocking: If `True`, the method will block until the tokens are available.
                If `False`, the method will return immediately with the result of
                the attempt.

        Returns:
            `True` if the tokens were successfully acquired, `False` otherwise.
        N selfr   s     Z/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_core/rate_limiters.pyacquirezBaseRateLimiter.acquire   s        c                  K   ywr	   r
   r   s     r   aacquirezBaseRateLimiter.aacquire/   s     s   Nr   boolreturnr   )__name__
__module____qualname____doc__abcabstractmethodr   r   r
   r   r   r   r      sA      	*.  $ 	15  r   r   c                  T    e Zd ZdZdddd	 	 	 	 	 	 	 ddZddZdddd	Zdddd
Zy)InMemoryRateLimitera  An in memory rate limiter based on a token bucket algorithm.

    This is an in memory rate limiter, so it cannot rate limit across
    different processes.

    The rate limiter only allows time-based rate limiting and does not
    take into account any information about the input or the output, so it
    cannot be used to rate limit based on the size of the request.

    It is thread safe and can be used in either a sync or async context.

    The in memory rate limiter is based on a token bucket. The bucket is filled
    with tokens at a given rate. Each request consumes a token. If there are
    not enough tokens in the bucket, the request is blocked until there are
    enough tokens.

    These tokens have nothing to do with LLM tokens. They are just
    a way to keep track of how many requests can be made at a given time.

    Current limitations:

    - The rate limiter is not designed to work across different processes. It is
        an in-memory rate limiter, but it is thread safe.
    - The rate limiter only supports time-based rate limiting. It does not take
        into account the size of the request or any other factors.

    Example:
        ```python
        import time

        from langchain_core.rate_limiters import InMemoryRateLimiter

        rate_limiter = InMemoryRateLimiter(
            requests_per_second=0.1,  # <-- Can only make a request once every 10 seconds!!
            check_every_n_seconds=0.1,  # Wake up every 100 ms to check whether allowed to make a request,
            max_bucket_size=10,  # Controls the maximum burst size.
        )

        from langchain_anthropic import ChatAnthropic

        model = ChatAnthropic(
            model_name="claude-sonnet-4-5-20250929", rate_limiter=rate_limiter
        )

        for _ in range(5):
            tic = time.time()
            model.invoke("hello")
            toc = time.time()
            print(toc - tic)
        ```
       g?)requests_per_secondcheck_every_n_secondsmax_bucket_sizec               |    || _         d| _        || _        t        j                         | _        d| _        || _        y)a  A rate limiter based on a token bucket.

        These tokens have nothing to do with LLM tokens. They are just
        a way to keep track of how many requests can be made at a given time.

        This rate limiter is designed to work in a threaded environment.

        It works by filling up a bucket with tokens at a given rate. Each
        request consumes a given number of tokens. If there are not enough
        tokens in the bucket, the request is blocked until there are enough
        tokens.

        Args:
            requests_per_second: The number of tokens to add per second to the bucket.
                The tokens represent "credit" that can be used to make requests.
            check_every_n_seconds: Check whether the tokens are available
                every this many seconds. Can be a float to represent
                fractions of a second.
            max_bucket_size: The maximum number of tokens that can be in the bucket.
                Must be at least `1`. Used to prevent bursts of requests.
        g        N)r   available_tokensr    	threadingLock_consume_locklastr   )r   r   r   r    s       r   __init__zInMemoryRateLimiter.__init__x   s<    : $7  #. '^^-"&	%:"r   c                   | j                   5  t        j                         }| j                  || _        || j                  z
  }|| j                  z  dk\  r)| xj
                  || j                  z  z  c_        || _        t        | j
                  | j                        | _        | j
                  dk\  r| xj
                  dz  c_        	 ddd       y	 ddd       y# 1 sw Y   yxY w)a  Try to consume a token.

        Returns:
            True means that the tokens were consumed, and the caller can proceed to
            make the request. A False means that the tokens were not consumed, and
            the caller should try again later.
        Nr   TF)r%   time	monotonicr&   r   r"   minr    )r   nowelapseds      r   _consumezInMemoryRateLimiter._consume   s      	.."C yy 	DIIoG111Q6%%43K3K)KK%	 %((=(=t?S?S$TD! $$)%%*%)	 	, -	 	 	s   B<CCC%Tr   c                   |s| j                         S | j                         s0t        j                  | j                         | j                         s0y)ac  Attempt to acquire a token from the rate limiter.

        This method blocks until the required tokens are available if `blocking`
        is set to `True`.

        If `blocking` is set to `False`, the method will immediately return the result
        of the attempt to acquire the tokens.

        Args:
            blocking: If `True`, the method will block until the tokens are available.
                If `False`, the method will return immediately with the result of
                the attempt.

        Returns:
            `True` if the tokens were successfully acquired, `False` otherwise.
        T)r.   r)   sleepr   r   s     r   r   zInMemoryRateLimiter.acquire   s<    " ==?"--/JJt112 --/r   c                  K   |s| j                         S | j                         s8t        j                  | j                         d{    | j                         s8y7 w)ar  Attempt to acquire a token from the rate limiter. Async version.

        This method blocks until the required tokens are available if `blocking`
        is set to `True`.

        If `blocking` is set to `False`, the method will immediately return the result
        of the attempt to acquire the tokens.

        Args:
            blocking: If `True`, the method will block until the tokens are available.
                If `False`, the method will return immediately with the result of
                the attempt.

        Returns:
            `True` if the tokens were successfully acquired, `False` otherwise.
        NT)r.   asyncior0   r   r   s     r   r   zInMemoryRateLimiter.aacquire   sO     " ==?"--/ -- : :;;; --/  <s   AA AA A N)r   floatr   r3   r    r3   r   None)r   r   r   )r   r   r   r   r'   r.   r   r   r
   r   r   r   r   C   s[    2n &''*!"&; #&;  %	&;
 &; 
&;P@ +/ 0 26 r   r   )r   
__future__r   r   r2   r#   r)   ABCr   r   __all__r
   r   r   <module>r8      sF    A " 
   5cgg 5pq/ qj r   