json.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import json
  2. from json_repair import repair_json
  3. from opendevin.core.exceptions import LLMOutputError
  4. def my_encoder(obj):
  5. """
  6. Encodes objects as dictionaries
  7. Parameters:
  8. - obj (Object): An object that will be converted
  9. Returns:
  10. - dict: If the object can be converted it is returned in dict format
  11. """
  12. if hasattr(obj, 'to_dict'):
  13. return obj.to_dict()
  14. def dumps(obj, **kwargs):
  15. """
  16. Serialize an object to str format
  17. """
  18. return json.dumps(obj, default=my_encoder, **kwargs)
  19. def loads(json_str, **kwargs):
  20. """
  21. Create a JSON object from str
  22. """
  23. depth = 0
  24. start = -1
  25. for i, char in enumerate(json_str):
  26. if char == '{':
  27. if depth == 0:
  28. start = i
  29. depth += 1
  30. elif char == '}':
  31. depth -= 1
  32. if depth == 0 and start != -1:
  33. response = json_str[start : i + 1]
  34. try:
  35. json_str = repair_json(response)
  36. return json.loads(json_str, **kwargs)
  37. except (json.JSONDecodeError, ValueError, TypeError) as e:
  38. raise LLMOutputError(
  39. 'Invalid JSON in response. Please make sure the response is a valid JSON object.'
  40. ) from e
  41. raise LLMOutputError('No valid JSON object found in response.')