{"record":{"id":"8c12bc3f135a6a5a","repo":"crewAIInc/crewAI","slug":"cannot-convert-type-v-name-to-file-source","errorCode":null,"errorMessage":"Cannot convert {type(v).__name__} to file source","messagePattern":"Cannot convert (.+?) to file source","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"lib/crewai-files/src/crewai_files/core/types.py","lineNumber":46,"sourceCode":"class _FileSourceCoercer:\n    \"\"\"Pydantic-compatible type that coerces various inputs to FileSource.\"\"\"\n\n    @classmethod\n    def _coerce(cls, v: Any) -> FileSource:\n        \"\"\"Convert raw input to appropriate FileSource type.\"\"\"\n        if isinstance(v, (FilePath, FileBytes, FileStream, FileUrl)):\n            return v\n        if isinstance(v, str):\n            if v.startswith((\"http://\", \"https://\")):\n                return FileUrl(url=v)\n            return FilePath(path=Path(v))\n        if isinstance(v, Path):\n            return FilePath(path=v)\n        if isinstance(v, bytes):\n            return FileBytes(data=v)\n        if isinstance(v, (IOBase, BinaryIO)):\n            return FileStream(stream=v)\n        raise ValueError(f\"Cannot convert {type(v).__name__} to file source\")\n\n    @classmethod\n    def __get_pydantic_core_schema__(\n        cls,\n        _source_type: Any,\n        _handler: GetCoreSchemaHandler,\n    ) -> CoreSchema:\n        \"\"\"Generate Pydantic core schema for FileSource coercion.\"\"\"\n        return core_schema.no_info_plain_validator_function(\n            cls._coerce,\n            serialization=core_schema.plain_serializer_function_ser_schema(\n                lambda v: v,\n                info_arg=False,\n                return_schema=core_schema.any_schema(),\n            ),\n        )\n\n","sourceCodeStart":28,"sourceCodeEnd":64,"githubUrl":"https://github.com/crewAIInc/crewAI/blob/754d7323beb2fd042e33444a115ea2d5a47193f0/lib/crewai-files/src/crewai_files/core/types.py#L28-L64","documentation":"Same final-coercion failure as error 137 but in the FileSource union's _coerce validator (core/types.py): the value is not a FileSource instance, str, Path, bytes, or IOBase/BinaryIO. Note this variant accepts IOBase (broader for stdlib streams) but, unlike sources.py's normalizer, does NOT special-case AsyncReadable. So async streams that pass elsewhere fail here. Raised as ValueError during pydantic validation of a FileSource-typed field.","triggerScenarios":"Assigning an int, dict, list, or generator to a field typed FileSource; assigning an aiofiles/async stream object — accepted by _normalize_source (sources.py) via AsyncReadable but rejected here because only IOBase/BinaryIO sync streams coerce; passing a StringO (text IO) where BinaryIO is required is borderline and type-checkers flag it.","commonSituations":"The same conceptual input working through one entry point (FileSourceInput) but failing through another (FileSource field), confusing users; async uploads routed into sync-typed models.","solutions":["Materialize async streams to bytes first (await stream.read()) and pass FileBytes(data=...).","Use one of the concrete classes (FilePath, FileBytes, FileStream, FileUrl) instead of a raw object.","Wrap sync streams in io.BytesIO so they are proper IOBase instances."],"exampleFix":"# before\nfile = File(source=aiofiles_handle)  # async handle fails FileSource._coerce\n\n# after\ndata = await aiofiles_handle.read()\nfile = File(source=FileBytes(data=data))","handlingStrategy":"type-guard","validationCode":"from io import IOBase\nfrom pathlib import Path\n\ndef filesource_coercible(v) -> bool:\n    return isinstance(v, (str, Path, bytes, IOBase))","typeGuard":"from io import IOBase\nfrom pathlib import Path\n\ndef to_filesource(v):\n    if isinstance(v, (str, Path, bytes, IOBase)):\n        return v  # let pydantic coerce\n    if hasattr(v, \"read\") and hasattr(v, \"seek\"):\n        import io\n        return io.BytesIO(v.read())\n    raise TypeError(f\"cannot coerce {type(v).__name__}\")","tryCatchPattern":"try:\n    File(source=v)\nexcept ValidationError as e:\n    if \"to file source\" in str(e):\n        data = await v.read() if hasattr(v, \"read\") else None\n        if data:\n            File(source=FileBytes(data=data))","preventionTips":["Remember FileSource._coerce has no AsyncReadable branch — materialize async streams to bytes first.","Wrap sync streams in io.BytesIO so they pass the IOBase isinstance check."],"tags":["pydantic","validation","file-sources","async","type-coercion"],"backgroundTag":null,"analyzedSha":"754d7323beb2fd042e33444a115ea2d5a47193f0","analyzedAt":"2026-08-15T04:06:56.746Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}