Skip to content

Commit

Permalink
Address comments
Browse files Browse the repository at this point in the history
  • Loading branch information
majdyz committed Nov 13, 2024
1 parent 8375181 commit 4f7e7d0
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
6 changes: 5 additions & 1 deletion autogpt_platform/backend/backend/data/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,11 @@ def from_db(execution: AgentGraphExecution):
duration = (end_time - start_time).total_seconds()
total_run_time = duration

stats = json.loads(execution.stats or "{}", target_type=dict[str, Any])
try:
stats = json.loads(execution.stats or "{}", target_type=dict[str, Any])
except ValueError:
stats = {}

duration = stats.get("walltime", duration)
total_run_time = stats.get("nodes_walltime", total_run_time)

Expand Down
6 changes: 4 additions & 2 deletions autogpt_platform/backend/backend/util/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from fastapi.encoders import jsonable_encoder

from .type import convert
from .type import type_match


def to_dict(data) -> dict:
Expand All @@ -27,4 +27,6 @@ def loads(data: str, *args, **kwargs) -> Any: ...

def loads(data: str, *args, target_type: Type[T] | None = None, **kwargs) -> Any:
parsed = json.loads(data, *args, **kwargs)
return convert(parsed, target_type) if target_type else parsed
if target_type:
return type_match(parsed, target_type)
return parsed
10 changes: 8 additions & 2 deletions autogpt_platform/backend/backend/util/type.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def __convert_bool(value: Any) -> bool:
return bool(value)


def _convert(value: Any, target_type: Type):
def _try_convert(value: Any, target_type: Type, raise_on_mismatch: bool) -> Any:
origin = get_origin(target_type)
args = get_args(target_type)
if origin is None:
Expand Down Expand Up @@ -133,6 +133,8 @@ def _convert(value: Any, target_type: Type):
return {convert(v, args[0]) for v in value}
else:
return value
elif raise_on_mismatch:
raise ConversionError(f"Failed to convert {value} to {target_type}")
else:
# Need to convert value to the origin type
if origin is list:
Expand Down Expand Up @@ -180,8 +182,12 @@ def _convert(value: Any, target_type: Type):
T = TypeVar("T")


def type_match(value: Any, target_type: Type[T]) -> T:
return cast(T, _try_convert(value, target_type, raise_on_mismatch=True))


def convert(value: Any, target_type: Type[T]) -> T:
try:
return cast(T, _convert(value, target_type))
return cast(T, _try_convert(value, target_type, raise_on_mismatch=False))
except Exception as e:
raise ConversionError(f"Failed to convert {value} to {target_type}") from e

0 comments on commit 4f7e7d0

Please sign in to comment.