"""Functionality for loading agents."""importjsonimportloggingfrompathlibimportPathfromtypingimportAny,List,Optional,Unionimportyamlfromlangchain_core._apiimportdeprecatedfromlangchain_core.language_modelsimportBaseLanguageModelfromlangchain_core.toolsimportToolfromlangchain.agents.agentimportBaseMultiActionAgent,BaseSingleActionAgentfromlangchain.agents.typesimportAGENT_TO_CLASSfromlangchain.chains.loadingimportload_chain,load_chain_from_configlogger=logging.getLogger(__file__)URL_BASE="https://raw.githubusercontent.com/hwchase17/langchain-hub/master/agents/"def_load_agent_from_tools(config:dict,llm:BaseLanguageModel,tools:List[Tool],**kwargs:Any)->Union[BaseSingleActionAgent,BaseMultiActionAgent]:config_type=config.pop("_type")ifconfig_typenotinAGENT_TO_CLASS:raiseValueError(f"Loading {config_type} agent not supported")agent_cls=AGENT_TO_CLASS[config_type]combined_config={**config,**kwargs}returnagent_cls.from_llm_and_tools(llm,tools,**combined_config)
[docs]@deprecated("0.1.0",removal="1.0")defload_agent_from_config(config:dict,llm:Optional[BaseLanguageModel]=None,tools:Optional[List[Tool]]=None,**kwargs:Any,)->Union[BaseSingleActionAgent,BaseMultiActionAgent]:"""Load agent from Config Dict. Args: config: Config dict to load agent from. llm: Language model to use as the agent. tools: List of tools this agent has access to. kwargs: Additional keyword arguments passed to the agent executor. Returns: An agent executor. Raises: ValueError: If agent type is not specified in the config. """if"_type"notinconfig:raiseValueError("Must specify an agent Type in config")load_from_tools=config.pop("load_from_llm_and_tools",False)ifload_from_tools:ifllmisNone:raiseValueError("If `load_from_llm_and_tools` is set to True, ""then LLM must be provided")iftoolsisNone:raiseValueError("If `load_from_llm_and_tools` is set to True, ""then tools must be provided")return_load_agent_from_tools(config,llm,tools,**kwargs)config_type=config.pop("_type")ifconfig_typenotinAGENT_TO_CLASS:raiseValueError(f"Loading {config_type} agent not supported")agent_cls=AGENT_TO_CLASS[config_type]if"llm_chain"inconfig:config["llm_chain"]=load_chain_from_config(config.pop("llm_chain"))elif"llm_chain_path"inconfig:config["llm_chain"]=load_chain(config.pop("llm_chain_path"))else:raiseValueError("One of `llm_chain` and `llm_chain_path` should be specified.")if"output_parser"inconfig:logger.warning("Currently loading output parsers on agent is not supported, ""will just use the default one.")delconfig["output_parser"]combined_config={**config,**kwargs}returnagent_cls(**combined_config)# type: ignore
[docs]@deprecated("0.1.0",removal="1.0")defload_agent(path:Union[str,Path],**kwargs:Any)->Union[BaseSingleActionAgent,BaseMultiActionAgent]:"""Unified method for loading an agent from LangChainHub or local fs. Args: path: Path to the agent file. kwargs: Additional keyword arguments passed to the agent executor. Returns: An agent executor. Raises: RuntimeError: If loading from the deprecated github-based Hub is attempted. """ifisinstance(path,str)andpath.startswith("lc://"):raiseRuntimeError("Loading from the deprecated github-based Hub is no longer supported. ""Please use the new LangChain Hub at https://smith.langchain.com/hub ""instead.")return_load_agent_from_file(path,**kwargs)
def_load_agent_from_file(file:Union[str,Path],**kwargs:Any)->Union[BaseSingleActionAgent,BaseMultiActionAgent]:"""Load agent from file."""valid_suffixes={"json","yaml"}# Convert file to Path object.ifisinstance(file,str):file_path=Path(file)else:file_path=file# Load from either json or yaml.iffile_path.suffix[1:]=="json":withopen(file_path)asf:config=json.load(f)eliffile_path.suffix[1:]=="yaml":withopen(file_path,"r")asf:config=yaml.safe_load(f)else:raiseValueError(f"Unsupported file type, must be one of {valid_suffixes}.")# Load the agent from the config now.returnload_agent_from_config(config,**kwargs)