
    >'h                    4   d dl mZ d dlZd dlmZmZ 	 d dlmZ d dl	m
Z
 d dlmZmZ ddl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 ddlmZ dZ G d d      Z G d de      Z G d de      Z G d de      Z G d de      Zy# e$ r	 d dlmZ Y |w xY w)    )annotationsN)AnyProtocol)Self)meta)	BaseModelValidationError   )DefaultCacheRenderCache)config)env)
AsyncError)ChatMessagechat_message_from_text)generate_canary_word0c                      e Zd Zdddddd	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZedd       Zedd       Zedd       Zedd       Z	edd	       Z
dd
Zy)
BasePromptN)nameversionmetadatacanary_wordrender_cachec                  |xs i | _         |xs t        t        j                               | _        || _        |xs
 t               | _        t        j                  |      | _
        |xs t        | _        d|xs
 t               i| _        y)aD  
        Prompt constructor.

        Parameters:
            text: The template text.
            name: The name to identify this prompt.
            version: The version string attached to this prompt.
            metadata: A key-value set of metadata pairs attached to this prompt.
            canary_word: The string to use for the `{{canary_word}}` extension. If `None`, a default string will be
                generated.
            render_cache: The caching backend to store rendered prompts. If `None`, the default in-memory backend will
                be used.
        r   N)	_metadatastruuiduuid4_name_rawr   _render_cacher   from_string	_templateDEFAULT_VERSION_versionr   defaults)selftextr   r   r   r   r   s          S/home/kushmeetdev/Regenta/Chatbot/venv/lib/python3.12/site-packages/banks/prompt.py__init__zBasePrompt.__init__   sm    . "R.S.
	);\^.2?&(M7K7MN    c                <    || j                   S || j                   z  S Nr'   )r(   datas     r*   _get_contextzBasePrompt._get_context<   s     <== dmm##r,   c                    | j                   S r.   )r   r(   s    r*   r   zBasePrompt.metadataA   s    ~~r,   c                    | j                   S r.   )r    r3   s    r*   r   zBasePrompt.nameE   s    zzr,   c                    | j                   S )z#Returns the raw text of the prompt.)r!   r3   s    r*   rawzBasePrompt.rawI   s     yyr,   c                    | j                   S r.   )r&   r3   s    r*   r   zBasePrompt.versionN   s    }}r,   c                j    t        j                  | j                        }t        j                  |      S r.   )r   parser6   r   find_undeclared_variables)r(   asts     r*   	variableszBasePrompt.variablesR   s%    ii!--c22r,   c                $    | j                   d   |v S )z^Returns whether the canary word is present in `text`, signalling the prompt might have leaked.r   r/   )r(   r)   s     r*   canary_leakedzBasePrompt.canary_leakedW   s    }}]+t33r,   )r)   r   r   
str | Noner   r?   r   dict[str, Any] | Noner   r?   r   zRenderCache | NonereturnNone)r0   zdict | NonerA   dict)rA   zdict[str, Any])rA   r   )rA   r?   )rA   zset[str])r)   r   rA   bool)__name__
__module____qualname__r+   r1   propertyr   r   r6   r   r<   r>    r,   r*   r   r      s    
  "*."&+/OO 	O
 O (O  O )O 
O@$
         3 34r,   r   c                  $    e Zd ZdZdddZdddZy)Prompta  
    The `Prompt` class is the only thing you need to know about Banks on the Python side. The class can be
    initialized with a string variable containing the prompt template text, then you can invoke the method `text`
    on your instance to pass the data needed to render the template and get back the final prompt.

    A quick example:
    ```py
    from banks import Prompt


    p = Prompt("Write a 500-word blog post on {{ topic }}.")
    my_topic = "retrogame computing"
    print(p.text({"topic": my_topic}))
    ```
    Nc                    | j                  |      }| j                  j                  |      }|r|S | j                  j	                  |      }| j                  j                  ||       |S )
        Render the prompt using variables present in `data`

        Parameters:
            data: A dictionary containing the context variables.
        )r1   r"   getr$   rendersetr(   r0   cachedrendereds       r*   r)   zPrompt.textm   sa       &##''-M--d3tX.r,   c                   | j                  |      }| j                  j                  |      }|s7| j                  j	                  |      }| j                  j                  ||       g }|j                         j                  d      D ]'  }	 |j                  t        j                  |             ) |s|j                  t        d|             |S # t        $ r Y Uw xY w)rM   
user)rolecontent)r1   r"   rN   r$   rO   rP   stripsplitappendr   model_validate_jsonr	   r   )r(   r0   rS   messageslines        r*   chat_messageszPrompt.chat_messages}   s       &%%))$/~~,,T2H""42&(NN$**40 	D ? ? EF	  OO2QR # s   $C	CCr.   r0   r@   rA   r   )r0   r@   rA   zlist[ChatMessage])rE   rF   rG   __doc__r)   r_   rI   r,   r*   rK   rK   \   s      r,   rK   c                  .     e Zd ZdZd fdZdddZ xZS )AsyncPrompta-  
    Banks provides async support through the machinery [provided by Jinja](https://jinja.palletsprojects.com/en/3.0.x/api/#async-support)

    Since the Jinja environment is a global state in banks, the library can work either with or
    without async support, and this must be known before importing anything.

    If the application using banks runs within an `asyncio` loop, you can do two things
    to optimize banks' execution:

    1. Set the environment variable `BANKS_ASYNC_ENABLED=true`.
    2. Use the `AsyncPrompt` class that has an awaitable `run` method.

    For example, let's render a prompt that contains some calls to the `generate` extension. Those calls
    will be heavily I/O bound, so other tasks can take advantage and advance while the prompt is being
    rendered.

    Example:
    ```python
    # Enable async support before importing from banks
    import os

    os.environ["BANKS_ASYNC_ENABLED"] = "true"

    # Show logs to see what's happening at runtime
    import logging

    logging.basicConfig(level=logging.INFO)

    import asyncio
    from banks import AsyncPrompt

    prompt_template = """
    Generate a tweet about the topic '{{ topic }}' with a positive sentiment.
    """

    async def task(task_id: int, sleep_time: int):
        logging.info(f"Task {task_id} is running.")
        await asyncio.sleep(sleep_time)
        logging.info(f"Task {task_id} done.")


    async def main():
        p = AsyncPrompt(prompt_template)
        # Schedule the prompt rendering along with two executions of 'task', one sleeping for 10 seconds
        # and one sleeping for 1 second
        results = await asyncio.gather(p.text({"topic": "AI frameworks"}), task(1, 10), task(2, 1))
        print("All tasks done, rendered prompt:")
        print(results[0])


    asyncio.run(main())
    ```
    c                ^    t        |   |i | t        j                  sd}t	        |      y )NzaAsync is not enabled. Please set the environment variable 'BANKS_ASYNC_ENABLED=on' and try again.)superr+   r   ASYNC_ENABLEDr   )r(   argskwargsmsg	__class__s       r*   r+   zAsyncPrompt.__init__   s2    $)&)##uCS/! $r,   c                   K   | j                  |      }| j                  j                  |      }|r|S | j                  j	                  |       d{   }| j                  j                  ||       |S 7 "w)rM   N)r1   r"   rN   r$   render_asyncrP   rQ   s       r*   r)   zAsyncPrompt.text   sn        &##''-M"nn99$??tX. @s   AA6A4#A6)rg   r   rh   r   rA   rB   r.   r`   )rE   rF   rG   ra   r+   r)   __classcell__)rj   s   @r*   rc   rc      s    4l" r,   rc   c                  ,    e Zd ZdZddddZddd	dZy)
PromptRegistryz:Interface to be implemented by concrete prompt registries.N)r   c                    y r.   rI   )r(   r   r   s      r*   rN   zPromptRegistry.get       r,   F)	overwritec                    y r.   rI   )r(   promptrr   s      r*   rP   zPromptRegistry.set   rq   r,   )r   r   r   r?   rA   rK   )rt   rK   rr   rD   rA   rB   )rE   rF   rG   ra   rN   rP   rI   r,   r*   ro   ro      s    D6:J7<Jr,   ro   c                  X    e Zd ZU dZded<   dZded<   dZded<   dZded	<   edd
       Z	y)PromptModelz(Serializable representation of a Prompt.r   r)   Nr?   r   r   r@   r   c                j     | |j                   |j                  |j                  |j                        S )N)r)   r   r   r   )r6   r   r   r   )clsrt   s     r*   from_promptzPromptModel.from_prompt   s&    

fnnW]WfWfggr,   )rx   z
type[Self]rt   rK   rA   r   )
rE   rF   rG   ra   __annotations__r   r   r   classmethodry   rI   r,   r*   rv   rv      s=    2
ID*GZ&*H#*h hr,   rv   ) 
__future__r   r   typingr   r   r   ImportErrortyping_extensionsjinja2r   pydanticr   r	   cacher   r   r   r   errorsr   typesr   r   utilsr   r%   r   rK   rc   ro   rv   rI   r,   r*   <module>r      s    #   '  / ,    6 '>4 >4B;Z ;|L* L^KX K
h) 
hM  '&'s   B	 	BB