mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-12-03 11:03:07 +01:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
441a583d3f | ||
|
|
b810003ced |
No files matched your search
@@ -13,7 +13,11 @@ import click
|
||||
import httpx
|
||||
|
||||
from langgraph_cli.schemas import Config, Distros
|
||||
from langgraph_cli.uv_lock import python_config_to_docker_uv_lock
|
||||
from langgraph_cli.uv_lock import (
|
||||
_load_pyproject,
|
||||
_normalize_package_name,
|
||||
python_config_to_docker_uv_lock,
|
||||
)
|
||||
|
||||
MIN_NODE_VERSION = "20"
|
||||
DEFAULT_NODE_VERSION = "20"
|
||||
@@ -153,13 +157,14 @@ def _get_pip_cleanup_lines(
|
||||
to_uninstall: tuple[str] | None,
|
||||
pip_installer: Literal["uv", "pip"],
|
||||
) -> str:
|
||||
# One RUN, so BuildKit takes one snapshot for the whole tail instead of one
|
||||
# per step. Commands keep their order and are chained with `&&`; each
|
||||
# `rm -rf ... || true` group is wrapped in a subshell so its `|| true`
|
||||
# only covers that group, exactly as when it was its own RUN.
|
||||
commands = [
|
||||
f"""# -- Ensure user deps didn't inadvertently overwrite langgraph-api
|
||||
RUN mkdir -p /api/langgraph_api /api/langgraph_runtime /api/langgraph_license && \
|
||||
touch /api/langgraph_api/__init__.py /api/langgraph_runtime/__init__.py /api/langgraph_license/__init__.py
|
||||
RUN PYTHONDONTWRITEBYTECODE=1 {install_cmd} --no-cache-dir --no-deps -e /api
|
||||
# -- End of ensuring user deps didn't inadvertently overwrite langgraph-api --
|
||||
# -- Removing build deps from the final image ~<:===~~~ --"""
|
||||
"mkdir -p /api/langgraph_api /api/langgraph_runtime /api/langgraph_license",
|
||||
"touch /api/langgraph_api/__init__.py /api/langgraph_runtime/__init__.py /api/langgraph_license/__init__.py",
|
||||
f"PYTHONDONTWRITEBYTECODE=1 {install_cmd} --no-cache-dir --no-deps -e /api",
|
||||
]
|
||||
if to_uninstall:
|
||||
for pack in to_uninstall:
|
||||
@@ -168,30 +173,29 @@ RUN PYTHONDONTWRITEBYTECODE=1 {install_cmd} --no-cache-dir --no-deps -e /api
|
||||
f"Invalid build tool: {pack}; must be one of {', '.join(_BUILD_TOOLS)}"
|
||||
)
|
||||
packs_str = " ".join(sorted(to_uninstall))
|
||||
commands.append(f"RUN pip uninstall -y {packs_str}")
|
||||
commands.append(f"pip uninstall -y {packs_str}")
|
||||
# Ensure the directories are removed entirely
|
||||
packages_rm = " ".join(
|
||||
f"/usr/local/lib/python*/site-packages/{pack}*" for pack in to_uninstall
|
||||
)
|
||||
if "pip" in to_uninstall:
|
||||
packages_rm += ' && find /usr/local/bin -name "pip*" -delete || true'
|
||||
commands.append(f"RUN rm -rf {packages_rm}")
|
||||
commands.append(f"(rm -rf {packages_rm})")
|
||||
wolfi_packages_rm = " ".join(
|
||||
f"/usr/lib/python*/site-packages/{pack}*" for pack in to_uninstall
|
||||
)
|
||||
if "pip" in to_uninstall:
|
||||
wolfi_packages_rm += ' && find /usr/bin -name "pip*" -delete || true'
|
||||
commands.append(f"RUN rm -rf {wolfi_packages_rm}")
|
||||
commands.append(f"(rm -rf {wolfi_packages_rm})")
|
||||
if pip_installer == "uv":
|
||||
commands.append(
|
||||
f"RUN uv pip uninstall --system {packs_str} && rm /usr/bin/uv /usr/bin/uvx"
|
||||
)
|
||||
else:
|
||||
if pip_installer == "uv":
|
||||
commands.append(
|
||||
"RUN rm /usr/bin/uv /usr/bin/uvx\n# -- End of build deps removal --"
|
||||
)
|
||||
return "\n".join(commands)
|
||||
commands.append(f"uv pip uninstall --system {packs_str}")
|
||||
if pip_installer == "uv":
|
||||
commands.append("rm /usr/bin/uv /usr/bin/uvx")
|
||||
return (
|
||||
"# -- Ensure user deps didn't inadvertently overwrite langgraph-api, "
|
||||
"then remove build deps from the final image --\n"
|
||||
"RUN " + " && \\\n ".join(commands)
|
||||
)
|
||||
|
||||
|
||||
def _parse_version(version_str: str) -> tuple[int, int]:
|
||||
@@ -1393,6 +1397,149 @@ def get_build_tools_to_uninstall(config: Config) -> tuple[str]:
|
||||
)
|
||||
|
||||
|
||||
_SAFE_MOUNT_PATH = re.compile(r"^[A-Za-z0-9._/+-]+$")
|
||||
_UNSAFE_REQUIREMENT_CHARS = re.compile(r"[\x00-\x1f\x7f\\$`]")
|
||||
_REQUIREMENT_NAME = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)\s*(.*)$", re.DOTALL)
|
||||
|
||||
|
||||
def _static_project_dependencies(
|
||||
pkg_dir: pathlib.Path,
|
||||
) -> tuple[str, list[str]] | None:
|
||||
"""Return a local package's (normalized name, dependencies) if both are static.
|
||||
|
||||
Returns None whenever the dependencies installed by `pip install -e .` might
|
||||
differ from `[project].dependencies`: setup.py/setup.cfg, dynamic metadata,
|
||||
uv sources/workspaces, or Poetry dependency tables.
|
||||
"""
|
||||
if (pkg_dir / "setup.py").exists() or (pkg_dir / "setup.cfg").exists():
|
||||
return None
|
||||
try:
|
||||
pyproject = _load_pyproject(pkg_dir / "pyproject.toml")
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
project = pyproject.get("project")
|
||||
tool = pyproject.get("tool", {})
|
||||
if not isinstance(project, dict) or not isinstance(tool, dict):
|
||||
return None
|
||||
name = project.get("name")
|
||||
dependencies = project.get("dependencies", [])
|
||||
dynamic = project.get("dynamic", [])
|
||||
uv = tool.get("uv", {})
|
||||
poetry = tool.get("poetry", {})
|
||||
if (
|
||||
not isinstance(name, str)
|
||||
or not isinstance(dependencies, list)
|
||||
or not all(isinstance(dep, str) for dep in dependencies)
|
||||
or not isinstance(dynamic, list)
|
||||
or "dependencies" in dynamic
|
||||
or not isinstance(uv, dict)
|
||||
or "sources" in uv
|
||||
or "workspace" in uv
|
||||
or not isinstance(poetry, dict)
|
||||
or "dependencies" in poetry
|
||||
):
|
||||
return None
|
||||
return _normalize_package_name(name), dependencies
|
||||
|
||||
|
||||
def _local_deps_preinstall_str(
|
||||
config_path: pathlib.Path, local_deps: LocalDeps, install_cmd: str
|
||||
) -> str:
|
||||
"""Pre-install the third-party dependencies of local packages before their source.
|
||||
|
||||
Only `pyproject.toml` (and `uv.toml`) are bind-mounted, so this layer stays
|
||||
cached when only source files change. Packages are processed in the same
|
||||
order as the `/deps/*` install loop, and that loop still runs unchanged
|
||||
afterwards and remains authoritative: this step only installs what it
|
||||
would install anyway, and if it fails the loop does all the work as before.
|
||||
|
||||
Returns "" (today's layout) unless every local package has static metadata.
|
||||
A dependency on another local package is replaced by that package's own
|
||||
third-party dependencies, so each resolution sees the same requirements.
|
||||
"""
|
||||
if not local_deps.real_pkgs:
|
||||
return ""
|
||||
# Faux packages are local too; their generated pyproject has no dependencies.
|
||||
declared: dict[str, list[str]] = {
|
||||
_normalize_package_name(path.name): [] for path in local_deps.faux_pkgs
|
||||
}
|
||||
packages: list[tuple[str, str, pathlib.Path]] = []
|
||||
for path, (_, container_name) in local_deps.real_pkgs.items():
|
||||
static = _static_project_dependencies(path)
|
||||
if static is None or static[0] in declared:
|
||||
return ""
|
||||
declared[static[0]] = static[1]
|
||||
packages.append((container_name, static[0], path))
|
||||
third_party: dict[str, list[str]] = {name: [] for name in declared}
|
||||
siblings: dict[str, list[str]] = {name: [] for name in declared}
|
||||
for name, dependencies in declared.items():
|
||||
for requirement in dependencies:
|
||||
match = _REQUIREMENT_NAME.match(requirement)
|
||||
if (
|
||||
match is None
|
||||
or _UNSAFE_REQUIREMENT_CHARS.search(requirement)
|
||||
or "@" in requirement.split(";", 1)[0]
|
||||
):
|
||||
return ""
|
||||
dep_name, rest = _normalize_package_name(match.group(1)), match.group(2)
|
||||
if dep_name == name:
|
||||
return ""
|
||||
if dep_name in declared:
|
||||
# A version specifier is fine (the install loop still checks it);
|
||||
# extras or markers would change which sibling deps apply.
|
||||
if rest.startswith("[") or ";" in rest:
|
||||
return ""
|
||||
siblings[name].append(dep_name)
|
||||
else:
|
||||
third_party[name].append(requirement)
|
||||
|
||||
def flatten(name: str, seen: set[str]) -> list[str]:
|
||||
requirements = list(third_party[name])
|
||||
for sibling in siblings[name]:
|
||||
if sibling not in seen:
|
||||
seen.add(sibling)
|
||||
requirements.extend(flatten(sibling, seen))
|
||||
return requirements
|
||||
|
||||
mounts: list[str] = []
|
||||
steps: list[str] = []
|
||||
# Same order as the `/deps/*` glob in the install loop (C collation in both images).
|
||||
for container_name, name, path in sorted(packages, key=lambda p: p[0].encode()):
|
||||
requirements = list(dict.fromkeys(flatten(name, {name})))
|
||||
if not requirements:
|
||||
continue
|
||||
for manifest in ("pyproject.toml", "uv.toml"):
|
||||
if not (path / manifest).exists():
|
||||
continue
|
||||
target = f"/deps/{container_name}/{manifest}"
|
||||
if path in local_deps.additional_contexts:
|
||||
values = [container_name, target]
|
||||
source = f"from={container_name},source={manifest}"
|
||||
else:
|
||||
relative = (path.relative_to(config_path.parent) / manifest).as_posix()
|
||||
values = [relative, target]
|
||||
source = f"source={relative}"
|
||||
# Mount options are comma-separated and unquoted; also guards `cd`.
|
||||
if not all(_SAFE_MOUNT_PATH.match(value) for value in values):
|
||||
return ""
|
||||
mounts.append(f"--mount=type=bind,{source},target={target}")
|
||||
steps.append(
|
||||
f"(cd /deps/{container_name} && {install_cmd} "
|
||||
+ " ".join(shlex.quote(r) for r in requirements)
|
||||
+ ")"
|
||||
)
|
||||
if not steps:
|
||||
return ""
|
||||
joined_steps = " && \\\n ".join(steps)
|
||||
return (
|
||||
"# -- Pre-installing local package dependencies --\n"
|
||||
"RUN " + " \\\n ".join(mounts) + " \\\n"
|
||||
f" ({joined_steps}) || \\\n"
|
||||
" echo 'Dependency pre-install failed; the install below resolves them.'\n"
|
||||
"# -- End of pre-installing local package dependencies --"
|
||||
)
|
||||
|
||||
|
||||
def python_config_to_docker(
|
||||
config_path: pathlib.Path,
|
||||
config: Config,
|
||||
@@ -1541,8 +1688,19 @@ ADD {relpath} /deps/{name}
|
||||
else ""
|
||||
)
|
||||
|
||||
install_steps = [install_node_str, pip_config_file_str, pip_pkgs_str, pip_reqs_str]
|
||||
install_steps.extend([local_pkgs_str, faux_pkgs_str])
|
||||
# Set WORKDIR before the first source-dependent step so it stays cached
|
||||
# across source-only changes, instead of re-running after every one.
|
||||
workdir_str = f"WORKDIR {local_deps.working_dir}" if local_deps.working_dir else ""
|
||||
install_steps = [
|
||||
install_node_str,
|
||||
pip_config_file_str,
|
||||
pip_pkgs_str,
|
||||
workdir_str,
|
||||
pip_reqs_str,
|
||||
_local_deps_preinstall_str(config_path, local_deps, global_reqs_pip_install),
|
||||
local_pkgs_str,
|
||||
faux_pkgs_str,
|
||||
]
|
||||
installs = f"{os.linesep}{os.linesep}".join(
|
||||
filter(
|
||||
None,
|
||||
@@ -1558,7 +1716,6 @@ ADD {relpath} /deps/{name}
|
||||
[
|
||||
"# -- Installing JS dependencies --",
|
||||
f"ENV NODE_VERSION={config.get('node_version') or DEFAULT_NODE_VERSION}",
|
||||
f"WORKDIR {local_deps.working_dir}",
|
||||
f"RUN {_get_node_pm_install_cmd(config_path.parent)} && tsx /api/langgraph_api/js/build.mts",
|
||||
"# -- End of JS dependencies install --",
|
||||
]
|
||||
@@ -1607,8 +1764,6 @@ ADD {relpath} /deps/{name}
|
||||
to_uninstall=build_tools_to_uninstall,
|
||||
pip_installer=pip_installer,
|
||||
),
|
||||
"",
|
||||
f"WORKDIR {local_deps.working_dir}" if local_deps.working_dir else "",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@@ -135,6 +135,7 @@ services:
|
||||
dockerfile_inline: |
|
||||
# syntax=docker/dockerfile:1.4
|
||||
FROM langchain/langgraph-api:3.11
|
||||
WORKDIR /deps/cli
|
||||
# -- Adding local package . --
|
||||
ADD . /deps/cli
|
||||
# -- End of local package . --
|
||||
@@ -146,7 +147,6 @@ services:
|
||||
# -- End of local dependencies install --
|
||||
ENV LANGSERVE_GRAPHS='{{"agent": "agent.py:graph"}}'
|
||||
{textwrap.indent(textwrap.dedent(FORMATTED_CLEANUP_LINES), " ")}
|
||||
WORKDIR /deps/cli
|
||||
|
||||
develop:
|
||||
watch:
|
||||
|
||||
@@ -910,6 +910,7 @@ def test_config_to_docker_simple():
|
||||
expected_docker_stdin = f"""\
|
||||
# syntax=docker/dockerfile:1.4
|
||||
FROM langchain/langgraph-api:3.11
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
# -- Installing local requirements --
|
||||
COPY --from=outer-requirements.txt requirements.txt /deps/outer-graphs_reqs_a/graphs_reqs_a/requirements.txt
|
||||
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -r /deps/outer-graphs_reqs_a/graphs_reqs_a/requirements.txt
|
||||
@@ -950,8 +951,7 @@ RUN for dep in /deps/*; do echo "Installing $dep"; if [
|
||||
# -- End of local dependencies install --
|
||||
ENV LANGGRAPH_HTTP='{{"app": "/deps/examples/my_app.py:app"}}'
|
||||
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
|
||||
{FORMATTED_CLEANUP_LINES}
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests\
|
||||
{FORMATTED_CLEANUP_LINES}\
|
||||
"""
|
||||
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
|
||||
|
||||
@@ -974,6 +974,7 @@ def test_config_to_docker_outside_path():
|
||||
"""\
|
||||
# syntax=docker/dockerfile:1.4
|
||||
FROM langchain/langgraph-api:3.11
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
# -- Adding non-package dependency unit_tests --
|
||||
ADD . /deps/outer-unit_tests/unit_tests
|
||||
RUN set -ex && \\
|
||||
@@ -1008,9 +1009,6 @@ RUN for dep in /deps/*; do echo "Installing $dep"; if [
|
||||
ENV LANGSERVE_GRAPHS='{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}'
|
||||
"""
|
||||
+ FORMATTED_CLEANUP_LINES
|
||||
+ """
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests\
|
||||
"""
|
||||
)
|
||||
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
|
||||
assert additional_contexts == {
|
||||
@@ -1035,6 +1033,7 @@ def test_config_to_docker_pipconfig():
|
||||
"""\
|
||||
FROM langchain/langgraph-api:3.11
|
||||
ADD pipconfig.txt /pipconfig.txt
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
# -- Adding non-package dependency unit_tests --
|
||||
ADD . /deps/outer-unit_tests/unit_tests
|
||||
RUN set -ex && \\
|
||||
@@ -1055,9 +1054,6 @@ RUN for dep in /deps/*; do echo "Installing $dep"; if [
|
||||
ENV LANGSERVE_GRAPHS='{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}'
|
||||
"""
|
||||
+ FORMATTED_CLEANUP_LINES
|
||||
+ """
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests\
|
||||
"""
|
||||
)
|
||||
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
|
||||
assert additional_contexts == {}
|
||||
@@ -1144,6 +1140,12 @@ dependencies = ["langchain"]"""
|
||||
os.remove(pyproject_path)
|
||||
expected_docker_stdin = (
|
||||
"""FROM langchain/langgraph-api:3.11
|
||||
WORKDIR /deps/unit_tests
|
||||
# -- Pre-installing local package dependencies --
|
||||
RUN --mount=type=bind,source=pyproject.toml,target=/deps/unit_tests/pyproject.toml \\
|
||||
((cd /deps/unit_tests && PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt langchain)) || \\
|
||||
echo 'Dependency pre-install failed; the install below resolves them.'
|
||||
# -- End of pre-installing local package dependencies --
|
||||
# -- Adding local package . --
|
||||
ADD . /deps/unit_tests
|
||||
# -- End of local package . --
|
||||
@@ -1153,9 +1155,6 @@ RUN for dep in /deps/*; do echo "Installing $dep"; if [
|
||||
ENV LANGSERVE_GRAPHS='{"agent": "/deps/unit_tests/graphs/agent.py:graph"}'
|
||||
"""
|
||||
+ FORMATTED_CLEANUP_LINES
|
||||
+ "\n"
|
||||
+ "WORKDIR /deps/unit_tests"
|
||||
""
|
||||
)
|
||||
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
|
||||
assert additional_contexts == {}
|
||||
@@ -1525,6 +1524,7 @@ def test_config_to_docker_gen_ui_python():
|
||||
|
||||
expected_docker_stdin = f"""FROM langchain/langgraph-api:3.11
|
||||
RUN /storage/install-node.sh
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
# -- Adding non-package dependency unit_tests --
|
||||
ADD . /deps/outer-unit_tests/unit_tests
|
||||
RUN set -ex && \\
|
||||
@@ -1547,11 +1547,9 @@ ENV LANGGRAPH_UI_CONFIG='{{"shared": ["nuqs"]}}'
|
||||
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
|
||||
# -- Installing JS dependencies --
|
||||
ENV NODE_VERSION=20
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
RUN npm i && tsx /api/langgraph_api/js/build.mts
|
||||
# -- End of JS dependencies install --
|
||||
{FORMATTED_CLEANUP_LINES}
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests"""
|
||||
{FORMATTED_CLEANUP_LINES}"""
|
||||
|
||||
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
|
||||
assert additional_contexts == {}
|
||||
@@ -1572,6 +1570,7 @@ def test_config_to_docker_multiplatform():
|
||||
|
||||
expected_docker_stdin = f"""FROM langchain/langgraph-api:3.11
|
||||
RUN /storage/install-node.sh
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
# -- Adding non-package dependency unit_tests --
|
||||
ADD . /deps/outer-unit_tests/unit_tests
|
||||
RUN set -ex && \\
|
||||
@@ -1592,11 +1591,9 @@ RUN for dep in /deps/*; do echo "Installing $dep"; if [
|
||||
ENV LANGSERVE_GRAPHS='{{"python": "/deps/outer-unit_tests/unit_tests/multiplatform/python.py:graph", "js": "/deps/outer-unit_tests/unit_tests/multiplatform/js.mts:graph"}}'
|
||||
# -- Installing JS dependencies --
|
||||
ENV NODE_VERSION=22
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
RUN npm i && tsx /api/langgraph_api/js/build.mts
|
||||
# -- End of JS dependencies install --
|
||||
{FORMATTED_CLEANUP_LINES}
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests"""
|
||||
{FORMATTED_CLEANUP_LINES}"""
|
||||
|
||||
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
|
||||
assert additional_contexts == {}
|
||||
@@ -2803,7 +2800,7 @@ def test_config_retain_build_tools():
|
||||
"/usr/local/lib/python*/site-packages/" + pckg + "*" in docker_true
|
||||
for pckg in _BUILD_TOOLS
|
||||
)
|
||||
assert "RUN pip uninstall -y pip setuptools wheel" not in docker_true
|
||||
assert "pip uninstall" not in docker_true
|
||||
config_false = validate_config(
|
||||
{**copy.deepcopy(base_config), "keep_pkg_tools": False}
|
||||
)
|
||||
@@ -2814,7 +2811,7 @@ def test_config_retain_build_tools():
|
||||
"/usr/local/lib/python*/site-packages/" + pckg + "*" in docker_false
|
||||
for pckg in _BUILD_TOOLS
|
||||
)
|
||||
assert "RUN pip uninstall -y pip setuptools wheel" in docker_false
|
||||
assert "pip uninstall -y pip setuptools wheel && \\" in docker_false
|
||||
config_list = validate_config(
|
||||
{**copy.deepcopy(base_config), "keep_pkg_tools": ["pip", "setuptools"]}
|
||||
)
|
||||
@@ -2829,8 +2826,79 @@ def test_config_retain_build_tools():
|
||||
"/usr/local/lib/python*/site-packages/" + pckg + "*" in docker_list
|
||||
for pckg in ("pip", "setuptools")
|
||||
)
|
||||
assert "RUN pip uninstall -y wheel" in docker_list
|
||||
assert "RUN pip uninstall -y pip setuptools" not in docker_list
|
||||
assert "pip uninstall -y wheel && \\" in docker_list
|
||||
assert "pip uninstall -y pip setuptools" not in docker_list
|
||||
|
||||
|
||||
_CLEANUP_PREFIX = """\
|
||||
# -- Ensure user deps didn't inadvertently overwrite langgraph-api, then remove build deps from the final image --
|
||||
RUN mkdir -p /api/langgraph_api /api/langgraph_runtime /api/langgraph_license && \\
|
||||
touch /api/langgraph_api/__init__.py /api/langgraph_runtime/__init__.py /api/langgraph_license/__init__.py && \\
|
||||
PYTHONDONTWRITEBYTECODE=1 {install_cmd} --no-cache-dir --no-deps -e /api"""
|
||||
_RM_ALL = """ && \\
|
||||
pip uninstall -y pip setuptools wheel && \\
|
||||
(rm -rf /usr/local/lib/python*/site-packages/pip* /usr/local/lib/python*/site-packages/setuptools* /usr/local/lib/python*/site-packages/wheel* && find /usr/local/bin -name "pip*" -delete || true) && \\
|
||||
(rm -rf /usr/lib/python*/site-packages/pip* /usr/lib/python*/site-packages/setuptools* /usr/lib/python*/site-packages/wheel* && find /usr/bin -name "pip*" -delete || true)"""
|
||||
_UV = "uv pip install --system"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("install_cmd", "to_uninstall", "pip_installer", "expected_tail"),
|
||||
[
|
||||
(
|
||||
_UV,
|
||||
_BUILD_TOOLS,
|
||||
"uv",
|
||||
_RM_ALL
|
||||
+ """ && \\
|
||||
uv pip uninstall --system pip setuptools wheel && \\
|
||||
rm /usr/bin/uv /usr/bin/uvx""",
|
||||
),
|
||||
("pip install", _BUILD_TOOLS, "pip", _RM_ALL),
|
||||
# keep_pkg_tools: true
|
||||
(_UV, (), "uv", " && \\\n rm /usr/bin/uv /usr/bin/uvx"),
|
||||
("pip install", (), "pip", ""),
|
||||
# keep_pkg_tools: ["pip", "setuptools"]
|
||||
(
|
||||
_UV,
|
||||
("wheel",),
|
||||
"uv",
|
||||
""" && \\
|
||||
pip uninstall -y wheel && \\
|
||||
(rm -rf /usr/local/lib/python*/site-packages/wheel*) && \\
|
||||
(rm -rf /usr/lib/python*/site-packages/wheel*) && \\
|
||||
uv pip uninstall --system wheel && \\
|
||||
rm /usr/bin/uv /usr/bin/uvx""",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_pip_cleanup_lines_single_run(
|
||||
install_cmd, to_uninstall, pip_installer, expected_tail
|
||||
):
|
||||
# The whole repair/cleanup tail is one RUN (one BuildKit snapshot), and
|
||||
# each `|| true` is scoped to its own `rm -rf` group by a subshell.
|
||||
actual = _get_pip_cleanup_lines(install_cmd, to_uninstall, pip_installer)
|
||||
assert actual == _CLEANUP_PREFIX.format(install_cmd=install_cmd) + expected_tail
|
||||
assert actual.count("RUN ") == 1
|
||||
|
||||
|
||||
def test_config_to_docker_workdir_before_sources():
|
||||
docker, _ = config_to_docker(
|
||||
PATH_TO_CONFIG,
|
||||
validate_config(
|
||||
{
|
||||
"dependencies": ["langchain", "."],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
}
|
||||
),
|
||||
base_image="langchain/langgraph-api",
|
||||
)
|
||||
lines = clean_empty_lines(docker).splitlines()
|
||||
workdir = lines.index("WORKDIR /deps/outer-unit_tests/unit_tests")
|
||||
# After the PyPI deps install (not source-dependent), before the first ADD.
|
||||
assert lines[workdir - 1].startswith("RUN ") and "langchain" in lines[workdir - 1]
|
||||
assert lines[workdir + 2] == "ADD . /deps/outer-unit_tests/unit_tests"
|
||||
assert [ln for ln in lines if ln.startswith("WORKDIR")] == [lines[workdir]]
|
||||
|
||||
|
||||
# config_to_compose
|
||||
@@ -2843,6 +2911,7 @@ def test_config_to_compose_simple_config():
|
||||
context: .
|
||||
dockerfile_inline: |
|
||||
FROM langchain/langgraph-api:3.11
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
# -- Adding non-package dependency unit_tests --
|
||||
ADD . /deps/outer-unit_tests/unit_tests
|
||||
RUN set -ex && \\
|
||||
@@ -2862,7 +2931,6 @@ def test_config_to_compose_simple_config():
|
||||
# -- End of local dependencies install --
|
||||
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
|
||||
{textwrap.indent(textwrap.dedent(FORMATTED_CLEANUP_LINES), " ")}
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
"""
|
||||
actual_compose_stdin = config_to_compose(
|
||||
PATH_TO_CONFIG,
|
||||
@@ -2884,6 +2952,7 @@ def test_config_to_compose_env_vars():
|
||||
context: .
|
||||
dockerfile_inline: |
|
||||
FROM langchain/langgraph-api-custom:3.11
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
# -- Adding non-package dependency unit_tests --
|
||||
ADD . /deps/outer-unit_tests/unit_tests
|
||||
RUN set -ex && \\
|
||||
@@ -2903,7 +2972,6 @@ def test_config_to_compose_env_vars():
|
||||
# -- End of local dependencies install --
|
||||
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
|
||||
{textwrap.indent(textwrap.dedent(FORMATTED_CLEANUP_LINES), " ")}
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
"""
|
||||
openai_api_key = "key"
|
||||
actual_compose_stdin = config_to_compose(
|
||||
@@ -2929,6 +2997,7 @@ def test_config_to_compose_env_file():
|
||||
context: .
|
||||
dockerfile_inline: |
|
||||
FROM langchain/langgraph-api:3.11
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
# -- Adding non-package dependency unit_tests --
|
||||
ADD . /deps/outer-unit_tests/unit_tests
|
||||
RUN set -ex && \\
|
||||
@@ -2948,7 +3017,6 @@ def test_config_to_compose_env_file():
|
||||
# -- End of local dependencies install --
|
||||
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
|
||||
{textwrap.indent(textwrap.dedent(FORMATTED_CLEANUP_LINES), " ")}
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
"""
|
||||
actual_compose_stdin = config_to_compose(
|
||||
PATH_TO_CONFIG,
|
||||
@@ -2967,6 +3035,7 @@ def test_config_to_compose_watch():
|
||||
context: .
|
||||
dockerfile_inline: |
|
||||
FROM langchain/langgraph-api:3.11
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
# -- Adding non-package dependency unit_tests --
|
||||
ADD . /deps/outer-unit_tests/unit_tests
|
||||
RUN set -ex && \\
|
||||
@@ -2986,7 +3055,6 @@ def test_config_to_compose_watch():
|
||||
# -- End of local dependencies install --
|
||||
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
|
||||
{textwrap.indent(textwrap.dedent(FORMATTED_CLEANUP_LINES), " ")}
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
|
||||
develop:
|
||||
watch:
|
||||
@@ -3014,6 +3082,7 @@ def test_config_to_compose_end_to_end():
|
||||
context: .
|
||||
dockerfile_inline: |
|
||||
FROM langchain/langgraph-api:3.11
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
# -- Adding non-package dependency unit_tests --
|
||||
ADD . /deps/outer-unit_tests/unit_tests
|
||||
RUN set -ex && \\
|
||||
@@ -3033,7 +3102,6 @@ def test_config_to_compose_end_to_end():
|
||||
# -- End of local dependencies install --
|
||||
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
|
||||
{textwrap.indent(textwrap.dedent(FORMATTED_CLEANUP_LINES), " ")}
|
||||
WORKDIR /deps/outer-unit_tests/unit_tests
|
||||
|
||||
develop:
|
||||
watch:
|
||||
@@ -3812,3 +3880,183 @@ class TestHasDisallowedBuildCommandContent:
|
||||
)
|
||||
def test_valid_commands_allowed(self, cmd: str) -> None:
|
||||
assert not has_disallowed_build_command_content(cmd)
|
||||
|
||||
|
||||
def _write_local_package(root: pathlib.Path, dirname: str, pyproject: str) -> None:
|
||||
(root / dirname).mkdir(parents=True, exist_ok=True)
|
||||
(root / dirname / "pyproject.toml").write_text(textwrap.dedent(pyproject))
|
||||
|
||||
|
||||
def _monorepo_docker(tmp_path: pathlib.Path, **config) -> str:
|
||||
"""Project `proj` depending on sibling local packages `b_lib` and `A_lib`."""
|
||||
_write_local_package(
|
||||
tmp_path,
|
||||
"A_lib",
|
||||
"""
|
||||
[project]
|
||||
name = "a-lib"
|
||||
version = "0.1"
|
||||
dependencies = ["httpx>=0.28", "tomli>=2 ; python_version < '3.11'"]
|
||||
""",
|
||||
)
|
||||
_write_local_package(
|
||||
tmp_path,
|
||||
"b_lib",
|
||||
"""
|
||||
[project]
|
||||
name = "b_lib"
|
||||
version = "0.1"
|
||||
dependencies = ["structlog", "A-Lib"]
|
||||
""",
|
||||
)
|
||||
_write_local_package(
|
||||
tmp_path,
|
||||
"proj",
|
||||
"""
|
||||
[project]
|
||||
name = "proj"
|
||||
version = "0.1"
|
||||
dependencies = ["tenacity", "b-lib>=0.1", "a_lib"]
|
||||
[tool.uv]
|
||||
default-groups = ["dev"]
|
||||
""",
|
||||
)
|
||||
(tmp_path / "proj" / "uv.toml").write_text("")
|
||||
(tmp_path / "proj" / "agent.py").write_text("graph = None\n")
|
||||
docker, _ = config_to_docker(
|
||||
tmp_path / "proj" / "langgraph.json",
|
||||
validate_config(
|
||||
{
|
||||
"dependencies": [".", "../b_lib", "../A_lib"],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
**config,
|
||||
}
|
||||
),
|
||||
base_image="langchain/langgraph-api",
|
||||
)
|
||||
return docker
|
||||
|
||||
|
||||
def test_config_to_docker_preinstalls_local_package_deps(tmp_path):
|
||||
docker = _monorepo_docker(tmp_path)
|
||||
install = "PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt"
|
||||
a_deps = "'httpx>=0.28' 'tomli>=2 ; python_version < '\"'\"'3.11'\"'\"''"
|
||||
# `/deps/*` glob order (A_lib < b_lib < proj); a dependency on a sibling is
|
||||
# replaced by the sibling's own third-party deps.
|
||||
expected = f"""\
|
||||
WORKDIR /deps/proj
|
||||
# -- Pre-installing local package dependencies --
|
||||
RUN --mount=type=bind,from=A_lib,source=pyproject.toml,target=/deps/A_lib/pyproject.toml \\
|
||||
--mount=type=bind,from=b_lib,source=pyproject.toml,target=/deps/b_lib/pyproject.toml \\
|
||||
--mount=type=bind,source=pyproject.toml,target=/deps/proj/pyproject.toml \\
|
||||
--mount=type=bind,source=uv.toml,target=/deps/proj/uv.toml \\
|
||||
((cd /deps/A_lib && {install} {a_deps}) && \\
|
||||
(cd /deps/b_lib && {install} structlog {a_deps}) && \\
|
||||
(cd /deps/proj && {install} tenacity structlog {a_deps})) || \\
|
||||
echo 'Dependency pre-install failed; the install below resolves them.'
|
||||
# -- End of pre-installing local package dependencies --
|
||||
# -- Adding local package . --
|
||||
ADD . /deps/proj
|
||||
"""
|
||||
assert expected in clean_empty_lines(docker)
|
||||
# The install loop that follows the source copy is unchanged.
|
||||
assert '(cd "$dep" && ' + install + " -e .)" in docker
|
||||
|
||||
|
||||
def test_config_to_docker_preinstall_respects_pip_installer(tmp_path):
|
||||
docker = _monorepo_docker(tmp_path, pip_installer="pip")
|
||||
assert (
|
||||
"(cd /deps/A_lib && PYTHONDONTWRITEBYTECODE=1 pip install --no-cache-dir "
|
||||
"-c /api/constraints.txt 'httpx>=0.28'"
|
||||
) in docker
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("dirname", "filename", "content"),
|
||||
[
|
||||
("proj", "setup.py", "from setuptools import setup; setup()"),
|
||||
("proj", "setup.cfg", "[options]\ninstall_requires = six"),
|
||||
(
|
||||
"b_lib",
|
||||
"pyproject.toml",
|
||||
'[project]\nname = "b_lib"\ndynamic = ["dependencies"]',
|
||||
),
|
||||
("b_lib", "pyproject.toml", '[tool.poetry]\nname = "b_lib"'),
|
||||
(
|
||||
"b_lib",
|
||||
"pyproject.toml",
|
||||
'[project]\nname = "b_lib"\n[tool.uv.sources]\nx = { path = "../x" }',
|
||||
),
|
||||
(
|
||||
"b_lib",
|
||||
"pyproject.toml",
|
||||
'[project]\nname = "b_lib"\n[tool.uv.workspace]\nmembers = []',
|
||||
),
|
||||
(
|
||||
"b_lib",
|
||||
"pyproject.toml",
|
||||
'[project]\nname = "b_lib"\n[tool.poetry.dependencies]\nsix = "*"',
|
||||
),
|
||||
(
|
||||
"b_lib",
|
||||
"pyproject.toml",
|
||||
'[project]\nname = "b_lib"\ndependencies = ["x @ file:///deps/x"]',
|
||||
),
|
||||
(
|
||||
"b_lib",
|
||||
"pyproject.toml",
|
||||
'[project]\nname = "b_lib"\ndependencies = ["a-lib[extra]"]',
|
||||
),
|
||||
(
|
||||
"b_lib",
|
||||
"pyproject.toml",
|
||||
'[project]\nname = "b_lib"\ndependencies = ["a-lib ; sys_platform == \'linux\'"]',
|
||||
),
|
||||
(
|
||||
"b_lib",
|
||||
"pyproject.toml",
|
||||
'[project]\nname = "b_lib"\ndependencies = ["b-lib"]',
|
||||
),
|
||||
(
|
||||
"b_lib",
|
||||
"pyproject.toml",
|
||||
'[project]\nname = "b_lib"\ndependencies = ["x$(id)"]',
|
||||
),
|
||||
("b_lib", "pyproject.toml", '[project]\nname = "a_lib"'),
|
||||
("b_lib", "pyproject.toml", "not toml ["),
|
||||
],
|
||||
)
|
||||
def test_config_to_docker_preinstall_falls_back(tmp_path, dirname, filename, content):
|
||||
"""Any local package whose installed deps might differ from its static
|
||||
`[project].dependencies` keeps today's layout for the whole config."""
|
||||
original_write = _write_local_package
|
||||
|
||||
def write(root, name, pyproject):
|
||||
original_write(root, name, pyproject)
|
||||
if name == dirname:
|
||||
(root / name / filename).write_text(content)
|
||||
|
||||
with patch(f"{__name__}._write_local_package", write):
|
||||
docker = _monorepo_docker(tmp_path)
|
||||
assert "Pre-installing" not in docker
|
||||
assert "--mount" not in docker
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dirname", ["my lib", "a,b"])
|
||||
def test_config_to_docker_preinstall_skips_unsafe_paths(tmp_path, dirname):
|
||||
_write_local_package(tmp_path, "proj", '[project]\nname = "x"')
|
||||
_write_local_package(
|
||||
tmp_path, dirname, '[project]\nname = "y"\ndependencies = ["six"]'
|
||||
)
|
||||
(tmp_path / "proj" / "agent.py").write_text("graph = None\n")
|
||||
docker, _ = config_to_docker(
|
||||
tmp_path / "proj" / "langgraph.json",
|
||||
validate_config(
|
||||
{
|
||||
"dependencies": [".", f"../{dirname}"],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
}
|
||||
),
|
||||
base_image="langchain/langgraph-api",
|
||||
)
|
||||
assert "--mount" not in docker
|
||||
Reference in new issue
Block a user