
    tni{$                         d Z ddlZddlmZmZmZ ddlZddlmZm	Z	 ddl
mZmZmZmZ  G d d          Z G d d	          Z G d
 d          ZdS )z#
Runpod | Python | Endpoint Runner
    N)AnyDictOptional)HTTPAdapterRetry)API_KEY_NOT_SET_MSGFINAL_STATESUNAUTHORIZED_MSGis_completedc            	       ~    e Zd ZdZddee         fdZ	 	 ddededee         d	efd
Z	ddeded	efdZ
dded	efdZdS )RunPodClientz$A client for running endpoint calls.Napi_keyc                 :   ddl m}m} |p|| _        | j        t          t                    t          j                    | _        t          ddddg          }| j        	                    d	t          |
                     dd| j         d| _        || _        dS )z
        Initialize a RunPodClient instance.

        Args:
            api_key: Optional API key. If not provided, uses global api_key.

        Raises:
            RuntimeError: If the API key has not been initialized.
        r   )r   endpoint_url_baseN      i  i  )totalbackoff_factorstatus_forcelistzhttp://)max_retrieszapplication/jsonzBearer )zContent-TypeAuthorization)runpodr   r   RuntimeErrorr   requestsSession
rp_sessionr   mountr   headers)selfr   global_api_keyr   retriess        S/var/www/html/gpu-tools/venv/lib/python3.11/site-packages/runpod/endpoint/runner.py__init__zRunPodClient.__init__   s    	
 	
 	
 	
 	
 	
 	
 	
 0.<2333"*,,aS#JOOOi)I)I)IJJJ /5t|55
 

 "3    
   methodendpointdatatimeoutc                     | j          d| }| j                            ||| j        ||          }|j        dk    rt          t                    |                                 |                                S )a  
        Make a request to the specified endpoint using the given HTTP method.

        Args:
            method: The HTTP method to use ('GET' or 'POST').
            endpoint: The endpoint path to which the request will be made.
            data: The JSON payload to send with the request.
            timeout: The number of seconds to wait for the server to send data before giving up.

        Returns:
            The JSON response from the server.

        Raises:
            RuntimeError: If the response returns a 401 Unauthorized status.
            requests.HTTPError: If the response contains an unsuccessful status code.
        /)r   jsonr)   i  )	r   r   requestr   status_coder   r
   raise_for_statusr,   )r   r&   r'   r(   r)   urlresponses          r"   _requestzRunPodClient._request9   s    ( '44(44?**CD' + 
 
 3&&/000!!###}}r$   c                 2    |                      d|||          S )zPost to the endpoint.POSTr2   )r   r'   r(   r)   s       r"   postzRunPodClient.postX   s    }}VXtW===r$   c                 2    |                      d||          S )zGet from the endpoint.GETr)   r5   )r   r'   r)   s      r"   getzRunPodClient.get\   s    }}UHg}>>>r$   N)Nr%   )r%   )__name__
__module____qualname____doc__r   strr#   dictintr2   r6   r:    r$   r"   r   r      s        ..3 3 3 3 3 3B BF %(08   >> >S > >s > > > >? ?C ?# ? ? ? ? ? ?r$   r   c                   ~    e Zd ZdZdededefdZddedeeef         fd	Z	d
 Z
ddedefdZdefdZddedefdZdS )Jobz1Represents a job to be run on the Runpod service.endpoint_idjob_idclientc                 L    || _         || _        || _        d| _        d| _        dS )a  
        Initialize a Job instance with the given endpoint ID and job ID.

        Args:
            endpoint_id: The identifier for the endpoint.
            job_id: The identifier for the job.
            client: An instance of the RunPodClient to make requests with.
        N)rF   rG   	rp_client
job_status
job_output)r   rF   rG   rH   s       r"   r#   zJob.__init__g   s,     'r$   statussourcereturnc                     | j          d| d| j         }| j                            |          }t	          |d                   r(|d         | _        |                    dd          | _        |S )zBReturns the raw json of the status, raises an exception if invalidr+   )r'   rM   outputN)rF   rG   rJ   r:   r   rK   rL   )r   rN   
status_url	job_states       r"   
_fetch_jobzJob._fetch_jobw   sv    (AA6AADKAA
N&&
&;;		(+,, 	<'1DO'mmHd;;DOr$   c                 R    | j         | j         S |                                 d         S )z&Returns the status of the job request.NrM   )rK   rT   )r   s    r"   rM   z
Job.status   s'    ?&?"  **r$   r   r)   c                 Z   |dk    rpt          |                                           sOt          j        d           |dz  }|dk    rt	          d          t          |                                           O| j        | j        S |                                                     dd          S )z
        Returns the output of the job request.

        Args:
            timeout: The number of seconds to wait for the server to send data before giving up.
        r   r   zJob timed out.NrQ   )r   rM   timesleepTimeoutErrorrL   rT   r:   r   r)   s     r"   rQ   z
Job.output   s     Q;;"4;;==11 9
11a<<&'7888	 #4;;==11 9 ?&?"  $$Xt444r$   c              #     K   	 t          j        d           |                     d          }|d         t          vst	          |d                   dk    r$|                    dg           D ]}|d         V  n|d         t          v rdS )	z>Returns a generator that yields the output of the job request.Tr   stream)rN   rM   r   rQ   N)rW   rX   rT   r	   lenr:   )r   stream_partialchunks      r"   r\   z
Job.stream   s      
	JqMMM!__H_==Nx(<<~h/00144+//"== * *E/))))*)\99
	r$      c                 Z    | j                             | j         d| j         d|          S )z
        Cancels the job and returns the result of the cancellation request.

        Args:
            timeout: The number of seconds to wait for the server to respond before giving up.
        z/cancel/Nr(   r)   )rJ   r6   rF   rG   rZ   s     r"   cancelz
Job.cancel   s?     ~""6666 # 
 
 	
r$   N)rM   )r   r`   )r<   r=   r>   r?   r@   r   r#   r   r   rT   rM   rB   rQ   r\   rc   rC   r$   r"   rE   rE   d   s        ;;C  l     	 	 	DcN 	 	 	 	+ + +5 5c 5# 5 5 5 5&    
 
c 
# 
 
 
 
 
 
r$   rE   c            	           e Zd ZdZddedee         fdZdeeef         de	fdZ
	 ddeeef         d
edeeef         fdZdd
edeeef         fdZdd
edeeef         fdZdS )Endpointz6Manages an endpoint to run jobs on the Runpod service.NrF   r   c                 >    || _         t          |          | _        dS )a  
        Initialize an Endpoint instance with the given endpoint ID.

        Args:
            endpoint_id: The identifier for the endpoint.
            api_key: Optional API key for this endpoint instance.

        Example:
            >>> endpoint = runpod.Endpoint("ENDPOINT_ID")
            >>> run_request = endpoint.run({"your_model_input_key": "your_model_input_value"})
            >>> print(run_request.status())
            >>> print(run_request.output())
        )r   N)rF   r   rJ   )r   rF   r   s      r"   r#   zEndpoint.__init__   s"     '%g666r$   request_inputrO   c                     |                     d          sd|i}| j                            | j         d|          }t	          | j        |d         | j                  S )z
        Run the endpoint with the given input.

        Args:
            request_input: The input to pass into the endpoint.

        Returns:
            A Job instance for the run request.
        inputz/runid)r:   rJ   r6   rF   rE   )r   rh   job_requests      r"   runzEndpoint.run   sk       )) 	5$m4Mn))%%%
 
 4#[%6GGGr$   Q r)   c                 2   |                     d          sd|i}| j                            | j         d||          }|d         t          v r|                     dd          S t          | j        |d         | j                                      |          S )z
        Run the endpoint with the given input synchronously.

        Args:
            request_input: The input to pass into the endpoint.
            timeout: Maximum time to wait for the job to complete.
        rj   z/runsyncr9   rM   rQ   Nrk   )r:   rJ   r6   rF   r	   rE   rQ   )r   rh   r)   rl   s       r"   run_synczEndpoint.run_sync   s       )) 	5$m4Mn))))) * 
 
 x L00??8T222k$/
 

&&
!
!	"r$   r`   c                 J    | j                             | j         d|          S )z
        Check the health of the endpoint (number/state of workers, number/state of requests).

        Args:
            timeout: The number of seconds to wait for the server to respond before giving up.
        z/healthr9   )rJ   r:   rF   rZ   s     r"   healthzEndpoint.health   s5     ~!!((( " 
 
 	
r$   c                 L    | j                             | j         dd|          S )z
        Purges the endpoint's job queue and returns the result of the purge request.

        Args:
            timeout: The number of seconds to wait for the server to respond before giving up.
        z/purge-queueNrb   )rJ   r6   rF   rZ   s     r"   purge_queuezEndpoint.purge_queue  s8     ~""--- # 
 
 	
r$   r;   )rn   rd   )r<   r=   r>   r?   r@   r   r#   r   r   rE   rm   rB   rp   rr   rt   rC   r$   r"   rf   rf      s       @@7 7C 7(3- 7 7 7 7"Hc3h HC H H H H( =B" "!#s(^"69"	c3h" " " "4

 

c 

$sCx. 

 

 

 


 
3 
tCH~ 
 
 
 
 
 
r$   rf   )r?   rW   typingr   r   r   r   requests.adaptersr   r   runpod.endpoint.helpersr   r	   r
   r   r   rE   rf   rC   r$   r"   <module>rx      s3     & & & & & & & & & &  0 0 0 0 0 0 0 0           H? H? H? H? H? H? H? H?\Q
 Q
 Q
 Q
 Q
 Q
 Q
 Q
nX
 X
 X
 X
 X
 X
 X
 X
 X
 X
r$   