U
    Î~fh.  ã                   @  sÆ   d dl mZ d dlZd dlZd dlZd dlZd dlmZmZm	Z	m
Z
 d dlmZ d dlZd dlZd dlZedƒZedƒZejdkrŠejZndd	d
ddœdd„Zdd	d
ddœdd„Zdddœdd„ZdS )é    )ÚannotationsN)ÚAnyÚTypeVarÚCallableÚ	Awaitable)Ú	ParamSpecÚT_RetvalÚT_ParamSpec)é   é	   zCallable[T_ParamSpec, T_Retval]úT_ParamSpec.argsúT_ParamSpec.kwargsr   )ÚfuncÚargsÚkwargsÚreturnc                Ï  s:   t j ¡ }t ¡ }tj|j| f|ž|Ž}| d|¡I dH S )aŸ  Asynchronously run function *func* in a separate thread.

        Any *args and **kwargs supplied for this function are directly passed
        to *func*. Also, the current :class:`contextvars.Context` is propagated,
        allowing context variables from the main thread to be accessed in the
        separate thread.

        Returns a coroutine that can be awaited to get the eventual result of *func*.
        N)	ÚasyncioÚeventsZget_running_loopÚcontextvarsZcopy_contextÚ	functoolsÚpartialÚrunZrun_in_executor)r   r   r   ZloopÚctxZ	func_call© r   ú7/tmp/pip-unpacked-wheel-rjiviquo/openai/_utils/_sync.pyÚ_asyncio_to_thread   s    
r   c                Ï  sB   t  ¡ dkr"t| f|ž|ŽI d H S tj tj| f|ž|Ž¡I d H S )Nr   )ÚsniffioZcurrent_async_libraryr   ÚanyioÚ	to_threadZrun_syncr   r   )r   r   r   r   r   r   r   )   s
    ÿr   z*Callable[T_ParamSpec, Awaitable[T_Retval]])Úfunctionr   c                   s   ddddœ‡ fdd„}|S )aP  
    Take a blocking function and create an async one that receives the same
    positional and keyword arguments. For python version 3.9 and above, it uses
    asyncio.to_thread to run the function in a separate thread. For python version
    3.8, it uses locally defined copy of the asyncio.to_thread function which was
    introduced in python 3.9.

    Usage:

    ```python
    def blocking_func(arg1, arg2, kwarg1=None):
        # blocking code
        return result


    result = asyncify(blocking_function)(arg1, arg2, kwarg1=value1)
    ```

    ## Arguments

    `function`: a blocking regular callable (e.g. a function)

    ## Return

    An async function that takes the same positional and keyword arguments as the
    original one, that when called runs the same original function in a thread worker
    and returns the result.
    r   r   r   )r   r   r   c                  Ÿ  s   t ˆ f| ž|ŽI d H S )N)r   )r   r   ©r   r   r   ÚwrapperS   s    zasyncify.<locals>.wrapperr   )r   r!   r   r    r   Úasyncify5   s    r"   )Ú
__future__r   Úsysr   r   r   Útypingr   r   r   r   Ztyping_extensionsr   r   r   Zanyio.to_threadr   r	   Úversion_infor   r   r"   r   r   r   r   Ú<module>   s    
