Improve fix for UnicodeDecodeError in JSON loading

This commit is contained in:
PierrunoYT 2025-05-03 20:36:38 +02:00
parent bbad86b733
commit 2582a845dc
2 changed files with 32 additions and 27 deletions

View file

@ -58,36 +58,18 @@ class LiteLLMExceptions:
self._load()
def _load(self, strict=False):
# Patch litellm's JSON loading to use UTF-8 encoding
import json
# Import litellm - json.load is already patched in aider.llm
import litellm
from pathlib import Path
# Monkey patch json.load in litellm.utils to handle UTF-8 encoding
original_json_load = json.load
# Load litellm exceptions
for var in dir(litellm):
if var.endswith("Error"):
if var not in self.exception_info:
raise ValueError(f"{var} is in litellm but not in aider's exceptions list")
def patched_json_load(fp, *args, **kwargs):
# Read the file content with UTF-8 encoding
content = Path(fp.name).read_text(encoding='utf-8')
# Parse the content as JSON
return json.loads(content, *args, **kwargs)
# Apply the monkey patch
json.load = patched_json_load
try:
# Now load litellm exceptions
for var in dir(litellm):
if var.endswith("Error"):
if var not in self.exception_info:
raise ValueError(f"{var} is in litellm but not in aider's exceptions list")
for var in self.exception_info:
ex = getattr(litellm, var)
self.exceptions[ex] = self.exception_info[var]
finally:
# Restore the original json.load function
json.load = original_json_load
for var in self.exception_info:
ex = getattr(litellm, var)
self.exceptions[ex] = self.exception_info[var]
def exceptions_tuple(self):
return tuple(self.exceptions)

View file

@ -1,6 +1,8 @@
import importlib
import json
import os
import warnings
from pathlib import Path
from aider.dump import dump # noqa: F401
@ -17,6 +19,27 @@ os.environ["LITELLM_MODE"] = "PRODUCTION"
VERBOSE = False
# Patch json.load to handle UTF-8 encoding for litellm
original_json_load = json.load
def patched_json_load(fp, *args, **kwargs):
try:
# First try the original method
return original_json_load(fp, *args, **kwargs)
except UnicodeDecodeError:
# If it fails with UnicodeDecodeError, try with UTF-8 encoding
try:
# Read the file content with UTF-8 encoding
content = Path(fp.name).read_text(encoding='utf-8')
# Parse the content as JSON
return json.loads(content, *args, **kwargs)
except Exception:
# If that also fails, re-raise the original exception
raise
# Apply the monkey patch
json.load = patched_json_load
class LazyLiteLLM:
_lazy_module = None