"""Base interface for loading large language model APIs."""importjsonfrompathlibimportPathfromtypingimportAny,Unionimportyamlfromlangchain_core.language_models.llmsimportBaseLLMfromlangchain_core.utils.pydanticimportget_fieldsfromlangchain_community.llmsimportget_type_to_cls_dict_ALLOW_DANGEROUS_DESERIALIZATION_ARG="allow_dangerous_deserialization"
[docs]defload_llm_from_config(config:dict,**kwargs:Any)->BaseLLM:"""Load LLM from Config Dict."""if"_type"notinconfig:raiseValueError("Must specify an LLM Type in config")config_type=config.pop("_type")type_to_cls_dict=get_type_to_cls_dict()ifconfig_typenotintype_to_cls_dict:raiseValueError(f"Loading {config_type} LLM not supported")llm_cls=type_to_cls_dict[config_type]()load_kwargs={}if_ALLOW_DANGEROUS_DESERIALIZATION_ARGinget_fields(llm_cls):load_kwargs[_ALLOW_DANGEROUS_DESERIALIZATION_ARG]=kwargs.get(_ALLOW_DANGEROUS_DESERIALIZATION_ARG,False)returnllm_cls(**config,**load_kwargs)
[docs]defload_llm(file:Union[str,Path],**kwargs:Any)->BaseLLM:"""Load LLM from a file."""# 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==".json":withopen(file_path)asf:config=json.load(f)eliffile_path.suffix.endswith((".yaml",".yml")):withopen(file_path,"r")asf:config=yaml.safe_load(f)else:raiseValueError("File type must be json or yaml")# Load the LLM from the config now.returnload_llm_from_config(config,**kwargs)