Source code for langchain_community.utilities.dataherald
"""Util that calls Dataherald."""fromtypingimportAny,Dict,Optionalfromlangchain_core.utilsimportget_from_dict_or_envfrompydanticimportBaseModel,ConfigDict,model_validator
[docs]classDataheraldAPIWrapper(BaseModel):"""Wrapper for Dataherald. Docs for using: 1. Go to dataherald and sign up 2. Create an API key 3. Save your API key into DATAHERALD_API_KEY env variable 4. pip install dataherald """dataherald_client:Any=None#: :meta private:db_connection_id:strdataherald_api_key: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."""dataherald_api_key=get_from_dict_or_env(values,"dataherald_api_key","DATAHERALD_API_KEY")values["dataherald_api_key"]=dataherald_api_keytry:importdataheraldexceptImportError:raiseImportError("dataherald is not installed. ""Please install it with `pip install dataherald`")client=dataherald.Dataherald(api_key=dataherald_api_key)values["dataherald_client"]=clientreturnvalues
[docs]defrun(self,prompt:str)->str:"""Generate a sql query through Dataherald and parse result."""fromdataherald.types.sql_generation_create_paramsimportPromptprompt_obj=Prompt(text=prompt,db_connection_id=self.db_connection_id)res=self.dataherald_client.sql_generations.create(prompt=prompt_obj)try:answer=res.sqlifnotanswer:# We don't want to return the assumption alone if answer is emptyreturn"No answer"else:returnf"Answer: {answer}"exceptStopIteration:return"Dataherald wasn't able to answer it"