mirror of
https://github.com/langgenius/dify.git
synced 2024-11-15 19:22:36 +08:00
enhancement (json): enhance JSON Process Tool extraction to return structured messages and improve error handling
This commit is contained in:
parent
16b9665033
commit
643fb5c4b1
|
@ -28,13 +28,17 @@ class JSONParseTool(BuiltinTool):
|
||||||
|
|
||||||
ensure_ascii = tool_parameters.get("ensure_ascii", True)
|
ensure_ascii = tool_parameters.get("ensure_ascii", True)
|
||||||
try:
|
try:
|
||||||
result = self._extract(content, json_filter, ensure_ascii)
|
json_string, json_objs = self._extract(content, json_filter, ensure_ascii)
|
||||||
return self.create_text_message(str(result))
|
json_objs_dict = {str(index): item for index, item in enumerate(json_objs)}
|
||||||
except Exception:
|
return [
|
||||||
return self.create_text_message("Failed to extract JSON content")
|
self.create_text_message(str(json_string)),
|
||||||
|
self.create_json_message(json_objs_dict),
|
||||||
|
]
|
||||||
|
except Exception as e:
|
||||||
|
return self.create_text_message(f"Failed to extract JSON content: {str(e)}")
|
||||||
|
|
||||||
# Extract data from JSON content
|
# Extract data from JSON content
|
||||||
def _extract(self, content: str, json_filter: str, ensure_ascii: bool) -> str:
|
def _extract(self, content: str, json_filter: str, ensure_ascii: bool) -> tuple[str, list]:
|
||||||
try:
|
try:
|
||||||
input_data = json.loads(content)
|
input_data = json.loads(content)
|
||||||
expr = parse(json_filter)
|
expr = parse(json_filter)
|
||||||
|
@ -44,10 +48,14 @@ class JSONParseTool(BuiltinTool):
|
||||||
result = result[0]
|
result = result[0]
|
||||||
|
|
||||||
if isinstance(result, dict | list):
|
if isinstance(result, dict | list):
|
||||||
return json.dumps(result, ensure_ascii=ensure_ascii)
|
json_string = json.dumps(result, ensure_ascii=ensure_ascii)
|
||||||
elif isinstance(result, str | int | float | bool) or result is None:
|
elif isinstance(result, str | int | float | bool) or result is None:
|
||||||
return str(result)
|
json_string = str(result)
|
||||||
else:
|
else:
|
||||||
return repr(result)
|
json_string = repr(result)
|
||||||
|
|
||||||
|
return json_string, result
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
raise ValueError(f"Invalid JSON content: {str(e)}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return str(e)
|
raise ValueError(f"Error processing JSON content: {str(e)}")
|
||||||
|
|
Loading…
Reference in New Issue
Block a user