[docs]classToTChain(Chain):""" Chain implementing the Tree of Thought (ToT). """llm:BaseLanguageModel""" Language model to use. It must be set to produce different variations for the same prompt. """checker:ToTChecker"""ToT Checker to use."""output_key:str="response"#: :meta private:k:int=10"""The maximum number of conversation rounds"""c:int=3"""The number of children to explore at each node"""tot_memory:ToTDFSMemory=ToTDFSMemory()tot_controller:ToTController=ToTController()tot_strategy_class:Type[BaseThoughtGenerationStrategy]=ProposePromptStrategyverbose_llm:bool=Falsemodel_config=ConfigDict(arbitrary_types_allowed=True,extra="forbid",)
[docs]@classmethoddeffrom_llm(cls,llm:BaseLanguageModel,**kwargs:Any)->ToTChain:""" Create a ToTChain from a language model. :param llm: The language model to use. :param kwargs: Additional arguments to pass to the ToTChain constructor. """returncls(llm=llm,**kwargs)
def__init__(self,**kwargs:Any):super().__init__(**kwargs)self.tot_controller.c=self.c@propertydefinput_keys(self)->List[str]:"""Will be whatever keys the prompt expects. :meta private: """return["problem_description"]@propertydefoutput_keys(self)->List[str]:"""Will always return text key. :meta private: """return[self.output_key]
def_call(self,inputs:Dict[str,Any],run_manager:Optional[CallbackManagerForChainRun]=None,)->Dict[str,str]:_run_manager=run_managerorCallbackManagerForChainRun.get_noop_manager()ifrun_manager:run_manager.on_text(text="Starting the ToT solve procedure.\n")problem_description=inputs["problem_description"]checker_inputs={"problem_description":problem_description}thoughts_path:tuple[str,...]=()thought_generator=self.tot_strategy_class(# type: ignore[call-arg]llm=self.llm,c=self.c,verbose=self.verbose_llm)level=0for_inrange(self.k):level=self.tot_memory.levelthought_text=thought_generator.next_thought(problem_description,thoughts_path,callbacks=_run_manager.get_child())checker_inputs["thoughts"]=thoughts_path+(thought_text,)thought_validity=self.checker(checker_inputs,callbacks=_run_manager.get_child())["validity"]thought=Thought(text=thought_text,validity=thought_validity)ifthought.validity==ThoughtValidity.VALID_FINAL:self.log_thought(thought,level,run_manager)return{self.output_key:thought.text}self.tot_memory.store(thought)self.log_thought(thought,level,run_manager)thoughts_path=self.tot_controller(self.tot_memory)return{self.output_key:"No solution found"}asyncdef_acall(self,inputs:Dict[str,Any],run_manager:Optional[AsyncCallbackManagerForChainRun]=None,)->Dict[str,str]:raiseNotImplementedError("Async not implemented yet")@propertydef_chain_type(self)->str:return"tot"