a
    dg+                     @  sD  d Z ddlmZ ddlZddlmZmZmZmZm	Z	m
Z
 ddlZddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZmZmZmZ ddl m!Z" ddl#m!Z$ ddl%m!Z& ddl'm!Z( G dd deZ)G dd de)Z*G dd de)Z+G dd de)Z,G dd de)Z-G dd de)Z.dS )z
CPAL Chain and its subchains
    )annotationsN)AnyClassVarDictListOptionalType)BaseLanguageModel)Chain)LLMChain)PydanticOutputParser)CallbackManagerForChainRun)PromptTemplate)Constant)CausalModelInterventionModelNarrativeModel
QueryModel
StoryModel)templatec                   @  s   e Zd ZU ded< ejjZded< ejjZ	ded< dZ
ded< dZd	ed
< eddddZeddddZeddddZeddddddZdddddddZdS )_BaseStoryElementChainr   chainstr	input_key
output_keyNz,ClassVar[Optional[Type[pydantic.BaseModel]]]pydantic_modelzClassVar[Optional[str]]r   r   )returnc                 C  s&   | j du rtd| j t| j dS )z(Parse LLM output into a pydantic object.Nz#pydantic_model not implemented for )Zpydantic_object)r   NotImplementedError__name__r   )cls r    n/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_experimental/cpal/base.pyparser1   s
    

z_BaseStoryElementChain.parserz	List[str]c                 C  s   | j gS )z7Return the input keys.

        :meta private:
        )r   )selfr    r    r!   
input_keys:   s    z!_BaseStoryElementChain.input_keysc                 C  s   | j g}|S )z8Return the output keys.

        :meta private:
        )r   )r#   Z_output_keysr    r    r!   output_keysB   s    z"_BaseStoryElementChain.output_keysr	   r   llmkwargsr   c                 K  s@   | f dt |ttjjg|d| jd|   iddi|S )Nr   r   Zformat_instructions)input_variablesr   Zpartial_variablesr'   prompt)	r   r   r   narrative_inputvaluegetr   r"   Zget_format_instructionsr   r'   r(   r    r    r!   from_univariate_promptK   s    z-_BaseStoryElementChain.from_univariate_promptDict[str, Any]$Optional[CallbackManagerForChainRun])inputsrun_managerr   c                 C  s6   | j || j }| j |}tjj|tj	jd iS )N)
r   runr   	__class__r"   parser   
chain_datar-   chain_answer)r#   r3   r4   
completionZpydantic_datar    r    r!   _call_   s
    z_BaseStoryElementChain._call)N)r   
__module____qualname____annotations__r   r,   r-   r   r9   r   r   r   classmethodr"   propertyr$   r%   r0   r;   r    r    r    r!   r   (   s    

 r   c                   @  s*   e Zd ZU dZeZded< eZded< dS )NarrativeChainzhDecompose the narrative into its story elements.

    - causal model
    - query
    - intervention
    "ClassVar[Type[pydantic.BaseModel]]r   ClassVar[str]r   N)	r   r<   r=   __doc__r   r   r>   narrative_templater   r    r    r    r!   rA   l   s   
rA   c                   @  s*   e Zd ZU dZeZded< eZded< dS )CausalChainz:Translate the causal narrative into a stack of operations.rB   r   rC   r   N)	r   r<   r=   rD   r   r   r>   causal_templater   r    r    r    r!   rF   x   s   
rF   c                   @  s*   e Zd ZU dZeZded< eZded< dS )InterventionChainz5Set the hypothetical conditions for the causal model.rB   r   rC   r   N)	r   r<   r=   rD   r   r   r>   intervention_templater   r    r    r    r!   rH      s   
rH   c                   @  s*   e Zd ZU dZeZded< eZded< dS )
QueryChainar  Query the outcome table using SQL.

    *Security note*: This class implements an AI technique that generates SQL code.
        If those SQL commands are executed, it's critical to ensure they use credentials
        that are narrowly-scoped to only include the permissions this chain needs.
        Failure to do so may result in data corruption or loss, since this chain may
        attempt commands like `DROP TABLE` or `INSERT` if appropriately prompted.
        The best way to guard against such negative outcomes is to (as appropriate)
        limit the permissions granted to the credentials used with this chain.
    rB   r   rC   r   N)	r   r<   r=   rD   r   r   r>   query_templater   r    r    r    r!   rJ      s   
rJ   c                   @  s   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
< dZded< e	j
ddZded< eddd dddZddddddddZdddddZdS )	CPALChaina  Causal program-aided language (CPAL) chain implementation.

    *Security note*: The building blocks of this class include the implementation
        of an AI technique that generates SQL code. If those SQL commands
        are executed, it's critical to ensure they use credentials that
        are narrowly-scoped to only include the permissions this chain needs.
        Failure to do so may result in data corruption or loss, since this chain may
        attempt commands like `DROP TABLE` or `INSERT` if appropriately prompted.
        The best way to guard against such negative outcomes is to (as appropriate)
        limit the permissions granted to the credentials used with this chain.
    r	   r'   NzOptional[NarrativeChain]narrative_chainzOptional[CausalChain]causal_chainzOptional[InterventionChain]intervention_chainzOptional[QueryChain]query_chain)defaultr   _storyr   r&   c              
   K  sP   | f |t |tddgdddtj|dtj|dtj|dtj|dd|S )a  instantiation depends on component chains

        *Security note*: The building blocks of this class include the implementation
            of an AI technique that generates SQL code. If those SQL commands
            are executed, it's critical to ensure they use credentials that
            are narrowly-scoped to only include the permissions this chain needs.
            Failure to do so may result in data corruption or loss, since this chain may
            attempt commands like `DROP TABLE` or `INSERT` if appropriately prompted.
            The best way to guard against such negative outcomes is to (as appropriate)
            limit the permissions granted to the credentials used with this chain.
        questionquery_resultzFSummarize this answer '{query_result}' to this question '{question}'? )r)   r   r*   r'   )r'   r   rM   rN   rO   rP   )r   r   rA   r0   rF   rH   rJ   r/   r    r    r!   r0      s     




z CPALChain.from_univariate_promptr1   r2   )r3   r4   r(   r   c                 K  s  | j d u rtj| jd| _ | jd u r4tj| jd| _| jd u rNtj| jd| _| jd u rht	j| jd| _|  |t
jj t
jj }t| |jt
jj | |jt
jj | |jt
jj d}|| _dddddd}|pt }|j|d|j dd	| jd
 dddddd}|j|d|j dd	| jd
 |jjjr`td|j d|j  nt|jjjd d }	t
jj|| j |	i|}
|
S )NrU   )Zcausal_operationsZinterventionqueryr   )titledr   c                 S  s   | d | S )N
r    rW   rX   r    r    r!   pretty_print_str   s    z)CPALChain._call.<locals>.pretty_print_strzstory outcome datagreenz

)colorendverbosedictc                 S  s   | d t j|dd S )NrY      )indent)jsondumpsrZ   r    r    r!   pretty_print_dict   s    z*CPALChain._call.<locals>.pretty_print_dictz
query databluez9unanswerable, query and outcome are incoherent

outcome:
z
query:
r   )!rM   rA   r0   r'   rN   rF   rO   rH   rP   rJ   r   r,   r-   r8   r   Z
story_plotZstory_hypotheticalZstory_outcome_questionrR   r   Zget_noop_managerZon_textZ_outcome_tableZ	to_stringr_   rV   r`   Z_result_tableempty
ValueErrorfloatvaluesr   )r#   r3   r4   r(   Z	narrativeZstoryr[   Z_run_managerre   rT   outputr    r    r!   r;      sn    






zCPALChain._callNone)r(   r   c                 K  s   | j jjf i | dS )z
        CPAL chain can draw its resulting DAG.

        Usage in a jupyter notebook:

            >>> from IPython.display import SVG
            >>> cpal_chain.draw(path="graph.svg")
            >>> SVG('graph.svg')
        N)rR   Z_networkx_wrapperZdraw_graphviz)r#   r(   r    r    r!   draw%  s    
zCPALChain.draw)N)r   r<   r=   rD   r>   rM   rN   rO   rP   pydanticZPrivateAttrrR   r?   r0   r;   rn   r    r    r    r!   rL      s   
& WrL   )/rD   
__future__r   rc   typingr   r   r   r   r   r   ro   Zlangchain.base_languager	   Zlangchain.chains.baser
   Zlangchain.chains.llmr   Zlangchain.output_parsersr   Z langchain_core.callbacks.managerr   Zlangchain_core.prompts.promptr   Z%langchain_experimental.cpal.constantsr   Z"langchain_experimental.cpal.modelsr   r   r   r   r   Z7langchain_experimental.cpal.templates.univariate.causalr   rG   Z=langchain_experimental.cpal.templates.univariate.interventionrI   Z:langchain_experimental.cpal.templates.univariate.narrativerE   Z6langchain_experimental.cpal.templates.univariate.queryrK   r   rA   rF   rH   rJ   rL   r    r    r    r!   <module>   s,    D