"""Chain that implements the ReAct paper from https://arxiv.org/pdf/2210.03629.pdf."""from__future__importannotationsfromtypingimportTYPE_CHECKING,Any,List,Optional,Sequencefromlangchain_core._apiimportdeprecatedfromlangchain_core.documentsimportDocumentfromlangchain_core.language_modelsimportBaseLanguageModelfromlangchain_core.promptsimportBasePromptTemplatefromlangchain_core.toolsimportBaseTool,ToolfrompydanticimportFieldfromlangchain._api.deprecationimportAGENT_DEPRECATION_WARNINGfromlangchain.agents.agentimportAgent,AgentExecutor,AgentOutputParserfromlangchain.agents.agent_typesimportAgentTypefromlangchain.agents.react.output_parserimportReActOutputParserfromlangchain.agents.react.textworld_promptimportTEXTWORLD_PROMPTfromlangchain.agents.react.wiki_promptimportWIKI_PROMPTfromlangchain.agents.utilsimportvalidate_tools_single_inputifTYPE_CHECKING:fromlangchain_community.docstore.baseimportDocstore
[docs]@deprecated("0.1.0",message=AGENT_DEPRECATION_WARNING,removal="1.0",)classReActDocstoreAgent(Agent):"""Agent for the ReAct chain."""output_parser:AgentOutputParser=Field(default_factory=ReActOutputParser)@classmethoddef_get_default_output_parser(cls,**kwargs:Any)->AgentOutputParser:returnReActOutputParser()@propertydef_agent_type(self)->str:"""Return Identifier of an agent type."""returnAgentType.REACT_DOCSTORE
@classmethoddef_validate_tools(cls,tools:Sequence[BaseTool])->None:validate_tools_single_input(cls.__name__,tools)super()._validate_tools(tools)iflen(tools)!=2:raiseValueError(f"Exactly two tools must be specified, but got {tools}")tool_names={tool.namefortoolintools}iftool_names!={"Lookup","Search"}:raiseValueError(f"Tool names should be Lookup and Search, got {tool_names}")@propertydefobservation_prefix(self)->str:"""Prefix to append the observation with."""return"Observation: "@propertydef_stop(self)->List[str]:return["\nObservation:"]@propertydefllm_prefix(self)->str:"""Prefix to append the LLM call with."""return"Thought:"
[docs]@deprecated("0.1.0",message=AGENT_DEPRECATION_WARNING,removal="1.0",)classDocstoreExplorer:"""Class to assist with exploration of a document store."""
[docs]def__init__(self,docstore:Docstore):"""Initialize with a docstore, and set initial document to None."""self.docstore=docstoreself.document:Optional[Document]=Noneself.lookup_str=""self.lookup_index=0
[docs]defsearch(self,term:str)->str:"""Search for a term in the docstore, and if found save."""result=self.docstore.search(term)ifisinstance(result,Document):self.document=resultreturnself._summaryelse:self.document=Nonereturnresult
[docs]deflookup(self,term:str)->str:"""Lookup a term in document (if saved)."""ifself.documentisNone:raiseValueError("Cannot lookup without a successful search first")ifterm.lower()!=self.lookup_str:self.lookup_str=term.lower()self.lookup_index=0else:self.lookup_index+=1lookups=[pforpinself._paragraphsifself.lookup_strinp.lower()]iflen(lookups)==0:return"No Results"elifself.lookup_index>=len(lookups):return"No More Results"else:result_prefix=f"(Result {self.lookup_index+1}/{len(lookups)})"returnf"{result_prefix}{lookups[self.lookup_index]}"
@propertydef_summary(self)->str:returnself._paragraphs[0]@propertydef_paragraphs(self)->List[str]:ifself.documentisNone:raiseValueError("Cannot get paragraphs without a document")returnself.document.page_content.split("\n\n")
[docs]@deprecated("0.1.0",message=AGENT_DEPRECATION_WARNING,removal="1.0",)classReActTextWorldAgent(ReActDocstoreAgent):"""Agent for the ReAct TextWorld chain."""
@classmethoddef_validate_tools(cls,tools:Sequence[BaseTool])->None:validate_tools_single_input(cls.__name__,tools)super()._validate_tools(tools)iflen(tools)!=1:raiseValueError(f"Exactly one tool must be specified, but got {tools}")tool_names={tool.namefortoolintools}iftool_names!={"Play"}:raiseValueError(f"Tool name should be Play, got {tool_names}")
[docs]@deprecated("0.1.0",message=AGENT_DEPRECATION_WARNING,removal="1.0",)classReActChain(AgentExecutor):"""[Deprecated] Chain that implements the ReAct paper."""def__init__(self,llm:BaseLanguageModel,docstore:Docstore,**kwargs:Any):"""Initialize with the LLM and a docstore."""docstore_explorer=DocstoreExplorer(docstore)tools=[Tool(name="Search",func=docstore_explorer.search,description="Search for a term in the docstore.",),Tool(name="Lookup",func=docstore_explorer.lookup,description="Lookup a term in the docstore.",),]agent=ReActDocstoreAgent.from_llm_and_tools(llm,tools)super().__init__(agent=agent,tools=tools,**kwargs)