
    9i9w                     
   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 d dl	Z	d dl
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mZmZmZmZ dd
lmZmZ ddlmZ  ej@                  e!      Z" e       rd dl#Z# e       rddl$m%Z%m&Z& ddlm'Z' ne(Z%da)e*e+e,e-e.e/dZ0e G d d             Z1i a2g dZ3d%dZ4d Z5d&dZ6d'dZ7d Z8d Z9 G d d      Z: G d de:      Z; G d de:      Z< G d d e:      Z= G d! d"e:      Z> G d# d$e%      Z?y)(    N)	dataclass)Dict)HfFolderhf_hub_downloadlist_spaces   )AutoTokenizer)is_offline_modeis_openai_availableis_torch_availablelogging   )TASK_MAPPINGTOOL_CONFIG_FILETool	load_toolsupports_remote)CHAT_MESSAGE_PROMPTdownload_prompt)evaluate)StoppingCriteriaStoppingCriteriaList)AutoModelForCausalLMF)printrangefloatintboolstrc                   ,    e Zd ZU eed<   eed<   eed<   y)PreTooltaskdescriptionrepo_idN)__name__
__module____qualname__r   __annotations__     c/var/www/html/backtest/airagagent/rag_env/lib/python3.12/site-packages/transformers/tools/agents.pyr!   r!   ;   s    
ILr*   r!   )zimage-transformationztext-downloadztext-to-imageztext-to-videoc                 r   t               rt        j                  d       i S t        |       }i }|D ]v  }|j                  }t        |t        d      }t        |d      5 }t        j                  |      }d d d        |j                  d      d   }t        |d	   |
      ||d   <   x |S # 1 sw Y   8xY w)Nz;You are in offline mode, so remote tools are not available.)authorspace)	repo_typezutf-8)encoding/r#   r"   r#   r$   name)r
   loggerinfor   idr   r   openjsonloadsplitr!   )	organizationspacestools
space_infor$   resolved_config_filereaderconfigr"   s	            r+   get_remote_toolsrC   M   s    QR	-FE g
--.w8HT[\&9 	'VYYv&F	' }}S!"% 'Tvm?T^e ffVng L	' 	's    B--B6	c                     t         ry t        j                  d      } | j                  }t	               }t        j                         D ]<  \  }}t        ||      }|j                  }t        ||d       t        |j                  <   > t               sQt        D ]H  }d}|j                         D ]!  \  }}	|	j                  |k(  s|	t        |<   d} n |r<t        | d       da y )Ntransformersr3   FTz is not implemented on the Hub.)_tools_are_initialized	importlibimport_moduler>   rC   r   itemsgetattrr#   r!   HUGGINGFACE_DEFAULT_TOOLSr4   r
   "HUGGINGFACE_DEFAULT_TOOLS_FROM_HUBr"   
ValueError)
main_moduletools_moduleremote_tools	task_nametool_class_name
tool_classr#   found	tool_nametools
             r+   _setup_default_toolsrW   `   s     )).9K$$L#%L&2&8&8&: t"	?\?;
 ,,5<)Ydnr5s!*//2t
 ; 		PIE#/#5#5#7 	499	);?-i8 E	  I;.M!NOO		P "r*   c                 ,   |t         j                         }n|}|j                         D ]g  \  }}|| vs||v rt        |t              r|||<   %|j
                  |j                  n|j
                  }|xr t        |      }t        ||      ||<   i |S )Nremote)	BASE_PYTHON_TOOLScopyrI   
isinstancer   r$   r"   r   r   )	codetoolboxrZ   cached_toolsresolved_toolsr4   rV   task_or_repo_id_remotes	            r+   resolve_toolsrd      s    *//1%mmo 	N
dtt~5dD!#'N4 +/<<+?diiT\\OA!AG#,_W#MN4 	N r*   c                    ddg}|j                         D ]c  \  }}|| vst        |t              r|j                  |j                  n|j                  }| d| d}|r|dz  }|dz  }|j                  |       e dj                  |      dz   S )Nz"from transformers import load_tool z = load_tool(""z, remote=True)
)rI   r]   r   r$   r"   appendjoin)r^   r_   rZ   
code_linesr4   rV   rb   lines           r+   get_tool_creation_codern      s    6;Jmmo 	 
dtz$5'+||';$))~o%6a8O#D$	  99Z 4''r*   c                 J   | j                  d      }d}|t        |      k  rX||   j                         j                  d      s6|dz  }|t        |      k  r#||   j                         j                  d      s6dj	                  |d |       j                         }|t        |      k(  r|d fS |dz  }|}||   j                         j                  d      s(|dz  }||   j                         j                  d      s(dj	                  |||       j                         }||fS )Nri   r   ```r   )r;   lenlstrip
startswithrk   strip)resultlinesidxexplanation	start_idxr^   s         r+   clean_code_for_chatrz      s   LLE
C
E

5:#4#4#6#A#A%#Hq E

5:#4#4#6#A#A%#H))E$3K(..0K
c%jD  1HCICj!,,U3q Cj!,,U399U9S)*002Dr*   c                     d|  } | j                  d      \  }}|j                         }|j                         }|j                  d      }|d   dv r|dd  }|d   dk(  r|d d }dj                  |      }||fS )	NzI will use the following zAnswer:ri   r   )rp   z```pyz	```pythonr   r2   rp   )r;   rt   rk   )ru   rx   r^   rl   s       r+   clean_code_for_runr|      s    (1FY/K##%K::<DD!J!}55^
"~_
99Z Dr*   c                   t    e Zd ZdZddZedeeef   fd       Z	ddZ
d Zddd	d
Zd Zddd	dZd Zd Zy)Agenta&  
    Base class for all agents which contains the main API methods.

    Args:
        chat_prompt_template (`str`, *optional*):
            Pass along your own prompt if you want to override the default template for the `chat` method. Can be the
            actual prompt template or a repo ID (on the Hugging Face Hub). The prompt should be in a file named
            `chat_prompt_template.txt` in this repo in this case.
        run_prompt_template (`str`, *optional*):
            Pass along your own prompt if you want to override the default template for the `run` method. Can be the
            actual prompt template or a repo ID (on the Hugging Face Hub). The prompt should be in a file named
            `run_prompt_template.txt` in this repo in this case.
        additional_tools ([`Tool`], list of tools or dictionary with tool values, *optional*):
            Any additional tools to include on top of the default ones. If you pass along a tool with the same name as
            one of the default tools, that default tool will be overridden.
    Nc           
         t                | j                  j                  }t        ||d      | _        t        ||d      | _        t        j                         | _        t        | _
        |>t        |t        t        f      r|D ci c]  }|j                  | }}nt        |t              s|j                  |i}|j!                         D ci c]  \  }}|t        v s|| }}}| j                  j#                  |       t%        |      dkD  rRdj'                  |j!                         D 	cg c]  \  }	}d|	 d|  c}}	      }
t(        j+                  d|
 d	       nHt%        |      dk(  r:t        |j-                               d
   }t(        j+                  | d||    d       | j/                          y c c}w c c}}w c c}}	w )Nchat)moderunr   ri   - : zSThe following tools have been replaced by the ones provided in `additional_tools`:
.r   z has been replaced by z# as provided in `additional_tools`.)rW   	__class__r%   r   chat_prompt_templaterun_prompt_templaterK   r\   _toolboxr   logr]   listtupler4   dictrI   updaterq   rk   r5   warningkeysprepare_for_new_chat)selfr   r   additional_tools
agent_nametr4   rV   replacementsnnamess              r+   __init__zAgent.__init__   s   ^^,,
$34H*[a$b!#23F
Y^#_ 1668'*T5M:7G#H!AFFAI#H #H 0$7$4$9$9;K#L 9I9O9O9Qw:4UY]vUvD$JwLwMM  !12< 1$		\=O=O=Q"RTQRs"QC="RSjkpjqqrs \"a'L--/03$'=l4>P=QQtuv!!# $I x #Ss   F=G!G0G
returnc                     | j                   S )z-Get all tool currently available to the agent)r   r   s    r+   r_   zAgent.toolbox   s     }}r*   Fc           
         dj                  | j                  j                         D cg c]  \  }}d| d|j                    c}}      }|rP| j                  | j
                  j                  d|      }n| j                  }|t        j                  d|      z  }|S | j                  j                  d|      }|j                  d|      }|S c c}}w )Nri   r   r   z<<all_tools>>z<<task>>z
<<prompt>>)	rk   r_   rI   r#   chat_historyr   replacer   r   )r   r"   	chat_moder4   rV   r#   prompts          r+   format_promptzAgent.format_prompt   s    iiSWS_S_SeSeSg hZT42dV2d.>.>-?!@ hi  (22::?KX**)11*dCCF  --55o{SF^^L$7F !is   C
c                     || _         y)z
        Set the function use to stream results (which is `print` by default).

        Args:
            streamer (`callable`): The function to call when streaming results from the LLM.
        N)r   )r   streamers     r+   
set_streamzAgent.set_stream  s     r*   )return_coderZ   c                *   | j                  |d      }| j                  |ddg      }||j                         z   dz   | _        t	        |      \  }}| j                  d|        || j                  d	|        |sw| j                  d
       t        || j                  || j                        | _        | j                  j                  |       t        || j                  | j                  d      S t        || j                  |      }	|	 d| S y)a  
        Sends a new request to the agent in a chat. Will use the previous ones in its history.

        Args:
            task (`str`): The task to perform
            return_code (`bool`, *optional*, defaults to `False`):
                Whether to just return code and not evaluate it.
            remote (`bool`, *optional*, defaults to `False`):
                Whether or not to use remote tools (inference endpoints) instead of local ones.
            kwargs (additional keyword arguments, *optional*):
                Any keyword argument to send to the agent when evaluating the code.

        Example:

        ```py
        from transformers import HfAgent

        agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder")
        agent.chat("Draw me a picture of rivers and lakes")

        agent.chat("Transform the picture so that there is a rock in there")
        ```
        T)r   zHuman:z=====stopri   ==Explanation from the agent==
N"

==Code generated by the agent==


==Result==rZ   r`   rY   )r   generate_onert   r   rz   r   rd   r_   r`   
chat_stater   r   rn   
r   r"   r   rZ   kwargsr   ru   rx   r^   	tool_codes
             r+   r   z
Agent.chat  s   0 ##DD#9""670C"D"V\\^3d:/7T3K=ABHH<TFCD)*$1$Vbfbsbs$t!&&v.d&7&7TXYY24fU	#Btf-- r*   c                 .    d| _         i | _        d| _        y)zG
        Clears the history of prior calls to [`~Agent.chat`].
        N)r   r   r`   r   s    r+   r   zAgent.prepare_for_new_chat6  s     ! r*   c                   | j                  |      }| j                  |dg      }t        |      \  }}| j                  d|        | j                  d|        |s_| j                  d       t	        || j
                  || j                        | _        t        || j                  |j                               S t        || j
                  |      }	|	 d	| S )
a  
        Sends a request to the agent.

        Args:
            task (`str`): The task to perform
            return_code (`bool`, *optional*, defaults to `False`):
                Whether to just return code and not evaluate it.
            remote (`bool`, *optional*, defaults to `False`):
                Whether or not to use remote tools (inference endpoints) instead of local ones.
            kwargs (additional keyword arguments, *optional*):
                Any keyword argument to send to the agent when evaluating the code.

        Example:

        ```py
        from transformers import HfAgent

        agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder")
        agent.run("Draw me a picture of rivers and lakes")
        ```
        zTask:r   r   r   r   r   )staterY   ri   )
r   r   r|   r   rd   r_   r`   r   r\   rn   r   s
             r+   r   z	Agent.run>  s    , ##D)""6	":.v6T3K=AB8?@HH%& -dDLL^b^o^o pDD$"3"36;;=II.tT\\&QI[4&))r*   c                     t         N)NotImplementedErrorr   r   r   s      r+   r   zAgent.generate_onec  s    !!r*   c                 L    |D cg c]  }| j                  ||       c}S c c}w r   )r   r   promptsr   r   s       r+   generate_manyzAgent.generate_manyg  s#    >EFF!!&$/FFFs   !NNNF)r%   r&   r'   __doc__r   propertyr   r   r   r_   r   r   r   r   r   r   r   r)   r*   r+   r~   r~      sc    "$6 c4i   ).e (.T! (-U #*J"Gr*   r~   c                   F     e Zd ZdZ	 	 	 	 	 d fd	Zd Zd Zd Zd Z xZ	S )OpenAiAgentu!  
    Agent that uses the openai API to generate code.

    <Tip warning={true}>

    The openAI models are used in generation mode, so even for the `chat()` API, it's better to use models like
    `"text-davinci-003"` over the chat-GPT variant. Proper support for chat-GPT models will come in a next version.

    </Tip>

    Args:
        model (`str`, *optional*, defaults to `"text-davinci-003"`):
            The name of the OpenAI model to use.
        api_key (`str`, *optional*):
            The API key to use. If unset, will look for the environment variable `"OPENAI_API_KEY"`.
        chat_prompt_template (`str`, *optional*):
            Pass along your own prompt if you want to override the default template for the `chat` method. Can be the
            actual prompt template or a repo ID (on the Hugging Face Hub). The prompt should be in a file named
            `chat_prompt_template.txt` in this repo in this case.
        run_prompt_template (`str`, *optional*):
            Pass along your own prompt if you want to override the default template for the `run` method. Can be the
            actual prompt template or a repo ID (on the Hugging Face Hub). The prompt should be in a file named
            `run_prompt_template.txt` in this repo in this case.
        additional_tools ([`Tool`], list of tools or dictionary with tool values, *optional*):
            Any additional tools to include on top of the default ones. If you pass along a tool with the same name as
            one of the default tools, that default tool will be overridden.

    Example:

    ```py
    from transformers import OpenAiAgent

    agent = OpenAiAgent(model="text-davinci-003", api_key=xxx)
    agent.run("Is the following `text` (in Spanish) positive or negative?", text="¡Este es un API muy agradable!")
    ```
    c                     t               st        d      | t        j                  j	                  dd       }|t        d      |t        _        || _        t        | )  |||       y )N<Using `OpenAiAgent` requires `openai`: `pip install openai`.OPENAI_API_KEYzYou need an openai key to use `OpenAIAgent`. You can get one here: Get one here https://openai.com/api/`. If you have one, set it in your env with `os.environ['OPENAI_API_KEY'] = xxx.r   r   r   )r   ImportErrorosenvirongetrM   openaiapi_keymodelsuperr   )r   r   r   r   r   r   r   s         r+   r   zOpenAiAgent.__init__  ss     #$\]]?jjnn%5t<G?  %FN
!5 3- 	 	
r*   c                     d| j                   v r |D cg c]  }| j                  ||       c}S | j                  ||      S c c}w )Ngptr   _chat_generate_completion_generater   s       r+   r   zOpenAiAgent.generate_many  sE    DJJDKL&D''5LL,,Wd;; Ms   Ac                 n    d| j                   v r| j                  ||      S | j                  |g|      d   S )Nr   r   r   r   s      r+   r   zOpenAiAgent.generate_one  s;    DJJ&&vt44,,fXt<Q??r*   c                     t         j                  j                  | j                  d|dgd|      }|d   d   d   d   S )Nuserrolecontentr   )r   messagestemperaturer   choicesmessager   )r   ChatCompletioncreater   r   r   r   ru   s       r+   r   zOpenAiAgent._chat_generate  sQ    &&--**%&9:	 . 
 i #I.y99r*   c                     t         j                  j                  | j                  |d|d      }|d   D cg c]  }|d   	 c}S c c}w )Nr      )r   r   r   r   
max_tokensr   text)r   
Completionr   r   r   r   r   ru   answers        r+   r   z OpenAiAgent._completion_generate  sO    ""))** * 
 .4I->?6v???   A)ztext-davinci-003NNNN
r%   r&   r'   r   r   r   r   r   r   __classcell__r   s   @r+   r   r   l  s5    #N !! 
8<@:@r*   r   c                   J     e Zd ZdZ	 	 	 	 	 	 	 d fd	Zd Zd Zd Zd Z xZ	S )AzureOpenAiAgentu	  
    Agent that uses Azure OpenAI to generate code. See the [official
    documentation](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/) to learn how to deploy an openAI
    model on Azure

    <Tip warning={true}>

    The openAI models are used in generation mode, so even for the `chat()` API, it's better to use models like
    `"text-davinci-003"` over the chat-GPT variant. Proper support for chat-GPT models will come in a next version.

    </Tip>

    Args:
        deployment_id (`str`):
            The name of the deployed Azure openAI model to use.
        api_key (`str`, *optional*):
            The API key to use. If unset, will look for the environment variable `"AZURE_OPENAI_API_KEY"`.
        resource_name (`str`, *optional*):
            The name of your Azure OpenAI Resource. If unset, will look for the environment variable
            `"AZURE_OPENAI_RESOURCE_NAME"`.
        api_version (`str`, *optional*, default to `"2022-12-01"`):
            The API version to use for this agent.
        is_chat_mode (`bool`, *optional*):
            Whether you are using a completion model or a chat model (see note above, chat models won't be as
            efficient). Will default to `gpt` being in the `deployment_id` or not.
        chat_prompt_template (`str`, *optional*):
            Pass along your own prompt if you want to override the default template for the `chat` method. Can be the
            actual prompt template or a repo ID (on the Hugging Face Hub). The prompt should be in a file named
            `chat_prompt_template.txt` in this repo in this case.
        run_prompt_template (`str`, *optional*):
            Pass along your own prompt if you want to override the default template for the `run` method. Can be the
            actual prompt template or a repo ID (on the Hugging Face Hub). The prompt should be in a file named
            `run_prompt_template.txt` in this repo in this case.
        additional_tools ([`Tool`], list of tools or dictionary with tool values, *optional*):
            Any additional tools to include on top of the default ones. If you pass along a tool with the same name as
            one of the default tools, that default tool will be overridden.

    Example:

    ```py
    from transformers import AzureOpenAiAgent

    agent = AzureAiAgent(deployment_id="Davinci-003", api_key=xxx, resource_name=yyy)
    agent.run("Is the following `text` (in Spanish) positive or negative?", text="¡Este es un API muy agradable!")
    ```
    c	                    t               st        d      || _        dt        _        | t
        j                  j                  dd       }|t        d      |t        _	        | t
        j                  j                  dd       }|t        d      d| dt        _
        |t        _        |d	|j                         v }|| _        t        	| =  |||
       y )Nr   azureAZURE_OPENAI_API_KEYzYou need an Azure openAI key to use `AzureOpenAIAgent`. If you have one, set it in your env with `os.environ['AZURE_OPENAI_API_KEY'] = xxx.AZURE_OPENAI_RESOURCE_NAMEzYou need a resource_name to use `AzureOpenAIAgent`. If you have one, set it in your env with `os.environ['AZURE_OPENAI_RESOURCE_NAME'] = xxx.zhttps://z.openai.azure.comr   r   )r   r   deployment_idr   api_typer   r   r   rM   r   api_baseapi_versionloweris_chat_modelr   r   )
r   r   r   resource_namer   r   r   r   r   r   s
            r+   r   zAzureOpenAiAgent.__init__  s     #$\]]*!?jjnn%;TBG?= 
 %FN JJNN+GNM C 
 !)7HIFO( !]%8%8%::M*!5 3- 	 	
r*   c                     | j                   r |D cg c]  }| j                  ||       c}S | j                  ||      S c c}w r   r   r   r   r   s       r+   r   zAzureOpenAiAgent.generate_many,  sB    DKL&D''5LL,,Wd;; Ms   ?c                 j    | j                   r| j                  ||      S | j                  |g|      d   S )Nr   r   r   s      r+   r   zAzureOpenAiAgent.generate_one2  s8    &&vt44,,fXt<Q??r*   c                     t         j                  j                  | j                  d|dgd|      }|d   d   d   d   S )Nr   r   r   )enginer   r   r   r   r   r   )r   r   r   r   r   s       r+   r   zAzureOpenAiAgent._chat_generate8  sS    &&--%%%&9:	 . 
 i #I.y99r*   c                     t         j                  j                  | j                  |d|d      }|d   D cg c]  }|d   	 c}S c c}w )Nr   r   )r   r   r   r   r   r   r   )r   r   r   r   r   s        r+   r   z%AzureOpenAiAgent._completion_generateA  sQ    ""))%% * 
 .4I->?6v???r   )NNz
2022-12-01NNNNr   r   s   @r+   r   r     s<    -d  ! ,
\<@:@r*   r   c                   ,     e Zd ZdZ	 d fd	Zd Z xZS )HfAgentuc  
    Agent that uses an inference endpoint to generate code.

    Args:
        url_endpoint (`str`):
            The name of the url endpoint to use.
        token (`str`, *optional*):
            The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated when
            running `huggingface-cli login` (stored in `~/.huggingface`).
        chat_prompt_template (`str`, *optional*):
            Pass along your own prompt if you want to override the default template for the `chat` method. Can be the
            actual prompt template or a repo ID (on the Hugging Face Hub). The prompt should be in a file named
            `chat_prompt_template.txt` in this repo in this case.
        run_prompt_template (`str`, *optional*):
            Pass along your own prompt if you want to override the default template for the `run` method. Can be the
            actual prompt template or a repo ID (on the Hugging Face Hub). The prompt should be in a file named
            `run_prompt_template.txt` in this repo in this case.
        additional_tools ([`Tool`], list of tools or dictionary with tool values, *optional*):
            Any additional tools to include on top of the default ones. If you pass along a tool with the same name as
            one of the default tools, that default tool will be overridden.

    Example:

    ```py
    from transformers import HfAgent

    agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder")
    agent.run("Is the following `text` (in Spanish) positive or negative?", text="¡Este es un API muy agradable!")
    ```
    c                     || _         |!dt               j                          | _        n4|j	                  d      s|j	                  d      r|| _        n
d| | _        t
        |   |||       y )NzBearer BearerBasicr   )url_endpointr   	get_tokentokenrs   r   r   )r   r  r  r   r   r   r   s         r+   r   zHfAgent.__init__l  sw     )="8:#7#7#9":;DJh'5+;+;G+DDJ"5'*DJ!5 3- 	 	
r*   c                    d| j                   i}|dd|dd}t        j                  | j                  ||      }|j                  dk(  r;t
        j                  d       t        j                  d	       | j                  |      S |j                  dk7  r)t        d
|j                   d|j                                |j                         d   d   }|D ]$  }|j                  |      s|d t        |        c S  |S )NAuthorizationr   F)max_new_tokensreturn_full_textr   )inputs
parameters)r9   headersi  z=Getting rate-limited, waiting a tiny bit before trying again.r   zError r   r   generated_text)r  requestspostr  status_coder5   r6   timesleep_generate_onerM   r9   endswithrq   )r   r   r   r  r  responseru   stop_seqs           r+   r   zHfAgent.generate_one|  s    "DJJ/-0eUYZ

 ==!2!2Q3&KKWXJJqM%%f--!!S(vh&:&:%;2hmmo=NOPP#$45 	0Hx(.X//	0 r*   )NNNN)r%   r&   r'   r   r   r   r   r   s   @r+   r  r  L  s    @ os
 r*   r  c                   J     e Zd ZdZd fd	Zed        Zed        Zd Z	 xZ
S )
LocalAgenta  
    Agent that uses a local model and tokenizer to generate code.

    Args:
        model ([`PreTrainedModel`]):
            The model to use for the agent.
        tokenizer ([`PreTrainedTokenizer`]):
            The tokenizer to use for the agent.
        chat_prompt_template (`str`, *optional*):
            Pass along your own prompt if you want to override the default template for the `chat` method. Can be the
            actual prompt template or a repo ID (on the Hugging Face Hub). The prompt should be in a file named
            `chat_prompt_template.txt` in this repo in this case.
        run_prompt_template (`str`, *optional*):
            Pass along your own prompt if you want to override the default template for the `run` method. Can be the
            actual prompt template or a repo ID (on the Hugging Face Hub). The prompt should be in a file named
            `run_prompt_template.txt` in this repo in this case.
        additional_tools ([`Tool`], list of tools or dictionary with tool values, *optional*):
            Any additional tools to include on top of the default ones. If you pass along a tool with the same name as
            one of the default tools, that default tool will be overridden.

    Example:

    ```py
    import torch
    from transformers import AutoModelForCausalLM, AutoTokenizer, LocalAgent

    checkpoint = "bigcode/starcoder"
    model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto", torch_dtype=torch.bfloat16)
    tokenizer = AutoTokenizer.from_pretrained(checkpoint)

    agent = LocalAgent(model, tokenizer)
    agent.run("Draw me a picture of rivers and lakes.")
    ```
    c                 F    || _         || _        t        |   |||       y )Nr   )r   	tokenizerr   r   )r   r   r  r   r   r   r   s         r+   r   zLocalAgent.__init__  s,    
"!5 3- 	 	
r*   c                 l    t        j                  |fi |}t        j                  |fi |} | ||      S )a  
        Convenience method to build a `LocalAgent` from a pretrained checkpoint.

        Args:
            pretrained_model_name_or_path (`str` or `os.PathLike`):
                The name of a repo on the Hub or a local path to a folder containing both model and tokenizer.
            kwargs (`Dict[str, Any]`, *optional*):
                Keyword arguments passed along to [`~PreTrainedModel.from_pretrained`].

        Example:

        ```py
        import torch
        from transformers import LocalAgent

        agent = LocalAgent.from_pretrained("bigcode/starcoder", device_map="auto", torch_dtype=torch.bfloat16)
        agent.run("Draw me a picture of rivers and lakes.")
        ```
        )r   from_pretrainedr	   )clspretrained_model_name_or_pathr   r   r  s        r+   r  zLocalAgent.from_pretrained  s?    * %445R]V\]!112OZSYZ	5)$$r*   c                     t        | j                  d      r0t        | j                  j                  j	                               d   S | j                  j                         D ]  }|j                  c S  y )Nhf_device_mapr   )hasattrr   r   r"  valuesr  device)r   params     r+   _model_devicezLocalAgent._model_device  sY    4::/

00779:1==ZZ**, 	 E<<	 r*   c                    | j                  |d      j                  | j                        }|d   j                  d   }t	        t        || j                         g      }| j                  j                  |d   d|      }| j                   j                  |d   j                         |d        }|D ]#  }|j                  |      s|d t        |        }% |S )Npt)return_tensors	input_idsr   r   )r
  stopping_criteriar   )r  tor'  shaper   StopSequenceCriteriar   generatedecodetolistr  rq   )	r   r   r   encoded_inputssrc_lenr,  outputsru   r  s	            r+   r   zLocalAgent.generate_one  s    tDGGHZHZ[ -33A602FtT^^2\1]^**%%;'O` & 
 &&wqz'8'8':78'DE 	2Hx( 03x=.1	2 r*   r   )r%   r&   r'   r   r   classmethodr  r   r'  r   r   r   s   @r+   r  r    s;    !F
 % %0    r*   r  c                   "    e Zd ZdZd ZdefdZy)r/  a6  
    This class can be used to stop generation whenever a sequence of tokens is encountered.

    Args:
        stop_sequences (`str` or `List[str]`):
            The sequence (or list of sequences) on which to stop execution.
        tokenizer:
            The tokenizer used to decode the model outputs.
    c                 F    t        |t              r|g}|| _        || _        y r   )r]   r   stop_sequencesr  )r   r9  r  s      r+   r   zStopSequenceCriteria.__init__  s#    nc*,-N,"r*   r   c                     | j                   j                  |j                         d         t        fd| j                  D              S )Nr   c              3   @   K   | ]  }j                  |        y wr   )r  ).0stop_sequencedecoded_outputs     r+   	<genexpr>z0StopSequenceCriteria.__call__.<locals>.<genexpr>  s     cm>**=9cs   )r  r1  r2  anyr9  )r   r+  scoresr   r>  s       @r+   __call__zStopSequenceCriteria.__call__  s<    ..y/?/?/A!/DEctObObcccr*   N)r%   r&   r'   r   r   r   rB  r)   r*   r+   r/  r/    s    #dt dr*   r/  )zhuggingface-tools)FNr   )@importlib.utilrG   r9   r   r  dataclassesr   typingr   r  huggingface_hubr   r   r   models.autor	   utilsr
   r   r   r   baser   r   r   r   r   r   r   r   python_interpreterr   
get_loggerr%   r5   r   
generationr   r   r   objectrF   r   r   r   r   r   r   r[   r!   rK   rL   rC   rW   rd   rn   rz   r|   r~   r   r   r  r  r/  r)   r*   r+   <module>rN     s/  "   	  !   B B ' U U R R 9 ( 
		H	% C2        & "&">&( $ eG eGP_@% _@D{@u {@|De DNZ Zzd+ dr*   