From 88455be8cf76c09fa01b0ff6602769a6888c8d62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Gr=C3=B3dek?= Date: Wed, 20 Sep 2023 08:45:02 +0200 Subject: [PATCH] Add function to build docker from in-memory dockerfile --- .../langchain/utilities/docker_containers.py | 27 +++++++++++++++++++ .../utilities/test_docker_containers.py | 6 +++++ 2 files changed, 33 insertions(+) diff --git a/libs/langchain/langchain/utilities/docker_containers.py b/libs/langchain/langchain/utilities/docker_containers.py index c86409d4167af..08d1bf567ffc2 100644 --- a/libs/langchain/langchain/utilities/docker_containers.py +++ b/libs/langchain/langchain/utilities/docker_containers.py @@ -141,6 +141,33 @@ def from_dockerfile( return cls(name=img_name) + @classmethod + def from_dockerfile_content( + cls, + dockerfile_str: str, + name: Union[str, Callable[[], str]] = generate_langchain_container_tag, + **kwargs: Any, + ) -> "DockerImage": + """Build a new image from Dockerfile given a string with Dockerfile content.""" + + img_name = ( + name + if isinstance(name, str) and name + else generate_langchain_container_tag() + ) + import io + + buff = io.BytesIO(dockerfile_str.encode("utf-8")) + + docker_client = get_docker_client() + from pathlib import Path + + docker_client.images.build( + fileobj=buff, tag=img_name, rm=True, path=str(Path.cwd()), **kwargs + ) + + return cls(name=img_name) + class DockerContainer: """An isolated environment for running commands, based on docker container. diff --git a/libs/langchain/tests/integration_tests/utilities/test_docker_containers.py b/libs/langchain/tests/integration_tests/utilities/test_docker_containers.py index 459cd9f2176d3..4cfa458226489 100644 --- a/libs/langchain/tests/integration_tests/utilities/test_docker_containers.py +++ b/libs/langchain/tests/integration_tests/utilities/test_docker_containers.py @@ -53,6 +53,12 @@ def test_build_image_from_dockerfile_dirpath() -> None: run_container_cowsay(image) +@pytest.mark.requires("docker") +def test_build_image_from_dockerfile_string_content() -> None: + dockerfile_str = "FROM alpine\nRUN touch /animal.txt" + DockerImage.from_dockerfile_content(dockerfile_str) + + @pytest.mark.requires("docker") def test_docker_spawn_run_works() -> None: container = DockerContainer(DockerImage.from_tag("alpine"))