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.

feat(blocks): add file input support to Replicate model block (#13272)

Zamil Majdy6c2faf0c1566
diff --git a/autogpt_platform/backend/backend/blocks/replicate/replicate_block.py b/autogpt_platform/backend/backend/blocks/replicate/replicate_block.py
index 99a66dbff7..7050f99883 100644
--- a/autogpt_platform/backend/backend/blocks/replicate/replicate_block.py
+++ b/autogpt_platform/backend/backend/blocks/replicate/replicate_block.py
@@ -1,3 +1,4 @@
+import asyncio
import logging
from typing import Optional
@@ -17,6 +18,7 @@ from backend.blocks.replicate._auth import (
ReplicateCredentialsInput,
)
from backend.blocks.replicate._helper import extract_result
+from backend.data.execution import ExecutionContext
from backend.data.model import (
APIKeyCredentials,
CredentialsField,
@@ -24,6 +26,7 @@ from backend.data.model import (
SchemaField,
)
from backend.util.exceptions import BlockExecutionError, BlockInputError
+from backend.util.file import MediaFileType, store_media_file
logger = logging.getLogger(__name__)
@@ -67,6 +70,29 @@ class ReplicateModelBlock(Block):
placeholder='{"prompt": "a beautiful landscape", "num_outputs": 1, "generate_audio": false}',
advanced=False,
)
+ files: list[MediaFileType] = SchemaField(
+ default_factory=list,
+ description=(
+ "Files (image, audio, video, etc.) to send to the model. Each "
+ "file is uploaded to Replicate and passed to the model under "
+ "the field named by ``file_input_field``. Pass file references "
+ "(URLs, uploaded files) here instead of inlining base64 in "
+ "``model_inputs``."
+ ),
+ advanced=False,
+ )
+ file_input_field: str = SchemaField(
+ default="image",
+ description=(
+ "Name of the model input field that receives the uploaded "
+ "``files``. Defaults to ``image``, the most common name. Check "
+ "the model's schema on Replicate for the exact name (common "
+ "alternatives: ``input_image``, ``img``, ``image_input``, "
+ "``audio``, ``video``, ``mask``). A single file is sent as one "
+ "value; multiple files are sent as a list."
+ ),
+ advanced=False,
+ )
version: Optional[str] = SchemaField(
default=None,
description="Specific version hash of the model (optional)",
@@ -110,7 +136,12 @@ class ReplicateModelBlock(Block):
)
async def run(
- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs
+ self,
+ input_data: Input,
+ *,
+ credentials: APIKeyCredentials,
+ execution_context: ExecutionContext,
+ **kwargs,
) -> BlockOutput:
"""
Execute the Replicate model with the provided inputs.
@@ -118,6 +149,7 @@ class ReplicateModelBlock(Block):
Args:
input_data: The input data containing model name and inputs
credentials: The API credentials
+ execution_context: Context used to resolve uploaded file references
Yields:
BlockOutput containing the model results and metadata
@@ -128,9 +160,8 @@ class ReplicateModelBlock(Block):
else:
model_ref = input_data.model_name
logger.debug(f"Running Replicate model: {model_ref}")
- result = await self.run_model(
- model_ref, input_data.model_inputs, credentials.api_key
- )
+ model_inputs = await self._build_model_inputs(input_data, execution_context)
+ result = await self.run_model(model_ref, model_inputs, credentials.api_key)
yield "result", result
yield "status", "succeeded"
yield "model_name", input_data.model_name
@@ -157,6 +188,38 @@ class ReplicateModelBlock(Block):
block_id=self.id,
) from e
+ async def _build_model_inputs(
+ self, input_data: Input, execution_context: ExecutionContext
+ ) -> dict:
+ """Merge uploaded ``files`` into ``model_inputs`` under ``file_input_field``.
+
+ Files are converted to data URIs so Replicate can fetch them, letting
+ AutoPilot pass file references instead of inlining base64 by hand. A
+ single file is bound as one value; multiple files as a list — matching
+ how most Replicate model schemas type their file fields.
+ """
+ model_inputs: dict[str, str | int | float | bool | list[str]] = dict(
+ input_data.model_inputs
+ )
+ if not input_data.files:
+ return model_inputs
+
+ uploaded = await asyncio.gather(
+ *(
+ store_media_file(
+ file=file,
+ execution_context=execution_context,
+ return_format="for_external_api",
+ )
+ for file in input_data.files
+ )
+ )
+ data_uris = [str(uri) for uri in uploaded]
+ model_inputs[input_data.file_input_field] = (
+ data_uris[0] if len(data_uris) == 1 else data_uris
+ )
+ return model_inputs
+
async def run_model(self, model_ref: str, model_inputs: dict, api_key: SecretStr):
"""
Run the Replicate model. This method can be mocked for testing.
diff --git a/autogpt_platform/backend/backend/blocks/replicate/replicate_block_file_input_test.py b/autogpt_platform/backend/backend/blocks/replicate/replicate_block_file_input_test.py
new file mode 100644
index 0000000000..1c81271604
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/replicate/replicate_block_file_input_test.py
@@ -0,0 +1,121 @@
+"""Unit tests for ReplicateModelBlock file-input handling.
+
+Verifies that uploaded ``files`` are merged into ``model_inputs`` under
+``file_input_field`` so AutoPilot can pass file references instead of inlining
+base64 into the inputs dict by hand:
+
+1. No files → model_inputs passed through unchanged (and not mutated in place)
+2. Single file → bound as a single data URI under the default field ``image``
+3. Multiple files → bound as a list of data URIs
+4. Custom ``file_input_field`` → files bound under the chosen name
+5. files take precedence over a same-named key in model_inputs
+"""
+
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from backend.blocks.replicate._auth import TEST_CREDENTIALS_INPUT
+from backend.blocks.replicate.replicate_block import ReplicateModelBlock
+from backend.data.execution import ExecutionContext
+
+
+def _make_input(**overrides):
+ base = {
+ "credentials": TEST_CREDENTIALS_INPUT,
+ "model_name": "owner/model",
+ }
+ base.update(overrides)
+ return ReplicateModelBlock.Input(**base)
+
+
+def _exec_context():
+ return ExecutionContext(user_id="user-1", graph_exec_id="exec-1")
+
+
+async def test_no_files_returns_inputs_unchanged():
+ block = ReplicateModelBlock()
+ original = {"prompt": "hi", "num_outputs": 1}
+ input_data = _make_input(model_inputs=dict(original))
+
+ result = await block._build_model_inputs(input_data, _exec_context())
+
+ assert result == original
+ # The returned dict must be a copy, not the schema's own dict.
+ assert result is not input_data.model_inputs
+
+
+async def test_single_file_bound_as_string_under_default_field():
+ block = ReplicateModelBlock()
+ input_data = _make_input(
+ model_inputs={"prompt": "describe"},
+ files=["workspace://abc"],
+ )
+
+ with patch(
+ "backend.blocks.replicate.replicate_block.store_media_file",
+ new=AsyncMock(return_value="data:image/png;base64,AAAA"),
+ ):
+ result = await block._build_model_inputs(input_data, _exec_context())
+
+ assert result == {
+ "prompt": "describe",
+ "image": "data:image/png;base64,AAAA",
+ }
+
+
+async def test_multiple_files_bound_as_list():
+ block = ReplicateModelBlock()
+ input_data = _make_input(
+ files=["workspace://a", "workspace://b"],
+ )
+
+ with patch(
+ "backend.blocks.replicate.replicate_block.store_media_file",
+ new=AsyncMock(
+ side_effect=["data:image/png;base64,A", "data:image/png;base64,B"]
+ ),
+ ):
+ result = await block._build_model_inputs(input_data, _exec_context())
+
+ assert result["image"] == [
+ "data:image/png;base64,A",
+ "data:image/png;base64,B",
+ ]
+
+
+async def test_custom_file_input_field():
+ block = ReplicateModelBlock()
+ input_data = _make_input(
+ files=["workspace://a"],
+ file_input_field="input_image",
+ )
+
+ with patch(
+ "backend.blocks.replicate.replicate_block.store_media_file",
+ new=AsyncMock(return_value="data:image/png;base64,Z"),
+ ):
+ result = await block._build_model_inputs(input_data, _exec_context())
+
+ assert result == {"input_image": "data:image/png;base64,Z"}
+
+
+async def test_files_override_same_named_model_input():
+ block = ReplicateModelBlock()
+ input_data = _make_input(
+ model_inputs={"image": "stale-value"},
+ files=["workspace://a"],
+ )
+
+ with patch(
+ "backend.blocks.replicate.replicate_block.store_media_file",
+ new=AsyncMock(return_value="data:image/png;base64,NEW"),
+ ):
+ result = await block._build_model_inputs(input_data, _exec_context())
+
+ assert result["image"] == "data:image/png;base64,NEW"
diff --git a/docs/integrations/block-integrations/replicate/replicate_block.md b/docs/integrations/block-integrations/replicate/replicate_block.md
index be4ea759b8..d096ae4125 100644
--- a/docs/integrations/block-integrations/replicate/replicate_block.md
+++ b/docs/integrations/block-integrations/replicate/replicate_block.md
@@ -21,6 +21,8 @@ The block waits for completion and returns the model output along with status in
|-------|-------------|------|----------|
| model_name | The Replicate model name (format: 'owner/model-name') | str | Yes |
| model_inputs | Dictionary of inputs to pass to the model. Values may be strings, integers, floats, or booleans — Replicate model schemas commonly require booleans (e.g. ``generate_audio``, ``safety_checker``) and floats (e.g. ``temperature``, ``guidance_scale``). | Dict[str, str \| int \| float \| bool] | No |
+| files | Files (image, audio, video, etc.) to send to the model. Each file is uploaded to Replicate and passed to the model under the field named by ``file_input_field``. Pass file references (URLs, uploaded files) here instead of inlining base64 in ``model_inputs``. | List[str (file)] | No |
+| file_input_field | Name of the model input field that receives the uploaded ``files``. Defaults to ``image``, the most common name. Check the model's schema on Replicate for the exact name (common alternatives: ``input_image``, ``img``, ``image_input``, ``audio``, ``video``, ``mask``). A single file is sent as one value; multiple files are sent as a list. | str | No |
| version | Specific version hash of the model (optional) | str | No |
### Outputs