Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend;frontend): Add auto-type convertion support for optional types (#10325)

Zamil Majdy02d3b42745f1
diff --git a/autogpt_platform/backend/backend/util/type.py b/autogpt_platform/backend/backend/util/type.py
index b49da4f590..e1cda80203 100644
--- a/autogpt_platform/backend/backend/util/type.py
+++ b/autogpt_platform/backend/backend/util/type.py
@@ -1,5 +1,6 @@
import json
-from typing import Any, Type, TypeVar, cast, get_args, get_origin
+import types
+from typing import Any, Type, TypeVar, Union, cast, get_args, get_origin, overload
from prisma import Json as PrismaJson
@@ -104,9 +105,37 @@ def __convert_bool(value: Any) -> bool:
return bool(value)
-def _try_convert(value: Any, target_type: Type, raise_on_mismatch: bool) -> Any:
+def _try_convert(value: Any, target_type: Any, raise_on_mismatch: bool) -> Any:
origin = get_origin(target_type)
args = get_args(target_type)
+
+ # Handle Union types (including Optional which is Union[T, None])
+ if origin is Union or origin is types.UnionType:
+ # Handle None values for Optional types
+ if value is None:
+ if type(None) in args:
+ return None
+ elif raise_on_mismatch:
+ raise TypeError(f"Value {value} is not of expected type {target_type}")
+ else:
+ return value
+
+ # Try to convert to each type in the union, excluding None
+ non_none_types = [arg for arg in args if arg is not type(None)]
+
+ # Try each type in the union, using the original raise_on_mismatch behavior
+ for arg_type in non_none_types:
+ try:
+ return _try_convert(value, arg_type, raise_on_mismatch)
+ except (TypeError, ValueError, ConversionError):
+ continue
+
+ # If no conversion succeeded
+ if raise_on_mismatch:
+ raise TypeError(f"Value {value} is not of expected type {target_type}")
+ else:
+ return value
+
if origin is None:
origin = target_type
if origin not in [list, dict, tuple, str, set, int, float, bool]:
@@ -189,11 +218,19 @@ 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:
+@overload
+def convert(value: Any, target_type: Type[T]) -> T: ...
+
+
+@overload
+def convert(value: Any, target_type: Any) -> Any: ...
+
+
+def convert(value: Any, target_type: Any) -> Any:
try:
if isinstance(value, PrismaJson):
value = value.data
- return cast(T, _try_convert(value, target_type, raise_on_mismatch=False))
+ return _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
@@ -203,6 +240,7 @@ class FormattedStringType(str):
@classmethod
def __get_pydantic_core_schema__(cls, source_type, handler):
+ _ = source_type # unused parameter required by pydantic
return handler(str)
@classmethod
diff --git a/autogpt_platform/backend/backend/util/type_test.py b/autogpt_platform/backend/backend/util/type_test.py
index f9a14d10a0..becadf48b2 100644
--- a/autogpt_platform/backend/backend/util/type_test.py
+++ b/autogpt_platform/backend/backend/util/type_test.py
@@ -1,3 +1,5 @@
+from typing import List, Optional
+
from backend.util.type import convert
@@ -5,6 +7,8 @@ def test_type_conversion():
assert convert(5.5, int) == 5
assert convert("5.5", int) == 5
assert convert([1, 2, 3], int) == 3
+ assert convert("7", Optional[int]) == 7
+ assert convert("7", int | None) == 7
assert convert("5.5", float) == 5.5
assert convert(5, float) == 5.0
@@ -25,8 +29,6 @@ def test_type_conversion():
assert convert([1, 2, 3], dict) == {0: 1, 1: 2, 2: 3}
assert convert((1, 2, 3), dict) == {0: 1, 1: 2, 2: 3}
- from typing import List
-
assert convert("5", List[int]) == [5]
assert convert("[5,4,2]", List[int]) == [5, 4, 2]
assert convert([5, 4, 2], List[str]) == ["5", "4", "2"]
diff --git a/autogpt_platform/frontend/src/components/agents/agent-run-draft-view.tsx b/autogpt_platform/frontend/src/components/agents/agent-run-draft-view.tsx
index 43675644e8..f7e047dc64 100644
--- a/autogpt_platform/frontend/src/components/agents/agent-run-draft-view.tsx
+++ b/autogpt_platform/frontend/src/components/agents/agent-run-draft-view.tsx
@@ -90,14 +90,14 @@ export default function AgentRunDraftView({
const agentInputFields = useMemo(
() =>
Object.fromEntries(
- Object.entries(agentInputSchema.properties).filter(
+ Object.entries(agentInputSchema?.properties || {}).filter(
([_, subSchema]) => !subSchema.hidden,
),
),
[agentInputSchema],
);
const agentCredentialsInputFields = useMemo(
- () => agent.credentials_input_schema?.properties,
+ () => agent.credentials_input_schema?.properties || {},
[agent],
);