a
    •˜ëjà   ã                   @  sX  d Z ddlmZ ddlmZ ddl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m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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& e�rddl'm(Z( ddl)m*Z* ddl+m,Z, e
dddd�G dd„ deƒƒZ-e
ddd�G dd„ deƒƒZ.ddd d!d"œd#d$„Z/d%S )&z%Chain that does self-ask with search.é    )Úannotations)ÚSequence)ÚTYPE_CHECKINGÚAnyÚUnion)Ú
deprecated)ÚBaseLanguageModel)ÚBasePromptTemplate)ÚRunnableÚRunnablePassthrough)ÚBaseToolÚTool)ÚField)Úoverride)ÚAgentÚAgentExecutorÚAgentOutputParser)Ú	AgentType©Úformat_log_to_str©ÚSelfAskOutputParser©ÚPROMPT)Úvalidate_tools_single_input)ÚGoogleSerperAPIWrapper)ÚSearchApiAPIWrapper)ÚSerpAPIWrapperz0.1.0Zcreate_self_ask_with_searchz1.0)ÚalternativeÚremovalc                      s¦   e Zd ZU dZeed�Zded< ee	dddœdd„ƒƒZ
ed	d
œdd„ƒZee	dddœdd„ƒƒZedddœ‡ fdd„ƒZed	d
œdd„ƒZed	d
œdd„ƒZ‡  ZS )ÚSelfAskWithSearchAgentz)Agent for the self-ask-with-search paper.)Údefault_factoryr   Úoutput_parserr   )ÚkwargsÚreturnc                 K  s   t ƒ S )Nr   )Úclsr#   © r&   úi/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain/agents/self_ask_with_search/base.pyÚ_get_default_output_parser#   s    z1SelfAskWithSearchAgent._get_default_output_parserÚstr)r$   c                 C  s   t jS )z#Return Identifier of an agent type.)r   ZSELF_ASK_WITH_SEARCH©Úselfr&   r&   r'   Ú_agent_type(   s    z"SelfAskWithSearchAgent._agent_typeúSequence[BaseTool]r	   )Útoolsr$   c                 C  s   t S )z Prompt does not depend on tools.r   )r%   r.   r&   r&   r'   Úcreate_prompt-   s    z$SelfAskWithSearchAgent.create_promptÚNonec                   sd   t | j|ƒ tƒ  |¡ t|ƒdkr6d|› �}t|ƒ‚dd„ |D ƒ}|dhkr`d|› �}t|ƒ‚d S )Né   z,Exactly one tool must be specified, but got c                 S  s   h | ]
}|j ’qS r&   )Úname)Ú.0Útoolr&   r&   r'   Ú	<setcomp>:   ó    z9SelfAskWithSearchAgent._validate_tools.<locals>.<setcomp>úIntermediate Answerz-Tool name should be Intermediate Answer, got )r   Ú__name__ÚsuperÚ_validate_toolsÚlenÚ
ValueError)r%   r.   ÚmsgZ
tool_names©Ú	__class__r&   r'   r:   3   s    


z&SelfAskWithSearchAgent._validate_toolsc                 C  s   dS )z&Prefix to append the observation with.zIntermediate answer: r&   r*   r&   r&   r'   Úobservation_prefix?   s    z)SelfAskWithSearchAgent.observation_prefixc                 C  s   dS )z#Prefix to append the LLM call with.Ú r&   r*   r&   r&   r'   Ú
llm_prefixD   s    z!SelfAskWithSearchAgent.llm_prefix)r8   Ú
__module__Ú__qualname__Ú__doc__r   r   r"   Ú__annotations__Úclassmethodr   r(   Úpropertyr,   r/   r:   r@   rB   Ú__classcell__r&   r&   r>   r'   r       s    
r    )r   c                      s*   e Zd ZdZddddœ‡ fdd„Z‡  ZS )ÚSelfAskWithSearchChainz2[Deprecated] Chain that does self-ask with search.r   zBUnion[GoogleSerperAPIWrapper, SearchApiAPIWrapper, SerpAPIWrapper]r   )ÚllmÚsearch_chainr#   c                   s@   t d|j|jdd�}t ||g¡}tƒ jf ||gdœ|¤Ž dS )z/Initialize only with an LLM and a search chain.r7   ZSearch)r2   ÚfuncÚ	coroutineÚdescription)Úagentr.   N)r   ÚrunZarunr    Zfrom_llm_and_toolsr9   Ú__init__)r+   rK   rL   r#   Zsearch_toolrP   r>   r&   r'   rR   N   s    üzSelfAskWithSearchChain.__init__)r8   rC   rD   rE   rR   rI   r&   r&   r>   r'   rJ   J   s   rJ   r   r-   r	   r
   )rK   r.   Úpromptr$   c                 C  sš   dh  |jt|jƒ ¡}|r.d|› �}t|ƒ‚t|ƒdkrFd}t|ƒ‚tt|ƒƒ}|jdkrhd}t|ƒ‚| j	dgd�}t
jd	d
„ dd
„ d�|B |B tƒ B S )a¾  Create an agent that uses self-ask with search prompting.

    Args:
        llm: LLM to use as the agent.
        tools: List of tools. Should just be of length 1, with that tool having
            name `Intermediate Answer`
        prompt: The prompt to use, must have input key `agent_scratchpad` which will
            contain agent actions and tool outputs.

    Returns:
        A Runnable sequence representing an agent. It takes as input all the same input
        variables as the prompt passed in does. It returns as output either an
        AgentAction or AgentFinish.

    Examples:

        .. code-block:: python

            from langchain import hub
            from langchain_community.chat_models import ChatAnthropic
            from langchain.agents import (
                AgentExecutor,
                create_self_ask_with_search_agent,
            )

            prompt = hub.pull("hwchase17/self-ask-with-search")
            model = ChatAnthropic(model="claude-3-haiku-20240307")
            tools = [...]  # Should just be one tool with name `Intermediate Answer`

            agent = create_self_ask_with_search_agent(model, tools, prompt)
            agent_executor = AgentExecutor(agent=agent, tools=tools)

            agent_executor.invoke({"input": "hi"})

    Prompt:

        The prompt must have input key `agent_scratchpad` which will
            contain agent actions and tool outputs as a string.

        Here's an example:

        .. code-block:: python

            from langchain_core.prompts import PromptTemplate

            template = '''Question: Who lived longer, Muhammad Ali or Alan Turing?
            Are follow up questions needed here: Yes.
            Follow up: How old was Muhammad Ali when he died?
            Intermediate answer: Muhammad Ali was 74 years old when he died.
            Follow up: How old was Alan Turing when he died?
            Intermediate answer: Alan Turing was 41 years old when he died.
            So the final answer is: Muhammad Ali

            Question: When was the founder of craigslist born?
            Are follow up questions needed here: Yes.
            Follow up: Who was the founder of craigslist?
            Intermediate answer: Craigslist was founded by Craig Newmark.
            Follow up: When was Craig Newmark born?
            Intermediate answer: Craig Newmark was born on December 6, 1952.
            So the final answer is: December 6, 1952

            Question: Who was the maternal grandfather of George Washington?
            Are follow up questions needed here: Yes.
            Follow up: Who was the mother of George Washington?
            Intermediate answer: The mother of George Washington was Mary Ball Washington.
            Follow up: Who was the father of Mary Ball Washington?
            Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
            So the final answer is: Joseph Ball

            Question: Are both the directors of Jaws and Casino Royale from the same country?
            Are follow up questions needed here: Yes.
            Follow up: Who is the director of Jaws?
            Intermediate answer: The director of Jaws is Steven Spielberg.
            Follow up: Where is Steven Spielberg from?
            Intermediate answer: The United States.
            Follow up: Who is the director of Casino Royale?
            Intermediate answer: The director of Casino Royale is Martin Campbell.
            Follow up: Where is Martin Campbell from?
            Intermediate answer: New Zealand.
            So the final answer is: No

            Question: {input}
            Are followup questions needed here:{agent_scratchpad}'''

            prompt = PromptTemplate.from_template(template)

    Úagent_scratchpadz#Prompt missing required variables: r1   z#This agent expects exactly one toolr7   z=This agent expects the tool to be named `Intermediate Answer`z
Intermediate answer:)Ústopc                 S  s   t | d ddd�S )NZintermediate_stepsz
Intermediate answer: rA   )r@   rB   r   ©Úxr&   r&   r'   Ú<lambda>Ñ   s   ýz3create_self_ask_with_search_agent.<locals>.<lambda>c                 S  s   |   dd¡S )NÚchat_historyrA   )ÚgetrV   r&   r&   r'   rX   ×   r6   )rT   rY   )Ú
differenceZinput_variablesÚlistZpartial_variablesr<   r;   ÚnextÚiterr2   Úbindr   Zassignr   )rK   r.   rS   Zmissing_varsr=   r4   Zllm_with_stopr&   r&   r'   Ú!create_self_ask_with_search_agentc   s2    \ÿ

ù	÷
öõÿr`   N)0rE   Ú
__future__r   Úcollections.abcr   Útypingr   r   r   Zlangchain_core._apir   Zlangchain_core.language_modelsr   Zlangchain_core.promptsr	   Zlangchain_core.runnablesr
   r   Zlangchain_core.toolsr   r   Zpydanticr   Ztyping_extensionsr   Zlangchain.agents.agentr   r   r   Zlangchain.agents.agent_typesr   Z"langchain.agents.format_scratchpadr   Z3langchain.agents.self_ask_with_search.output_parserr   Z,langchain.agents.self_ask_with_search.promptr   Zlangchain.agents.utilsr   Z+langchain_community.utilities.google_serperr   Z'langchain_community.utilities.searchapir   Z%langchain_community.utilities.serpapir   r    rJ   r`   r&   r&   r&   r'   Ú<module>   s2   ,
