o
    ZhA                     @   sj  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Z5	 e
d Z6dedefddZ7dedeg ef f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=d!e.d"edefd#d$Z>d%e?d&e?d'e4d"ed(e@d)ee6 defd*d+ZAd!e.d'e4d"ed(e@d)ee6 defd,d-ZB			.		/	0d8d!e.d'e4d"ed1ee d2ee d3e@d4eee?ef  d(e@d)ee6 d5edefd6d7ZCdS )9zLAgent 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   i/var/www/html/lang_env/lib/python3.10/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                   @   x   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< 	 ded	efd
dZded	ef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y } z|d }~ww |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                       t  NNotImplementedErrorrO   r?   r3   r3   r4   _aruna      z RequestsGetToolWithParsing._arunN)__name__
__module____qualname____doc__r9   rK   __annotations__r   r:   MAX_RESPONSE_LENGTHr;   intr   r6   r   r>   r   rR   rX   r3   r3   r3   r4   r8   C   s   
 r8   c                   @   r7   )RequestsPostToolWithParsingzIRequests POST tool with LLM-instructed extraction of truncated responses.Zrequests_postr9   r:   r;   r<   r>   r?   r-   c              
   C   z   ddl m} z||}W n tjy } z|d }~ww 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      z RequestsPostToolWithParsing._runc                    rS   rT   rU   rW   r3   r3   r4   rX      rY   z!RequestsPostToolWithParsing._arunN)rZ   r[   r\   r]   r9   rK   r^   r!   r:   r_   r;   r`   r   r6   r   r>   r   rR   rX   r3   r3   r3   r4   ra   e      
 ra   c                   @   r7   )RequestsPatchToolWithParsingzJRequests PATCH tool with LLM-instructed extraction of truncated responses.Zrequests_patchr9   r:   r;   r<   r>   r?   r-   c              
   C   rb   rc   )rG   rA   rH   rI   r
   rK   rL   patchr;   r>   rM   rN   re   r3   r3   r4   rR      s    z!RequestsPatchToolWithParsing._runc                    rS   rT   rU   rW   r3   r3   r4   rX      rY   z"RequestsPatchToolWithParsing._arunN)rZ   r[   r\   r]   r9   rK   r^   r    r:   r_   r;   r`   r   r6   r   r>   r   rR   rX   r3   r3   r3   r4   rh      s   
 rh   c                   @   r7   )RequestsPutToolWithParsingzHRequests PUT tool with LLM-instructed extraction of truncated responses.Zrequests_putr9   r:   r;   r<   r>   r?   r-   c              
   C   rb   rc   )rG   rA   rH   rI   r
   rK   rL   putr;   r>   rM   rN   re   r3   r3   r4   rR      rf   zRequestsPutToolWithParsing._runc                    rS   rT   rU   rW   r3   r3   r4   rX      rY   z RequestsPutToolWithParsing._arunN)rZ   r[   r\   r]   r9   rK   r^   r"   r:   r_   r;   r`   r   r6   r   r>   r   rR   rX   r3   r3   r3   r4   rj      rg   rj   c                   @   s|   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< 	 ded	efd
dZded	efddZdS )RequestsDeleteToolWithParsingz9Tool that sends a DELETE request and parses the response.Zrequests_deleter9   r:   r;   r<   r>   r?   r-   c              
   C   st   ddl m} z||}W n tjy } z|d }~ww 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   re   r3   r3   r4   rR      s   z"RequestsDeleteToolWithParsing._runc                    rS   rT   rU   rW   r3   r3   r4   rX      rY   z#RequestsDeleteToolWithParsing._arunN)rZ   r[   r\   r]   r9   rK   r^   r   r:   r_   r;   r   r`   r   r6   r   r>   r   rR   rX   r3   r3   r3   r4   rl      s   
 rl   api_specr1   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   ).0r9   r:   _r3   r3   r4   
<listcomp>   s    z,_create_api_planner_tool.<locals>.<listcomp>query	endpointsz- templateZinput_variablesZpartial_variablesr0   )r9   r:   func)
r2   r/   rt   r   r   joinr   r   r   run)rn   r1   r/   Zendpoint_descriptionsr,   chaintoolr3   r3   r4   _create_api_planner_tool   s    r|   api_urlapi_docsrL   allow_dangerous_requestsallowed_operationsc              
   C   sf  ddl m} ddlm} ddlm} g }	d|v r(||td}
|	t||
|d d|v r<||t	d}|	t
|||d d	|v rP||td}|	t|||d d
|v rd||td}|	t|||d d|v rx||td}|	t|||d |	s~t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>   r   r(   r)   r*   r+   zTools not foundinputagent_scratchpad, c                 S      g | ]}|j qS r3   r9   rp   r{   r3   r3   r4   rr   ?      z0_create_api_controller_agent.<locals>.<listcomp>
c                 S      g | ]}|j  d |j qS z: r9   r:   r   r3   r3   r4   rr   A      )r}   r~   
tool_namestool_descriptionsru   c                 S   r   r3   r   r   r3   r3   r4   rr   G  r   r>   Zallowed_toolsT)agenttoolsverbose)langchain.agents.agentr   langchain.agents.mrkl.baser   r2   r/   r   appendr8   r   ra   r   rj   r   rl   r   rh   
ValueErrorr   r   rx   from_agent_and_tools)r}   r~   rL   r1   r   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   c                    s<   j d d dtdtf 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 ]5}d}jD ]$\}}}	t t dd|}
|
|r>d}|d	| d
t|	 d7 }q|sHt| 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)rp   r   r   r3   r3   r4   rr   _  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findallrt   compilesubmatchyamldumpr   r   ry   )r   patternmatchesZendpoint_namesZdocs_strZendpoint_namefound_matchr9   rq   docsZ
regex_namer   r   r   rn   base_urlr1   rL   r3   r4   $_create_and_run_api_controller_agent\  s4   

zI_create_api_controller_tool.<locals>._create_and_run_api_controller_agent)r9   rw   r:   )ZserversrK   r   r   r   )rn   rL   r1   r   r   r   r3   r   r4   _create_api_controller_toolL  s    r   TFr'   r(   shared_memorycallback_managerr   agent_executor_kwargskwargsc	                 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}|d||||ddd	 |D d|	}|
jd||||d|p[i 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   r   r3   r   r   r3   r3   r4   rr     r   z(create_openapi_agent.<locals>.<listcomp>r   c                 S   r   r   r   r   r3   r3   r4   rr     r   )r   r   ru   )r1   r,   Zmemoryc                 S   r   r3   r   r   r3   r3   r4   rr     r   r   )r   r   r   r   Nr3   )r   r   r   r   r2   r/   r|   r   r   r   rx   r   )rn   rL   r1   r   r   r   r   r   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   r8   ra   rh   rj   rl   r|   rK   boolr   r   r   r3   r3   r3   r4   <module>   s    (L	

"!#

O
7	
