Source code for langchain_community.utilities.wolfram_alpha
"""Util that calls WolframAlpha."""fromtypingimportAny,Dict,Optionalfromlangchain_core.utilsimportget_from_dict_or_envfrompydanticimportBaseModel,ConfigDict,model_validator
[docs]classWolframAlphaAPIWrapper(BaseModel):"""Wrapper for Wolfram Alpha. Docs for using: 1. Go to wolfram alpha and sign up for a developer account 2. Create an app and get your APP ID 3. Save your APP ID into WOLFRAM_ALPHA_APPID env variable 4. pip install wolframalpha """wolfram_client:Any=None#: :meta private:wolfram_alpha_appid:Optional[str]=Nonemodel_config=ConfigDict(extra="forbid",)@model_validator(mode="before")@classmethoddefvalidate_environment(cls,values:Dict)->Any:"""Validate that api key and python package exists in environment."""wolfram_alpha_appid=get_from_dict_or_env(values,"wolfram_alpha_appid","WOLFRAM_ALPHA_APPID")values["wolfram_alpha_appid"]=wolfram_alpha_appidtry:importwolframalphaexceptImportError:raiseImportError("wolframalpha is not installed. ""Please install it with `pip install wolframalpha`")client=wolframalpha.Client(wolfram_alpha_appid)values["wolfram_client"]=clientreturnvalues
[docs]defrun(self,query:str)->str:"""Run query through WolframAlpha and parse result."""res=self.wolfram_client.query(query)try:assumption=next(res.pods).textanswer=next(res.results).textexceptStopIteration:return"Wolfram Alpha wasn't able to answer it"ifanswerisNoneoranswer=="":# We don't want to return the assumption alone if answer is emptyreturn"No good Wolfram Alpha Result was found"else:returnf"Assumption: {assumption}\nAnswer: {answer}"