a
    bgA                     @   s*  d Z ddlZddlZddlmZ ddlmZmZ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mZ ddlmZmZ dd	lmZ dd
lmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 dZ5e
d Z6eedddZ7eeg ef dddZ8G dd de2eZ9G dd de2eZ:G dd de2eZ;G dd de2eZ<G dd de2eZ=e.eed d!d"Z>e?e?e4ee@ee6 ed#d$d%ZAe.e4ee@ee6 ed&d'd(ZBd/e.e4eee ee e@eee?ef  e@ee6 eed,d-d.ZCdS )0zLAgent that interacts with OpenAPI APIs via a hierarchical planning approach.    N)partial)AnyCallableDictListLiteralOptionalSequencecast)BaseCallbackManager)BaseLanguageModel)BasePromptTemplatePromptTemplate)BaseToolTool)Field)API_CONTROLLER_PROMPTAPI_CONTROLLER_TOOL_DESCRIPTIONAPI_CONTROLLER_TOOL_NAMEAPI_ORCHESTRATOR_PROMPTAPI_PLANNER_PROMPTAPI_PLANNER_TOOL_DESCRIPTIONAPI_PLANNER_TOOL_NAMEPARSING_DELETE_PROMPTPARSING_GET_PROMPTPARSING_PATCH_PROMPTPARSING_POST_PROMPTPARSING_PUT_PROMPT REQUESTS_DELETE_TOOL_DESCRIPTIONREQUESTS_GET_TOOL_DESCRIPTIONREQUESTS_PATCH_TOOL_DESCRIPTIONREQUESTS_POST_TOOL_DESCRIPTIONREQUESTS_PUT_TOOL_DESCRIPTION)ReducedOpenAPISpec)OpenAI)BaseRequestsTool)RequestsWrapperi  )GETPOSTPUTDELETEPATCH)promptreturnc                 C   s   ddl m} |t | dS )Nr   LLMChainllmr,   )langchain.chains.llmr/   r$   )r,   r/    r3   /var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/agent_toolkits/openapi/planner.py_get_default_llm_chain3   s
    r5   c                 C   s
   t t| S )z#Returns a default LLMChain factory.)r   r5   )r,   r3   r3   r4   _get_default_llm_chain_factory<   s    r6   c                   @   sl   e Zd ZU dZdZeed< eZeed< e	Z
eed< eeedZeed< eedd	d
ZeedddZdS )RequestsGetToolWithParsingzHRequests GET tool with LLM-instructed extraction of truncated responses.Zrequests_getnamedescriptionresponse_lengthdefault_factory	llm_chaintextr-   c              
   C   s   ddl m} z||}W n* tjyB } z|W Y d }~n
d }~0 0 |d}tt| jj|d |d}|d | j }| j	j
||d d S )Nr   parse_json_markdownparamsurl)rB   output_instructionsresponseZinstructions)langchain.output_parsers.jsonrA   jsonJSONDecodeErrorgetr
   strrequests_wrapperr:   r=   predictstrip)selfr?   rA   dataeZdata_paramsrF   r3   r3   r4   _runQ   s    
zRequestsGetToolWithParsing._runc                    s
   t  d S NNotImplementedErrorrO   r?   r3   r3   r4   _aruna   s    z RequestsGetToolWithParsing._arunN)__name__
__module____qualname____doc__r8   rK   __annotations__r   r9   MAX_RESPONSE_LENGTHr:   intr   r6   r   r=   r   rR   rW   r3   r3   r3   r4   r7   C   s   
r7   c                   @   sl   e Zd ZU dZdZeed< eZeed< e	Z
eed< eeedZeed< eedd	d
ZeedddZdS )RequestsPostToolWithParsingzIRequests POST tool with LLM-instructed extraction of truncated responses.Zrequests_postr8   r9   r:   r;   r=   r>   c              
   C   s   ddl m} z||}W n* tjyB } z|W Y d }~n
d }~0 0 tt| j|d |d }|d | j }| j	j
||d d S Nr   r@   rC   rP   rD   rE   )rG   rA   rH   rI   r
   rK   rL   postr:   r=   rM   rN   rO   r?   rA   rP   rQ   rF   r3   r3   r4   rR   s   s    z RequestsPostToolWithParsing._runc                    s
   t  d S rS   rT   rV   r3   r3   r4   rW      s    z!RequestsPostToolWithParsing._arunN)rX   rY   rZ   r[   r8   rK   r\   r!   r9   r]   r:   r^   r   r6   r   r=   r   rR   rW   r3   r3   r3   r4   r_   e   s   
r_   c                   @   sl   e Zd ZU dZdZeed< eZeed< e	Z
eed< eeedZeed< eedd	d
ZeedddZdS )RequestsPatchToolWithParsingzJRequests PATCH tool with LLM-instructed extraction of truncated responses.Zrequests_patchr8   r9   r:   r;   r=   r>   c              
   C   s   ddl m} z||}W n* tjyB } z|W Y d }~n
d }~0 0 tt| j|d |d }|d | j }| j	j
||d d S r`   )rG   rA   rH   rI   r
   rK   rL   patchr:   r=   rM   rN   rb   r3   r3   r4   rR      s    z!RequestsPatchToolWithParsing._runc                    s
   t  d S rS   rT   rV   r3   r3   r4   rW      s    z"RequestsPatchToolWithParsing._arunN)rX   rY   rZ   r[   r8   rK   r\   r    r9   r]   r:   r^   r   r6   r   r=   r   rR   rW   r3   r3   r3   r4   rc      s   
rc   c                   @   sl   e Zd ZU dZdZeed< eZeed< e	Z
eed< eeedZeed< eedd	d
ZeedddZdS )RequestsPutToolWithParsingzHRequests PUT tool with LLM-instructed extraction of truncated responses.Zrequests_putr8   r9   r:   r;   r=   r>   c              
   C   s   ddl m} z||}W n* tjyB } z|W Y d }~n
d }~0 0 tt| j|d |d }|d | j }| j	j
||d d S r`   )rG   rA   rH   rI   r
   rK   rL   putr:   r=   rM   rN   rb   r3   r3   r4   rR      s    zRequestsPutToolWithParsing._runc                    s
   t  d S rS   rT   rV   r3   r3   r4   rW      s    z RequestsPutToolWithParsing._arunN)rX   rY   rZ   r[   r8   rK   r\   r"   r9   r]   r:   r^   r   r6   r   r=   r   rR   rW   r3   r3   r3   r4   re      s   
re   c                   @   sp   e Zd ZU dZdZeed< eZeed< e	Z
ee ed< eeedZeed< eedd	d
ZeedddZdS )RequestsDeleteToolWithParsingz9Tool that sends a DELETE request and parses the response.Zrequests_deleter8   r9   r:   r;   r=   r>   c              
   C   s   ddl m} z||}W n* tjyB } z|W Y d }~n
d }~0 0 tt| j|d }|d | j }| j	j
||d d S )Nr   r@   rC   rD   rE   )rG   rA   rH   rI   r
   rK   rL   deleter:   r=   rM   rN   rb   r3   r3   r4   rR      s    z"RequestsDeleteToolWithParsing._runc                    s
   t  d S rS   rT   rV   r3   r3   r4   rW      s    z#RequestsDeleteToolWithParsing._arunN)rX   rY   rZ   r[   r8   rK   r\   r   r9   r]   r:   r   r^   r   r6   r   r=   r   rR   rW   r3   r3   r3   r4   rg      s   
rg   )api_specr1   r-   c                 C   sZ   ddl m} dd | jD }ttdgddd| id}|||d	}ttt|j	d
}|S )Nr   r.   c                 S   s    g | ]\}}}| d | qS ) r3   ).0r8   r9   _r3   r3   r4   
<listcomp>   s   z,_create_api_planner_tool.<locals>.<listcomp>query	endpointsz- templateZinput_variablesZpartial_variablesr0   )r8   r9   func)
r2   r/   ro   r   r   joinr   r   r   run)ri   r1   r/   Zendpoint_descriptionsr,   chaintoolr3   r3   r4   _create_api_planner_tool   s     rw   )api_urlapi_docsrL   r1   allow_dangerous_requestsallowed_operationsr-   c              
   C   sf  ddl m} ddlm} ddlm} g }	d|v rP||td}
|	t||
|d d|v rx||t	d}|	t
|||d d	|v r||td}|	t|||d d
|v r||td}|	t|||d d|v r||td}|	t|||d |	stdttddg| |ddd |	D ddd |	D dd}||||ddd |	D d}|j||	ddS )Nr   AgentExecutorZeroShotAgentr.   r'   r0   )rL   r=   rz   r(   r)   r*   r+   zTools not foundinputagent_scratchpad, c                 S   s   g | ]
}|j qS r3   r8   rk   rv   r3   r3   r4   rm   ?      z0_create_api_controller_agent.<locals>.<listcomp>
c                 S   s   g | ]}|j  d |j qS z: r8   r9   r   r3   r3   r4   rm   A  r   )rx   ry   
tool_namestool_descriptionsrp   c                 S   s   g | ]
}|j qS r3   r   r   r3   r3   r4   rm   G  r   r=   Zallowed_toolsT)agenttoolsverbose)langchain.agents.agentr}   langchain.agents.mrkl.baser   r2   r/   r   appendr7   r   r_   r   re   r   rg   r   rc   
ValueErrorr   r   rs   from_agent_and_tools)rx   ry   rL   r1   rz   r{   r}   r   r/   r   Zget_llm_chainZpost_llm_chainZput_llm_chainZdelete_llm_chainZpatch_llm_chainr,   r   r3   r3   r4   _create_api_controller_agent   s    
r   )ri   rL   r1   rz   r{   r-   c                    s:   j d d ttd fdd}tt|tdS )zExpose controller as a tool.

    The tool is invoked with a plan from the planner, and dynamically
    creates a controller agent with relevant documentation only to
    constrain the context.
    r   rC   )plan_strr-   c              	      s   d}t || }dd |D }d}|D ]j}d}jD ]H\}}}	t t dd|}
|
|r4d}|d	| d
t|	 d7 }q4|s&t| dq&t	| }|
| S )Nz'\b(GET|POST|PATCH|DELETE|PUT)\s+(/\S+)*c                 S   s(   g | ] \}}d j ||dd dqS )z{method} {route}?r   )methodroute)formatsplit)rk   r   r   r3   r3   r4   rm   _  s   z]_create_api_controller_tool.<locals>._create_and_run_api_controller_agent.<locals>.<listcomp> Fz\{.*?\}z.*Tz== Docs for z == 
r   z endpoint does not exist.)refindallro   compilesubmatchyamldumpr   r   rt   )r   patternmatchesZendpoint_namesZdocs_strZendpoint_namefound_matchr8   rl   docsZ
regex_namer   rz   r{   ri   base_urlr1   rL   r3   r4   $_create_and_run_api_controller_agent\  s0    
zI_create_api_controller_tool.<locals>._create_and_run_api_controller_agent)r8   rr   r9   )ZserversrK   r   r   r   )ri   rL   r1   rz   r{   r   r3   r   r4   _create_api_controller_toolL  s    r   TFr'   r(   )ri   rL   r1   shared_memorycallback_managerr   agent_executor_kwargsrz   r{   kwargsr-   c	                 K   s   ddl m}
 ddlm} ddlm} t| |t| ||||g}tt	ddgd
dd	 |D d

dd	 |D dd}|f ||||ddd	 |D d|	}|
jf ||||d|pi S )a  Construct an OpenAI API planner and controller for a given spec.

    Inject credentials via requests_wrapper.

    We use a top-level "orchestrator" agent to invoke the planner and controller,
    rather than a top-level planner
    that invokes a controller with its plan. This is to keep the planner simple.

    You need to set allow_dangerous_requests to True to use Agent with BaseRequestsTool.
    Requests can be dangerous and can lead to security vulnerabilities.
    For example, users can ask a server to make a request to an internal
    server. It's recommended to use requests through a proxy server
    and avoid accepting inputs from untrusted sources without proper sandboxing.
    Please see: https://python.langchain.com/docs/security
    for further security information.

    Args:
        api_spec: The OpenAPI spec.
        requests_wrapper: The requests wrapper.
        llm: The language model.
        shared_memory: Optional. The shared memory. Default is None.
        callback_manager: Optional. The callback manager. Default is None.
        verbose: Optional. Whether to print verbose output. Default is True.
        agent_executor_kwargs: Optional. Additional keyword arguments
            for the agent executor.
        allow_dangerous_requests: Optional. Whether to allow dangerous requests.
            Default is False.
        allowed_operations: Optional. The allowed operations.
            Default is ("GET", "POST").
        kwargs: Additional arguments.

    Returns:
        The agent executor.
    r   r|   r~   r.   r   r   r   c                 S   s   g | ]
}|j qS r3   r   r   r3   r3   r4   rm     r   z(create_openapi_agent.<locals>.<listcomp>r   c                 S   s   g | ]}|j  d |j qS r   r   r   r3   r3   r4   rm     r   )r   r   rp   )r1   r,   Zmemoryc                 S   s   g | ]
}|j qS r3   r   r   r3   r3   r4   rm     r   r   )r   r   r   r   )r   r}   r   r   r2   r/   rw   r   r   r   rs   r   )ri   rL   r1   r   r   r   r   rz   r{   r   r}   r   r/   r   r,   r   r3   r3   r4   create_openapi_agent  sF    .

r   )NNTNFr   )Dr[   rH   r   	functoolsr   typingr   r   r   r   r   r   r	   r
   r   Zlangchain_core.callbacksr   Zlangchain_core.language_modelsr   Zlangchain_core.promptsr   r   Zlangchain_core.toolsr   r   Zpydanticr   Z9langchain_community.agent_toolkits.openapi.planner_promptr   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   Z/langchain_community.agent_toolkits.openapi.specr#   Zlangchain_community.llmsr$   Z'langchain_community.tools.requests.toolr%   Z&langchain_community.utilities.requestsr&   r]   Z	Operationr5   r6   r7   r_   rc   re   rg   rw   rK   boolr   r   r   r3   r3   r3   r4   <module>   s~   (L

"!$P7      