Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(backend): Enable json parsing with typing & conversion #8578

Merged
merged 17 commits into from
Nov 15, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion autogpt_platform/backend/backend/data/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class ExecutionResult(BaseModel):
def from_db(execution: AgentNodeExecution):
if execution.executionData:
# Execution that has been queued for execution will persist its data.
input_data = json.loads(execution.executionData)
input_data = json.loads(execution.executionData, target_type=dict[str, Any])
else:
# For incomplete execution, executionData will not be yet available.
input_data: BlockInput = defaultdict()
Expand Down
15 changes: 8 additions & 7 deletions autogpt_platform/backend/backend/data/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ def from_db(node: AgentNode):
obj = Node(
id=node.id,
block_id=node.AgentBlock.id,
input_default=json.loads(node.constantInput),
metadata=json.loads(node.metadata),
input_default=json.loads(node.constantInput, target_type=dict[str, Any]),
metadata=json.loads(node.metadata, target_type=dict[str, Any]),
)
obj.input_links = [Link.from_db(link) for link in node.Input or []]
obj.output_links = [Link.from_db(link) for link in node.Output or []]
Expand All @@ -79,10 +79,9 @@ def from_db(execution: AgentGraphExecution):
duration = (end_time - start_time).total_seconds()
total_run_time = duration

if execution.stats:
stats = json.loads(execution.stats)
duration = stats.get("walltime", duration)
total_run_time = stats.get("nodes_walltime", total_run_time)
stats = json.loads(execution.stats or "{}", target_type=dict[str, Any])
duration = stats.get("walltime", duration)
total_run_time = stats.get("nodes_walltime", total_run_time)

return GraphExecution(
id=execution.id,
Expand Down Expand Up @@ -290,7 +289,9 @@ def from_db(graph: AgentGraph, hide_credentials: bool = False):
def _process_node(node: AgentNode, hide_credentials: bool) -> Node:
node_dict = node.model_dump()
if hide_credentials and "constantInput" in node_dict:
constant_input = json.loads(node_dict["constantInput"])
constant_input = json.loads(
node_dict["constantInput"], target_type=dict[str, Any]
)
constant_input = Graph._hide_credentials_in_input(constant_input)
node_dict["constantInput"] = json.dumps(constant_input)
return Node.from_db(AgentNode(**node_dict))
Expand Down
18 changes: 17 additions & 1 deletion autogpt_platform/backend/backend/util/json.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import json
from typing import Any, Type, TypeVar, overload

from fastapi.encoders import jsonable_encoder

from .type import convert


def to_dict(data) -> dict:
return jsonable_encoder(data)
Expand All @@ -11,4 +14,17 @@ def dumps(data) -> str:
return json.dumps(jsonable_encoder(data))


loads = json.loads
T = TypeVar("T")


@overload
def loads(data: str, *args, target_type: Type[T], **kwargs) -> T: ...


@overload
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
16 changes: 13 additions & 3 deletions autogpt_platform/backend/backend/util/type.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import json
from typing import Any, Type, TypeVar, get_args, get_origin
from typing import Any, Type, TypeVar, cast, get_args, get_origin


class ConversionError(Exception):
class ConversionError(ValueError):
pass


Expand Down Expand Up @@ -102,7 +102,7 @@ def __convert_bool(value: Any) -> bool:
return bool(value)


def convert(value: Any, target_type: Type):
def _convert(value: Any, target_type: Type):
origin = get_origin(target_type)
args = get_args(target_type)
if origin is None:
Expand Down Expand Up @@ -175,3 +175,13 @@ def convert(value: Any, target_type: Type):
return __convert_bool(value)
else:
return value


T = TypeVar("T")


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