    async def to_http_response(cls, obj: t.Any, serde: Serde) -> Response:
        """Convert a output value to HTTP response"""
        import itertools
        import mimetypes

        from starlette.responses import FileResponse
        from starlette.responses import Response
        from starlette.responses import StreamingResponse

        if inspect.isasyncgen(obj):
            try:
                # try if there is any error before the first yield
                # if so, the error can be surfaced in the response
                first_chunk = await obj.__anext__()
            except StopAsyncIteration:
                pre_chunks = []
            else:
                pre_chunks = [first_chunk]

            async def gen() -> t.AsyncGenerator[t.Any, None]:
                for chunk in pre_chunks:
                    yield chunk
                async for chunk in obj:
                    yield chunk

            async def async_stream() -> t.AsyncGenerator[str | bytes, None]:
                try:
                    async for item in gen():
                        if isinstance(item, (str, bytes)):
                            yield item
                        else:
                            obj_item = (
                                cls(item) if issubclass(cls, IORootModel) else item
                            )
                            for chunk in serde.serialize_model(
                                t.cast(IODescriptor, obj_item)
                            ).data:
                                yield chunk
                except Exception:
                    logger.exception("Error while streaming response")

            return StreamingResponse(async_stream(), media_type=cls.mime_type())

        elif inspect.isgenerator(obj):
            trial, obj = itertools.tee(obj)
            try:
                next(trial)  # try if there is any error before the first yield
            except StopIteration:
                pass

            def content_stream() -> t.Generator[str | bytes, None, None]:
                try:
                    for item in obj:
                        if isinstance(item, (str, bytes)):
                            yield item
                        else:
                            obj_item = (
                                cls(item) if issubclass(cls, IORootModel) else item
                            )
                            yield from serde.serialize_model(
                                t.cast(IODescriptor, obj_item)
                            ).data
                except Exception:
                    logger.exception("Error while streaming response")

            return StreamingResponse(content_stream(), media_type=cls.mime_type())
        elif not issubclass(cls, IORootModel):
            if cls.multipart_fields:
                return Response(
                    "Multipart response is not supported yet", status_code=500
                )
            payload = serde.serialize_model(t.cast(IODescriptor, obj))
            return IterableResponse(
                content=payload.data,
                media_type=cls.mime_type(),
                headers=payload.headers,
            )
        else:
            if is_file_type(type(obj)):
                if isinstance(obj, pathlib.PurePath):
                    media_type = mimetypes.guess_type(obj)[0] or cls.mime_type()
                    should_inline = media_type.startswith("image")
                    content_disposition_type = (
                        "inline" if should_inline else "attachment"
                    )
                    return FileResponse(
                        obj,
                        filename=obj.name,
                        media_type=media_type,
                        content_disposition_type=content_disposition_type,
                    )
                else:  # is PIL Image
                    buffer = io.BytesIO()
                    image_format = obj.format or "PNG"
                    obj.save(buffer, format=image_format)
                    return Response(
                        content=buffer.getvalue(),
                        media_type=f"image/{image_format.lower()}",
                    )

            if not isinstance(obj, IORootModel):
                ins: IODescriptor = t.cast(IODescriptor, cls(obj))
            else:
                ins = t.cast(IODescriptor, obj)
            if isinstance(rendered := ins.model_dump(), (str, bytes)):
                return Response(content=rendered, media_type=cls.mime_type())
            else:
                payload = serde.serialize_model(ins)
                return IterableResponse(
                    content=payload.data,
                    media_type=cls.mime_type(),
                    headers=payload.headers,
                )
Convert a output value to HTTP response
src/_bentoml_sdk/io_models.py