"""Attempt to implement MRKL systems as described in arxiv.org/pdf/2205.00445.pdf."""from__future__importannotationsfromtypingimportAny,Callable,List,NamedTuple,Optional,Sequencefromlangchain_core._apiimportdeprecatedfromlangchain_core.callbacksimportBaseCallbackManagerfromlangchain_core.language_modelsimportBaseLanguageModelfromlangchain_core.promptsimportPromptTemplatefromlangchain_core.toolsimportBaseTool,Toolfromlangchain_core.tools.renderimportrender_text_descriptionfrompydanticimportFieldfromlangchain._api.deprecationimportAGENT_DEPRECATION_WARNINGfromlangchain.agents.agentimportAgent,AgentExecutor,AgentOutputParserfromlangchain.agents.agent_typesimportAgentTypefromlangchain.agents.mrkl.output_parserimportMRKLOutputParserfromlangchain.agents.mrkl.promptimportFORMAT_INSTRUCTIONS,PREFIX,SUFFIXfromlangchain.agents.utilsimportvalidate_tools_single_inputfromlangchain.chainsimportLLMChain
[docs]classChainConfig(NamedTuple):"""Configuration for a chain to use in MRKL system. Parameters: action_name: Name of the action. action: Action function to call. action_description: Description of the action. """action_name:straction:Callableaction_description:str
[docs]@deprecated("0.1.0",message=AGENT_DEPRECATION_WARNING,removal="1.0",)classZeroShotAgent(Agent):"""Agent for the MRKL chain. Parameters: output_parser: Output parser for the agent. """output_parser:AgentOutputParser=Field(default_factory=MRKLOutputParser)@classmethoddef_get_default_output_parser(cls,**kwargs:Any)->AgentOutputParser:returnMRKLOutputParser()@propertydef_agent_type(self)->str:"""Return Identifier of agent type."""returnAgentType.ZERO_SHOT_REACT_DESCRIPTION@propertydefobservation_prefix(self)->str:"""Prefix to append the observation with. Returns: "Observation: " """return"Observation: "@propertydefllm_prefix(self)->str:"""Prefix to append the llm call with. Returns: "Thought: " """return"Thought:"
[docs]@classmethoddefcreate_prompt(cls,tools:Sequence[BaseTool],prefix:str=PREFIX,suffix:str=SUFFIX,format_instructions:str=FORMAT_INSTRUCTIONS,input_variables:Optional[List[str]]=None,)->PromptTemplate:"""Create prompt in the style of the zero shot agent. Args: tools: List of tools the agent will have access to, used to format the prompt. prefix: String to put before the list of tools. Defaults to PREFIX. suffix: String to put after the list of tools. Defaults to SUFFIX. format_instructions: Instructions on how to use the tools. Defaults to FORMAT_INSTRUCTIONS input_variables: List of input variables the final prompt will expect. Defaults to None. Returns: A PromptTemplate with the template assembled from the pieces here. """tool_strings=render_text_description(list(tools))tool_names=", ".join([tool.namefortoolintools])format_instructions=format_instructions.format(tool_names=tool_names)template="\n\n".join([prefix,tool_strings,format_instructions,suffix])ifinput_variables:returnPromptTemplate(template=template,input_variables=input_variables)returnPromptTemplate.from_template(template)
[docs]@classmethoddeffrom_llm_and_tools(cls,llm:BaseLanguageModel,tools:Sequence[BaseTool],callback_manager:Optional[BaseCallbackManager]=None,output_parser:Optional[AgentOutputParser]=None,prefix:str=PREFIX,suffix:str=SUFFIX,format_instructions:str=FORMAT_INSTRUCTIONS,input_variables:Optional[List[str]]=None,**kwargs:Any,)->Agent:"""Construct an agent from an LLM and tools. Args: llm: The LLM to use as the agent LLM. tools: The tools to use. callback_manager: The callback manager to use. Defaults to None. output_parser: The output parser to use. Defaults to None. prefix: The prefix to use. Defaults to PREFIX. suffix: The suffix to use. Defaults to SUFFIX. format_instructions: The format instructions to use. Defaults to FORMAT_INSTRUCTIONS. input_variables: The input variables to use. Defaults to None. kwargs: Additional parameters to pass to the agent. """cls._validate_tools(tools)prompt=cls.create_prompt(tools,prefix=prefix,suffix=suffix,format_instructions=format_instructions,input_variables=input_variables,)llm_chain=LLMChain(# type: ignore[misc]llm=llm,prompt=prompt,callback_manager=callback_manager,)tool_names=[tool.namefortoolintools]_output_parser=output_parserorcls._get_default_output_parser()returncls(llm_chain=llm_chain,allowed_tools=tool_names,output_parser=_output_parser,**kwargs,)
@classmethoddef_validate_tools(cls,tools:Sequence[BaseTool])->None:validate_tools_single_input(cls.__name__,tools)iflen(tools)==0:raiseValueError(f"Got no tools for {cls.__name__}. At least one tool must be provided.")fortoolintools:iftool.descriptionisNone:raiseValueError(f"Got a tool {tool.name} without a description. For this agent, "f"a description must always be provided.")super()._validate_tools(tools)
[docs]@deprecated("0.1.0",message=AGENT_DEPRECATION_WARNING,removal="1.0",)classMRKLChain(AgentExecutor):"""Chain that implements the MRKL system."""
[docs]@classmethoddeffrom_chains(cls,llm:BaseLanguageModel,chains:List[ChainConfig],**kwargs:Any)->AgentExecutor:"""User-friendly way to initialize the MRKL chain. This is intended to be an easy way to get up and running with the MRKL chain. Args: llm: The LLM to use as the agent LLM. chains: The chains the MRKL system has access to. **kwargs: parameters to be passed to initialization. Returns: An initialized MRKL chain. """tools=[Tool(name=c.action_name,func=c.action,description=c.action_description,)forcinchains]agent=ZeroShotAgent.from_llm_and_tools(llm,tools)returncls(agent=agent,tools=tools,**kwargs)