diff --git a/openbb_platform/core/openbb_core/api/router/commands.py b/openbb_platform/core/openbb_core/api/router/commands.py index 96334f549fa..7b644cca372 100644 --- a/openbb_platform/core/openbb_core/api/router/commands.py +++ b/openbb_platform/core/openbb_core/api/router/commands.py @@ -134,19 +134,26 @@ def validate_output(c_out: OBBject) -> OBBject: json_schema_extra = field.json_schema_extra if field else None # case where 1st layer field needs to be excluded - if json_schema_extra and json_schema_extra.get("exclude_from_api", None): + if ( + json_schema_extra + and isinstance(json_schema_extra, dict) + and json_schema_extra.get("exclude_from_api", None) + ): delattr(c_out, key) # if it's a model with nested fields elif is_model(type_): for field_name, field in type_.__fields__.items(): - if field.json_schema_extra and field.json_schema_extra.get( - "exclude_from_api", None + extra = getattr(field, "json_schema_extra", None) + if ( + extra + and isinstance(extra, dict) + and extra.get("exclude_from_api", None) ): delattr(value, field_name) # if it's a yet a nested model we need to go deeper in the recursion - elif is_model(field.annotation): + elif is_model(getattr(field, "annotation", None)): exclude_fields_from_api(field_name, getattr(value, field_name)) for k, v in c_out.model_copy(): diff --git a/openbb_platform/core/openbb_core/app/model/obbject.py b/openbb_platform/core/openbb_core/app/model/obbject.py index 23d9bc21434..a86eb14b6b4 100644 --- a/openbb_platform/core/openbb_core/app/model/obbject.py +++ b/openbb_platform/core/openbb_core/app/model/obbject.py @@ -192,9 +192,9 @@ class OBBject(Tagged, Generic[T]): # List[List | str | int | float] | Dict[str, Dict | List | BaseModel] else: try: - df = pd.DataFrame(res) + df = pd.DataFrame(res) # type: ignore[call-overload] # Set index, if any - if index is not None and index in df.columns: + if df and index and index in df.columns: df.set_index(index, inplace=True) except ValueError: @@ -267,8 +267,9 @@ class OBBject(Tagged, Generic[T]): orient == "list" and isinstance(self.results, dict) and all( - isinstance(value, dict) for value in self.results.values() - ) # pylint: disable=no-member + isinstance(value, dict) + for value in self.results.values() # pylint: disable=no-member + ) ): df = df.T results = df.to_dict(orient=orient) diff --git a/openbb_platform/core/openbb_core/app/provider_interface.py b/openbb_platform/core/openbb_core/app/provider_interface.py index eab7ea1e807..0b5267e58b8 100644 --- a/openbb_platform/core/openbb_core/app/provider_interface.py +++ b/openbb_platform/core/openbb_core/app/provider_interface.py @@ -18,7 +18,7 @@ from openbb_core.provider.query_executor import QueryExecutor from openbb_core.provider.registry_map import MapType, RegistryMap from openbb_core.provider.utils.helpers import to_snake_case -TupleFieldType = Tuple[str, type, Any] +TupleFieldType = Tuple[str, Optional[Type], Optional[Any]] @dataclass @@ -26,8 +26,8 @@ class DataclassField: """Dataclass field.""" name: str - type_: type - default: Any + annotation: Optional[Type] + default: Optional[Any] @dataclass @@ -154,20 +154,19 @@ class ProviderInterface(metaclass=SingletonMeta): def create_executor(self) -> QueryExecutor: """Get query executor.""" - return self._query_executor(self._registry_map.registry) # type: ignore + return self._query_executor(self._registry_map.registry) # type: ignore[operator] @staticmethod def _merge_fields( current: DataclassField, incoming: DataclassField, query: bool = False ) -> DataclassField: - current_name = current.name - current_type = current.type_ - current_desc = getattr(current.default, "description", "") + """Merge 2 dataclass fields.""" + curr_name = current.name + curr_type: Optional[Type] = current.annotation + curr_desc = getattr(current.default, "description", "") - incoming_type = incoming.type_ - incoming_desc = getattr(incoming.default, "description", "") - - F: Union[Callable, object] = Query if query else FieldInfo + inc_type: Optional[Type] = incoming.annotation + inc_desc = getattr(incoming.default, "description", "") def split_desc(desc: str) -> str: """Split field description.""" @@ -175,34 +174,33 @@ class ProviderInterface(metaclass=SingletonMeta): detail = item[0] if item else "" return detail - curr_detail = split_desc(current_desc) - inc_detail = split_desc(incoming_desc) + curr_detail = split_desc(curr_desc) + inc_detail = split_desc(inc_desc) - providers = f"{current.default.title},{incoming.default.title}" + curr_title = getattr(current.default, "title", "") + inc_title = getattr(incoming.default, "title", "") + providers = ",".join([curr_title, inc_title]) formatted_prov = providers.replace(",", ", ") if SequenceMatcher(None, curr_detail, inc_detail).ratio() > 0.8: new_desc = f"{curr_detail} (provider: {formatted_prov})" else: - new_desc = f"{current_desc};\n {incoming_desc}" + new_desc = f"{curr_desc};\n {inc_desc}" - merged_default = F( # type: ignore - default=current.default.default, + QF: Callable = Query if query else FieldInfo # type: ignore[assignment] + merged_default = QF( + default=getattr(current.default, "default", None), title=providers, description=new_desc, ) - merged_type = ( - Union[current_type, incoming_type] - if current_type != incoming_type - else current_type + merged_type: Optional[Type] = ( + Union[curr_type, inc_type] # type: ignore[assignment] + if curr_type != inc_type + else curr_type ) - return DataclassField( - name=current_name, - type_=merged_type, # type: ignore - default=merged_default, - ) + return DataclassField(curr_name, merged_type, merged_default) @staticmethod def _create_field( @@ -213,9 +211,7 @@ class ProviderInterface(metaclass=SingletonMeta): force_optional: bool = False, ) -> DataclassField: new_name = name.replace(".", "_") - # field.type_ don't work for nested types - # field.outer_type_ don't work for Optional nested types - type_ = field.annotation + annotation = field.annotation additional_description = "" if (extra := field.json_schema_extra) and ( @@ -239,7 +235,7 @@ class ProviderInterface(metaclass=SingletonMeta): if field.is_required(): if force_optional: - type_ = Optional[type_] # type: ignore + annotation = Optional[annotation] # type: ignore default = None else: default = ... @@ -247,24 +243,32 @@ class ProviderInterface(metaclass=SingletonMeta): default = field.default if query: - # We need to use query if we want the field description to show up in the - # swagger, it's a fastapi limitation - default = Query( - default=default, - title=provider_name, - description=description, - alias=field.alias or None, - json_schema_extra=field.json_schema_extra, + # We need to use query if we want the field description to show + # up in the swagger, it's a fastapi limitation + return DataclassField( + new_name, + annotation, + Query( + default=default, + title=provider_name, + description=description, + alias=field.alias or None, + json_schema_extra=getattr(field, "json_schema_extra", None), + ), ) - elif provider_name: - default: FieldInfo = Field( - default=default or None, - title=provider_name, - description=description, - json_schema_extra=field.json_schema_extra, + if provider_name: + return DataclassField( + new_name, + annotation, + Field( + default=default or None, + title=provider_name, + description=description, + json_schema_extra=field.json_schema_extra, + ), ) - return DataclassField(new_name, type_, default) + return DataclassField(new_name, annotation, default) @classmethod def _extract_params( @@ -282,7 +286,7 @@ class ProviderInterface(metaclass=SingletonMeta): standard[incoming.name] = ( incoming.name, - incoming.type_, + incoming.annotation, incoming.default, ) else: @@ -305,7 +309,7 @@ class ProviderInterface(metaclass=SingletonMeta): extra[updated.name] = ( updated.name, - updated.type_, + updated.annotation, updated.default, ) @@ -331,7 +335,7 @@ class ProviderInterface(metaclass=SingletonMeta): standard[incoming.name] = ( incoming.name, - incoming.type_, + incoming.annotation, incoming.default, ) else: @@ -357,7 +361,7 @@ class ProviderInterface(metaclass=SingletonMeta): extra[updated.name] = ( updated.name, - updated.type_, + updated.annotation, updated.default, ) @@ -393,14 +397,14 @@ class ProviderInterface(metaclass=SingletonMeta): standard, extra = self._extract_params(providers) result[model_name] = { - "standard": make_dataclass( # type: ignore + "standard": make_dataclass( cls_name=model_name, - fields=list(standard.values()), + fields=list(standard.values()), # type: ignore[arg-type] bases=(StandardParams,), ), - "extra": make_dataclass( # type: ignore + "extra": make_dataclass( cls_name=model_name, - fields=list(extra.values()), + fields=list(extra.values()), # type: ignore[arg-type] bases=(ExtraParams,), ), } @@ -464,14 +468,14 @@ class ProviderInterface(metaclass=SingletonMeta): extra: dict standard, extra = self._extract_data(providers) result[model_name] = { - "standard": make_dataclass( # type: ignore + "standard": make_dataclass( cls_name=model_name, - fields=list(standard.values()), + fields=list(standard.values()), # type: ignore[arg-type] bases=(StandardData,), ), - "extra": make_dataclass( # type: ignore + "extra": make_dataclass( cls_name=model_name, - fields=list(extra.values()), + fields=list(extra.values()), # type: ignore[arg-type] bases=(ExtraData,), ), } diff --git a/openbb_platform/core/openbb_core/app/router.py b/openbb_platform/core/openbb_core/app/router.py index 3968d5892a0..218629be8ba 100644 --- a/openbb_platform/core/openbb_core/app/router.py +++ b/openbb_platform/core/openbb_core/app/router.py @@ -350,7 +350,7 @@ class SignatureInspector: func = cls.inject_return_type( func=func, - return_map=provider_interface.return_map.get(model), + return_map=provider_interface.return_map.get(model, {}), model=model, ) @@ -374,11 +374,7 @@ class SignatureInspector: return_map: Dict[str, dict], model: str, ) -> Callable[P, OBBject]: - """ - Inject full return model into the function. - Also updates __name__ and __doc__ for API schemas. - """ - + """Inject full return model into the function. Also updates __name__ and __doc__ for API schemas.""" results: Dict[str, Any] = {"list_type": [], "dict_type": []} for provider, return_data in return_map.items(): @@ -397,7 +393,7 @@ class SignatureInspector: if not v: continue - inner_type = SerializeAsAny[ + inner_type: Any = SerializeAsAny[ # type: ignore[misc,valid-type] Annotated[ Union[tuple(v)], # type: ignore Field(discriminator="provider"), diff --git a/openbb_platform/core/openbb_core/app/utils.py b/openbb_platform/core/openbb_core/app/utils.py index 9f8d51b5b40..f7c6c1ca7dc 100644 --- a/openbb_platform/core/openbb_core/app/utils.py +++ b/openbb_platform/core/openbb_core/app/utils.py @@ -3,7 +3,7 @@ import ast import json from datetime import time -from typing import Dict, Iterable, List, Optional, Union +from typing import Dict, List, Optional, Union import numpy as np import pandas as pd diff --git a/openbb_platform/core/tests/app/test_platform_router.py b/openbb_platform/core/tests/app/test_platform_router.py index 590a2709aa6..e42e0f49e3e 100644 --- a/openbb_platform/core/tests/app/test_platform_router.py +++ b/openbb_platform/core/tests/app/test_platform_router.py @@ -187,7 +187,7 @@ def test_signature_inspector_init(signature_inspector): def test_complete_signature(signature_inspector): """Test complete_signature.""" - async def sample_function( + async def sample_function( # type: ignore[empty-body] cc: CommandContext, provider_choices: ProviderChoices, standard_params: StandardParams,