Source code for langchain_community.tools.json.tool
# flake8: noqa"""Tools for working with JSON specs."""from__future__importannotationsimportjsonimportrefrompathlibimportPathfromtypingimportDict,List,Optional,Unionfromlangchain_core.pydantic_v1importBaseModelfromlangchain_core.callbacksimport(AsyncCallbackManagerForToolRun,CallbackManagerForToolRun,)fromlangchain_core.toolsimportBaseTooldef_parse_input(text:str)->List[Union[str,int]]:"""Parse input of the form data["key1"][0]["key2"] into a list of keys."""_res=re.findall(r"\[.*?]",text)# strip the brackets and quotes, convert to int if possibleres=[i[1:-1].replace('"',"").replace("'","")foriin_res]res=[int(i)ifi.isdigit()elseiforiinres]returnres
[docs]classJsonSpec(BaseModel):"""Base class for JSON spec."""dict_:Dictmax_value_length:int=200
[docs]@classmethoddeffrom_file(cls,path:Path)->JsonSpec:"""Create a JsonSpec from a file."""ifnotpath.exists():raiseFileNotFoundError(f"File not found: {path}")dict_=json.loads(path.read_text())returncls(dict_=dict_)
[docs]defkeys(self,text:str)->str:"""Return the keys of the dict at the given path. Args: text: Python representation of the path to the dict (e.g. data["key1"][0]["key2"]). """try:items=_parse_input(text)val=self.dict_foriinitems:ifi:val=val[i]ifnotisinstance(val,dict):raiseValueError(f"Value at path `{text}` is not a dict, get the value directly.")returnstr(list(val.keys()))exceptExceptionase:returnrepr(e)
[docs]defvalue(self,text:str)->str:"""Return the value of the dict at the given path. Args: text: Python representation of the path to the dict (e.g. data["key1"][0]["key2"]). """try:items=_parse_input(text)val=self.dict_foriinitems:val=val[i]ifisinstance(val,dict)andlen(str(val))>self.max_value_length:return"Value is a large dictionary, should explore its keys directly"str_val=str(val)iflen(str_val)>self.max_value_length:str_val=str_val[:self.max_value_length]+"..."returnstr_valexceptExceptionase:returnrepr(e)
[docs]classJsonListKeysTool(BaseTool):"""Tool for listing keys in a JSON spec."""name:str="json_spec_list_keys"description:str=""" Can be used to list all keys at a given path. Before calling this you should be SURE that the path to this exists. The input is a text representation of the path to the dict in Python syntax (e.g. data["key1"][0]["key2"]). """spec:JsonSpecdef_run(self,tool_input:str,run_manager:Optional[CallbackManagerForToolRun]=None,)->str:returnself.spec.keys(tool_input)asyncdef_arun(self,tool_input:str,run_manager:Optional[AsyncCallbackManagerForToolRun]=None,)->str:returnself._run(tool_input)
[docs]classJsonGetValueTool(BaseTool):"""Tool for getting a value in a JSON spec."""name:str="json_spec_get_value"description:str=""" Can be used to see value in string format at a given path. Before calling this you should be SURE that the path to this exists. The input is a text representation of the path to the dict in Python syntax (e.g. data["key1"][0]["key2"]). """spec:JsonSpecdef_run(self,tool_input:str,run_manager:Optional[CallbackManagerForToolRun]=None,)->str:returnself.spec.value(tool_input)asyncdef_arun(self,tool_input:str,run_manager:Optional[AsyncCallbackManagerForToolRun]=None,)->str:returnself._run(tool_input)